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,101 | Why can we ignore missing data if it's missing at random? | I really like the following figure from Daniel, Kenward, Cousens, & De Stavola (2012) that gives an intuitive view of why Missing At Random (MAR) given X is not a problem, but MAR given Y is a problem.
(NOTE that this figure uses the symbol A instead of X for the predictor.)
For the sake of illustration this figure shows an exaggerated situation where the missingness is either 0% or 100%, depending on the value of an observed variable. But the same principles hold in more realistic cases where missingness depends in a more fuzzy way on the observed variables.
The top panel shows MAR given X. In this situation, the efficiency/precision of the slope estimate is certainly lower, but the average estimate is the same as it would be if there were no missing data.
The bottom panel shows MAR given Y. Here the average slope estimate is not the same as it would be if there were no missing data -- that is, it's biased. That's because the missing large Y values lead the OLS slope estimates to be too shallow.
This figure can also be used to illustrate why even certain kinds of Missing Not At Random (MNAR) are not a problem either, although I won't get into that right now.
If you want to understand this better, you may be interested in this old blog post I wrote on the topic:
Using causal graphs to understand missingness and how to deal with it | Why can we ignore missing data if it's missing at random? | I really like the following figure from Daniel, Kenward, Cousens, & De Stavola (2012) that gives an intuitive view of why Missing At Random (MAR) given X is not a problem, but MAR given Y is a problem | Why can we ignore missing data if it's missing at random?
I really like the following figure from Daniel, Kenward, Cousens, & De Stavola (2012) that gives an intuitive view of why Missing At Random (MAR) given X is not a problem, but MAR given Y is a problem.
(NOTE that this figure uses the symbol A instead of X for the predictor.)
For the sake of illustration this figure shows an exaggerated situation where the missingness is either 0% or 100%, depending on the value of an observed variable. But the same principles hold in more realistic cases where missingness depends in a more fuzzy way on the observed variables.
The top panel shows MAR given X. In this situation, the efficiency/precision of the slope estimate is certainly lower, but the average estimate is the same as it would be if there were no missing data.
The bottom panel shows MAR given Y. Here the average slope estimate is not the same as it would be if there were no missing data -- that is, it's biased. That's because the missing large Y values lead the OLS slope estimates to be too shallow.
This figure can also be used to illustrate why even certain kinds of Missing Not At Random (MNAR) are not a problem either, although I won't get into that right now.
If you want to understand this better, you may be interested in this old blog post I wrote on the topic:
Using causal graphs to understand missingness and how to deal with it | Why can we ignore missing data if it's missing at random?
I really like the following figure from Daniel, Kenward, Cousens, & De Stavola (2012) that gives an intuitive view of why Missing At Random (MAR) given X is not a problem, but MAR given Y is a problem |
34,102 | Question of understanding regarding Bayesian Optimization, Gaussian process and acquisition function | In addition to Tim's answer, here are some slight nitpicks/clarifications which might assist your intuitive understanding/prevent possible confusion in the future:
We start with a a-prior function, which is a gaussian process.
The Gaussian Process (GP) here is used as a prior over functions we consider as candidates for modelling the objective function, i.e., we use the GP as a surrogate for the function we want to optimise. This is usually because that function is "expensive" (in a certain sense) to query, but also because the GP provides a nice quantification of predictive uncertainty, which is used (by the acquisition function) to inform a search strategy. In other words, the uncertainty predicted by the GP/surrogate is used to inform the search strategy.
A gaussian process is something like a normal distribution but with functions, instead of with variables.
Yes, kind of. Another way of thinking about it is that it's a multivariate normal distribution defined "lazily" over a continuous space: you can pick any two points in the space and the Gaussian Process will "tell you how similar the values at those points are" by way of a mean vector and covariance matrix. The GP is lazy in the sense that it provides a way of calculating the mean vector and covariance matrix for any given combination of points when you want them. By choosing which values have similar values (and by how much), a practitioner can impose "structure" on the space they're modelling.
A gaussian process is mainly described by the expectation function 𝑚(𝑥) together with a covariance function 𝑘(𝑥,𝑥′).
A GP is completely defined ("parameterised") by the mean function and covariance function (the "kernel").
The gaussian process is used to optimize an acquisition function.
Not quite. The acquisition function is a function of the GP's predictive distribution, i.e., to evaluate the acquisition function at a point $x$, you first get the (posterior) predictive distribution of the GP at that point, and then that predictive distribution (the marginal distribution of the GP's predictive distribution at $x$, if you like) goes into the acquisition function to tell you how "useful" (in some sense) the point $x$ is. The acquisition function is usually (but not always) optimised using some gradient based method, because analytical derivatives of most acquisition functions are quite easy to calculate.
The maximum of the acquisition function determines where to check the next sample.
Yes. Following from the above, we pick "the most useful point" as determined by the acquisition function.
We use the next sample together with the a-priori/gaussian process (which both together form the so-called a-posterior function) to get a "new" a-priori function.
What happens here is you query your original "expensive" objective function (the function you're optimising using Bayesian optimisation), add that point to the "data" you have, and repeat the process. | Question of understanding regarding Bayesian Optimization, Gaussian process and acquisition function | In addition to Tim's answer, here are some slight nitpicks/clarifications which might assist your intuitive understanding/prevent possible confusion in the future:
We start with a a-prior function, w | Question of understanding regarding Bayesian Optimization, Gaussian process and acquisition function
In addition to Tim's answer, here are some slight nitpicks/clarifications which might assist your intuitive understanding/prevent possible confusion in the future:
We start with a a-prior function, which is a gaussian process.
The Gaussian Process (GP) here is used as a prior over functions we consider as candidates for modelling the objective function, i.e., we use the GP as a surrogate for the function we want to optimise. This is usually because that function is "expensive" (in a certain sense) to query, but also because the GP provides a nice quantification of predictive uncertainty, which is used (by the acquisition function) to inform a search strategy. In other words, the uncertainty predicted by the GP/surrogate is used to inform the search strategy.
A gaussian process is something like a normal distribution but with functions, instead of with variables.
Yes, kind of. Another way of thinking about it is that it's a multivariate normal distribution defined "lazily" over a continuous space: you can pick any two points in the space and the Gaussian Process will "tell you how similar the values at those points are" by way of a mean vector and covariance matrix. The GP is lazy in the sense that it provides a way of calculating the mean vector and covariance matrix for any given combination of points when you want them. By choosing which values have similar values (and by how much), a practitioner can impose "structure" on the space they're modelling.
A gaussian process is mainly described by the expectation function 𝑚(𝑥) together with a covariance function 𝑘(𝑥,𝑥′).
A GP is completely defined ("parameterised") by the mean function and covariance function (the "kernel").
The gaussian process is used to optimize an acquisition function.
Not quite. The acquisition function is a function of the GP's predictive distribution, i.e., to evaluate the acquisition function at a point $x$, you first get the (posterior) predictive distribution of the GP at that point, and then that predictive distribution (the marginal distribution of the GP's predictive distribution at $x$, if you like) goes into the acquisition function to tell you how "useful" (in some sense) the point $x$ is. The acquisition function is usually (but not always) optimised using some gradient based method, because analytical derivatives of most acquisition functions are quite easy to calculate.
The maximum of the acquisition function determines where to check the next sample.
Yes. Following from the above, we pick "the most useful point" as determined by the acquisition function.
We use the next sample together with the a-priori/gaussian process (which both together form the so-called a-posterior function) to get a "new" a-priori function.
What happens here is you query your original "expensive" objective function (the function you're optimising using Bayesian optimisation), add that point to the "data" you have, and repeat the process. | Question of understanding regarding Bayesian Optimization, Gaussian process and acquisition function
In addition to Tim's answer, here are some slight nitpicks/clarifications which might assist your intuitive understanding/prevent possible confusion in the future:
We start with a a-prior function, w |
34,103 | Question of understanding regarding Bayesian Optimization, Gaussian process and acquisition function | You are correct. The Gaussian process is a distribution over functions. As with other Bayesian methods, you start with a prior and combine it with data (observed outcome) through likelihood to get a posterior. The posterior can be used to make predictions and can be used as a prior for further analysis (Bayesian updating). The posterior distribution in Bayesian optimization is used for making guesses about the next move either by using it to find an optimal move given some definition of optimality or by sampling from it. In Bayesian optimization you optimize the function approximated by Gaussian process (or another model) rather than optimizing the function directly as in many other forms of optimization.
If you want to learn more, I recommend the book by Carl Rasmussen and Christopher Williams, the recorded talks by Carl Rasmussen, Neil Lawrence, and Michael Osborne, the blog posts by Katherine Bailey and Martin Krasser, including an additional one on Bayesian optimization, and the visual guide by Johen Görtler et al. When I first learned about Gaussian processes I found the notation and language a little bit confusing and implementing the stuff and playing around with the code helped a lot. After you feel that you understand it, I recommend re-reading the book by Rasmussen and Williams once more. | Question of understanding regarding Bayesian Optimization, Gaussian process and acquisition function | You are correct. The Gaussian process is a distribution over functions. As with other Bayesian methods, you start with a prior and combine it with data (observed outcome) through likelihood to get a p | Question of understanding regarding Bayesian Optimization, Gaussian process and acquisition function
You are correct. The Gaussian process is a distribution over functions. As with other Bayesian methods, you start with a prior and combine it with data (observed outcome) through likelihood to get a posterior. The posterior can be used to make predictions and can be used as a prior for further analysis (Bayesian updating). The posterior distribution in Bayesian optimization is used for making guesses about the next move either by using it to find an optimal move given some definition of optimality or by sampling from it. In Bayesian optimization you optimize the function approximated by Gaussian process (or another model) rather than optimizing the function directly as in many other forms of optimization.
If you want to learn more, I recommend the book by Carl Rasmussen and Christopher Williams, the recorded talks by Carl Rasmussen, Neil Lawrence, and Michael Osborne, the blog posts by Katherine Bailey and Martin Krasser, including an additional one on Bayesian optimization, and the visual guide by Johen Görtler et al. When I first learned about Gaussian processes I found the notation and language a little bit confusing and implementing the stuff and playing around with the code helped a lot. After you feel that you understand it, I recommend re-reading the book by Rasmussen and Williams once more. | Question of understanding regarding Bayesian Optimization, Gaussian process and acquisition function
You are correct. The Gaussian process is a distribution over functions. As with other Bayesian methods, you start with a prior and combine it with data (observed outcome) through likelihood to get a p |
34,104 | Get accurate eigenvectors, when eigenvalues are minuscule | The problem is due to "leakage" from the large eigenvectors. I will present a brief analysis and then offer a solution, with code, followed by some remarks about the nature and limitations of the solution.
Analysis
Let the eigenvalues of a real symmetric matrix $\mathbb M$ be $\lambda_1,\lambda_2,\ldots,\lambda_d$ ordered by decreasing absolute value so that $|\lambda_1|\ge |\lambda_2|\ge \cdots \ge |\lambda_d|.$ The objective, as stated in a comment to the question, is to find vectors $x$ so that $\mathbb{M}x$ is relatively small. Because the mapping $x\to\mathbb{M}x$ is linear, we may focus our study of such $x$ on those of unit length.
The Spectral Theorem guarantees the existence of an orthonormal basis $\{e_1,e_2,\ldots, e_d\}$ of corresponding eigenvectors in which $x$ may be expressed as the linear combination
$$x = \xi_1 e_1 + \xi_2 e_2 + \cdots + \xi_d e_d.$$
The orthonormality assures us that
$$1 = |x|^2 = \xi_1^2 + \xi_2^2 + \cdots + \xi_d^2.$$
Applying $\mathbb M$ yields
$$\mathbb{M}x = \xi_1 \mathbb{M} e_1 + \xi_2 \mathbb{M}e_2 + \cdots \xi_d \mathbb{M}e_d = \xi_1\lambda_1 e_1 + \xi_2\lambda_2 e_2 + \cdots + \xi_d\lambda_d e_d.$$
Suppose there is some slight error in the computation of the eigenvectors $e_i,$ so that where we think we are working with the eigenvector with eigenvalue $\lambda_i,$ we really are working with a perturbation $e_i^\prime$ where
$$e_i^\prime - e_i = \alpha_{i1}e_1 + \alpha_{i2}e_2 + \cdots + \alpha_{id}e_d.$$
These aren't quite eigenvectors anymore, as we may check by applying $\mathbb M$ to them:
$$\mathbb{M}e_i^\prime = \mathbb{M}e_i + \alpha_{i1}\mathbb{M}e_1 + \cdots + \alpha_{id}\mathbb{M}e_d = \lambda_i e_i + \alpha_{i1}\lambda_1 e_1 + \cdots + \alpha_{id}\lambda_d e_d.$$
Notice, in particular, that when $\lambda_i$ is tiny compared to $\lambda_1,$ the appearance of the multiple $\alpha_{i1}\lambda_1$ of $e_1$ can hugely alter the result, even when $\alpha_{i1}$ is tiny, due to that multiplication by $\lambda_1.$ This is the crux of the matter.
The problem propagates when applying $\mathbb{M}$ to the linear combination
$$x^\prime = \xi_1 e_1^\prime + \xi_2 e_2^\prime + \cdots + \xi_d e_d^\prime,$$
which we think is $x$ (because we think the $e_i^\prime$ are the $e_i$). Applying $\mathbb{M}$ separately to each of the $e_i^\prime$ on the right "leaks" potentially large multiples of $e_1$ into the result.
Solution
Fortunately there's a simple solution: remove the unexpected eigenvectors from the result. When (say) the first $k$ coefficients of $x$ are zero, $\xi_1=\xi_2=\cdots=\xi_k,$ then *there should not be any multiples of $e_1$ through $e_k$ in $\mathbb{M} x.$ We can remove them by projecting the result of $\mathbb{M}x$ onto the space generated by $e_{k+1},\ldots, e_d.$
This doesn't quite get us the correct value of $\mathbb{M}x,$ because of the "leakage" among the smaller eigenvectors. For instance, applying $\mathbb{M}$ to $x=e_d$ yields a linear combination of all the $e_i.$ Projecting out the first $k$ eigenvectors leaves us still with a linear combination
$$\lambda_{k+1}\alpha_{d,k+1} e_{k+1} + \lambda_{k+2}\alpha_{d,k+2} e_{k+2} + \cdots + \lambda_{d}(1+\alpha_{d,d}) e_{d}.$$
However, if (a) $|\lambda_{k+1}| \approx |\lambda_{k+2}| \approx \cdots \approx |\lambda_d|$ are of comparable orders of magnitude and (b) the $\alpha_{d,*}$ coefficients are all relatively small, the result will still be reasonably accurate.
Example
Let's see how this works with the matrix $\mathbb M$ of the question. Here $k=8$ and $\lambda_1\approx 1111$ and $\lambda_2 \approx 5\times 10^{-8}$ are much greater than any of the other eigenvectors. The appearance of tiny negative eigenvalues in a setting where (one assumes) non-negative values are expected is further evidence that the last six (really seven) eigenvalues might just be noisy versions of zero.
The R code below creates random vectors $x^\prime$ in the space generated by the last $8-2=6$ eigenvectors. It applies $\mathbb M$ to them in two ways: directly as $y=\mathbb{M}x^\prime$; and with the "projection method" in which $y$ is regressed against the first two eigenvectors. It returns the norms of those two results. We hope that the norms will be really tiny, because $\mathbb M$ shouldn't change the norm by more than $\max\{|\lambda_3|,\ldots, |\lambda_8|\}\approx 6.25\times 10^{-8}.$ To see what it really does, I plotted histograms of the two sets of results (left and middle). To compare the two approaches I also drew their scatterplot at the right.
The direct method (left) is awful: a considerable amount of $e_1$ has leaked into the eigenvectors, causing the norms to be inflated by approximately ten(!) orders of magnitude. After projecting the first two eigenvectors out, the norms are always of the expected magnitude. The scatterplot shows no relationship among the results. (In some cases, for other matrices $\mathbb M,$ there are some intriguing relationships induced by the magnitudes of the error coefficients $\alpha_{ij}.$)
Remarks
This solution guarantees that the result of computing $\mathbb{M}x$ will be orthogonal to the largest eigenspaces and will, with an accuracy relative to the magnitudes of the largest eigenvalues, reflect how much $\mathbb M$ affects the lengths. That's probably all that's needed in the intended application.
There's no prospect of doing any better, either. Many of the entries in matrices like $\mathbb M$ were already computed using floating point arithmetic and therefore cannot be considered any more precise than the results of those operations. The large condition numbers of matrices like $\mathbb M$ guarantee that even using infinitely precise arithmetic, the effects of either (a) changing any entry in $\mathbb M$ in its least significant bit or (b) changing any coefficient of $x$ in its least significant bit will hugely perturb the result.
The svd (singular value decomposition) function in R does a better job of computing the eigenvalues and vectors. This doesn't improve the direct calculation of $\mathbb M$ appreciably, though. If you would like to compare these methods, replace the line eig <- eigen(m) by eig <- with(svd(m), list(values = d, vectors = u)).
Code
This picks up after the definition of m in the question and the calculation of its eigenvectors using eigen.
lambda <- eig$values
i <- lambda >= max(lambda) * 1e-12 # Indexes of large eigenvalues.
#
# Generate unit movements in the small directions.
#
nu <- function(x) { # Standardize to unit length if possible
a <- sum(x^2)
if(a==0) x else x/sqrt(a)
}
set.seed(17)
sim <- replicate(500, {
# Naive (uncorrected) algorithm.
dx <- eig$vectors %*% rnorm(length(lambda)) * ifelse(i, 0, 1)
dy <- m %*% nu(dx)
# Corrected algorithm with projection.
dx <- residuals(lm(dx ~ eig$vectors[,i]))
dz <- m %*% nu(dx)
c(sqrt(sum(dy^2)), sqrt(sum(dz^2)))
})
#
# Compare.
#
par(mfrow=c(1,3))
hist(sim[1,], main="Magnitudes of resultants: direct method", cex.main=1)
hist(sim[2,], main="Magnitudes of resultants: projection method", cex.main=1)
plot(t(sim), xlab="Direct method", ylab="Projection method", main="Comparison", cex.main=1)
par(mfrow=c(1,1)) | Get accurate eigenvectors, when eigenvalues are minuscule | The problem is due to "leakage" from the large eigenvectors. I will present a brief analysis and then offer a solution, with code, followed by some remarks about the nature and limitations of the sol | Get accurate eigenvectors, when eigenvalues are minuscule
The problem is due to "leakage" from the large eigenvectors. I will present a brief analysis and then offer a solution, with code, followed by some remarks about the nature and limitations of the solution.
Analysis
Let the eigenvalues of a real symmetric matrix $\mathbb M$ be $\lambda_1,\lambda_2,\ldots,\lambda_d$ ordered by decreasing absolute value so that $|\lambda_1|\ge |\lambda_2|\ge \cdots \ge |\lambda_d|.$ The objective, as stated in a comment to the question, is to find vectors $x$ so that $\mathbb{M}x$ is relatively small. Because the mapping $x\to\mathbb{M}x$ is linear, we may focus our study of such $x$ on those of unit length.
The Spectral Theorem guarantees the existence of an orthonormal basis $\{e_1,e_2,\ldots, e_d\}$ of corresponding eigenvectors in which $x$ may be expressed as the linear combination
$$x = \xi_1 e_1 + \xi_2 e_2 + \cdots + \xi_d e_d.$$
The orthonormality assures us that
$$1 = |x|^2 = \xi_1^2 + \xi_2^2 + \cdots + \xi_d^2.$$
Applying $\mathbb M$ yields
$$\mathbb{M}x = \xi_1 \mathbb{M} e_1 + \xi_2 \mathbb{M}e_2 + \cdots \xi_d \mathbb{M}e_d = \xi_1\lambda_1 e_1 + \xi_2\lambda_2 e_2 + \cdots + \xi_d\lambda_d e_d.$$
Suppose there is some slight error in the computation of the eigenvectors $e_i,$ so that where we think we are working with the eigenvector with eigenvalue $\lambda_i,$ we really are working with a perturbation $e_i^\prime$ where
$$e_i^\prime - e_i = \alpha_{i1}e_1 + \alpha_{i2}e_2 + \cdots + \alpha_{id}e_d.$$
These aren't quite eigenvectors anymore, as we may check by applying $\mathbb M$ to them:
$$\mathbb{M}e_i^\prime = \mathbb{M}e_i + \alpha_{i1}\mathbb{M}e_1 + \cdots + \alpha_{id}\mathbb{M}e_d = \lambda_i e_i + \alpha_{i1}\lambda_1 e_1 + \cdots + \alpha_{id}\lambda_d e_d.$$
Notice, in particular, that when $\lambda_i$ is tiny compared to $\lambda_1,$ the appearance of the multiple $\alpha_{i1}\lambda_1$ of $e_1$ can hugely alter the result, even when $\alpha_{i1}$ is tiny, due to that multiplication by $\lambda_1.$ This is the crux of the matter.
The problem propagates when applying $\mathbb{M}$ to the linear combination
$$x^\prime = \xi_1 e_1^\prime + \xi_2 e_2^\prime + \cdots + \xi_d e_d^\prime,$$
which we think is $x$ (because we think the $e_i^\prime$ are the $e_i$). Applying $\mathbb{M}$ separately to each of the $e_i^\prime$ on the right "leaks" potentially large multiples of $e_1$ into the result.
Solution
Fortunately there's a simple solution: remove the unexpected eigenvectors from the result. When (say) the first $k$ coefficients of $x$ are zero, $\xi_1=\xi_2=\cdots=\xi_k,$ then *there should not be any multiples of $e_1$ through $e_k$ in $\mathbb{M} x.$ We can remove them by projecting the result of $\mathbb{M}x$ onto the space generated by $e_{k+1},\ldots, e_d.$
This doesn't quite get us the correct value of $\mathbb{M}x,$ because of the "leakage" among the smaller eigenvectors. For instance, applying $\mathbb{M}$ to $x=e_d$ yields a linear combination of all the $e_i.$ Projecting out the first $k$ eigenvectors leaves us still with a linear combination
$$\lambda_{k+1}\alpha_{d,k+1} e_{k+1} + \lambda_{k+2}\alpha_{d,k+2} e_{k+2} + \cdots + \lambda_{d}(1+\alpha_{d,d}) e_{d}.$$
However, if (a) $|\lambda_{k+1}| \approx |\lambda_{k+2}| \approx \cdots \approx |\lambda_d|$ are of comparable orders of magnitude and (b) the $\alpha_{d,*}$ coefficients are all relatively small, the result will still be reasonably accurate.
Example
Let's see how this works with the matrix $\mathbb M$ of the question. Here $k=8$ and $\lambda_1\approx 1111$ and $\lambda_2 \approx 5\times 10^{-8}$ are much greater than any of the other eigenvectors. The appearance of tiny negative eigenvalues in a setting where (one assumes) non-negative values are expected is further evidence that the last six (really seven) eigenvalues might just be noisy versions of zero.
The R code below creates random vectors $x^\prime$ in the space generated by the last $8-2=6$ eigenvectors. It applies $\mathbb M$ to them in two ways: directly as $y=\mathbb{M}x^\prime$; and with the "projection method" in which $y$ is regressed against the first two eigenvectors. It returns the norms of those two results. We hope that the norms will be really tiny, because $\mathbb M$ shouldn't change the norm by more than $\max\{|\lambda_3|,\ldots, |\lambda_8|\}\approx 6.25\times 10^{-8}.$ To see what it really does, I plotted histograms of the two sets of results (left and middle). To compare the two approaches I also drew their scatterplot at the right.
The direct method (left) is awful: a considerable amount of $e_1$ has leaked into the eigenvectors, causing the norms to be inflated by approximately ten(!) orders of magnitude. After projecting the first two eigenvectors out, the norms are always of the expected magnitude. The scatterplot shows no relationship among the results. (In some cases, for other matrices $\mathbb M,$ there are some intriguing relationships induced by the magnitudes of the error coefficients $\alpha_{ij}.$)
Remarks
This solution guarantees that the result of computing $\mathbb{M}x$ will be orthogonal to the largest eigenspaces and will, with an accuracy relative to the magnitudes of the largest eigenvalues, reflect how much $\mathbb M$ affects the lengths. That's probably all that's needed in the intended application.
There's no prospect of doing any better, either. Many of the entries in matrices like $\mathbb M$ were already computed using floating point arithmetic and therefore cannot be considered any more precise than the results of those operations. The large condition numbers of matrices like $\mathbb M$ guarantee that even using infinitely precise arithmetic, the effects of either (a) changing any entry in $\mathbb M$ in its least significant bit or (b) changing any coefficient of $x$ in its least significant bit will hugely perturb the result.
The svd (singular value decomposition) function in R does a better job of computing the eigenvalues and vectors. This doesn't improve the direct calculation of $\mathbb M$ appreciably, though. If you would like to compare these methods, replace the line eig <- eigen(m) by eig <- with(svd(m), list(values = d, vectors = u)).
Code
This picks up after the definition of m in the question and the calculation of its eigenvectors using eigen.
lambda <- eig$values
i <- lambda >= max(lambda) * 1e-12 # Indexes of large eigenvalues.
#
# Generate unit movements in the small directions.
#
nu <- function(x) { # Standardize to unit length if possible
a <- sum(x^2)
if(a==0) x else x/sqrt(a)
}
set.seed(17)
sim <- replicate(500, {
# Naive (uncorrected) algorithm.
dx <- eig$vectors %*% rnorm(length(lambda)) * ifelse(i, 0, 1)
dy <- m %*% nu(dx)
# Corrected algorithm with projection.
dx <- residuals(lm(dx ~ eig$vectors[,i]))
dz <- m %*% nu(dx)
c(sqrt(sum(dy^2)), sqrt(sum(dz^2)))
})
#
# Compare.
#
par(mfrow=c(1,3))
hist(sim[1,], main="Magnitudes of resultants: direct method", cex.main=1)
hist(sim[2,], main="Magnitudes of resultants: projection method", cex.main=1)
plot(t(sim), xlab="Direct method", ylab="Projection method", main="Comparison", cex.main=1)
par(mfrow=c(1,1)) | Get accurate eigenvectors, when eigenvalues are minuscule
The problem is due to "leakage" from the large eigenvectors. I will present a brief analysis and then offer a solution, with code, followed by some remarks about the nature and limitations of the sol |
34,105 | Get accurate eigenvectors, when eigenvalues are minuscule | Whuber has already done a better job of that than I could of answering the question, but I have some figures I generated for other work may help illustrate some of the issues. A similar version is in the supporting information associated with this paper on visual exploration of PCA for spectroscopists (open access)
Whuber indicated that SVD is good for accurate calculation of eigenvalues and vectors, and from my reading that is a widely held opinion, this arises from the use of matrix decomposition on the covariance matrix, which has the consequence that all eigenvectors are solved in conjunction and computation errors are spread over them all. Sequential/iterative methods such as the power method (sequential fitting of covariance matrix) or NIPALs (sequential fitting of residual) in contrast accrue errors in each eigenvector calculation and these can build up to the point they over power very low variance eigenvectors.
In that paper I had implemented PCA using NIPALs and as a sanity check I published data in the supporting information comparing the results to an established python function that used SVD. The first PC was very similar for both algorithms:
The difference between them was miniscule ($10^{-15}$), on the order of computational accuracy:
The difference was dependent on the specified tolerance for the NIPALs algorithm. Next we see a plot of the SVD rank against the NIPALs rank for the SVD-eigenvector that the NIPALs eigenvector most closely correlated with:
At first the rank is perfectly correlated, until we hit NIPALS PC24 where things get wobbly. NIPALS-24 is suddenly best correlated with SVD-1! Above NIPALS-24 the correlations get really messed up. It is not limited to rank, but actual eigenvector shape becomes much less consistent (even if we match by optimum correlation), as seen if we plot the correlation between SVD/NIPALs vs NIPALs rank:
This shows that information in the lower rank PCs is getting muddled up in the NIPALS wrt to SVD. If we look at SVD-1 (blue) and NIPALS-24 (orange) and the difference between them (green) we can seen that the two are indeed very similar and the difference is very noisy.
As you mention in the OP and Whuber mentions, this is usually handled by projection which also goes by the name of renormalisation or re-orthogonalisation . The process starts by applying the $PC_{1-i-1}$ eigenvectors to the residual and reconstructing (inner product of scores and eigenvectors), then recalculating the residual. If we done this after NIPALS-23 then the residual would have popped up as mostly NIPALS-1. Reconstructing the data at this point would have created a residual without the NIPALS-1 ghost and therefore would not have caused the same level of problems.
As Whuber indicates it is not possible to achieve infinitesimal accuracy, so it is a matter of what limits of precision do you need. | Get accurate eigenvectors, when eigenvalues are minuscule | Whuber has already done a better job of that than I could of answering the question, but I have some figures I generated for other work may help illustrate some of the issues. A similar version is in | Get accurate eigenvectors, when eigenvalues are minuscule
Whuber has already done a better job of that than I could of answering the question, but I have some figures I generated for other work may help illustrate some of the issues. A similar version is in the supporting information associated with this paper on visual exploration of PCA for spectroscopists (open access)
Whuber indicated that SVD is good for accurate calculation of eigenvalues and vectors, and from my reading that is a widely held opinion, this arises from the use of matrix decomposition on the covariance matrix, which has the consequence that all eigenvectors are solved in conjunction and computation errors are spread over them all. Sequential/iterative methods such as the power method (sequential fitting of covariance matrix) or NIPALs (sequential fitting of residual) in contrast accrue errors in each eigenvector calculation and these can build up to the point they over power very low variance eigenvectors.
In that paper I had implemented PCA using NIPALs and as a sanity check I published data in the supporting information comparing the results to an established python function that used SVD. The first PC was very similar for both algorithms:
The difference between them was miniscule ($10^{-15}$), on the order of computational accuracy:
The difference was dependent on the specified tolerance for the NIPALs algorithm. Next we see a plot of the SVD rank against the NIPALs rank for the SVD-eigenvector that the NIPALs eigenvector most closely correlated with:
At first the rank is perfectly correlated, until we hit NIPALS PC24 where things get wobbly. NIPALS-24 is suddenly best correlated with SVD-1! Above NIPALS-24 the correlations get really messed up. It is not limited to rank, but actual eigenvector shape becomes much less consistent (even if we match by optimum correlation), as seen if we plot the correlation between SVD/NIPALs vs NIPALs rank:
This shows that information in the lower rank PCs is getting muddled up in the NIPALS wrt to SVD. If we look at SVD-1 (blue) and NIPALS-24 (orange) and the difference between them (green) we can seen that the two are indeed very similar and the difference is very noisy.
As you mention in the OP and Whuber mentions, this is usually handled by projection which also goes by the name of renormalisation or re-orthogonalisation . The process starts by applying the $PC_{1-i-1}$ eigenvectors to the residual and reconstructing (inner product of scores and eigenvectors), then recalculating the residual. If we done this after NIPALS-23 then the residual would have popped up as mostly NIPALS-1. Reconstructing the data at this point would have created a residual without the NIPALS-1 ghost and therefore would not have caused the same level of problems.
As Whuber indicates it is not possible to achieve infinitesimal accuracy, so it is a matter of what limits of precision do you need. | Get accurate eigenvectors, when eigenvalues are minuscule
Whuber has already done a better job of that than I could of answering the question, but I have some figures I generated for other work may help illustrate some of the issues. A similar version is in |
34,106 | Get accurate eigenvectors, when eigenvalues are minuscule | If your eigenvalues are "sloppy" then the eigenvectors will necessarily be "sloppy" too. With a condition number on the order of $10^{17}$ as in your example, I'd be wary of any results you got regardless of what numerical approach you use.
The solution is to avoid this type of problem before it starts.
You don't provide details about the "multi-parameter models" that you're trying to fit, but something seems to be terribly wrong. For an 8 x 8 Hessian matrix, there is only 1 eigenvalue of any substantial magnitude.
> eig$values
[1] 1.110666e+03 5.014476e-08 7.523231e-14 1.113187e-14 -4.122444e-10
[6] -2.503845e-09 -1.832745e-08 -6.251041e-08
I suspect that there is substantial multicollinearity in your data, although other problems like an over-specified model might also be in play.
My first reaction is to use principal components of your data as predictors instead of the raw data. If multicollinearity is to blame for your problem, using just a few principal components could turn that weakness into a strength. Think also about whether the structure your model is contributing. | Get accurate eigenvectors, when eigenvalues are minuscule | If your eigenvalues are "sloppy" then the eigenvectors will necessarily be "sloppy" too. With a condition number on the order of $10^{17}$ as in your example, I'd be wary of any results you got regard | Get accurate eigenvectors, when eigenvalues are minuscule
If your eigenvalues are "sloppy" then the eigenvectors will necessarily be "sloppy" too. With a condition number on the order of $10^{17}$ as in your example, I'd be wary of any results you got regardless of what numerical approach you use.
The solution is to avoid this type of problem before it starts.
You don't provide details about the "multi-parameter models" that you're trying to fit, but something seems to be terribly wrong. For an 8 x 8 Hessian matrix, there is only 1 eigenvalue of any substantial magnitude.
> eig$values
[1] 1.110666e+03 5.014476e-08 7.523231e-14 1.113187e-14 -4.122444e-10
[6] -2.503845e-09 -1.832745e-08 -6.251041e-08
I suspect that there is substantial multicollinearity in your data, although other problems like an over-specified model might also be in play.
My first reaction is to use principal components of your data as predictors instead of the raw data. If multicollinearity is to blame for your problem, using just a few principal components could turn that weakness into a strength. Think also about whether the structure your model is contributing. | Get accurate eigenvectors, when eigenvalues are minuscule
If your eigenvalues are "sloppy" then the eigenvectors will necessarily be "sloppy" too. With a condition number on the order of $10^{17}$ as in your example, I'd be wary of any results you got regard |
34,107 | Random sampling and independence in a real world problem | This extract from the text suffers from ambiguity and incorrectness.
Let's deal with the latter first. Independence of two random variables $X$ and $Y$ is not about one variable "providing no information about the first" (a remarkably ambiguous phrase in its own right!). Independence is strictly about probabilities and it means nothing more nor less than the chance of any joint event (namely, that the value of $X$ lies in some set $\mathcal A$ and the value of $Y$ simultaneously lies in some other set $\mathcal B$) is determined from the separate chances alone (namely, by multiplying them).
In this context it is natural to set up an urn model to understand the sampling. An extreme instance of this situation occurs with a truncated school year (as many have recently experienced!) in which the student commutes on just two days. The urn would contain two slips of paper representing the two commutes. On each slip is written the time of that commute. A random sample of size one is obtained by withdrawing a single slip blindly. Let $X$ be the value on that slip: it is a random variable. Let $Y$ be the collection of values on all remaining slips in the urn (namely, the commuting day that was not selected). It is straightforward to show that the random variable $(X,Y)$ is not independent: indeed, the correlation between $X$ and $Y$ is $-1$ and any variables with nonzero correlation are not independent.
If you find samples of size $1$ conceptually objectionable, extend this example to a school year with three commuting days and consider a random sample (without replacement) of size $2.$ This sample consists of withdrawing two tickets -- in order -- without replacement. Let $X_1$ be the value written on the first ticket and $X_2$ the value on the second. The correlation of the random variable $(X_1,X_2)$ is $-1/2,$ again nonzero: these two commuting times are not independent. (Question on Covariance for sampling without replacement explains how to calculate this covariance.)
It is possible the authors had in mind a model in which the urn is filled with gazillions of tickets reflecting some distribution of "hypothetical" commuting times. If so, the sample values will behave practically as if they were independent. But what would be the conceptual basis for constructing such a model?
The authors might also have (implicitly) been appealing to the idea that when there is a "large" number of tickets in the urn and "relatively few" are withdrawn for the sample, the values on the sampled tickets are approximately independent. But that sounds just too qualitative and slippery to serve as a decent explanation for any audience.
The more we think about this situation, the more reality intrudes. For instance, even when a school year comprises a full 180 (or so) days, why should we suppose the commuting times sampled during winter months "provide no information" about other nearby commuting times? In regions with serious winter weather nobody would believe this. "I see it took you two hours to get to school yesterday. Must be a lot of snow out there. I bet your ride during the next week is going to be extra long."
We have already glossed over several ambiguities concerning what is meant by "no information" and what model is in use. There are other ambiguities. For the purposes of evaluating independence of values in the sample, should we -- or should we not -- suppose we might inspect the full contents of the urn? If one commuting time "provides no information" about any other commuting time in the sample, then how much less information must it provide about commuting times that weren't sampled! How, then, could it be possible to make any inferences at all about the year's commuting times based on the sampled values?
Although it might seem painful or excessively technical to do so, the only way to demonstrate independence of random variables must appeal to its probabilistic definition. That requires clearly indicating a probability model and showing that the probabilities in that model obey the product law that is characteristic of independence. Anything else is just hand-waving and threatens to confuse the thoughtful student. | Random sampling and independence in a real world problem | This extract from the text suffers from ambiguity and incorrectness.
Let's deal with the latter first. Independence of two random variables $X$ and $Y$ is not about one variable "providing no informa | Random sampling and independence in a real world problem
This extract from the text suffers from ambiguity and incorrectness.
Let's deal with the latter first. Independence of two random variables $X$ and $Y$ is not about one variable "providing no information about the first" (a remarkably ambiguous phrase in its own right!). Independence is strictly about probabilities and it means nothing more nor less than the chance of any joint event (namely, that the value of $X$ lies in some set $\mathcal A$ and the value of $Y$ simultaneously lies in some other set $\mathcal B$) is determined from the separate chances alone (namely, by multiplying them).
In this context it is natural to set up an urn model to understand the sampling. An extreme instance of this situation occurs with a truncated school year (as many have recently experienced!) in which the student commutes on just two days. The urn would contain two slips of paper representing the two commutes. On each slip is written the time of that commute. A random sample of size one is obtained by withdrawing a single slip blindly. Let $X$ be the value on that slip: it is a random variable. Let $Y$ be the collection of values on all remaining slips in the urn (namely, the commuting day that was not selected). It is straightforward to show that the random variable $(X,Y)$ is not independent: indeed, the correlation between $X$ and $Y$ is $-1$ and any variables with nonzero correlation are not independent.
If you find samples of size $1$ conceptually objectionable, extend this example to a school year with three commuting days and consider a random sample (without replacement) of size $2.$ This sample consists of withdrawing two tickets -- in order -- without replacement. Let $X_1$ be the value written on the first ticket and $X_2$ the value on the second. The correlation of the random variable $(X_1,X_2)$ is $-1/2,$ again nonzero: these two commuting times are not independent. (Question on Covariance for sampling without replacement explains how to calculate this covariance.)
It is possible the authors had in mind a model in which the urn is filled with gazillions of tickets reflecting some distribution of "hypothetical" commuting times. If so, the sample values will behave practically as if they were independent. But what would be the conceptual basis for constructing such a model?
The authors might also have (implicitly) been appealing to the idea that when there is a "large" number of tickets in the urn and "relatively few" are withdrawn for the sample, the values on the sampled tickets are approximately independent. But that sounds just too qualitative and slippery to serve as a decent explanation for any audience.
The more we think about this situation, the more reality intrudes. For instance, even when a school year comprises a full 180 (or so) days, why should we suppose the commuting times sampled during winter months "provide no information" about other nearby commuting times? In regions with serious winter weather nobody would believe this. "I see it took you two hours to get to school yesterday. Must be a lot of snow out there. I bet your ride during the next week is going to be extra long."
We have already glossed over several ambiguities concerning what is meant by "no information" and what model is in use. There are other ambiguities. For the purposes of evaluating independence of values in the sample, should we -- or should we not -- suppose we might inspect the full contents of the urn? If one commuting time "provides no information" about any other commuting time in the sample, then how much less information must it provide about commuting times that weren't sampled! How, then, could it be possible to make any inferences at all about the year's commuting times based on the sampled values?
Although it might seem painful or excessively technical to do so, the only way to demonstrate independence of random variables must appeal to its probabilistic definition. That requires clearly indicating a probability model and showing that the probabilities in that model obey the product law that is characteristic of independence. Anything else is just hand-waving and threatens to confuse the thoughtful student. | Random sampling and independence in a real world problem
This extract from the text suffers from ambiguity and incorrectness.
Let's deal with the latter first. Independence of two random variables $X$ and $Y$ is not about one variable "providing no informa |
34,108 | Random sampling and independence in a real world problem | This part of the book is wrong
Your misgivings on this matter are appropriate, because this part of the book is wrong. Even when making inferences about infinite populations, random sampling does not give independent random variables --- it gives conditionally independent random variables, conditional on the empirical distribution of the underlying superpopulation from which they were sampled. Once we reduce to sampling from a finite population, the sampled values are not conditionally independent given the underlying distribution of the population. In any case, it is not true that knowledge of the commuting time on one day gives no information about the commuting times on other days. Indeed, this is obviously not true, because if it were true then there would be no basis for making inferences from random samples at all.
If you would like to understand more about this topic, you can find a full elaboration (looking at both classical and Bayesian statistics) in O'Neill (2009). I'll give a short outline of the issue here, looking first at inferences in an infinite superpopulation. Consider a sequence of random variables $X_1,X_2,X_3,...$ with limiting empirical distribution $F_\infty$. De Finetti's representation theorem (as extended by Hewitt and Savage) shows that if the sequence is exchangeable (so that the first $n$ values are a simple random sample) then we have:
$$X_1,X_2,X_3,... | F_\infty \sim \text{IID } F_\infty.$$
This result means that random sampling from an infinite superpopulation gives values that are conditionally independent, conditional on the limiting empirical distribution. Once we condition on a finite population, things become even trickier. We can still say that the values are conditionally independent, conditional on $F_\infty$ (i.e., conditional on the distribution of an infinite superpopulation where the finite population is embedded), but this is not much use. Suppse we let $F_N$ denote the empirical distribution of the first $N$ values (a finite population), and we look at behaviour conditional on this distribution. Each sample value has this marginal distribution, but we cannot validly assert even conditional independence:
$$\quad \quad \quad \ \ X_i |F_N \sim F_N
\quad \quad \quad \quad \quad \ \text{(valid result)}$$
$$X_1,X_2,...,X_N | F_N \sim \text{IID } F_N.
\quad \quad \quad \text{(erroneous result)}$$
In fact, for any population values $i \neq k$ we have the conditional distribution:
$$X_i|X_k, F_N \sim F_{N,-k}$$
where $F_{N,-k}$ is the empirical distribution of the population, excluding the $k$th value (see below for details). Except in the case where all population values are the same, we have $F_N \neq F_{N,-k}$, which means that the values $X_i$ and $X_k$ are not independent. Your remarks about urn models illustrate exactly this.
Empirical distributions: The population empirical distribution $F_N: \mathbb{R} \rightarrow [0,1]$ is defined by:
$$F_N(x) = \frac{1}{N} \sum_{i=1}^N \mathbb{I}(x_i \leqslant x).$$
Excluding the $k$th value gives the corresponding empirical distribution $F_{N,-k}: \mathbb{R} \rightarrow [0,1]$, defined by:
$$F_{N,-k}(x) = \frac{1}{N-1} \sum_{i=1}^N \mathbb{I}(i \neq k) \cdot \mathbb{I}(x_i \leqslant x).$$
Since $(N-1) F_{N,-k}(x) + \mathbb{I}(x_k \leqslant x) = N F_N(x)$, we can write the latter in terms of the former as:
$$F_{N,-k}(x) = \frac{N}{N-1} \cdot (F_N(x) - \mathbb{I}(x_k \leqslant x)).$$ | Random sampling and independence in a real world problem | This part of the book is wrong
Your misgivings on this matter are appropriate, because this part of the book is wrong. Even when making inferences about infinite populations, random sampling does not | Random sampling and independence in a real world problem
This part of the book is wrong
Your misgivings on this matter are appropriate, because this part of the book is wrong. Even when making inferences about infinite populations, random sampling does not give independent random variables --- it gives conditionally independent random variables, conditional on the empirical distribution of the underlying superpopulation from which they were sampled. Once we reduce to sampling from a finite population, the sampled values are not conditionally independent given the underlying distribution of the population. In any case, it is not true that knowledge of the commuting time on one day gives no information about the commuting times on other days. Indeed, this is obviously not true, because if it were true then there would be no basis for making inferences from random samples at all.
If you would like to understand more about this topic, you can find a full elaboration (looking at both classical and Bayesian statistics) in O'Neill (2009). I'll give a short outline of the issue here, looking first at inferences in an infinite superpopulation. Consider a sequence of random variables $X_1,X_2,X_3,...$ with limiting empirical distribution $F_\infty$. De Finetti's representation theorem (as extended by Hewitt and Savage) shows that if the sequence is exchangeable (so that the first $n$ values are a simple random sample) then we have:
$$X_1,X_2,X_3,... | F_\infty \sim \text{IID } F_\infty.$$
This result means that random sampling from an infinite superpopulation gives values that are conditionally independent, conditional on the limiting empirical distribution. Once we condition on a finite population, things become even trickier. We can still say that the values are conditionally independent, conditional on $F_\infty$ (i.e., conditional on the distribution of an infinite superpopulation where the finite population is embedded), but this is not much use. Suppse we let $F_N$ denote the empirical distribution of the first $N$ values (a finite population), and we look at behaviour conditional on this distribution. Each sample value has this marginal distribution, but we cannot validly assert even conditional independence:
$$\quad \quad \quad \ \ X_i |F_N \sim F_N
\quad \quad \quad \quad \quad \ \text{(valid result)}$$
$$X_1,X_2,...,X_N | F_N \sim \text{IID } F_N.
\quad \quad \quad \text{(erroneous result)}$$
In fact, for any population values $i \neq k$ we have the conditional distribution:
$$X_i|X_k, F_N \sim F_{N,-k}$$
where $F_{N,-k}$ is the empirical distribution of the population, excluding the $k$th value (see below for details). Except in the case where all population values are the same, we have $F_N \neq F_{N,-k}$, which means that the values $X_i$ and $X_k$ are not independent. Your remarks about urn models illustrate exactly this.
Empirical distributions: The population empirical distribution $F_N: \mathbb{R} \rightarrow [0,1]$ is defined by:
$$F_N(x) = \frac{1}{N} \sum_{i=1}^N \mathbb{I}(x_i \leqslant x).$$
Excluding the $k$th value gives the corresponding empirical distribution $F_{N,-k}: \mathbb{R} \rightarrow [0,1]$, defined by:
$$F_{N,-k}(x) = \frac{1}{N-1} \sum_{i=1}^N \mathbb{I}(i \neq k) \cdot \mathbb{I}(x_i \leqslant x).$$
Since $(N-1) F_{N,-k}(x) + \mathbb{I}(x_k \leqslant x) = N F_N(x)$, we can write the latter in terms of the former as:
$$F_{N,-k}(x) = \frac{N}{N-1} \cdot (F_N(x) - \mathbb{I}(x_k \leqslant x)).$$ | Random sampling and independence in a real world problem
This part of the book is wrong
Your misgivings on this matter are appropriate, because this part of the book is wrong. Even when making inferences about infinite populations, random sampling does not |
34,109 | Random sampling and independence in a real world problem | I think you're overthinking it. When we conceptualize a study, and its sampling frame, we consider looking retrospectively at the outcomes, measured and unmeasured, from the study's completion. As noted in the example, the student plans to randomly sample days from the school year. So we can consider each of the year's 52*5 school days, and its associated commute time, as being one of the proverbial balls in the urn. | Random sampling and independence in a real world problem | I think you're overthinking it. When we conceptualize a study, and its sampling frame, we consider looking retrospectively at the outcomes, measured and unmeasured, from the study's completion. As not | Random sampling and independence in a real world problem
I think you're overthinking it. When we conceptualize a study, and its sampling frame, we consider looking retrospectively at the outcomes, measured and unmeasured, from the study's completion. As noted in the example, the student plans to randomly sample days from the school year. So we can consider each of the year's 52*5 school days, and its associated commute time, as being one of the proverbial balls in the urn. | Random sampling and independence in a real world problem
I think you're overthinking it. When we conceptualize a study, and its sampling frame, we consider looking retrospectively at the outcomes, measured and unmeasured, from the study's completion. As not |
34,110 | Is it possible for two random variables to be negatively correlated, but both be positively correlated with a third r.v.? | Certainly. Consider multivariate normally distributed data with a covariance matrix of the form
$$\begin{pmatrix} 1 & - & + \\ - & 1 & + \\ + & + & 1 \end{pmatrix}. $$
As an example, we can generate 1000 such observations with covariance matrix
$$\begin{pmatrix} 1 & -0.5 & 0.5 \\ -0.5 & 1 & 0.5 \\ 0.5 & 0.5 & 1 \end{pmatrix} $$
in R as follows:
library(mixtools)
set.seed(1)
xx <- rmvnorm(1e3,mu=rep(0,3),
sigma=rbind(c(1,-.5,.5),c(-.5,1,.5),c(.5,.5,1)))
cor(xx[,c(1,2)])
cor(xx[,c(1,3)])
cor(xx[,c(2,3)])
The first two columns are negatively correlated ($\rho=-0.5$), the first and the third and the second and the third are positively correlated ($\rho=0.5$). | Is it possible for two random variables to be negatively correlated, but both be positively correlat | Certainly. Consider multivariate normally distributed data with a covariance matrix of the form
$$\begin{pmatrix} 1 & - & + \\ - & 1 & + \\ + & + & 1 \end{pmatrix}. $$
As an example, we can generate 1 | Is it possible for two random variables to be negatively correlated, but both be positively correlated with a third r.v.?
Certainly. Consider multivariate normally distributed data with a covariance matrix of the form
$$\begin{pmatrix} 1 & - & + \\ - & 1 & + \\ + & + & 1 \end{pmatrix}. $$
As an example, we can generate 1000 such observations with covariance matrix
$$\begin{pmatrix} 1 & -0.5 & 0.5 \\ -0.5 & 1 & 0.5 \\ 0.5 & 0.5 & 1 \end{pmatrix} $$
in R as follows:
library(mixtools)
set.seed(1)
xx <- rmvnorm(1e3,mu=rep(0,3),
sigma=rbind(c(1,-.5,.5),c(-.5,1,.5),c(.5,.5,1)))
cor(xx[,c(1,2)])
cor(xx[,c(1,3)])
cor(xx[,c(2,3)])
The first two columns are negatively correlated ($\rho=-0.5$), the first and the third and the second and the third are positively correlated ($\rho=0.5$). | Is it possible for two random variables to be negatively correlated, but both be positively correlat
Certainly. Consider multivariate normally distributed data with a covariance matrix of the form
$$\begin{pmatrix} 1 & - & + \\ - & 1 & + \\ + & + & 1 \end{pmatrix}. $$
As an example, we can generate 1 |
34,111 | How to transform one Poisson distributed random variable to another with a different mean? | Not in general.
It's not possible to do it exactly if $\lambda_2>\lambda_1$, since a Poisson variable with mean $\lambda_2$ has higher entropy than one with mean $\lambda_1$, so it takes more information to specify it, even if you are willing to have a crazy non-monotone transformation.
For $\lambda_2<\lambda_1$, it is at least not always possible. Suppose $\lambda$ is small, so that the variable basically has only values 0 and 1, and the probability of 0 is $\exp(-\lambda)$. You can't transform between two distributions like this.
I can't see any easy way to rule out that it's possible in some cases with $1 \ll \lambda_2 \ll \lambda_1$. | How to transform one Poisson distributed random variable to another with a different mean? | Not in general.
It's not possible to do it exactly if $\lambda_2>\lambda_1$, since a Poisson variable with mean $\lambda_2$ has higher entropy than one with mean $\lambda_1$, so it takes more informat | How to transform one Poisson distributed random variable to another with a different mean?
Not in general.
It's not possible to do it exactly if $\lambda_2>\lambda_1$, since a Poisson variable with mean $\lambda_2$ has higher entropy than one with mean $\lambda_1$, so it takes more information to specify it, even if you are willing to have a crazy non-monotone transformation.
For $\lambda_2<\lambda_1$, it is at least not always possible. Suppose $\lambda$ is small, so that the variable basically has only values 0 and 1, and the probability of 0 is $\exp(-\lambda)$. You can't transform between two distributions like this.
I can't see any easy way to rule out that it's possible in some cases with $1 \ll \lambda_2 \ll \lambda_1$. | How to transform one Poisson distributed random variable to another with a different mean?
Not in general.
It's not possible to do it exactly if $\lambda_2>\lambda_1$, since a Poisson variable with mean $\lambda_2$ has higher entropy than one with mean $\lambda_1$, so it takes more informat |
34,112 | How to transform one Poisson distributed random variable to another with a different mean? | If you want it to be reversible and the result to have a Poisson distribution, it's not really possible.
Poisson distributions assign probability to the non-negative integers.
What monotonic transformations take non-negative integers to non-negative integers?
Unless you leave gaps in the middle of the sequence, I think all you have is shifts to the right, either of which doesn't leave you with another Poisson.
So that rules out readily interpretable (monotonic) transformations. Assuming you want a 1-to-1 transformation (otherwise you cannot transform back), you're at best going to be left with "shuffling" the values in some way.
But now note that the Poisson is unimodal (with an "edge case" of two adjacent modes when the parameter is an integer); the probabilities decrease either side of that. That severely limits your options (without even getting to the specific functional form)
Now consider a specific Poisson -- say a Poisson(1). It has a specific set of probabilities. Any deterministic 1-to-1 transformation will simply move those probabilities somewhere else. In general no other Poisson can share more than a fraction of those probabilities; where do the others go? e.g. with a Poisson(1) you have two probabilities of 1/e -- you might perhaps be able to find another Poisson that has a probability of 1/e, but can you find one with two of them, both the largest possible probabilities? It turns out you can't.
If you don't require a 1-to-1 transformation, so you can steal any number of probabilities from the far tail as needed, you might in some cases be able to have a transformation from a large parameter to a good approximation of a small one, but it might be hard to give a finite-time/space construction of one; I think this would not be a practical exercise in general. | How to transform one Poisson distributed random variable to another with a different mean? | If you want it to be reversible and the result to have a Poisson distribution, it's not really possible.
Poisson distributions assign probability to the non-negative integers.
What monotonic transfor | How to transform one Poisson distributed random variable to another with a different mean?
If you want it to be reversible and the result to have a Poisson distribution, it's not really possible.
Poisson distributions assign probability to the non-negative integers.
What monotonic transformations take non-negative integers to non-negative integers?
Unless you leave gaps in the middle of the sequence, I think all you have is shifts to the right, either of which doesn't leave you with another Poisson.
So that rules out readily interpretable (monotonic) transformations. Assuming you want a 1-to-1 transformation (otherwise you cannot transform back), you're at best going to be left with "shuffling" the values in some way.
But now note that the Poisson is unimodal (with an "edge case" of two adjacent modes when the parameter is an integer); the probabilities decrease either side of that. That severely limits your options (without even getting to the specific functional form)
Now consider a specific Poisson -- say a Poisson(1). It has a specific set of probabilities. Any deterministic 1-to-1 transformation will simply move those probabilities somewhere else. In general no other Poisson can share more than a fraction of those probabilities; where do the others go? e.g. with a Poisson(1) you have two probabilities of 1/e -- you might perhaps be able to find another Poisson that has a probability of 1/e, but can you find one with two of them, both the largest possible probabilities? It turns out you can't.
If you don't require a 1-to-1 transformation, so you can steal any number of probabilities from the far tail as needed, you might in some cases be able to have a transformation from a large parameter to a good approximation of a small one, but it might be hard to give a finite-time/space construction of one; I think this would not be a practical exercise in general. | How to transform one Poisson distributed random variable to another with a different mean?
If you want it to be reversible and the result to have a Poisson distribution, it's not really possible.
Poisson distributions assign probability to the non-negative integers.
What monotonic transfor |
34,113 | Isn't it futile to try to fix multicollinearity? | If the goal is prediction then your proposed solution sounds agreeable, but inference is a whole other beast.
The fact is that the theory, for example concerning sampling distributions of coefficients, is not capable of conditioning in such model selection procedures. Frank Harrell talks a little bit about this in Regression Modelling Strategies in the section about stepwise regression.
Statistics is not an algorithmic truth generating process. You need to be able to say "I think X is related to the outcome" in order to make inferences of the nature statistics affords us. | Isn't it futile to try to fix multicollinearity? | If the goal is prediction then your proposed solution sounds agreeable, but inference is a whole other beast.
The fact is that the theory, for example concerning sampling distributions of coefficients | Isn't it futile to try to fix multicollinearity?
If the goal is prediction then your proposed solution sounds agreeable, but inference is a whole other beast.
The fact is that the theory, for example concerning sampling distributions of coefficients, is not capable of conditioning in such model selection procedures. Frank Harrell talks a little bit about this in Regression Modelling Strategies in the section about stepwise regression.
Statistics is not an algorithmic truth generating process. You need to be able to say "I think X is related to the outcome" in order to make inferences of the nature statistics affords us. | Isn't it futile to try to fix multicollinearity?
If the goal is prediction then your proposed solution sounds agreeable, but inference is a whole other beast.
The fact is that the theory, for example concerning sampling distributions of coefficients |
34,114 | Isn't it futile to try to fix multicollinearity? | Eliminating variables is only one of several methods of dealing with collinearity. Others include (the list may not be exhaustive):
Getting more data
Principal components regression
Partial least squares regression
Ridge regression
Elastic net
Which of these is best (or if any is even necessary) depends on your goals and your particular situation. | Isn't it futile to try to fix multicollinearity? | Eliminating variables is only one of several methods of dealing with collinearity. Others include (the list may not be exhaustive):
Getting more data
Principal components regression
Partial least squ | Isn't it futile to try to fix multicollinearity?
Eliminating variables is only one of several methods of dealing with collinearity. Others include (the list may not be exhaustive):
Getting more data
Principal components regression
Partial least squares regression
Ridge regression
Elastic net
Which of these is best (or if any is even necessary) depends on your goals and your particular situation. | Isn't it futile to try to fix multicollinearity?
Eliminating variables is only one of several methods of dealing with collinearity. Others include (the list may not be exhaustive):
Getting more data
Principal components regression
Partial least squ |
34,115 | Why don't people trade significance level for power? | Why are experiments with moderately small $\alpha$ and very high power so rare?
This is all a bit relative, but one could certainly argue that the significance level $\alpha = 0.05$ is already weak, and already constitutes a sacrifice made for higher power (e.g., relative to the significance level $\alpha = 0.01$ or other lower significance levels). While opinions on this will differ, my own view is that this is already a very weak significance level, so choosing it at all is already a trade-off to get higher power.
From my understanding, after an experiment has been conducted, the significance level doesn't matter at all if the result is non-significant, because in this case, we are considering whether it makes sense to accept the null, and all we care about is the power. Similarly, if the result is significant, then the significance level becomes your evidence, while the power of the test makes absolutely zero difference.
I can see why you might think this, but it is not really true. In classical hypothesis testing there is quite a complex and subtle interaction in these things. Remember that both the p-value and the power pertain to probabilities that condition on the true state of the hypotheses (the p-value conditions on the null, and the power conditions on the alternative). When you get your result from the data, you make an inference about the hypotheses, but you still don't know their true state. Thus, it is not really legitimate to say that you can completely ignore the "other half" of the test. Regardless of whether the result is statistically significant or not, the interpretation of that result is made holistically, with respect to all the properties of the test.
It is also worth noting that, for a fixed model and test, and a fixed sample size, the power function is a function of the chosen significance level. The chosen significance level determines the rejection region, which directly affects the power of the test. So again, there is a relationship between these things, and you cannot ignore "one half" of the properties of the test.
Finally, it is also important to note that practitioners conducting a classical statistical tests will often just report the p-value of the test and leave it to the reader to choose their own significance level if a binary decision is required. (That is my preferred approach unless there is a specific need to make an immediate binary conclusion.) Modern statistical literature cautions strongly against reducing reported outcomes of hypothesis tests to a binary without also giving the underlying p-value. So in many practical cases, the significance level is not chosen prior to the analysis, and might not be chosen by the analyst conducting the test at all. | Why don't people trade significance level for power? | Why are experiments with moderately small $\alpha$ and very high power so rare?
This is all a bit relative, but one could certainly argue that the significance level $\alpha = 0.05$ is already weak, | Why don't people trade significance level for power?
Why are experiments with moderately small $\alpha$ and very high power so rare?
This is all a bit relative, but one could certainly argue that the significance level $\alpha = 0.05$ is already weak, and already constitutes a sacrifice made for higher power (e.g., relative to the significance level $\alpha = 0.01$ or other lower significance levels). While opinions on this will differ, my own view is that this is already a very weak significance level, so choosing it at all is already a trade-off to get higher power.
From my understanding, after an experiment has been conducted, the significance level doesn't matter at all if the result is non-significant, because in this case, we are considering whether it makes sense to accept the null, and all we care about is the power. Similarly, if the result is significant, then the significance level becomes your evidence, while the power of the test makes absolutely zero difference.
I can see why you might think this, but it is not really true. In classical hypothesis testing there is quite a complex and subtle interaction in these things. Remember that both the p-value and the power pertain to probabilities that condition on the true state of the hypotheses (the p-value conditions on the null, and the power conditions on the alternative). When you get your result from the data, you make an inference about the hypotheses, but you still don't know their true state. Thus, it is not really legitimate to say that you can completely ignore the "other half" of the test. Regardless of whether the result is statistically significant or not, the interpretation of that result is made holistically, with respect to all the properties of the test.
It is also worth noting that, for a fixed model and test, and a fixed sample size, the power function is a function of the chosen significance level. The chosen significance level determines the rejection region, which directly affects the power of the test. So again, there is a relationship between these things, and you cannot ignore "one half" of the properties of the test.
Finally, it is also important to note that practitioners conducting a classical statistical tests will often just report the p-value of the test and leave it to the reader to choose their own significance level if a binary decision is required. (That is my preferred approach unless there is a specific need to make an immediate binary conclusion.) Modern statistical literature cautions strongly against reducing reported outcomes of hypothesis tests to a binary without also giving the underlying p-value. So in many practical cases, the significance level is not chosen prior to the analysis, and might not be chosen by the analyst conducting the test at all. | Why don't people trade significance level for power?
Why are experiments with moderately small $\alpha$ and very high power so rare?
This is all a bit relative, but one could certainly argue that the significance level $\alpha = 0.05$ is already weak, |
34,116 | Why don't people trade significance level for power? | This is more of an extended comment than an answer. One interesting perspective can be found in this blog post, a short citation:
... contends the word [significance] carried much less weight in the
late 19th century, when it meant only that the result showed, or
signified, something. Then, in the 20th century, significance began to
gather the connotation it carries today, of not only signifying
something but signifying something of importance. ...
If this is correct then Fisher can have meant with significant rather something like worthy of taking a note (mental or in lab notebook), worthy for further investigation or replication.
This psyarxiv paper proposing to reduce standard significance level (in psychology research) from 0.05 to 0.005 is further evidence that many see (rightly ...) that 0.05 is already a rather weak requirement. | Why don't people trade significance level for power? | This is more of an extended comment than an answer. One interesting perspective can be found in this blog post, a short citation:
... contends the word [significance] carried much less weight in the | Why don't people trade significance level for power?
This is more of an extended comment than an answer. One interesting perspective can be found in this blog post, a short citation:
... contends the word [significance] carried much less weight in the
late 19th century, when it meant only that the result showed, or
signified, something. Then, in the 20th century, significance began to
gather the connotation it carries today, of not only signifying
something but signifying something of importance. ...
If this is correct then Fisher can have meant with significant rather something like worthy of taking a note (mental or in lab notebook), worthy for further investigation or replication.
This psyarxiv paper proposing to reduce standard significance level (in psychology research) from 0.05 to 0.005 is further evidence that many see (rightly ...) that 0.05 is already a rather weak requirement. | Why don't people trade significance level for power?
This is more of an extended comment than an answer. One interesting perspective can be found in this blog post, a short citation:
... contends the word [significance] carried much less weight in the |
34,117 | Why don't people trade significance level for power? | Because type II errors are considered to be less of a problem than type I errors. Type I errors have greater implications for future research. Moreover, most of the time, experiments with high power are much more expensive.
But of course you can also question both the whole NHST framework and the way it is frequently misused by unaware researchers... | Why don't people trade significance level for power? | Because type II errors are considered to be less of a problem than type I errors. Type I errors have greater implications for future research. Moreover, most of the time, experiments with high power a | Why don't people trade significance level for power?
Because type II errors are considered to be less of a problem than type I errors. Type I errors have greater implications for future research. Moreover, most of the time, experiments with high power are much more expensive.
But of course you can also question both the whole NHST framework and the way it is frequently misused by unaware researchers... | Why don't people trade significance level for power?
Because type II errors are considered to be less of a problem than type I errors. Type I errors have greater implications for future research. Moreover, most of the time, experiments with high power a |
34,118 | Why don't people trade significance level for power? | In a hypothesis test the null hypothesis and the alternative are not symmetric. Hypothesis test logic is connected to falsification logic. The idea is that one wants to be able to make a strong statement of having "statistically disproved" the null hypothesis in case of a significant result. Surely this requires a small significance level; 0.05 seems rather high in this respect, apart from the fact that in the meantime fishing for significance by running lots of tests and selectively reporting significant ones has made a mockery of the idea to "statistically disprove" a null hypothesis (which is one reason why some people advertise lowering the threshold to 0.005, although this won't stamp out selective reporting).
In fact if you run a test with significance level 0.2 and power 0.95 for a specific alternative, apart from subtleties with composite hypotheses, this means that rejecting the null hypothesis means hardly anything, as this will happen all the time (OK, 1/5 of times), whereas not rejecting is clear evidence against the alternative. Basically you run the test the other way round. | Why don't people trade significance level for power? | In a hypothesis test the null hypothesis and the alternative are not symmetric. Hypothesis test logic is connected to falsification logic. The idea is that one wants to be able to make a strong statem | Why don't people trade significance level for power?
In a hypothesis test the null hypothesis and the alternative are not symmetric. Hypothesis test logic is connected to falsification logic. The idea is that one wants to be able to make a strong statement of having "statistically disproved" the null hypothesis in case of a significant result. Surely this requires a small significance level; 0.05 seems rather high in this respect, apart from the fact that in the meantime fishing for significance by running lots of tests and selectively reporting significant ones has made a mockery of the idea to "statistically disprove" a null hypothesis (which is one reason why some people advertise lowering the threshold to 0.005, although this won't stamp out selective reporting).
In fact if you run a test with significance level 0.2 and power 0.95 for a specific alternative, apart from subtleties with composite hypotheses, this means that rejecting the null hypothesis means hardly anything, as this will happen all the time (OK, 1/5 of times), whereas not rejecting is clear evidence against the alternative. Basically you run the test the other way round. | Why don't people trade significance level for power?
In a hypothesis test the null hypothesis and the alternative are not symmetric. Hypothesis test logic is connected to falsification logic. The idea is that one wants to be able to make a strong statem |
34,119 | Why don't people trade significance level for power? | Why are experiments with moderately small α and very high power so rare?
High power is no problem, but the culprit is with the moderately small $\alpha$.
Experiments with only moderately small $\alpha$ are not precise and are prone to observe apparent effects that are not reality and only arrise due to imprecision and noise.
These imprecise, moderate $\alpha$ experiments are rare because the scientific community wants to read about results that are obtained with precision. To perform experiment with some small $\alpha$ is a scientific standard of performing an experiment that is sufficiently precise.
High power can not cure an experiment that is lacking precision. The high power does not change the uncertainty about the results.
so that you can confidentially accept the null
This is very similar to a test of equivalence in which you test the absence of a particular effect.
You do not really 'accept the null' only because you did not measure an effect. But you can reject some sort of the non-null, that the effect size is beyond some level, and accept the alternative that the effect (if it exists) must be small below some level. | Why don't people trade significance level for power? | Why are experiments with moderately small α and very high power so rare?
High power is no problem, but the culprit is with the moderately small $\alpha$.
Experiments with only moderately small $\alph | Why don't people trade significance level for power?
Why are experiments with moderately small α and very high power so rare?
High power is no problem, but the culprit is with the moderately small $\alpha$.
Experiments with only moderately small $\alpha$ are not precise and are prone to observe apparent effects that are not reality and only arrise due to imprecision and noise.
These imprecise, moderate $\alpha$ experiments are rare because the scientific community wants to read about results that are obtained with precision. To perform experiment with some small $\alpha$ is a scientific standard of performing an experiment that is sufficiently precise.
High power can not cure an experiment that is lacking precision. The high power does not change the uncertainty about the results.
so that you can confidentially accept the null
This is very similar to a test of equivalence in which you test the absence of a particular effect.
You do not really 'accept the null' only because you did not measure an effect. But you can reject some sort of the non-null, that the effect size is beyond some level, and accept the alternative that the effect (if it exists) must be small below some level. | Why don't people trade significance level for power?
Why are experiments with moderately small α and very high power so rare?
High power is no problem, but the culprit is with the moderately small $\alpha$.
Experiments with only moderately small $\alph |
34,120 | Posterior vs conditional probability | TLDR; Posterior probability is just the conditional probability that is outputted by the Bayes theorem. There is nothing special about it, it does not differ anyhow from any other conditional probability, it just has it's own name.
The Bayes theorem is about obtaining one conditional probability $P(A|B)$, given another one $P(B|A)$ and the prior $P(A)$,
$$
\underbrace{P(A|B)}_\text{posterior}=\frac{P(B|A)\,\overbrace{P(A)}^\text{prior}}{P(B)}
$$
So in the equation we have two random variables $A$ and $B$ and their conditional and marginal probabilities, that's all. Prior $P(A)$ is the probability of $A$ "before" learning about $B$, while posterior $P(A|B)$ is the probability of $A$ "after" learning about $B$, where the "before" and "after" refer to your procedure of calculating the probabilities, not any chronological order. The naming convention is that the left hand side is the posterior, while the prior appears in the right hand side part. Using Bayes theorem you can easily switch the sides back and forth (that's the point of the theorem). The usual use case is when you know only $P(B|A)$ and $P(A)$, but you don't know $P(A|B)$ and want to learn about it. Here you can find nice example of such usage of Bayes theorem.
The specific case is Bayesian inference, where we use Bayes theorem to learn about the distribution of the parameter of interest $\theta$ given the data $X$, i.e. obtain the posterior distribution $f(\theta|X)$. This is achieved by looking at the likelihood function (that looks at the "evidence" you gathered) and the prior (the distribution of $\theta$ that is assumed before looking at the data).
$$
\underbrace{f(\theta|X)}_\text{posterior}=\frac{\overbrace{f(X|\theta)}^\text{likelihood}\,\overbrace{f(\theta)}^\text{prior}}{\underbrace{f(X)}_\text{normalizing constant}}
$$
The most basic example of such usage of Bayes theorem is the beta-binomial model, but Bayesian inference is not only about probabilities of coin tosses, for example you can use it to do regression analysis and many other, even much more complicated, models.
To comment on your last question:
Doesn't "posterior" have something to do with the chronology of events
(their order of happening in time)?
Not at all. You can ask a valid probabilistic question is reverse time order, e.g. "What is the probability that it was raining in the morning given that the ground is wet?". | Posterior vs conditional probability | TLDR; Posterior probability is just the conditional probability that is outputted by the Bayes theorem. There is nothing special about it, it does not differ anyhow from any other conditional probabil | Posterior vs conditional probability
TLDR; Posterior probability is just the conditional probability that is outputted by the Bayes theorem. There is nothing special about it, it does not differ anyhow from any other conditional probability, it just has it's own name.
The Bayes theorem is about obtaining one conditional probability $P(A|B)$, given another one $P(B|A)$ and the prior $P(A)$,
$$
\underbrace{P(A|B)}_\text{posterior}=\frac{P(B|A)\,\overbrace{P(A)}^\text{prior}}{P(B)}
$$
So in the equation we have two random variables $A$ and $B$ and their conditional and marginal probabilities, that's all. Prior $P(A)$ is the probability of $A$ "before" learning about $B$, while posterior $P(A|B)$ is the probability of $A$ "after" learning about $B$, where the "before" and "after" refer to your procedure of calculating the probabilities, not any chronological order. The naming convention is that the left hand side is the posterior, while the prior appears in the right hand side part. Using Bayes theorem you can easily switch the sides back and forth (that's the point of the theorem). The usual use case is when you know only $P(B|A)$ and $P(A)$, but you don't know $P(A|B)$ and want to learn about it. Here you can find nice example of such usage of Bayes theorem.
The specific case is Bayesian inference, where we use Bayes theorem to learn about the distribution of the parameter of interest $\theta$ given the data $X$, i.e. obtain the posterior distribution $f(\theta|X)$. This is achieved by looking at the likelihood function (that looks at the "evidence" you gathered) and the prior (the distribution of $\theta$ that is assumed before looking at the data).
$$
\underbrace{f(\theta|X)}_\text{posterior}=\frac{\overbrace{f(X|\theta)}^\text{likelihood}\,\overbrace{f(\theta)}^\text{prior}}{\underbrace{f(X)}_\text{normalizing constant}}
$$
The most basic example of such usage of Bayes theorem is the beta-binomial model, but Bayesian inference is not only about probabilities of coin tosses, for example you can use it to do regression analysis and many other, even much more complicated, models.
To comment on your last question:
Doesn't "posterior" have something to do with the chronology of events
(their order of happening in time)?
Not at all. You can ask a valid probabilistic question is reverse time order, e.g. "What is the probability that it was raining in the morning given that the ground is wet?". | Posterior vs conditional probability
TLDR; Posterior probability is just the conditional probability that is outputted by the Bayes theorem. There is nothing special about it, it does not differ anyhow from any other conditional probabil |
34,121 | Name of "reshuffle trick" (randomly permute the dataset to estimate the bias of an estimator) | To answer the question in the title, AFAIK this is called a permutation test. If this is indeed what you are looking for though, it does not work as described in the question.
To be (somewhat) concise: the permutation test indeed works by shuffling one of the 'columns' and performing the test or calculation of interest. However, the trick is to do this a lot of times, shuffling the data each time. In small datasets it might even be possible to perform all possible permutations. In large datasets you usually perform an amount of permutation your computer can handle, but which is large enough to obtain a distribution of the statistic of interest.
Finally, you use this distribution to check whether, for example, the mean difference between two groups is >0 in 95% of the distribution. Simply put, this latter step of checking which part of the distribution is above/below a certain critical value is the 'p-value' for your hypothesis test.
If this is wildly different from the p-value in the original sample, I wouldn't say there's something wrong with the test/statistic of interest, but rather your sample containing certain datapoints which specifically influence the test result. This might be bias (selection bias due to including some weird cases; measurement error in specific cases, etc.), or it might be incorrect use of the test (e.g. violated assumptions).
See https://en.wikipedia.org/wiki/Resampling_(statistics) for further details
Moreover, see @amoeba 's answer to this question If you want to know more about how to combine permutation tests with variable selection. | Name of "reshuffle trick" (randomly permute the dataset to estimate the bias of an estimator) | To answer the question in the title, AFAIK this is called a permutation test. If this is indeed what you are looking for though, it does not work as described in the question.
To be (somewhat) concis | Name of "reshuffle trick" (randomly permute the dataset to estimate the bias of an estimator)
To answer the question in the title, AFAIK this is called a permutation test. If this is indeed what you are looking for though, it does not work as described in the question.
To be (somewhat) concise: the permutation test indeed works by shuffling one of the 'columns' and performing the test or calculation of interest. However, the trick is to do this a lot of times, shuffling the data each time. In small datasets it might even be possible to perform all possible permutations. In large datasets you usually perform an amount of permutation your computer can handle, but which is large enough to obtain a distribution of the statistic of interest.
Finally, you use this distribution to check whether, for example, the mean difference between two groups is >0 in 95% of the distribution. Simply put, this latter step of checking which part of the distribution is above/below a certain critical value is the 'p-value' for your hypothesis test.
If this is wildly different from the p-value in the original sample, I wouldn't say there's something wrong with the test/statistic of interest, but rather your sample containing certain datapoints which specifically influence the test result. This might be bias (selection bias due to including some weird cases; measurement error in specific cases, etc.), or it might be incorrect use of the test (e.g. violated assumptions).
See https://en.wikipedia.org/wiki/Resampling_(statistics) for further details
Moreover, see @amoeba 's answer to this question If you want to know more about how to combine permutation tests with variable selection. | Name of "reshuffle trick" (randomly permute the dataset to estimate the bias of an estimator)
To answer the question in the title, AFAIK this is called a permutation test. If this is indeed what you are looking for though, it does not work as described in the question.
To be (somewhat) concis |
34,122 | Name of "reshuffle trick" (randomly permute the dataset to estimate the bias of an estimator) | I finally found the answer in Frank Harrell's book "Regression Modeling Strategies" [1] in Section 5.2.4 (Improvements on Data-Splitting: Resampling.).
"The randomization method" is presented as an interesting method to estimate optimism through random permutations of the response, especially in combination with variable selection (as in the example in the OP).
He refers, among others, to [2] for related ideas.
The method is very simple: Let's say your complicated modelling strategy involves forward-/backward (and sideway) selection and your data set is too small to have a clean train/validation/test split. Furthermore, you might not fully trust cross-validation as it always mean to discard a certain proportion of the data within fold. How can you judge if your R-squared of 0.7 is valid or if it mostly a result of overfitting? The randomization method works as follows (here we talk about R-squared but it can be any performance measure of interest). If your strategy is unbiased, then you would expect the R-squared to be close to 0 if repeated on a data set with randomly permuted response variable.
Let's say you get an average R-squared of 0.6 instead of 0 after 20 permutations. So you know that the original R-squared of 0.7 is probably not much more than the result of overfitting. A more honest estimate of the "true" R-squared would be 0.7-0.6 = 0.1 (small). So you have shown how badly your strategy overfits.
Advantages of the method
Very simple
You always use the full data set
Disadvantages include
The estimate of optimism does not seem to be very accurate
The method is not well known in contrast to cross-validation or bootstrap validation.
[1] Frank Harrell, "Regression Modeling Strategies", 2001. Springer.
[2] R. Tibshirani and K. Knight. The covariance inflation criterion for adaptive model selection. JRSS B, 61:529-546, 1999. | Name of "reshuffle trick" (randomly permute the dataset to estimate the bias of an estimator) | I finally found the answer in Frank Harrell's book "Regression Modeling Strategies" [1] in Section 5.2.4 (Improvements on Data-Splitting: Resampling.).
"The randomization method" is presented as an in | Name of "reshuffle trick" (randomly permute the dataset to estimate the bias of an estimator)
I finally found the answer in Frank Harrell's book "Regression Modeling Strategies" [1] in Section 5.2.4 (Improvements on Data-Splitting: Resampling.).
"The randomization method" is presented as an interesting method to estimate optimism through random permutations of the response, especially in combination with variable selection (as in the example in the OP).
He refers, among others, to [2] for related ideas.
The method is very simple: Let's say your complicated modelling strategy involves forward-/backward (and sideway) selection and your data set is too small to have a clean train/validation/test split. Furthermore, you might not fully trust cross-validation as it always mean to discard a certain proportion of the data within fold. How can you judge if your R-squared of 0.7 is valid or if it mostly a result of overfitting? The randomization method works as follows (here we talk about R-squared but it can be any performance measure of interest). If your strategy is unbiased, then you would expect the R-squared to be close to 0 if repeated on a data set with randomly permuted response variable.
Let's say you get an average R-squared of 0.6 instead of 0 after 20 permutations. So you know that the original R-squared of 0.7 is probably not much more than the result of overfitting. A more honest estimate of the "true" R-squared would be 0.7-0.6 = 0.1 (small). So you have shown how badly your strategy overfits.
Advantages of the method
Very simple
You always use the full data set
Disadvantages include
The estimate of optimism does not seem to be very accurate
The method is not well known in contrast to cross-validation or bootstrap validation.
[1] Frank Harrell, "Regression Modeling Strategies", 2001. Springer.
[2] R. Tibshirani and K. Knight. The covariance inflation criterion for adaptive model selection. JRSS B, 61:529-546, 1999. | Name of "reshuffle trick" (randomly permute the dataset to estimate the bias of an estimator)
I finally found the answer in Frank Harrell's book "Regression Modeling Strategies" [1] in Section 5.2.4 (Improvements on Data-Splitting: Resampling.).
"The randomization method" is presented as an in |
34,123 | Laymen Statistics Talk | There are several statistical issues that are relevant to this short dialog.
The fact that John spilled his glass of wine on the table at that exact moment is peculiar. Never have I seen a man so masterful of his glass.
One way to interpret this statement is: "I've spent a lot of time watching John using a glass and he's never spilled it, even though other people who I've spent the same amount of time watching have made several spills. So the spill is surprising." This makes sense: John's rate seems to be below average, so it's more surprising when the event happens in his case than in a typical person's case.
Another way to interpret it, particularly given the phrasing "at that exact moment is peculiar", is "It's surprising that he spilled his glass at this moment rather than an earlier or later one." This doesn't make a lot of sense, without anything special to distinguish this moment. If you randomly choose an integer from 1 to 1,000,000, and you get 280,782, then it's not peculiar you got this number, even though the chance was as small as 1 in 1,000,000. If you had earlier announced that you would get this specific number, that would make it peculiar.
Well, then, statistically, it is time that he had an accident.
This sounds like the gambler's fallacy: the belief that in a sequence of independent events, seeing one outcome repeatedly makes a different outcome more likely. If you flip a fair coin 100 times and get heads every time, your chance of getting heads on the 101st flip is still as high as $\tfrac{1}{2}$, even though the probability of getting 101 heads in a row is as low as $10^{-30}$.
Layman A: We are not talking about some random case. Historically, not once has he spilled anything. So statistically, it is extremely odd.
Layman B: Something must be wrong with your reasoning. It suggests that the first time of anything for anybody is extremely odd.
Here, A is invoking the fact that he's observed John a lot in the past. B seems to be ignoring these previous observations. If you see a man who you met today laugh, that's not odd. But if you've been friends with a man for 10 years and not once has he laughed and then, for the first time, he laughs, that's extremely odd. | Laymen Statistics Talk | There are several statistical issues that are relevant to this short dialog.
The fact that John spilled his glass of wine on the table at that exact moment is peculiar. Never have I seen a man so mas | Laymen Statistics Talk
There are several statistical issues that are relevant to this short dialog.
The fact that John spilled his glass of wine on the table at that exact moment is peculiar. Never have I seen a man so masterful of his glass.
One way to interpret this statement is: "I've spent a lot of time watching John using a glass and he's never spilled it, even though other people who I've spent the same amount of time watching have made several spills. So the spill is surprising." This makes sense: John's rate seems to be below average, so it's more surprising when the event happens in his case than in a typical person's case.
Another way to interpret it, particularly given the phrasing "at that exact moment is peculiar", is "It's surprising that he spilled his glass at this moment rather than an earlier or later one." This doesn't make a lot of sense, without anything special to distinguish this moment. If you randomly choose an integer from 1 to 1,000,000, and you get 280,782, then it's not peculiar you got this number, even though the chance was as small as 1 in 1,000,000. If you had earlier announced that you would get this specific number, that would make it peculiar.
Well, then, statistically, it is time that he had an accident.
This sounds like the gambler's fallacy: the belief that in a sequence of independent events, seeing one outcome repeatedly makes a different outcome more likely. If you flip a fair coin 100 times and get heads every time, your chance of getting heads on the 101st flip is still as high as $\tfrac{1}{2}$, even though the probability of getting 101 heads in a row is as low as $10^{-30}$.
Layman A: We are not talking about some random case. Historically, not once has he spilled anything. So statistically, it is extremely odd.
Layman B: Something must be wrong with your reasoning. It suggests that the first time of anything for anybody is extremely odd.
Here, A is invoking the fact that he's observed John a lot in the past. B seems to be ignoring these previous observations. If you see a man who you met today laugh, that's not odd. But if you've been friends with a man for 10 years and not once has he laughed and then, for the first time, he laughs, that's extremely odd. | Laymen Statistics Talk
There are several statistical issues that are relevant to this short dialog.
The fact that John spilled his glass of wine on the table at that exact moment is peculiar. Never have I seen a man so mas |
34,124 | Laymen Statistics Talk | May I offer yet another interpretation layer of this sentence:
The fact that John spilled his glass of wine on the table at that exact moment is peculiar.
Layman A places some special quality/value on this "exact moment". Even though we do not have specifics, we could assume that something interesting happened, apart from the spill. Maybe it was spilled on someone, maybe someone was announcing something and the spill caused a distraction, or even a small fire started and the spill extinguished the fire :)
So it seems especially strange that the spill happened at this moment. It's "peculiar" as Layman A says. Implied in this is the notion that the spill may not have happened by chance. Maybe it was a deliberate spill, masquerading as an accident.
From a statistics point of view this is hypothesis testing. Given our observations and assumptions about prior probabilities, which of the two (or more) hypotheses is more likely? Layman A seems to be applying a "common sense" hypothesis testing, and tending to believe the not-an-accident hypothesis. | Laymen Statistics Talk | May I offer yet another interpretation layer of this sentence:
The fact that John spilled his glass of wine on the table at that exact moment is peculiar.
Layman A places some special quality/value | Laymen Statistics Talk
May I offer yet another interpretation layer of this sentence:
The fact that John spilled his glass of wine on the table at that exact moment is peculiar.
Layman A places some special quality/value on this "exact moment". Even though we do not have specifics, we could assume that something interesting happened, apart from the spill. Maybe it was spilled on someone, maybe someone was announcing something and the spill caused a distraction, or even a small fire started and the spill extinguished the fire :)
So it seems especially strange that the spill happened at this moment. It's "peculiar" as Layman A says. Implied in this is the notion that the spill may not have happened by chance. Maybe it was a deliberate spill, masquerading as an accident.
From a statistics point of view this is hypothesis testing. Given our observations and assumptions about prior probabilities, which of the two (or more) hypotheses is more likely? Layman A seems to be applying a "common sense" hypothesis testing, and tending to believe the not-an-accident hypothesis. | Laymen Statistics Talk
May I offer yet another interpretation layer of this sentence:
The fact that John spilled his glass of wine on the table at that exact moment is peculiar.
Layman A places some special quality/value |
34,125 | What does it mean intuitively to know a pdf "up to a constant"? | As explained in the comments, to know a pdf up to a normalizing constant means that for a random variable $X$ with pdf $f(x)$, we know that
$$f(x) \propto g(x) \Rightarrow f(x) = c g(x), $$
where $c = \int g(x) dx$ is unknown. Consider the standard normal distribution which has pdf
$$f(x) = \dfrac{1}{\sqrt{2\pi}} e^{\frac{-x^2}{2}}\,. $$
Now suppose we are in a situation, where we can only identify that
$$f(x) \propto e^{\frac{-x^2}{2}} \,,$$
and thus $g(x) = e^{\frac{-x^2}{2}}$ and the normalizing constant $c = \frac{1}{\sqrt{2\pi}}$ is not known. If we visualize this and plot $f(x)$ and $g(x)$, we get the following graph
The dotted line is the true pdf unknown to us, and the solid line is the known $g(x)$. The shape of the density remains the same, but the function is stretched or squeezed in the vertical direction depending on the unknown normalizing constant.
In Bayesian models, often we know the posterior only upto a normalizing constant, but we want to learn about different characteristics of the posterior distribution: like mean, mode, or quantile of the distribution. Well, clearly the mode of $g(x)$ corresponds to the mode of $f(x)$, so the normalizing constant is not needed. However, to calculate the mean for the distribution
$$E(X) = \int xf(x) dx = \int cx g(x) = c \int xg(x)dx\,. $$
Even if you can solve $\int xg(x)dx$, $c$ is unknown, and you can't find the mean of $X$. Here is where MCMC can be used since it is able to draw samples from the distribution of $X$, without requiring the normalizing constant $c$. | What does it mean intuitively to know a pdf "up to a constant"? | As explained in the comments, to know a pdf up to a normalizing constant means that for a random variable $X$ with pdf $f(x)$, we know that
$$f(x) \propto g(x) \Rightarrow f(x) = c g(x), $$
where $c = | What does it mean intuitively to know a pdf "up to a constant"?
As explained in the comments, to know a pdf up to a normalizing constant means that for a random variable $X$ with pdf $f(x)$, we know that
$$f(x) \propto g(x) \Rightarrow f(x) = c g(x), $$
where $c = \int g(x) dx$ is unknown. Consider the standard normal distribution which has pdf
$$f(x) = \dfrac{1}{\sqrt{2\pi}} e^{\frac{-x^2}{2}}\,. $$
Now suppose we are in a situation, where we can only identify that
$$f(x) \propto e^{\frac{-x^2}{2}} \,,$$
and thus $g(x) = e^{\frac{-x^2}{2}}$ and the normalizing constant $c = \frac{1}{\sqrt{2\pi}}$ is not known. If we visualize this and plot $f(x)$ and $g(x)$, we get the following graph
The dotted line is the true pdf unknown to us, and the solid line is the known $g(x)$. The shape of the density remains the same, but the function is stretched or squeezed in the vertical direction depending on the unknown normalizing constant.
In Bayesian models, often we know the posterior only upto a normalizing constant, but we want to learn about different characteristics of the posterior distribution: like mean, mode, or quantile of the distribution. Well, clearly the mode of $g(x)$ corresponds to the mode of $f(x)$, so the normalizing constant is not needed. However, to calculate the mean for the distribution
$$E(X) = \int xf(x) dx = \int cx g(x) = c \int xg(x)dx\,. $$
Even if you can solve $\int xg(x)dx$, $c$ is unknown, and you can't find the mean of $X$. Here is where MCMC can be used since it is able to draw samples from the distribution of $X$, without requiring the normalizing constant $c$. | What does it mean intuitively to know a pdf "up to a constant"?
As explained in the comments, to know a pdf up to a normalizing constant means that for a random variable $X$ with pdf $f(x)$, we know that
$$f(x) \propto g(x) \Rightarrow f(x) = c g(x), $$
where $c = |
34,126 | What does it mean intuitively to know a pdf "up to a constant"? | Adding to other comments and nice answer by Greenparker, normalizing constant is something that is needed so that probability density function integrates to unity and is a proper distribution.
We do not always need the probability densities to be normalized, e.g. when we are using maximum likelihood estimation, or Bayesian MCMC estimation we only need to know the relative relations between the values. For example, if you want to estimate parameter $p$ of binomial distribution by maximizing it's likelihood, then the only the only thing you need is the binomial density known up to a normalizing constant, i.e. $ p^k(1-p)^{n-k} $. The constant is $ \binom n k$ and since it does not change anything about finding maximum of likelihood function $L(p)$, it is not needed.
You can ask: So what? If we can use it or not, then why not use it always? The problem is that while for the commonly used distributions we know the normalizing constants, then they do not have to be obvious for other distributions. Imagine for example a Bayesian model $f(\theta|x) = c^{-1} \,f(x|\theta) \,f(\theta)$, where $c$ is the normalizing constant and $\theta$ is the parameter of interest. It is easy to multiply the prior by likelihood, but to obtain the normalizing constant you need to integrate $c = \int f(x|\theta) \,f(\theta) \,d\theta$ and this is more complicated (even for discrete distribution, with countably finite support, there are cases where you need to sum huge number of elements and it is computationally intensive problem). If you are dealing with complicated, multivariate distributions then solving the integral may be a problem by itself. Hopefully, we have computational tools like MCMC to deal with Bayesian models in form $f(\theta|x) \propto f(x|\theta) \,f(\theta)$, that enable us to draw samples from such distribution and conduct the estimation without knowing the constant.
So there are cases where the distribution is known up to a constant while the constant itself may not be obvious. Moreover, we are able to do many mathematical operations with the distributions without knowing the constant. | What does it mean intuitively to know a pdf "up to a constant"? | Adding to other comments and nice answer by Greenparker, normalizing constant is something that is needed so that probability density function integrates to unity and is a proper distribution.
We do n | What does it mean intuitively to know a pdf "up to a constant"?
Adding to other comments and nice answer by Greenparker, normalizing constant is something that is needed so that probability density function integrates to unity and is a proper distribution.
We do not always need the probability densities to be normalized, e.g. when we are using maximum likelihood estimation, or Bayesian MCMC estimation we only need to know the relative relations between the values. For example, if you want to estimate parameter $p$ of binomial distribution by maximizing it's likelihood, then the only the only thing you need is the binomial density known up to a normalizing constant, i.e. $ p^k(1-p)^{n-k} $. The constant is $ \binom n k$ and since it does not change anything about finding maximum of likelihood function $L(p)$, it is not needed.
You can ask: So what? If we can use it or not, then why not use it always? The problem is that while for the commonly used distributions we know the normalizing constants, then they do not have to be obvious for other distributions. Imagine for example a Bayesian model $f(\theta|x) = c^{-1} \,f(x|\theta) \,f(\theta)$, where $c$ is the normalizing constant and $\theta$ is the parameter of interest. It is easy to multiply the prior by likelihood, but to obtain the normalizing constant you need to integrate $c = \int f(x|\theta) \,f(\theta) \,d\theta$ and this is more complicated (even for discrete distribution, with countably finite support, there are cases where you need to sum huge number of elements and it is computationally intensive problem). If you are dealing with complicated, multivariate distributions then solving the integral may be a problem by itself. Hopefully, we have computational tools like MCMC to deal with Bayesian models in form $f(\theta|x) \propto f(x|\theta) \,f(\theta)$, that enable us to draw samples from such distribution and conduct the estimation without knowing the constant.
So there are cases where the distribution is known up to a constant while the constant itself may not be obvious. Moreover, we are able to do many mathematical operations with the distributions without knowing the constant. | What does it mean intuitively to know a pdf "up to a constant"?
Adding to other comments and nice answer by Greenparker, normalizing constant is something that is needed so that probability density function integrates to unity and is a proper distribution.
We do n |
34,127 | What's the difference between "mean independent" and independent? | The condition $E(u|x)=E(u)$ is not the same thing as independence in general.
It's implied by independence (when those expectations exist) but it can be true when you don't have independence.
Consider, for example, the case where some other aspect of the distribution changes with $x$ without changing the mean -- then you'd have dependence but mean-independence. (One example would be where the conditional variance was not constant.)
[If you're asking why did the author invoke mean-independence rather than independence, it's hard to say much without context; presumably only the weaker condition was necessary for whatever was being done.] | What's the difference between "mean independent" and independent? | The condition $E(u|x)=E(u)$ is not the same thing as independence in general.
It's implied by independence (when those expectations exist) but it can be true when you don't have independence.
Consider | What's the difference between "mean independent" and independent?
The condition $E(u|x)=E(u)$ is not the same thing as independence in general.
It's implied by independence (when those expectations exist) but it can be true when you don't have independence.
Consider, for example, the case where some other aspect of the distribution changes with $x$ without changing the mean -- then you'd have dependence but mean-independence. (One example would be where the conditional variance was not constant.)
[If you're asking why did the author invoke mean-independence rather than independence, it's hard to say much without context; presumably only the weaker condition was necessary for whatever was being done.] | What's the difference between "mean independent" and independent?
The condition $E(u|x)=E(u)$ is not the same thing as independence in general.
It's implied by independence (when those expectations exist) but it can be true when you don't have independence.
Consider |
34,128 | What's the difference between "mean independent" and independent? | As the direction of the arrows in the image below indicates, independence implies mean independence, which in turn implies zero correlation. The converse statements are not true: zero correlation does not imply mean independence, which in turn doesn't imply independence.
Intuitively, independence of u and x would mean that for each value of x, the conditional density function of u given x is identical. Mean independence is less restrictive as it is a one number summary of the values of u, for each level of x. To be more exact, mean independence between u and x would mean that for each value of x, a one number summary of the values of u, the average weighted by the conditional density function of u given x, is constant. You can now see intuitively that while the conditional density function of u given x may be different across different values of x, a one number summary of the conditional density function of u given x can be the same across all levels of x. This would be the case when u and x are not independent but are mean independent.
You ask "Why can't we simply say that u is independent of x? Is it possible to have u completely independent of x?" The answers to your questions are 1) Because mean independence suffices for our purposes, and 2) Yes, but we wouldn't want to do that. Let me expand on each of these.
The context of the assumption you reference, E(u│x)=E(u), is that of Assumptions for Simple Regression, and the u stands for the error term, or equivalently the factors that affect our dependent variable y, that are not captured by x. When combined with the assumption E(u)=0, a trivial one as long as an intercept is included in the regression, we obtain that E(u│x)=0. We care about this result because it implies that the population regression line is given by the conditional mean of y:
E(y|x)=β0 + β1*x.
If we were conducting a randomized controlled experiment, we would make sure to assign the values of x randomly, which would make x and u independent, which would then imply the weaker condition of mean independence, which would in turn imply zero correlation. In a sense, in a randomized controlled experiment, we get the independence of x and u for free. In contrast, in observational data we must assume how the unobserved factors, u, are related in the population to the factor we control for, x.
We could assume that x and u are independent, however that is too strong of an assumption. That would be equivalent to assuming that for each level of x, the conditional probability density function of u given x would be exactly the same and equal to the marginal probability density function of u. By assuming that the conditional probability density function of u given x would be exactly the same for each level of x, we would be assuming that all the moments of the distribution of u are exactly the same for each level of x. We would therefore be assuming that the first and second moments of the distribution of u would also be identical for each level of x. The latter of these is precisely the assumption of homoscedasticity, which says that the variance of u does not depend on the value of x:
Therefore, if we were to assume that x and u were independent, we'd be assuming homoscedasticity, and a lot more (think of the moments higher than 2). However, homoscedasticity, for one, is not as key of an assumption, as it has no bearing on the unbiasedness of the regression coefficients, so we'd want it as a separate assumption that we may or may not want to make. We wouldn't want this "nice to have" assumption mixed in with the most vital assumption of OLS, E(u│x)=E(u).
At the other extreme, we could assume that x and u are uncorrelated. In fact, that suffices for deriving the OLS estimates. However, that would not be sufficient to conclude that the population regression is given by the conditional mean E(y|x)=β0 + β1*x.
Good lecture notes that I used for inspiration: http://statweb.stanford.edu/~adembo/math-136/Orthogonality_note.pdf | What's the difference between "mean independent" and independent? | As the direction of the arrows in the image below indicates, independence implies mean independence, which in turn implies zero correlation. The converse statements are not true: zero correlation does | What's the difference between "mean independent" and independent?
As the direction of the arrows in the image below indicates, independence implies mean independence, which in turn implies zero correlation. The converse statements are not true: zero correlation does not imply mean independence, which in turn doesn't imply independence.
Intuitively, independence of u and x would mean that for each value of x, the conditional density function of u given x is identical. Mean independence is less restrictive as it is a one number summary of the values of u, for each level of x. To be more exact, mean independence between u and x would mean that for each value of x, a one number summary of the values of u, the average weighted by the conditional density function of u given x, is constant. You can now see intuitively that while the conditional density function of u given x may be different across different values of x, a one number summary of the conditional density function of u given x can be the same across all levels of x. This would be the case when u and x are not independent but are mean independent.
You ask "Why can't we simply say that u is independent of x? Is it possible to have u completely independent of x?" The answers to your questions are 1) Because mean independence suffices for our purposes, and 2) Yes, but we wouldn't want to do that. Let me expand on each of these.
The context of the assumption you reference, E(u│x)=E(u), is that of Assumptions for Simple Regression, and the u stands for the error term, or equivalently the factors that affect our dependent variable y, that are not captured by x. When combined with the assumption E(u)=0, a trivial one as long as an intercept is included in the regression, we obtain that E(u│x)=0. We care about this result because it implies that the population regression line is given by the conditional mean of y:
E(y|x)=β0 + β1*x.
If we were conducting a randomized controlled experiment, we would make sure to assign the values of x randomly, which would make x and u independent, which would then imply the weaker condition of mean independence, which would in turn imply zero correlation. In a sense, in a randomized controlled experiment, we get the independence of x and u for free. In contrast, in observational data we must assume how the unobserved factors, u, are related in the population to the factor we control for, x.
We could assume that x and u are independent, however that is too strong of an assumption. That would be equivalent to assuming that for each level of x, the conditional probability density function of u given x would be exactly the same and equal to the marginal probability density function of u. By assuming that the conditional probability density function of u given x would be exactly the same for each level of x, we would be assuming that all the moments of the distribution of u are exactly the same for each level of x. We would therefore be assuming that the first and second moments of the distribution of u would also be identical for each level of x. The latter of these is precisely the assumption of homoscedasticity, which says that the variance of u does not depend on the value of x:
Therefore, if we were to assume that x and u were independent, we'd be assuming homoscedasticity, and a lot more (think of the moments higher than 2). However, homoscedasticity, for one, is not as key of an assumption, as it has no bearing on the unbiasedness of the regression coefficients, so we'd want it as a separate assumption that we may or may not want to make. We wouldn't want this "nice to have" assumption mixed in with the most vital assumption of OLS, E(u│x)=E(u).
At the other extreme, we could assume that x and u are uncorrelated. In fact, that suffices for deriving the OLS estimates. However, that would not be sufficient to conclude that the population regression is given by the conditional mean E(y|x)=β0 + β1*x.
Good lecture notes that I used for inspiration: http://statweb.stanford.edu/~adembo/math-136/Orthogonality_note.pdf | What's the difference between "mean independent" and independent?
As the direction of the arrows in the image below indicates, independence implies mean independence, which in turn implies zero correlation. The converse statements are not true: zero correlation does |
34,129 | In Ridge regression and LASSO, why smaller $\beta$ would be better? | TL;DR - Same principle applies to both LASSO and Ridge
Less features make the model simpler and therefore less likely to be over-fitting
This is the same intuition with ridge regression - we prevent the model from over-fitting the data, but instead of targeting small, potentially spurious variables (which get reduced to zero in LASSO), we instead target the biggest coefficients which might be overstating the case for their respective variables.
The L2 penalty generally prevents the model from placing "too much" importance on any one variable, because large coefficients are penalized more than small ones.
This might not seem like it "simplifies" the model, but it does a similar task of preventing the model from over-fitting to the data at hand.
An example to build intuition
Take a concrete example - you might be trying to predict hospital readmissions based on patient characteristics.
In this case, you might have a relatively rare variable (such as an uncommon disease) that happens to be very highly correlated in your training set with readmission. In a dataset of 10,000 patients, you might only see this disease 10 times, with 9 readmissions (an extreme example to be sure)
As a result, the coefficient might be massive relative to the coefficient of other variables. By minimizing both MSE and the L2 penalty, this would be a good candidate for ridge regression to "shrink" towards a smaller value, since it is rare (so doesn't impact MSE as much), and an extreme coefficient value. | In Ridge regression and LASSO, why smaller $\beta$ would be better? | TL;DR - Same principle applies to both LASSO and Ridge
Less features make the model simpler and therefore less likely to be over-fitting
This is the same intuition with ridge regression - we prevent | In Ridge regression and LASSO, why smaller $\beta$ would be better?
TL;DR - Same principle applies to both LASSO and Ridge
Less features make the model simpler and therefore less likely to be over-fitting
This is the same intuition with ridge regression - we prevent the model from over-fitting the data, but instead of targeting small, potentially spurious variables (which get reduced to zero in LASSO), we instead target the biggest coefficients which might be overstating the case for their respective variables.
The L2 penalty generally prevents the model from placing "too much" importance on any one variable, because large coefficients are penalized more than small ones.
This might not seem like it "simplifies" the model, but it does a similar task of preventing the model from over-fitting to the data at hand.
An example to build intuition
Take a concrete example - you might be trying to predict hospital readmissions based on patient characteristics.
In this case, you might have a relatively rare variable (such as an uncommon disease) that happens to be very highly correlated in your training set with readmission. In a dataset of 10,000 patients, you might only see this disease 10 times, with 9 readmissions (an extreme example to be sure)
As a result, the coefficient might be massive relative to the coefficient of other variables. By minimizing both MSE and the L2 penalty, this would be a good candidate for ridge regression to "shrink" towards a smaller value, since it is rare (so doesn't impact MSE as much), and an extreme coefficient value. | In Ridge regression and LASSO, why smaller $\beta$ would be better?
TL;DR - Same principle applies to both LASSO and Ridge
Less features make the model simpler and therefore less likely to be over-fitting
This is the same intuition with ridge regression - we prevent |
34,130 | In Ridge regression and LASSO, why smaller $\beta$ would be better? | There's no guarantee that having smaller weights is actually better. Lasso and ridge regression work by imposing prior knowledge/assumptions/constraints on the solution. This approach will work well if the prior/assumptions/constraints are well suited to the actual distribution that generated the data, and may not work well otherwise. Regarding simplicity/complexity, it's not the individual models that are simpler or more complex. Rather, it's the family of models under consideration.
From a geometric perspective, lasso and ridge regression impose constraints on the weights. For example, the common penalty/Lagrangian form of ridge regression:
$$\min_\beta \|y - X\beta\|_2^2 + \lambda \|\beta\|_2^2$$
can be re-written in the equivalent constraint form:
$$\min_\beta \|y - X\beta\|_2^2 \quad \text{s.t. } \|\beta\|_2^2 \le c$$
This makes it clear that ridge regression constrains the weights to lie within a hypersphere whose radius is governed by the regularization parameter. Similarly, lasso constrains the weights to lie within a polytope whose size is governed by the regularization parameter. These constraints mean that most of the original parameter space is off-limits, and we search for the optimal weights within a much smaller subspace. This smaller subspace can be considered less 'complex' than the full space.
From a Bayesian perspective, one can think about the posterior distribution over all possible choices of weights. Both lasso and ridge regression are equivalent to MAP estimation after placing a prior on the weights (lasso uses a Laplacian prior and ridge regression uses a Gaussian prior). A narrower posterior corresponds to greater restriction and less complexity, because high posterior density is given to a smaller set of parameters. For example, multiplying the likelihood function by a narrow Gaussian prior (which corresponds to a large ridge penalty) produces a narrower posterior.
One of the primary reasons to impose constraints/priors is that choosing the optimal model from a more restricted family is less likely to overfit than choosing it from a less restricted family. This is because the less restricted family affords 'more' ways to fit the data, and it's increasingly likely that one of them will be able to fit random fluctuations in the training set. For a more formal treatment, see the bias-variance tradeoff. This doesn't necessarily mean that choosing a model from a more restricted family will work well. Getting good performance requires that the restricted family actually contains good models. This means we have to choose a prior/constraint that's well-matched to the specific problem at hand. | In Ridge regression and LASSO, why smaller $\beta$ would be better? | There's no guarantee that having smaller weights is actually better. Lasso and ridge regression work by imposing prior knowledge/assumptions/constraints on the solution. This approach will work well i | In Ridge regression and LASSO, why smaller $\beta$ would be better?
There's no guarantee that having smaller weights is actually better. Lasso and ridge regression work by imposing prior knowledge/assumptions/constraints on the solution. This approach will work well if the prior/assumptions/constraints are well suited to the actual distribution that generated the data, and may not work well otherwise. Regarding simplicity/complexity, it's not the individual models that are simpler or more complex. Rather, it's the family of models under consideration.
From a geometric perspective, lasso and ridge regression impose constraints on the weights. For example, the common penalty/Lagrangian form of ridge regression:
$$\min_\beta \|y - X\beta\|_2^2 + \lambda \|\beta\|_2^2$$
can be re-written in the equivalent constraint form:
$$\min_\beta \|y - X\beta\|_2^2 \quad \text{s.t. } \|\beta\|_2^2 \le c$$
This makes it clear that ridge regression constrains the weights to lie within a hypersphere whose radius is governed by the regularization parameter. Similarly, lasso constrains the weights to lie within a polytope whose size is governed by the regularization parameter. These constraints mean that most of the original parameter space is off-limits, and we search for the optimal weights within a much smaller subspace. This smaller subspace can be considered less 'complex' than the full space.
From a Bayesian perspective, one can think about the posterior distribution over all possible choices of weights. Both lasso and ridge regression are equivalent to MAP estimation after placing a prior on the weights (lasso uses a Laplacian prior and ridge regression uses a Gaussian prior). A narrower posterior corresponds to greater restriction and less complexity, because high posterior density is given to a smaller set of parameters. For example, multiplying the likelihood function by a narrow Gaussian prior (which corresponds to a large ridge penalty) produces a narrower posterior.
One of the primary reasons to impose constraints/priors is that choosing the optimal model from a more restricted family is less likely to overfit than choosing it from a less restricted family. This is because the less restricted family affords 'more' ways to fit the data, and it's increasingly likely that one of them will be able to fit random fluctuations in the training set. For a more formal treatment, see the bias-variance tradeoff. This doesn't necessarily mean that choosing a model from a more restricted family will work well. Getting good performance requires that the restricted family actually contains good models. This means we have to choose a prior/constraint that's well-matched to the specific problem at hand. | In Ridge regression and LASSO, why smaller $\beta$ would be better?
There's no guarantee that having smaller weights is actually better. Lasso and ridge regression work by imposing prior knowledge/assumptions/constraints on the solution. This approach will work well i |
34,131 | In Ridge regression and LASSO, why smaller $\beta$ would be better? | Though the question asked for an intuitive explanation, there is actually a rigorous derivation of the Mean Square Error (MSE) for the ridge regression that shows that there exists values of $\lambda$ achieving a better MSE than the linear regression.
Recall : $MSE(\hat{\beta})=\mathbb{E}[(\hat{\beta}-\beta)(\hat{\beta}-\beta)^T]$
Call $\hat{\beta_\lambda}$ the estimator of $\beta$ for a ridge regression whose shrinkage parameter is $\lambda$ and define : $M(\lambda)=MSE(\hat{\beta_\lambda})$.
Therefore $M(0)$ is the MSE of a linear regression.
Following these course notes one can show that:
$$M(0)-M(\lambda)=\lambda(X^TX+\lambda I)^{-1}(2\sigma²I+\lambda\sigma²(X^TX)^{-1}-\lambda\beta\beta^T) \{(X^TX+\lambda I)^{-1}\}^T$$
The terms $(X^TX+\lambda I)^{-1}$ are positive definite, but, for $\lambda<2\sigma^2(\beta^T\beta)^{-1}$, the term in the middle is positive as well. For these values, we have $M(0)>M(\lambda)$, showing that the ridge regression reduces the Mean Square Error. | In Ridge regression and LASSO, why smaller $\beta$ would be better? | Though the question asked for an intuitive explanation, there is actually a rigorous derivation of the Mean Square Error (MSE) for the ridge regression that shows that there exists values of $\lambda$ | In Ridge regression and LASSO, why smaller $\beta$ would be better?
Though the question asked for an intuitive explanation, there is actually a rigorous derivation of the Mean Square Error (MSE) for the ridge regression that shows that there exists values of $\lambda$ achieving a better MSE than the linear regression.
Recall : $MSE(\hat{\beta})=\mathbb{E}[(\hat{\beta}-\beta)(\hat{\beta}-\beta)^T]$
Call $\hat{\beta_\lambda}$ the estimator of $\beta$ for a ridge regression whose shrinkage parameter is $\lambda$ and define : $M(\lambda)=MSE(\hat{\beta_\lambda})$.
Therefore $M(0)$ is the MSE of a linear regression.
Following these course notes one can show that:
$$M(0)-M(\lambda)=\lambda(X^TX+\lambda I)^{-1}(2\sigma²I+\lambda\sigma²(X^TX)^{-1}-\lambda\beta\beta^T) \{(X^TX+\lambda I)^{-1}\}^T$$
The terms $(X^TX+\lambda I)^{-1}$ are positive definite, but, for $\lambda<2\sigma^2(\beta^T\beta)^{-1}$, the term in the middle is positive as well. For these values, we have $M(0)>M(\lambda)$, showing that the ridge regression reduces the Mean Square Error. | In Ridge regression and LASSO, why smaller $\beta$ would be better?
Though the question asked for an intuitive explanation, there is actually a rigorous derivation of the Mean Square Error (MSE) for the ridge regression that shows that there exists values of $\lambda$ |
34,132 | glmer vs lmer, what is best for a binomial outcome? | 1) In previous versions of the lme4 package, you could run lmer using the binomial family. However, all this did was to actually call glmer, and this functionality has now been removed. So at the time of writing Crawley was correct.
2) Yes, glmer is the correct function to use with a binary outcome.
3) glm can fit a model for binary data without random effects. However, it is incorrect to compare a model fitted with glm to one fitted with glmer using a likelihood-based test because the likelihoods are not comparable. From your description, you have repeated measures within chambers. So, assuming that you have sufficient chambers and these can be thought of as a random sample from a larger population of chambers, then a priori you should retain the random intercepts for Chamber to control for possible non-independence of observations within chambers. You can think of random intercepts as being part of the experimental design.
On the other hand, if the random effect variance is very small and/or the inference or predictions for both the glm and glmer model are the largely the same, then it really doesn't matter which you use anyway. | glmer vs lmer, what is best for a binomial outcome? | 1) In previous versions of the lme4 package, you could run lmer using the binomial family. However, all this did was to actually call glmer, and this functionality has now been removed. So at the time | glmer vs lmer, what is best for a binomial outcome?
1) In previous versions of the lme4 package, you could run lmer using the binomial family. However, all this did was to actually call glmer, and this functionality has now been removed. So at the time of writing Crawley was correct.
2) Yes, glmer is the correct function to use with a binary outcome.
3) glm can fit a model for binary data without random effects. However, it is incorrect to compare a model fitted with glm to one fitted with glmer using a likelihood-based test because the likelihoods are not comparable. From your description, you have repeated measures within chambers. So, assuming that you have sufficient chambers and these can be thought of as a random sample from a larger population of chambers, then a priori you should retain the random intercepts for Chamber to control for possible non-independence of observations within chambers. You can think of random intercepts as being part of the experimental design.
On the other hand, if the random effect variance is very small and/or the inference or predictions for both the glm and glmer model are the largely the same, then it really doesn't matter which you use anyway. | glmer vs lmer, what is best for a binomial outcome?
1) In previous versions of the lme4 package, you could run lmer using the binomial family. However, all this did was to actually call glmer, and this functionality has now been removed. So at the time |
34,133 | glmer vs lmer, what is best for a binomial outcome? | For 2, yes, you should use glmer or glm for binomial outcomes. If you have a little more time to wait for the model to fit---and especially if you are interested in inference for your random effects---I'd suggest using rstanarm::stan_glmer() and rstanarm::stan_glm respectively, which use the same syntax. The huge benefit here is that your uncertainty estimates come from a genuine posterior. Your predictions will also include uncertainty from the parameters. A tip though: make sure you scale your data to be in the single digits.
Be warned that the posterior density of random effects tend to be skewed, so using likelihood-based methods (as in lme4) will tend to give you bad random effect estimates.
3) The loo package allows comparison of your stan_ fits using an approximation to leave-one-out cross validation. I recommend taking a look.
https://cran.r-project.org/web/packages/rstanarm/vignettes/glmer.html | glmer vs lmer, what is best for a binomial outcome? | For 2, yes, you should use glmer or glm for binomial outcomes. If you have a little more time to wait for the model to fit---and especially if you are interested in inference for your random effects-- | glmer vs lmer, what is best for a binomial outcome?
For 2, yes, you should use glmer or glm for binomial outcomes. If you have a little more time to wait for the model to fit---and especially if you are interested in inference for your random effects---I'd suggest using rstanarm::stan_glmer() and rstanarm::stan_glm respectively, which use the same syntax. The huge benefit here is that your uncertainty estimates come from a genuine posterior. Your predictions will also include uncertainty from the parameters. A tip though: make sure you scale your data to be in the single digits.
Be warned that the posterior density of random effects tend to be skewed, so using likelihood-based methods (as in lme4) will tend to give you bad random effect estimates.
3) The loo package allows comparison of your stan_ fits using an approximation to leave-one-out cross validation. I recommend taking a look.
https://cran.r-project.org/web/packages/rstanarm/vignettes/glmer.html | glmer vs lmer, what is best for a binomial outcome?
For 2, yes, you should use glmer or glm for binomial outcomes. If you have a little more time to wait for the model to fit---and especially if you are interested in inference for your random effects-- |
34,134 | Deseasonalizing data with fourier analysis | The term you're looking for is "trend and seasonality decomposition of time series". Google this.
There are many approaches. If you really have only 100 points then Fourier will not work very well. Yule-Walker based approaches may work better. There are also filter based approaches. For instance, Google band pass filters such as bpassm from Atlanta Fed. The idea's that you filter out different frequency components from the series, so that low frequency would be trend, medium frequency the signal, and the high frequency - seasonality etc.
There's a full set of code in this matlab example. It takes you step by step through the process of deseasoning, it works quite well for economic data in my experience | Deseasonalizing data with fourier analysis | The term you're looking for is "trend and seasonality decomposition of time series". Google this.
There are many approaches. If you really have only 100 points then Fourier will not work very well. Yu | Deseasonalizing data with fourier analysis
The term you're looking for is "trend and seasonality decomposition of time series". Google this.
There are many approaches. If you really have only 100 points then Fourier will not work very well. Yule-Walker based approaches may work better. There are also filter based approaches. For instance, Google band pass filters such as bpassm from Atlanta Fed. The idea's that you filter out different frequency components from the series, so that low frequency would be trend, medium frequency the signal, and the high frequency - seasonality etc.
There's a full set of code in this matlab example. It takes you step by step through the process of deseasoning, it works quite well for economic data in my experience | Deseasonalizing data with fourier analysis
The term you're looking for is "trend and seasonality decomposition of time series". Google this.
There are many approaches. If you really have only 100 points then Fourier will not work very well. Yu |
34,135 | Deseasonalizing data with fourier analysis | Classic auto-regressive models can handle cycles! Going way back, Yule (1927) and Walker (1931) modeled the periodicity of sunspots using an equation of the form:
$$y_{t+1} = a + b_1 y_t + b_2 y_{t-1} + \epsilon_{t+1}$$
Sunspot activity tends to operate on 11 year cycles, and though it's not immediately obvious, the inclusion of two auto-regressive terms can create cyclic behavior! Auto-regressive models are now ubiquitous in modern time-series analysis. The U.S. Census Bureau uses an ARIMA model to calculate seasonal adjustment.
More generally, you can fit an ARIMA model which involves:
$p$ order auto-regressive terms (as above)
$q$ order moving-average terms
$d$ differences (to get the data stationary)
If you dive into the math, there's a relation between ARIMA models and representations in the frequency domain with a Fourier transform. You can represent a stationary time-series process using an auto-regressive model, moving average model, or the spectral density.
Practical way forward:
You first need to obtain a stationary time series. For example with gross domestic product or aggregate consumption, people typically take the logarithm and compute the first difference. (Basic idea is that distribution over percent changes in aggregate consumption is invariant across time.) To obtain a stationary time series $\Delta c_t$ from aggregate consumption $C_t$.
$$\Delta c_t = \log C_t - \log C_{t-1}$$
Once you have a stationary time series, it's easy to fit an auto-regressive AR(n) model. You can simply do least squares. For an AR(2) model you can run the regression.
$$ y_{t} = a + b_1 y_{t-!} + b_2 y_{t-2} + \epsilon_t $$
Of course you can get more fancy, but often simple stuff can work surprisingly well. There are well developed packages for time series analysis in R, EViews, Stata, etc... | Deseasonalizing data with fourier analysis | Classic auto-regressive models can handle cycles! Going way back, Yule (1927) and Walker (1931) modeled the periodicity of sunspots using an equation of the form:
$$y_{t+1} = a + b_1 y_t + b_2 y_{t-1} | Deseasonalizing data with fourier analysis
Classic auto-regressive models can handle cycles! Going way back, Yule (1927) and Walker (1931) modeled the periodicity of sunspots using an equation of the form:
$$y_{t+1} = a + b_1 y_t + b_2 y_{t-1} + \epsilon_{t+1}$$
Sunspot activity tends to operate on 11 year cycles, and though it's not immediately obvious, the inclusion of two auto-regressive terms can create cyclic behavior! Auto-regressive models are now ubiquitous in modern time-series analysis. The U.S. Census Bureau uses an ARIMA model to calculate seasonal adjustment.
More generally, you can fit an ARIMA model which involves:
$p$ order auto-regressive terms (as above)
$q$ order moving-average terms
$d$ differences (to get the data stationary)
If you dive into the math, there's a relation between ARIMA models and representations in the frequency domain with a Fourier transform. You can represent a stationary time-series process using an auto-regressive model, moving average model, or the spectral density.
Practical way forward:
You first need to obtain a stationary time series. For example with gross domestic product or aggregate consumption, people typically take the logarithm and compute the first difference. (Basic idea is that distribution over percent changes in aggregate consumption is invariant across time.) To obtain a stationary time series $\Delta c_t$ from aggregate consumption $C_t$.
$$\Delta c_t = \log C_t - \log C_{t-1}$$
Once you have a stationary time series, it's easy to fit an auto-regressive AR(n) model. You can simply do least squares. For an AR(2) model you can run the regression.
$$ y_{t} = a + b_1 y_{t-!} + b_2 y_{t-2} + \epsilon_t $$
Of course you can get more fancy, but often simple stuff can work surprisingly well. There are well developed packages for time series analysis in R, EViews, Stata, etc... | Deseasonalizing data with fourier analysis
Classic auto-regressive models can handle cycles! Going way back, Yule (1927) and Walker (1931) modeled the periodicity of sunspots using an equation of the form:
$$y_{t+1} = a + b_1 y_t + b_2 y_{t-1} |
34,136 | Deseasonalizing data with fourier analysis | If your data is a time series, you may want to look into triple exponential smoothing, also known as Holt-Winters' method. This can accommodate additive seasonality (where the seasonal amplitude does not grow with the upwards trend over time) and multiplicative seasonality. Here is the difference:
This section in Hyndman's & Athanasopoulos' free online forecasting textbook explains Holt-Winters. Here is the entire taxonomy of exponential smoothing methods, based on Gardner (2006, International Journal of Forecasting). To actually model such a series, extract trend, seasonal and error components and forecast, I recommend the ets() function in the forecast package for R. | Deseasonalizing data with fourier analysis | If your data is a time series, you may want to look into triple exponential smoothing, also known as Holt-Winters' method. This can accommodate additive seasonality (where the seasonal amplitude does | Deseasonalizing data with fourier analysis
If your data is a time series, you may want to look into triple exponential smoothing, also known as Holt-Winters' method. This can accommodate additive seasonality (where the seasonal amplitude does not grow with the upwards trend over time) and multiplicative seasonality. Here is the difference:
This section in Hyndman's & Athanasopoulos' free online forecasting textbook explains Holt-Winters. Here is the entire taxonomy of exponential smoothing methods, based on Gardner (2006, International Journal of Forecasting). To actually model such a series, extract trend, seasonal and error components and forecast, I recommend the ets() function in the forecast package for R. | Deseasonalizing data with fourier analysis
If your data is a time series, you may want to look into triple exponential smoothing, also known as Holt-Winters' method. This can accommodate additive seasonality (where the seasonal amplitude does |
34,137 | How can I test for differences in variation between groups in a mixed model (lme4)? | A few points:
sometimes log-transforming data can clear up heteroscedasticity nicely; this would be my first attempt, especially as you have a positive responses variable (song length), so we would expect it to be skewed if the coefficient of variation is large
assuming that zone in your model is equivalent to "site" in your verbal description (i.e. "site A vs. site B", is coded in the zone variable in your data), you can use the weights argument in nlme::lme to add heteroscedasticity (within-individual variability) to the model:
a <- lme(song_length~factor(zone)+date,
random=~1|male/songtype,
data, method="REML",
weights=varIdent(~zone))
You can do this a little bit more awkwardly with lmer by adding an observation-level variable and using a dummy variable to set its value to zero in the first site:
data <- transform(data,
obs=factor(1:nrow(data)),
zonedummy=as.numeric(zone=="B"))
a <- lmer(song_length~factor(zone)+date+
(1|male/songtype) + (zonedummy-1|obs),
data, REML=TRUE,
control=lmerControl(check.nobs.vs.nRE = "ignore",
check.nobs.vs.nlev = "ignore"))
You can do a similar thing for the among-bird variation by adding a term of the type (zonedummy-1|male); this adds an additional among-male variance term only in site B (you may have to use additional arguments to lmerControl to override some errors). | How can I test for differences in variation between groups in a mixed model (lme4)? | A few points:
sometimes log-transforming data can clear up heteroscedasticity nicely; this would be my first attempt, especially as you have a positive responses variable (song length), so we would e | How can I test for differences in variation between groups in a mixed model (lme4)?
A few points:
sometimes log-transforming data can clear up heteroscedasticity nicely; this would be my first attempt, especially as you have a positive responses variable (song length), so we would expect it to be skewed if the coefficient of variation is large
assuming that zone in your model is equivalent to "site" in your verbal description (i.e. "site A vs. site B", is coded in the zone variable in your data), you can use the weights argument in nlme::lme to add heteroscedasticity (within-individual variability) to the model:
a <- lme(song_length~factor(zone)+date,
random=~1|male/songtype,
data, method="REML",
weights=varIdent(~zone))
You can do this a little bit more awkwardly with lmer by adding an observation-level variable and using a dummy variable to set its value to zero in the first site:
data <- transform(data,
obs=factor(1:nrow(data)),
zonedummy=as.numeric(zone=="B"))
a <- lmer(song_length~factor(zone)+date+
(1|male/songtype) + (zonedummy-1|obs),
data, REML=TRUE,
control=lmerControl(check.nobs.vs.nRE = "ignore",
check.nobs.vs.nlev = "ignore"))
You can do a similar thing for the among-bird variation by adding a term of the type (zonedummy-1|male); this adds an additional among-male variance term only in site B (you may have to use additional arguments to lmerControl to override some errors). | How can I test for differences in variation between groups in a mixed model (lme4)?
A few points:
sometimes log-transforming data can clear up heteroscedasticity nicely; this would be my first attempt, especially as you have a positive responses variable (song length), so we would e |
34,138 | How can I test for differences in variation between groups in a mixed model (lme4)? | A mixed model may not be appropriate for your research question (about the difference in variance between groups).
Mixed models are used for inference and prediction in data where random effects are assumed to be present, such as in hierarchical data. Typically the interest is in modelling fixed effects while controlling for random effects or in the random effect themselves (such in understanding the variability across levels through variance components).
In most software, such as lme4, it is assumed that there is homoscedasticity. In some software heteroscedasticity can be modeled using weights. But there is no way to test for a difference in variation between groups in the model. Your question is about variation between groups, so one approach is simply to perform an F test of equal variance between site A and site B.
Your model formulation suggests that you are interested in the association between song_length and zone (fixed effect) while controlling for the confounder (date) and the random effects (male and songtype). I don't immediately see how gender can be a random effect - I would expect this to be a fixed effect. | How can I test for differences in variation between groups in a mixed model (lme4)? | A mixed model may not be appropriate for your research question (about the difference in variance between groups).
Mixed models are used for inference and prediction in data where random effects are a | How can I test for differences in variation between groups in a mixed model (lme4)?
A mixed model may not be appropriate for your research question (about the difference in variance between groups).
Mixed models are used for inference and prediction in data where random effects are assumed to be present, such as in hierarchical data. Typically the interest is in modelling fixed effects while controlling for random effects or in the random effect themselves (such in understanding the variability across levels through variance components).
In most software, such as lme4, it is assumed that there is homoscedasticity. In some software heteroscedasticity can be modeled using weights. But there is no way to test for a difference in variation between groups in the model. Your question is about variation between groups, so one approach is simply to perform an F test of equal variance between site A and site B.
Your model formulation suggests that you are interested in the association between song_length and zone (fixed effect) while controlling for the confounder (date) and the random effects (male and songtype). I don't immediately see how gender can be a random effect - I would expect this to be a fixed effect. | How can I test for differences in variation between groups in a mixed model (lme4)?
A mixed model may not be appropriate for your research question (about the difference in variance between groups).
Mixed models are used for inference and prediction in data where random effects are a |
34,139 | Distribution of a second degree polynomial of a Gaussian random variable | Note that $ax^2+bx+c=a(x-x_1)(x-x_2)$, where $x_1$ and $x_2$ are roots of the polynomial $ax^2+bx+c$. We must assume that $x_1$ and $x_2$ are real and non-equal, otherwise the probability in question is trivially zero or one.
We have two cases.
$a>0$, then $P(aX^2+bX+c<0) = P(x_1<X<x_2)$.
$a<0$, then $P(aX^2+bX+c<0) = P(X<x_1 \cup X>x_2)=1- P(x_1<X<x_2).$
Since $X$ is normal, the probabilities can be calculated using the cumulative distribution function of normal variable. | Distribution of a second degree polynomial of a Gaussian random variable | Note that $ax^2+bx+c=a(x-x_1)(x-x_2)$, where $x_1$ and $x_2$ are roots of the polynomial $ax^2+bx+c$. We must assume that $x_1$ and $x_2$ are real and non-equal, otherwise the probability in question | Distribution of a second degree polynomial of a Gaussian random variable
Note that $ax^2+bx+c=a(x-x_1)(x-x_2)$, where $x_1$ and $x_2$ are roots of the polynomial $ax^2+bx+c$. We must assume that $x_1$ and $x_2$ are real and non-equal, otherwise the probability in question is trivially zero or one.
We have two cases.
$a>0$, then $P(aX^2+bX+c<0) = P(x_1<X<x_2)$.
$a<0$, then $P(aX^2+bX+c<0) = P(X<x_1 \cup X>x_2)=1- P(x_1<X<x_2).$
Since $X$ is normal, the probabilities can be calculated using the cumulative distribution function of normal variable. | Distribution of a second degree polynomial of a Gaussian random variable
Note that $ax^2+bx+c=a(x-x_1)(x-x_2)$, where $x_1$ and $x_2$ are roots of the polynomial $ax^2+bx+c$. We must assume that $x_1$ and $x_2$ are real and non-equal, otherwise the probability in question |
34,140 | Random Forests out-of-bag sample size | It comes from the construction of a bootstrap sample: you're sampling $n$ observations with replacement to a sample size of $n$. The probability that an observation is omitted is $(1-\frac{1}{n})^n.$* Now consider the definition of $\exp(-1)=\lim \limits_{n\to\infty}(1-\frac{1}{n})^n$ and observe that $\exp(-1)=0.3678...\approx\frac{1}{3}.$
*To verify this, I will define the probability space of the bootstrap:
$\Omega=\{x_1, x_2, x_3, \dots, x_n\}$ where each $x_{i\in I=\{i\in\mathbb{N}:i\le n\}}$ is an observation, $\mathcal{F}=2^\Omega$. We will denote the boostrap sample as $B$. Note that we can take this $\sigma$-field $\mathcal{F}$ because we must have a finite number of observations. Collecting our bootstrap sample one observation at a time, our event of interest $E$ occurs when some observation $x_i$ is selected for the bootstrap sample, and we must define a probability measure for it. That is, $P(E)=P(\{x_i \in B\})$.
We can think of drawing a bootstrap sample as an experiment where there are $n$ trials. Each trial is selecting one of our observations uniformly at random with replacement, so it will either include $x_i$ with probability $P(E)=\frac{|E|}{|\Omega|}=\frac{1}{n},$ or exclude $x_i$ with probability $P(E^c)=\frac{|\Omega|-|E|}{|\Omega|}=1-\frac{1}{n}.$ Our probability space $(\Omega, \mathcal{F}, P)$ is now completely defined. The experiment we're performing has $n$ trials, so the probability that $x_i$ is omitted from all of them is $(\bigcup_{i=1}^n P(E))^c=\bigcap_{i=1}^n P(E^c)=(1-\frac{1}{n})^n$. | Random Forests out-of-bag sample size | It comes from the construction of a bootstrap sample: you're sampling $n$ observations with replacement to a sample size of $n$. The probability that an observation is omitted is $(1-\frac{1}{n})^n.$* | Random Forests out-of-bag sample size
It comes from the construction of a bootstrap sample: you're sampling $n$ observations with replacement to a sample size of $n$. The probability that an observation is omitted is $(1-\frac{1}{n})^n.$* Now consider the definition of $\exp(-1)=\lim \limits_{n\to\infty}(1-\frac{1}{n})^n$ and observe that $\exp(-1)=0.3678...\approx\frac{1}{3}.$
*To verify this, I will define the probability space of the bootstrap:
$\Omega=\{x_1, x_2, x_3, \dots, x_n\}$ where each $x_{i\in I=\{i\in\mathbb{N}:i\le n\}}$ is an observation, $\mathcal{F}=2^\Omega$. We will denote the boostrap sample as $B$. Note that we can take this $\sigma$-field $\mathcal{F}$ because we must have a finite number of observations. Collecting our bootstrap sample one observation at a time, our event of interest $E$ occurs when some observation $x_i$ is selected for the bootstrap sample, and we must define a probability measure for it. That is, $P(E)=P(\{x_i \in B\})$.
We can think of drawing a bootstrap sample as an experiment where there are $n$ trials. Each trial is selecting one of our observations uniformly at random with replacement, so it will either include $x_i$ with probability $P(E)=\frac{|E|}{|\Omega|}=\frac{1}{n},$ or exclude $x_i$ with probability $P(E^c)=\frac{|\Omega|-|E|}{|\Omega|}=1-\frac{1}{n}.$ Our probability space $(\Omega, \mathcal{F}, P)$ is now completely defined. The experiment we're performing has $n$ trials, so the probability that $x_i$ is omitted from all of them is $(\bigcup_{i=1}^n P(E))^c=\bigcap_{i=1}^n P(E^c)=(1-\frac{1}{n})^n$. | Random Forests out-of-bag sample size
It comes from the construction of a bootstrap sample: you're sampling $n$ observations with replacement to a sample size of $n$. The probability that an observation is omitted is $(1-\frac{1}{n})^n.$* |
34,141 | In linear regression, are the error and the predictor variable independent? | No. Here's an interesting counterexample.
Define a density function
$$g(x) = \frac{2}{\sqrt{2\pi}}\exp(-x^2/2)I(-t \le x \le 0 \text{ or } t \le x)$$
for $t = \sqrt{2\log(2)} \approx 1.17741$. ($I$ is the indicator function.)
The plot of $g$ is shown here in blue. If we define $h(x) = g(-x)$, its plot appears in red.
Direct calculation shows that any variable $Y$ with density $g$ has zero mean and unit variance. By construction, an equal mixture of $Y$ with $-Y$ (whose PDF is $h$) has a density function proportional to $\exp(-x^2/2)$: that is, it is standard Normal (with zero mean and unit variance).
Let $X_i$ have a Bernoulli$(1/2)$ distribution. Suppose $\varepsilon_i|X=0$ has density $g$ and $\varepsilon_i|X=1$ has density $h$, with all the $(X_i, \varepsilon_i)$ independent. The assumption about $Y_i$ is irrelevant (or true by definition of $Y_i$) and all the other assumptions hold by construction, yet none of the conditional distributions $\varepsilon_i | X_i = x$ are Normal for any value of $x$.
These plots show a dataset of $300$ samples from a bivariate distribution where $E[Y|X]=5 + X.$ The $x$ values in the scatterplot at the left have been horizontally jittered (displaced randomly) to resolve overlaps. The dotted red line is the least squares fit to these data. The three histograms show the conditional residuals--which are expected to follow $g$ and $h$ closely--and then the combined residuals, which are expected to be approximately Normal. | In linear regression, are the error and the predictor variable independent? | No. Here's an interesting counterexample.
Define a density function
$$g(x) = \frac{2}{\sqrt{2\pi}}\exp(-x^2/2)I(-t \le x \le 0 \text{ or } t \le x)$$
for $t = \sqrt{2\log(2)} \approx 1.17741$. ($I$ | In linear regression, are the error and the predictor variable independent?
No. Here's an interesting counterexample.
Define a density function
$$g(x) = \frac{2}{\sqrt{2\pi}}\exp(-x^2/2)I(-t \le x \le 0 \text{ or } t \le x)$$
for $t = \sqrt{2\log(2)} \approx 1.17741$. ($I$ is the indicator function.)
The plot of $g$ is shown here in blue. If we define $h(x) = g(-x)$, its plot appears in red.
Direct calculation shows that any variable $Y$ with density $g$ has zero mean and unit variance. By construction, an equal mixture of $Y$ with $-Y$ (whose PDF is $h$) has a density function proportional to $\exp(-x^2/2)$: that is, it is standard Normal (with zero mean and unit variance).
Let $X_i$ have a Bernoulli$(1/2)$ distribution. Suppose $\varepsilon_i|X=0$ has density $g$ and $\varepsilon_i|X=1$ has density $h$, with all the $(X_i, \varepsilon_i)$ independent. The assumption about $Y_i$ is irrelevant (or true by definition of $Y_i$) and all the other assumptions hold by construction, yet none of the conditional distributions $\varepsilon_i | X_i = x$ are Normal for any value of $x$.
These plots show a dataset of $300$ samples from a bivariate distribution where $E[Y|X]=5 + X.$ The $x$ values in the scatterplot at the left have been horizontally jittered (displaced randomly) to resolve overlaps. The dotted red line is the least squares fit to these data. The three histograms show the conditional residuals--which are expected to follow $g$ and $h$ closely--and then the combined residuals, which are expected to be approximately Normal. | In linear regression, are the error and the predictor variable independent?
No. Here's an interesting counterexample.
Define a density function
$$g(x) = \frac{2}{\sqrt{2\pi}}\exp(-x^2/2)I(-t \le x \le 0 \text{ or } t \le x)$$
for $t = \sqrt{2\log(2)} \approx 1.17741$. ($I$ |
34,142 | In linear regression, are the error and the predictor variable independent? | The assumption that the conditional variance is equal to the unconditional variance, together with the assumption that $E(\varepsilon_i)=0$, does imply zero conditional mean, namely
$$\{{\rm Var}(\varepsilon_i \mid X_i) = {\rm Var}(\varepsilon_i)\} \;\text {and}\;\{E(\varepsilon_i)=0\}\implies E(\varepsilon_i \mid X_i)=0 \tag{1}$$
The two assumptions imply that
$$E(\varepsilon_i^2 \mid X_i) -[E(\varepsilon_i \mid X_i]^2 = E(\varepsilon_i^2)$$
$$\implies E(\varepsilon_i^2 \mid X_i) - E(\varepsilon_i^2) = [E(\varepsilon_i \mid X_i]^2$$
Ad absurdum, assume that $E(\varepsilon_i \mid X_i)\neq 0 \implies [E(\varepsilon_i \mid X_i]^2 >0$
This in turn implies that $E(\varepsilon_i^2 \mid X_i) > E(\varepsilon_i^2)$. By the law of iterated expectations we have $E(\varepsilon_i^2) = E\big[ E(\varepsilon_i^2 \mid X_i)\big]$. For clarity set $Z \equiv E(\varepsilon_i^2 \mid X_i)$. Then we have that
$$E(\varepsilon_i \mid X_i)\neq 0 \implies Z > E(Z)$$
But this cannot be since a random variable cannot be strictly greater than its own expected value. So $(1)$ must hold.
Note that the reverse is not necessarily true.
As for providing an example to show that even if the above results hold, and even under the marginal normality assumption, the conditional distribution is not necessarily identical to the marginal (which would establish independence), whuber beat me to it. | In linear regression, are the error and the predictor variable independent? | The assumption that the conditional variance is equal to the unconditional variance, together with the assumption that $E(\varepsilon_i)=0$, does imply zero conditional mean, namely
$$\{{\rm Var}(\var | In linear regression, are the error and the predictor variable independent?
The assumption that the conditional variance is equal to the unconditional variance, together with the assumption that $E(\varepsilon_i)=0$, does imply zero conditional mean, namely
$$\{{\rm Var}(\varepsilon_i \mid X_i) = {\rm Var}(\varepsilon_i)\} \;\text {and}\;\{E(\varepsilon_i)=0\}\implies E(\varepsilon_i \mid X_i)=0 \tag{1}$$
The two assumptions imply that
$$E(\varepsilon_i^2 \mid X_i) -[E(\varepsilon_i \mid X_i]^2 = E(\varepsilon_i^2)$$
$$\implies E(\varepsilon_i^2 \mid X_i) - E(\varepsilon_i^2) = [E(\varepsilon_i \mid X_i]^2$$
Ad absurdum, assume that $E(\varepsilon_i \mid X_i)\neq 0 \implies [E(\varepsilon_i \mid X_i]^2 >0$
This in turn implies that $E(\varepsilon_i^2 \mid X_i) > E(\varepsilon_i^2)$. By the law of iterated expectations we have $E(\varepsilon_i^2) = E\big[ E(\varepsilon_i^2 \mid X_i)\big]$. For clarity set $Z \equiv E(\varepsilon_i^2 \mid X_i)$. Then we have that
$$E(\varepsilon_i \mid X_i)\neq 0 \implies Z > E(Z)$$
But this cannot be since a random variable cannot be strictly greater than its own expected value. So $(1)$ must hold.
Note that the reverse is not necessarily true.
As for providing an example to show that even if the above results hold, and even under the marginal normality assumption, the conditional distribution is not necessarily identical to the marginal (which would establish independence), whuber beat me to it. | In linear regression, are the error and the predictor variable independent?
The assumption that the conditional variance is equal to the unconditional variance, together with the assumption that $E(\varepsilon_i)=0$, does imply zero conditional mean, namely
$$\{{\rm Var}(\var |
34,143 | Logistic regression: what happens to the coefficients when we switch the labels (0/1) of the binary outcome | With a logistic regression model one models the probability of occurence of a binary event, in your case the probability that it rains. As any other model, your model will have to make assumptions and one of your assumptions is that this probability of rain depends on five explanatory variables, for the ease of notation I will call them $x_i, i=1,2, \dots 5$. Furthermore, your model assumes that the probability of rain, given values of the $x_i$ (notation: $P(rain=true|_{x_i})$ has a particular functional $S$-shaped form namely
$P(rain=true|_{x_i})=\frac{1}{1+e^{-(\beta_0+\sum_i \beta_i x_i)}}$.
After some manipulations we can transform this to $\ln \left( \frac{P(rain=true|_{x_i})}{1-P(rain=true|_{x_i})} \right)=\beta_0+\sum_i \beta_i x_i$. ($\ln$ is the natural logarithm)
If $\pi$ is the probability of an occurence of an event, then $\frac{\pi}{1-\pi}$ is the odds of the event. For example, if you make a bet with a fair coin, and you win the bet when head turns up, then, as $\pi=0.5$, the odds of winning are $\frac{0.5}{1-0.5}=1$ or you have as much chance of winning the bet than of losing it. If you make a bet and you win when a die turns up with '1', then the odds are $\frac{\frac{1}{6}}{1-\frac{1}{6}}=\frac{1}{5}$ or the odds is 1/5 or you have five times more chance of losing the bet.
From the above it follows that a logistic regression model assumes (a) that the probability of rain is a function of the $x_i$ and (b) that the log of the odds of rain against no rain is linear in the $x_i$.
(Note: further assumptions must be made for estimating the coefficients (e.g. independence of observations)).
Your coefficient of $x_{10}$ is (rounded) 0.64 meaning that if $x_{10}$ increases by one unit then, all other things equal, the log of the odds of rain against no rain will increase by $0.64$.
If the log of the odds increases by $0.64$ then, all other things equal, the odds increase by $e^{0.64}$ (for each unit increase in $x_{10}$).
Maybe good to note with respect to your 'most influential variables': In the above paragraph I said 'change in log-odds for one unit change in $x_i$'. This is important if you want to analyse 'most influential variables', indeed, variables can be espressed in different units: if the coeffient of $x_1$ is 1 and $x_1$ is in kilometer while the coefficient of $x_2$ is 0.1 with $x_2$ in meter then (a) a unit change in $x_1$ (1 km) changes the log-odds by 1 and (b) a unit change in $x_2$ (1 m) changes the log-odds by 0.1.
So in order to assess the impact of variables, an analysis of the magnitude of the coefficients alone is not suffcient, you should take the units of the variables into account (or use standardised variables).
EDIT: I added this after you asked the question in your comment: "what happens if I predict the odds of no rain instead of the odds of rain?"
Obviously it holds that $P(rain=FALSE|_{x_i})=1-P(rain=true|_{x_i})$. So the log-odds of no rain against rain is $ln \left( \frac{P(rain=FALSE|_{x_i})}{1-P(rain=FALSE|_{x_i})} \right) =\ln \left( \frac{1-P(rain=true|_{x_i})}{P(rain=true|_{x_i})} \right)=-\ln \left( \frac{P(rain=true|_{x_i})}{1-P(rain=true|_{x_i})} \right )$.
(note that $\ln \left( \frac{1}{x} \right)=-\ln(x)$).
So we find that the odds of 'no rain' against 'rain' is $\ln \left( \frac{P(rain=FALSE|_{x_i})}{1-P(rain=FALSE|_{x_i})} \right) = -(\beta_0+\sum_i \beta_i x_i) $. In words: the sign of the coefficients changes.
As @Scortchi has indicated in the comments, one would have serious doubt about the logistic regression if simply switching the class labels would yield a completely different result.
The code below illustrates the 'sign switch' :
# Generate some data: outcome is binary and x is the explanatory
# step 1: generate success probabilities for Bernouilli variables
set.seed(1)
x<-runif(n=5000, min=-2, max=2)
p<-1/(1+exp(-(2*x-1)))
# step 2: generate binary outcome with these probabilities
outcome<-(runif(n=5000,min=0,max=1) <=p)
# Estimate logit using: estimate binary outcome with x as explanatory
glm.lr1<-glm(outcome ~ x +1, family=binomial)
coef(glm.lr1)
# estimate logit using **'outcome' SWITCHED** ('!' in front of it)
glm.lr2<-glm(!outcome ~ x +1, family=binomial)
coef(glm.lr2)
Note for the results: The way we generated the data, the intercept should be close to -1 and the coefficient of x close to 2 in the first case and with reversed signs in the second case | Logistic regression: what happens to the coefficients when we switch the labels (0/1) of the binary | With a logistic regression model one models the probability of occurence of a binary event, in your case the probability that it rains. As any other model, your model will have to make assumptions an | Logistic regression: what happens to the coefficients when we switch the labels (0/1) of the binary outcome
With a logistic regression model one models the probability of occurence of a binary event, in your case the probability that it rains. As any other model, your model will have to make assumptions and one of your assumptions is that this probability of rain depends on five explanatory variables, for the ease of notation I will call them $x_i, i=1,2, \dots 5$. Furthermore, your model assumes that the probability of rain, given values of the $x_i$ (notation: $P(rain=true|_{x_i})$ has a particular functional $S$-shaped form namely
$P(rain=true|_{x_i})=\frac{1}{1+e^{-(\beta_0+\sum_i \beta_i x_i)}}$.
After some manipulations we can transform this to $\ln \left( \frac{P(rain=true|_{x_i})}{1-P(rain=true|_{x_i})} \right)=\beta_0+\sum_i \beta_i x_i$. ($\ln$ is the natural logarithm)
If $\pi$ is the probability of an occurence of an event, then $\frac{\pi}{1-\pi}$ is the odds of the event. For example, if you make a bet with a fair coin, and you win the bet when head turns up, then, as $\pi=0.5$, the odds of winning are $\frac{0.5}{1-0.5}=1$ or you have as much chance of winning the bet than of losing it. If you make a bet and you win when a die turns up with '1', then the odds are $\frac{\frac{1}{6}}{1-\frac{1}{6}}=\frac{1}{5}$ or the odds is 1/5 or you have five times more chance of losing the bet.
From the above it follows that a logistic regression model assumes (a) that the probability of rain is a function of the $x_i$ and (b) that the log of the odds of rain against no rain is linear in the $x_i$.
(Note: further assumptions must be made for estimating the coefficients (e.g. independence of observations)).
Your coefficient of $x_{10}$ is (rounded) 0.64 meaning that if $x_{10}$ increases by one unit then, all other things equal, the log of the odds of rain against no rain will increase by $0.64$.
If the log of the odds increases by $0.64$ then, all other things equal, the odds increase by $e^{0.64}$ (for each unit increase in $x_{10}$).
Maybe good to note with respect to your 'most influential variables': In the above paragraph I said 'change in log-odds for one unit change in $x_i$'. This is important if you want to analyse 'most influential variables', indeed, variables can be espressed in different units: if the coeffient of $x_1$ is 1 and $x_1$ is in kilometer while the coefficient of $x_2$ is 0.1 with $x_2$ in meter then (a) a unit change in $x_1$ (1 km) changes the log-odds by 1 and (b) a unit change in $x_2$ (1 m) changes the log-odds by 0.1.
So in order to assess the impact of variables, an analysis of the magnitude of the coefficients alone is not suffcient, you should take the units of the variables into account (or use standardised variables).
EDIT: I added this after you asked the question in your comment: "what happens if I predict the odds of no rain instead of the odds of rain?"
Obviously it holds that $P(rain=FALSE|_{x_i})=1-P(rain=true|_{x_i})$. So the log-odds of no rain against rain is $ln \left( \frac{P(rain=FALSE|_{x_i})}{1-P(rain=FALSE|_{x_i})} \right) =\ln \left( \frac{1-P(rain=true|_{x_i})}{P(rain=true|_{x_i})} \right)=-\ln \left( \frac{P(rain=true|_{x_i})}{1-P(rain=true|_{x_i})} \right )$.
(note that $\ln \left( \frac{1}{x} \right)=-\ln(x)$).
So we find that the odds of 'no rain' against 'rain' is $\ln \left( \frac{P(rain=FALSE|_{x_i})}{1-P(rain=FALSE|_{x_i})} \right) = -(\beta_0+\sum_i \beta_i x_i) $. In words: the sign of the coefficients changes.
As @Scortchi has indicated in the comments, one would have serious doubt about the logistic regression if simply switching the class labels would yield a completely different result.
The code below illustrates the 'sign switch' :
# Generate some data: outcome is binary and x is the explanatory
# step 1: generate success probabilities for Bernouilli variables
set.seed(1)
x<-runif(n=5000, min=-2, max=2)
p<-1/(1+exp(-(2*x-1)))
# step 2: generate binary outcome with these probabilities
outcome<-(runif(n=5000,min=0,max=1) <=p)
# Estimate logit using: estimate binary outcome with x as explanatory
glm.lr1<-glm(outcome ~ x +1, family=binomial)
coef(glm.lr1)
# estimate logit using **'outcome' SWITCHED** ('!' in front of it)
glm.lr2<-glm(!outcome ~ x +1, family=binomial)
coef(glm.lr2)
Note for the results: The way we generated the data, the intercept should be close to -1 and the coefficient of x close to 2 in the first case and with reversed signs in the second case | Logistic regression: what happens to the coefficients when we switch the labels (0/1) of the binary
With a logistic regression model one models the probability of occurence of a binary event, in your case the probability that it rains. As any other model, your model will have to make assumptions an |
34,144 | How can Poisson GLM work with non-count data (rate data)? [duplicate] | I don't know why glm() doesn't blow up. To figure that out, you'll have to unpack all of the underlying code. (In addition, if your only question is how the R code works, this question is off topic here.)
What I can say is that you are not modeling the rates correctly. If you want to model rates instead of counts, you need to include an offset in the model's formula. (There is a nice discussion on CV of what an offset is here: When to use an offset in a Poisson regression?) Using your example the code would be:
pois_mdl2 <- glm(y~x+offset(log(rep(1000,14))), family=poisson(link="log"))
Note that, although the coefficient estimates are the same, the standard errors are quite different:
summary(pois_mdl2)$coefficients
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) -6.5681214 0.25118701 -26.14833 1.029521e-150
# x 0.2565236 0.02203911 11.63947 2.596237e-31
summary(pois_mdl)$coefficients
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) -6.5681214 7.9431516 -0.8268911 0.4082988
# x 0.2565236 0.6969324 0.3680753 0.7128171 | How can Poisson GLM work with non-count data (rate data)? [duplicate] | I don't know why glm() doesn't blow up. To figure that out, you'll have to unpack all of the underlying code. (In addition, if your only question is how the R code works, this question is off topic | How can Poisson GLM work with non-count data (rate data)? [duplicate]
I don't know why glm() doesn't blow up. To figure that out, you'll have to unpack all of the underlying code. (In addition, if your only question is how the R code works, this question is off topic here.)
What I can say is that you are not modeling the rates correctly. If you want to model rates instead of counts, you need to include an offset in the model's formula. (There is a nice discussion on CV of what an offset is here: When to use an offset in a Poisson regression?) Using your example the code would be:
pois_mdl2 <- glm(y~x+offset(log(rep(1000,14))), family=poisson(link="log"))
Note that, although the coefficient estimates are the same, the standard errors are quite different:
summary(pois_mdl2)$coefficients
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) -6.5681214 0.25118701 -26.14833 1.029521e-150
# x 0.2565236 0.02203911 11.63947 2.596237e-31
summary(pois_mdl)$coefficients
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) -6.5681214 7.9431516 -0.8268911 0.4082988
# x 0.2565236 0.6969324 0.3680753 0.7128171 | How can Poisson GLM work with non-count data (rate data)? [duplicate]
I don't know why glm() doesn't blow up. To figure that out, you'll have to unpack all of the underlying code. (In addition, if your only question is how the R code works, this question is off topic |
34,145 | How can Poisson GLM work with non-count data (rate data)? [duplicate] | While I don't recommend looking at the source code for glm for those that wish to preserve their mental health, I looked at the source code to glm. The reason R doesn't blow up seems to be that it just doesn't bother to do the kind of defensive checks it probably should.
The main iteratively re-weighted least squares loop works by using the methods attached to a family object of the appropriate type. In this case, that is poisson:
> poi <- poisson()
> class(poi)
[1] "family"
This family object has all that glm needs to fit the model, for example:
> poi$linkfun(1)
[1] 0
> poi$linkinv(1)
[1] 2.718282
Another, here's the derivative of the inverse link:
> poi$mu.eta(1)
[1] 2.718282
The y data comes in on line 258:
dev <- sum(dev.resids(y, mu, weights))
Unfortunately, dev.resids could not care at all whether y is positive integer valued:
> poi$dev.resid(1.5, 1, 1)
[1] 0.2163953
So I guess R doesn't blow up because it didn't think to blow up. | How can Poisson GLM work with non-count data (rate data)? [duplicate] | While I don't recommend looking at the source code for glm for those that wish to preserve their mental health, I looked at the source code to glm. The reason R doesn't blow up seems to be that it ju | How can Poisson GLM work with non-count data (rate data)? [duplicate]
While I don't recommend looking at the source code for glm for those that wish to preserve their mental health, I looked at the source code to glm. The reason R doesn't blow up seems to be that it just doesn't bother to do the kind of defensive checks it probably should.
The main iteratively re-weighted least squares loop works by using the methods attached to a family object of the appropriate type. In this case, that is poisson:
> poi <- poisson()
> class(poi)
[1] "family"
This family object has all that glm needs to fit the model, for example:
> poi$linkfun(1)
[1] 0
> poi$linkinv(1)
[1] 2.718282
Another, here's the derivative of the inverse link:
> poi$mu.eta(1)
[1] 2.718282
The y data comes in on line 258:
dev <- sum(dev.resids(y, mu, weights))
Unfortunately, dev.resids could not care at all whether y is positive integer valued:
> poi$dev.resid(1.5, 1, 1)
[1] 0.2163953
So I guess R doesn't blow up because it didn't think to blow up. | How can Poisson GLM work with non-count data (rate data)? [duplicate]
While I don't recommend looking at the source code for glm for those that wish to preserve their mental health, I looked at the source code to glm. The reason R doesn't blow up seems to be that it ju |
34,146 | Convergence of moments of binomial to Poisson | Because the characteristic function (cf) of a Bernoulli$(p)$ variate is
$$\psi_p(t) = 1 + p(e^{it}-1),$$
the cf of a sum of $n$ independent such variates (which is a Binomial$(p,n)$ variable) is
$$\psi_p(t)^n = \left(1 + p(e^{it}-1)\right)^n = \left(1 + \frac{np(e^{it}-1)}{n}\right)^n.$$
It is well known (and easy to show, even for Complex numbers) that
$$\left(1 + \frac{x}{n}\right)^n$$
converges to $\exp(x)$ as $n\to \infty$. Keeping $np=a$ constant as $n$ increases allows us to write
$$x = np(e^{it}-1) = a(e^{it}-1).$$
Therefore
$$\psi_p(t)^n \to \exp(x) = \exp(a(e^{it}-1)).$$
Because this is the characteristic function of a Poisson$(a)$ distribution, and all the characteristic functions we have considered are analytic in a neighborhood of $t=0$ with power series whose coefficients give the moments, the moments of the Binomial distributions must have converged to the moments of this Poisson distribution, QED. | Convergence of moments of binomial to Poisson | Because the characteristic function (cf) of a Bernoulli$(p)$ variate is
$$\psi_p(t) = 1 + p(e^{it}-1),$$
the cf of a sum of $n$ independent such variates (which is a Binomial$(p,n)$ variable) is
$$\ps | Convergence of moments of binomial to Poisson
Because the characteristic function (cf) of a Bernoulli$(p)$ variate is
$$\psi_p(t) = 1 + p(e^{it}-1),$$
the cf of a sum of $n$ independent such variates (which is a Binomial$(p,n)$ variable) is
$$\psi_p(t)^n = \left(1 + p(e^{it}-1)\right)^n = \left(1 + \frac{np(e^{it}-1)}{n}\right)^n.$$
It is well known (and easy to show, even for Complex numbers) that
$$\left(1 + \frac{x}{n}\right)^n$$
converges to $\exp(x)$ as $n\to \infty$. Keeping $np=a$ constant as $n$ increases allows us to write
$$x = np(e^{it}-1) = a(e^{it}-1).$$
Therefore
$$\psi_p(t)^n \to \exp(x) = \exp(a(e^{it}-1)).$$
Because this is the characteristic function of a Poisson$(a)$ distribution, and all the characteristic functions we have considered are analytic in a neighborhood of $t=0$ with power series whose coefficients give the moments, the moments of the Binomial distributions must have converged to the moments of this Poisson distribution, QED. | Convergence of moments of binomial to Poisson
Because the characteristic function (cf) of a Bernoulli$(p)$ variate is
$$\psi_p(t) = 1 + p(e^{it}-1),$$
the cf of a sum of $n$ independent such variates (which is a Binomial$(p,n)$ variable) is
$$\ps |
34,147 | Convergence of moments of binomial to Poisson | I think I found an answer using factorial moments. Still, I will accept someone else's answer if they can shed some light into the more general case, such as giving sufficient conditions that assure convergence.
The $r$-th factorial moment of the binomial distribution is easily computed as
$$
\mathrm E[(X)_r] = (n)_r\, p^r,
$$
where $(a)_r = a(a-1)\cdots(a-r+1)$ denotes the falling factorial; and that of the Poisson distribution is
$$
\mathrm E[(X)_r] = a^r.
$$
It is clear that $(n)_r\, p^r$ tends to $a^r$ as $n\rightarrow \infty$, $p \rightarrow 0$ with $np=a$. Thus the binomial factorial moments converge to the Poisson ones.
The $r$-th moment is a linear combination of the $0$-th, ..., $r$-th factorial moments:
$$
\mathrm E[X^r] = \sum_{k=0}^r \left\lbrace\ r\atop k \right\rbrace \mathrm E[(X)_r],
$$
where $\left\lbrace\ r\atop k \right\rbrace$ denotes the Stirling numbers of the second kind. This expression, together with the convergence of the factorial moments, implies the convergence of the moments. | Convergence of moments of binomial to Poisson | I think I found an answer using factorial moments. Still, I will accept someone else's answer if they can shed some light into the more general case, such as giving sufficient conditions that assure c | Convergence of moments of binomial to Poisson
I think I found an answer using factorial moments. Still, I will accept someone else's answer if they can shed some light into the more general case, such as giving sufficient conditions that assure convergence.
The $r$-th factorial moment of the binomial distribution is easily computed as
$$
\mathrm E[(X)_r] = (n)_r\, p^r,
$$
where $(a)_r = a(a-1)\cdots(a-r+1)$ denotes the falling factorial; and that of the Poisson distribution is
$$
\mathrm E[(X)_r] = a^r.
$$
It is clear that $(n)_r\, p^r$ tends to $a^r$ as $n\rightarrow \infty$, $p \rightarrow 0$ with $np=a$. Thus the binomial factorial moments converge to the Poisson ones.
The $r$-th moment is a linear combination of the $0$-th, ..., $r$-th factorial moments:
$$
\mathrm E[X^r] = \sum_{k=0}^r \left\lbrace\ r\atop k \right\rbrace \mathrm E[(X)_r],
$$
where $\left\lbrace\ r\atop k \right\rbrace$ denotes the Stirling numbers of the second kind. This expression, together with the convergence of the factorial moments, implies the convergence of the moments. | Convergence of moments of binomial to Poisson
I think I found an answer using factorial moments. Still, I will accept someone else's answer if they can shed some light into the more general case, such as giving sufficient conditions that assure c |
34,148 | lsmeans (R): Adjust for multiple comparisons with interaction terms | Both of the lsmeans statements you show generate lists of lsmobjs, and each element of those lists is handled separately. If you want to incorporate an overall adjustment for two or more lists combined, it is technical and it takes a bit of work.
First, save the list:
lsmlist = lsmeans(warp.lm, list(pairwise ~ wool|tension,
pairwise ~ tension|wool))
This creates a list of 4 lsmobjs (originally two lists of two)
> names(lsmlist)
[1] "lsmeans of wool | tension"
[2] "pairwise differences of contrast, tension | tension"
[3] "lsmeans of tension | wool"
[4] "pairwise differences of contrast, wool | wool"
The user wants to combine the three comparisons in lsmlist[[2]] with the six in lsmlist[[4]] and have an overall multiplicity adjustment for those 9 comparisons.
To start, create a new lsmobj from one of the results, and fix it up.
mydiffs = lsmlist[[4]]
First, bind together the linear functions for the two sets of comparisons:
mydiffs@linfct = rbind(lsmlist[[2]]@linfct, lsmlist[[4]]@linfct)
We also need to define the grid slot, which defines the factors associated with each linear function. To make it simple, I just define a factor named contrast with 9 levels for the 9 contrasts (something fancier could be done here).
mydiffs@grid = data.frame(contrast = 1:9)
Finally, fix up the auxiliary info that does the bookkeeping. We now use our new contrast factor as the only variable, with no "by" variables. For the combined family of 9 contrasts, the Tukey adjustment makes no sense so we use the multivariate $t$ ("mvt") method:
mydiffs = update(mydiffs, pri.vars = "contrast", by.vars = NULL,
adjust="mvt")
Now, we can look at the resulting summary:
> mydiffs
contrast estimate SE df t.ratio p.value
1 16.3333333 5.157299 48 3.167 0.0205
2 -4.7777778 5.157299 48 -0.926 0.9119
3 5.7777778 5.157299 48 1.120 0.8258
4 20.5555556 5.157299 48 3.986 0.0019
5 20.0000000 5.157299 48 3.878 0.0026
6 -0.5555556 5.157299 48 -0.108 1.0000
7 -0.5555556 5.157299 48 -0.108 1.0000
8 9.4444444 5.157299 48 1.831 0.3796
9 10.0000000 5.157299 48 1.939 0.3190
P value adjustment: mvt method for 9 tests
I could consider adding a feature for combining pieces of lsm.list objects, but it is not straightforward -- primarily because of complications in obtaining meaningful labels for the results (the grid part). It is also a problem that different users expect different defaults. | lsmeans (R): Adjust for multiple comparisons with interaction terms | Both of the lsmeans statements you show generate lists of lsmobjs, and each element of those lists is handled separately. If you want to incorporate an overall adjustment for two or more lists combine | lsmeans (R): Adjust for multiple comparisons with interaction terms
Both of the lsmeans statements you show generate lists of lsmobjs, and each element of those lists is handled separately. If you want to incorporate an overall adjustment for two or more lists combined, it is technical and it takes a bit of work.
First, save the list:
lsmlist = lsmeans(warp.lm, list(pairwise ~ wool|tension,
pairwise ~ tension|wool))
This creates a list of 4 lsmobjs (originally two lists of two)
> names(lsmlist)
[1] "lsmeans of wool | tension"
[2] "pairwise differences of contrast, tension | tension"
[3] "lsmeans of tension | wool"
[4] "pairwise differences of contrast, wool | wool"
The user wants to combine the three comparisons in lsmlist[[2]] with the six in lsmlist[[4]] and have an overall multiplicity adjustment for those 9 comparisons.
To start, create a new lsmobj from one of the results, and fix it up.
mydiffs = lsmlist[[4]]
First, bind together the linear functions for the two sets of comparisons:
mydiffs@linfct = rbind(lsmlist[[2]]@linfct, lsmlist[[4]]@linfct)
We also need to define the grid slot, which defines the factors associated with each linear function. To make it simple, I just define a factor named contrast with 9 levels for the 9 contrasts (something fancier could be done here).
mydiffs@grid = data.frame(contrast = 1:9)
Finally, fix up the auxiliary info that does the bookkeeping. We now use our new contrast factor as the only variable, with no "by" variables. For the combined family of 9 contrasts, the Tukey adjustment makes no sense so we use the multivariate $t$ ("mvt") method:
mydiffs = update(mydiffs, pri.vars = "contrast", by.vars = NULL,
adjust="mvt")
Now, we can look at the resulting summary:
> mydiffs
contrast estimate SE df t.ratio p.value
1 16.3333333 5.157299 48 3.167 0.0205
2 -4.7777778 5.157299 48 -0.926 0.9119
3 5.7777778 5.157299 48 1.120 0.8258
4 20.5555556 5.157299 48 3.986 0.0019
5 20.0000000 5.157299 48 3.878 0.0026
6 -0.5555556 5.157299 48 -0.108 1.0000
7 -0.5555556 5.157299 48 -0.108 1.0000
8 9.4444444 5.157299 48 1.831 0.3796
9 10.0000000 5.157299 48 1.939 0.3190
P value adjustment: mvt method for 9 tests
I could consider adding a feature for combining pieces of lsm.list objects, but it is not straightforward -- primarily because of complications in obtaining meaningful labels for the results (the grid part). It is also a problem that different users expect different defaults. | lsmeans (R): Adjust for multiple comparisons with interaction terms
Both of the lsmeans statements you show generate lists of lsmobjs, and each element of those lists is handled separately. If you want to incorporate an overall adjustment for two or more lists combine |
34,149 | lsmeans (R): Adjust for multiple comparisons with interaction terms | Provision in upcoming version of lsmeans
The next update of lsmeans (2.20 or later) will include an rbind method for ref.grid and lsmobj objects. It makes it easy to combine two or ore objects into one family, and defaults to the "mvt" adjustment method. Here is the present example:
> w.t <- pairs(lsmeans(warp.lm, ~ wool | tension))
> t.w <- pairs(lsmeans(warp.lm, ~ tension | wool))
> rbind(w.t, t.w)
tension wool contrast estimate SE df t.ratio p.value
L . A - B 16.3333333 5.157299 48 3.167 0.0203
M . A - B -4.7777778 5.157299 48 -0.926 0.9119
H . A - B 5.7777778 5.157299 48 1.120 0.8258
. A L - M 20.5555556 5.157299 48 3.986 0.0018
. A L - H 20.0000000 5.157299 48 3.878 0.0027
. A M - H -0.5555556 5.157299 48 -0.108 1.0000
. B L - M -0.5555556 5.157299 48 -0.108 1.0000
. B L - H 9.4444444 5.157299 48 1.831 0.3793
. B M - H 10.0000000 5.157299 48 1.939 0.3191
P value adjustment: mvt method for 9 tests
If you do specify Tukey instead of mvt, it comes fairly close to the same result:
> test(rbind(w.t, t.w), adjust = "tukey")
tension wool contrast estimate SE df t.ratio p.value
L . A - B 16.3333333 5.157299 48 3.167 0.0196
M . A - B -4.7777778 5.157299 48 -0.926 0.8683
H . A - B 5.7777778 5.157299 48 1.120 0.7727
. A L - M 20.5555556 5.157299 48 3.986 0.0018
. A L - H 20.0000000 5.157299 48 3.878 0.0026
. A M - H -0.5555556 5.157299 48 -0.108 0.9999
. B L - M -0.5555556 5.157299 48 -0.108 0.9999
. B L - H 9.4444444 5.157299 48 1.831 0.3467
. B M - H 10.0000000 5.157299 48 1.939 0.2922
P value adjustment: tukey method for comparing a family of 4.772 estimates
The curiously fractional family size results from ${4.772 \choose 2} = 9$. | lsmeans (R): Adjust for multiple comparisons with interaction terms | Provision in upcoming version of lsmeans
The next update of lsmeans (2.20 or later) will include an rbind method for ref.grid and lsmobj objects. It makes it easy to combine two or ore objects into on | lsmeans (R): Adjust for multiple comparisons with interaction terms
Provision in upcoming version of lsmeans
The next update of lsmeans (2.20 or later) will include an rbind method for ref.grid and lsmobj objects. It makes it easy to combine two or ore objects into one family, and defaults to the "mvt" adjustment method. Here is the present example:
> w.t <- pairs(lsmeans(warp.lm, ~ wool | tension))
> t.w <- pairs(lsmeans(warp.lm, ~ tension | wool))
> rbind(w.t, t.w)
tension wool contrast estimate SE df t.ratio p.value
L . A - B 16.3333333 5.157299 48 3.167 0.0203
M . A - B -4.7777778 5.157299 48 -0.926 0.9119
H . A - B 5.7777778 5.157299 48 1.120 0.8258
. A L - M 20.5555556 5.157299 48 3.986 0.0018
. A L - H 20.0000000 5.157299 48 3.878 0.0027
. A M - H -0.5555556 5.157299 48 -0.108 1.0000
. B L - M -0.5555556 5.157299 48 -0.108 1.0000
. B L - H 9.4444444 5.157299 48 1.831 0.3793
. B M - H 10.0000000 5.157299 48 1.939 0.3191
P value adjustment: mvt method for 9 tests
If you do specify Tukey instead of mvt, it comes fairly close to the same result:
> test(rbind(w.t, t.w), adjust = "tukey")
tension wool contrast estimate SE df t.ratio p.value
L . A - B 16.3333333 5.157299 48 3.167 0.0196
M . A - B -4.7777778 5.157299 48 -0.926 0.8683
H . A - B 5.7777778 5.157299 48 1.120 0.7727
. A L - M 20.5555556 5.157299 48 3.986 0.0018
. A L - H 20.0000000 5.157299 48 3.878 0.0026
. A M - H -0.5555556 5.157299 48 -0.108 0.9999
. B L - M -0.5555556 5.157299 48 -0.108 0.9999
. B L - H 9.4444444 5.157299 48 1.831 0.3467
. B M - H 10.0000000 5.157299 48 1.939 0.2922
P value adjustment: tukey method for comparing a family of 4.772 estimates
The curiously fractional family size results from ${4.772 \choose 2} = 9$. | lsmeans (R): Adjust for multiple comparisons with interaction terms
Provision in upcoming version of lsmeans
The next update of lsmeans (2.20 or later) will include an rbind method for ref.grid and lsmobj objects. It makes it easy to combine two or ore objects into on |
34,150 | Covariance of two sample means | Covariance is a bilinear function meaning that
$$
\operatorname{cov}\left(\sum_{i=1}^n a_iC_i, \sum_{j=1}^m b_jD_j\right)
= \sum_{i=1}^n \sum_{j=1}^m a_i b_j\operatorname{cov}(C_i,D_j).$$
There is no need to mess with means etc.
Applying this to the question of the covariance of the sample means
of $n$ independent paired samples $(X_i, Y_i)$ (note: the pairs
are independent bivariate random variables; we are not claiming
that $X_i$ and $Y_i$ are independent random variables), we have that
\begin{align}
\operatorname{cov}\left(\bar{X},\bar{Y}\right)
&= \operatorname{cov}\left(\frac{1}{n}\sum_{i=1}^n X_i,
\frac 1n\sum_{j=1}^n Y_j\right)\\
&= \frac{1}{n^2}\sum_{i=1}^n \sum_{j=1}^n
\operatorname{cov} (X_i, Y_j)\\
&= \frac{1}{n^2}\sum_{i=1}^n
\operatorname{cov} (X_i, Y_i)
&\scriptstyle{\text{since $X_i$ and $Y_j$ are independent,
and thus uncorrelated, for
$i \neq j$}}\\
&= \frac 1n\operatorname{cov} (X, Y)
\end{align}
As noted below in a comment by flow2k, although $\operatorname{cov}(\bar{X},\bar{Y})$ is smaller than $\operatorname{cov}({X},{Y})$ by a factor of $n$, the (Pearson) correlation coefficients are the same: $\rho_{\bar{X},\bar{Y}} = \rho_{X,Y}$ !! Previously I had never given the correlation coefficients any thought at all. | Covariance of two sample means | Covariance is a bilinear function meaning that
$$
\operatorname{cov}\left(\sum_{i=1}^n a_iC_i, \sum_{j=1}^m b_jD_j\right)
= \sum_{i=1}^n \sum_{j=1}^m a_i b_j\operatorname{cov}(C_i,D_j).$$
There is n | Covariance of two sample means
Covariance is a bilinear function meaning that
$$
\operatorname{cov}\left(\sum_{i=1}^n a_iC_i, \sum_{j=1}^m b_jD_j\right)
= \sum_{i=1}^n \sum_{j=1}^m a_i b_j\operatorname{cov}(C_i,D_j).$$
There is no need to mess with means etc.
Applying this to the question of the covariance of the sample means
of $n$ independent paired samples $(X_i, Y_i)$ (note: the pairs
are independent bivariate random variables; we are not claiming
that $X_i$ and $Y_i$ are independent random variables), we have that
\begin{align}
\operatorname{cov}\left(\bar{X},\bar{Y}\right)
&= \operatorname{cov}\left(\frac{1}{n}\sum_{i=1}^n X_i,
\frac 1n\sum_{j=1}^n Y_j\right)\\
&= \frac{1}{n^2}\sum_{i=1}^n \sum_{j=1}^n
\operatorname{cov} (X_i, Y_j)\\
&= \frac{1}{n^2}\sum_{i=1}^n
\operatorname{cov} (X_i, Y_i)
&\scriptstyle{\text{since $X_i$ and $Y_j$ are independent,
and thus uncorrelated, for
$i \neq j$}}\\
&= \frac 1n\operatorname{cov} (X, Y)
\end{align}
As noted below in a comment by flow2k, although $\operatorname{cov}(\bar{X},\bar{Y})$ is smaller than $\operatorname{cov}({X},{Y})$ by a factor of $n$, the (Pearson) correlation coefficients are the same: $\rho_{\bar{X},\bar{Y}} = \rho_{X,Y}$ !! Previously I had never given the correlation coefficients any thought at all. | Covariance of two sample means
Covariance is a bilinear function meaning that
$$
\operatorname{cov}\left(\sum_{i=1}^n a_iC_i, \sum_{j=1}^m b_jD_j\right)
= \sum_{i=1}^n \sum_{j=1}^m a_i b_j\operatorname{cov}(C_i,D_j).$$
There is n |
34,151 | Covariance of two sample means | I think the algebra issue is resolved with the following:
\begin{align}{1 \over n^2}E\left(\sum_{i=1}^n x_i \sum_{i=1}^n y_i\right)&={1 \over n^2}E\left(\sum_{i=1}^n x_i y_i +\sum_{i\ne j}x_i y_j\right)\\&={1 \over n^2}(n(Cov(x_i,y_i)+\mu_X \mu_Y)+n(n-1)\mu_X \mu_Y)\\&={1 \over n^2}(n Cov(x_i,y_i)+n^2 \mu_X \mu_Y))\\&=Cov(x_i,y_i)/n+ \mu_X \mu_Y\end{align} | Covariance of two sample means | I think the algebra issue is resolved with the following:
\begin{align}{1 \over n^2}E\left(\sum_{i=1}^n x_i \sum_{i=1}^n y_i\right)&={1 \over n^2}E\left(\sum_{i=1}^n x_i y_i +\sum_{i\ne j}x_i y_j\righ | Covariance of two sample means
I think the algebra issue is resolved with the following:
\begin{align}{1 \over n^2}E\left(\sum_{i=1}^n x_i \sum_{i=1}^n y_i\right)&={1 \over n^2}E\left(\sum_{i=1}^n x_i y_i +\sum_{i\ne j}x_i y_j\right)\\&={1 \over n^2}(n(Cov(x_i,y_i)+\mu_X \mu_Y)+n(n-1)\mu_X \mu_Y)\\&={1 \over n^2}(n Cov(x_i,y_i)+n^2 \mu_X \mu_Y))\\&=Cov(x_i,y_i)/n+ \mu_X \mu_Y\end{align} | Covariance of two sample means
I think the algebra issue is resolved with the following:
\begin{align}{1 \over n^2}E\left(\sum_{i=1}^n x_i \sum_{i=1}^n y_i\right)&={1 \over n^2}E\left(\sum_{i=1}^n x_i y_i +\sum_{i\ne j}x_i y_j\righ |
34,152 | rnorm vs dnorm in R | You know the probability density function for a standard normal distribution is
$\frac{1}{\sqrt{2\pi}}e^\frac{-x^2}{2} $.
The dnorm() function is just used to calculate the value of this function.
You can test using the following R code
density_standard_norm <- function(x)
{
1/sqrt(2*pi)*exp(-0.5*x^2)
}
dnorm(1, mean = 0, sd = 1)
[1] 0.2419707
density_standard_norm(1)
[1] 0.2419707
dnorm(2, mean = 0, sd = 1)
[1] 0.05399097
density_standard_norm(2)
[1] 0.05399097
They are equal. For non-standard normal it's same. | rnorm vs dnorm in R | You know the probability density function for a standard normal distribution is
$\frac{1}{\sqrt{2\pi}}e^\frac{-x^2}{2} $.
The dnorm() function is just used to calculate the value of this function.
Y | rnorm vs dnorm in R
You know the probability density function for a standard normal distribution is
$\frac{1}{\sqrt{2\pi}}e^\frac{-x^2}{2} $.
The dnorm() function is just used to calculate the value of this function.
You can test using the following R code
density_standard_norm <- function(x)
{
1/sqrt(2*pi)*exp(-0.5*x^2)
}
dnorm(1, mean = 0, sd = 1)
[1] 0.2419707
density_standard_norm(1)
[1] 0.2419707
dnorm(2, mean = 0, sd = 1)
[1] 0.05399097
density_standard_norm(2)
[1] 0.05399097
They are equal. For non-standard normal it's same. | rnorm vs dnorm in R
You know the probability density function for a standard normal distribution is
$\frac{1}{\sqrt{2\pi}}e^\frac{-x^2}{2} $.
The dnorm() function is just used to calculate the value of this function.
Y |
34,153 | rnorm vs dnorm in R | It's difficult to describe dnorm in similar terms because that's a somewhat backwards way to think of rnorm.
The d in dnorm stands for probability density function, or PDF. The term "density" is chosen because a probability density function is analogous to the density of a substance in chemistry: the input is a location in the support of the probability distribution (analogous to a location in space inside the substance), and the output is a relative measure of how much "stuff" is near that position.
If you step on some dirt, the part you stepped on will be denser than the surrounding material
If a lake is partially frozen, the frozen part will be less dense than the liquid part
For normal-distributed variables, the probability of observing a point in $[-0.5, 0.5]$ is greater than the probability of observing a point in $[-2, -1]$.
The funny thing about continuous probability distributions is that the notion of a "location" is difficult to quantify. In fact, when we talk about a "location" in math, we are usually talking about a "point." A "point" is a structure so small that it has zero spatial extent; a point is infinitely small. Therefore we can't look at a random variable $Y$ that follows the normal distribution and say "the probability that $Y = 1.2$ is such-and-such", because $1.2$ is a point with zero spatial extent. Once you work through the underlying mathematics you realize that the probability is actually zero of $Y$ being equal to any real number.[1]
This is the case for any continuous probability distribution, including the normal (the norm part of dnorm) distribution. Therefore the best way to understand dnorm without equations, in my opinion, is to say that
if dnorm(y1) is bigger than dnorm(y2), then points near $y_1$ generally have higher probability than points near $y_2$.
This is a deliberately non-technical and non-rigorous definition. There's no universally applicable criterion for defining what "near" means in any particular context. But if you keep the analogy to the density of a physical substance in mind, you won't be entirely wrong.
Recall that I said your description of rnorm was somewhat backwards. That's because dnorm is actually the function that describes what it means for a random variable to follow the normal distribution. A function is just a mapping between inputs and outputs: dnorm is a complete description of the mapping between possible values for $Y$ and the probability densities of those values. That defines the probability distribution of $Y$. rnorm is just what happens when you repeatedly sample numbers in such a way that respects their relative density: values in higher-density regions are more likely to appear than values in lower-density regions. Just don't think too hard about what exactly a "region" is, or where a particular region starts and ends.
By the way, R does have the ability to plot smooth functions:
plot(dnorm, from = -4, to = 4)
works a lot better than
plot(density(rnorm(50000), bw = "nrd"), xlim = c(-4, 4))
and emphasizes the "fundamental" nature of dnorm versus the "derived" nature of rnorm.
[1]: If that makes your brain itch, maybe think of it this way: if the probability that $Y = 1.2$ is $p$, then what's the probability of $Y = 1.21$? How about $Y = 1.201$? Or $Y = 1.20000000000001$? The only reasonable way to cram infinitely many points into a finite space is to make each point infinitely small. | rnorm vs dnorm in R | It's difficult to describe dnorm in similar terms because that's a somewhat backwards way to think of rnorm.
The d in dnorm stands for probability density function, or PDF. The term "density" is chose | rnorm vs dnorm in R
It's difficult to describe dnorm in similar terms because that's a somewhat backwards way to think of rnorm.
The d in dnorm stands for probability density function, or PDF. The term "density" is chosen because a probability density function is analogous to the density of a substance in chemistry: the input is a location in the support of the probability distribution (analogous to a location in space inside the substance), and the output is a relative measure of how much "stuff" is near that position.
If you step on some dirt, the part you stepped on will be denser than the surrounding material
If a lake is partially frozen, the frozen part will be less dense than the liquid part
For normal-distributed variables, the probability of observing a point in $[-0.5, 0.5]$ is greater than the probability of observing a point in $[-2, -1]$.
The funny thing about continuous probability distributions is that the notion of a "location" is difficult to quantify. In fact, when we talk about a "location" in math, we are usually talking about a "point." A "point" is a structure so small that it has zero spatial extent; a point is infinitely small. Therefore we can't look at a random variable $Y$ that follows the normal distribution and say "the probability that $Y = 1.2$ is such-and-such", because $1.2$ is a point with zero spatial extent. Once you work through the underlying mathematics you realize that the probability is actually zero of $Y$ being equal to any real number.[1]
This is the case for any continuous probability distribution, including the normal (the norm part of dnorm) distribution. Therefore the best way to understand dnorm without equations, in my opinion, is to say that
if dnorm(y1) is bigger than dnorm(y2), then points near $y_1$ generally have higher probability than points near $y_2$.
This is a deliberately non-technical and non-rigorous definition. There's no universally applicable criterion for defining what "near" means in any particular context. But if you keep the analogy to the density of a physical substance in mind, you won't be entirely wrong.
Recall that I said your description of rnorm was somewhat backwards. That's because dnorm is actually the function that describes what it means for a random variable to follow the normal distribution. A function is just a mapping between inputs and outputs: dnorm is a complete description of the mapping between possible values for $Y$ and the probability densities of those values. That defines the probability distribution of $Y$. rnorm is just what happens when you repeatedly sample numbers in such a way that respects their relative density: values in higher-density regions are more likely to appear than values in lower-density regions. Just don't think too hard about what exactly a "region" is, or where a particular region starts and ends.
By the way, R does have the ability to plot smooth functions:
plot(dnorm, from = -4, to = 4)
works a lot better than
plot(density(rnorm(50000), bw = "nrd"), xlim = c(-4, 4))
and emphasizes the "fundamental" nature of dnorm versus the "derived" nature of rnorm.
[1]: If that makes your brain itch, maybe think of it this way: if the probability that $Y = 1.2$ is $p$, then what's the probability of $Y = 1.21$? How about $Y = 1.201$? Or $Y = 1.20000000000001$? The only reasonable way to cram infinitely many points into a finite space is to make each point infinitely small. | rnorm vs dnorm in R
It's difficult to describe dnorm in similar terms because that's a somewhat backwards way to think of rnorm.
The d in dnorm stands for probability density function, or PDF. The term "density" is chose |
34,154 | Is there a way to allow seasonality in regression coefficients? | Edit
(The same idea was proposed by Stephan Kolassa a few minutes before I posted my answer. The answer below can still give you some relevant details.)
You could use seasonal dummies. For simplicity I illustrate this for a quarterly time series. Seasonal dummies are indicator variables for each season. The $i$-th seasonal dummy takes on the value 1 for those observations related to season $i$ and 0 otherwise. For a quarterly series the seasonal dummies, $SD$, are defined as follows:
\begin{eqnarray}
SD = \left[
\begin{array}{cccc}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 \\
1 & 0 & 0 & 0 \\
\vdots & \vdots & \vdots & \vdots \\
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 \\
\end{array}
\right] \quad
SDB = \left[
\begin{array}{cccc}
B_{1} & 0 & 0 & 0 \\
0 & B_{2} & 0 & 0 \\
0 & 0 & B_{3} & 0 \\
0 & 0 & 0 & B_{4} \\
B_{5} & 0 & 0 & 0 \\
\vdots & \vdots & \vdots & \vdots \\
B_{n-3} & 0 & 0 & 0 \\
0 & B_{n-2} & 0 & 0 \\
0 & 0 & B_{n-1} & 0 \\
0 & 0 & 0 & B_{n} \\
\end{array}
\right]
\end{eqnarray}
You can multiply each column in $SD$ by your explanatory variable $B_t$ and get the matrix $SDB$ defined above.
Then, you can specify your model as follows:
$$
G_t = Z_t + \beta_{0,s} SD_t + \beta_{1,s} SDB_t \,,
$$
where the index $s$ indicates the season. Observe that we now have four coefficients (12 in your monthly series) $\beta_{1,s}$, one for each column in $SDB$.
The same for the intercept $\beta_0$ except that we must remove one column in $SD$ in order to avoid perfect collinearity. In a monthly series you would include for example the first 11 seasonal intercepts in $SD$.
Fitting the model for example by maximum likelihood will give you one coefficient estimate for each season. You could also test whether $\beta_{0,s}$ are the same for all $s$ or similarly if $\beta_{1,s}$ are constant across seasons. | Is there a way to allow seasonality in regression coefficients? | Edit
(The same idea was proposed by Stephan Kolassa a few minutes before I posted my answer. The answer below can still give you some relevant details.)
You could use seasonal dummies. For simplicity | Is there a way to allow seasonality in regression coefficients?
Edit
(The same idea was proposed by Stephan Kolassa a few minutes before I posted my answer. The answer below can still give you some relevant details.)
You could use seasonal dummies. For simplicity I illustrate this for a quarterly time series. Seasonal dummies are indicator variables for each season. The $i$-th seasonal dummy takes on the value 1 for those observations related to season $i$ and 0 otherwise. For a quarterly series the seasonal dummies, $SD$, are defined as follows:
\begin{eqnarray}
SD = \left[
\begin{array}{cccc}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 \\
1 & 0 & 0 & 0 \\
\vdots & \vdots & \vdots & \vdots \\
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 \\
\end{array}
\right] \quad
SDB = \left[
\begin{array}{cccc}
B_{1} & 0 & 0 & 0 \\
0 & B_{2} & 0 & 0 \\
0 & 0 & B_{3} & 0 \\
0 & 0 & 0 & B_{4} \\
B_{5} & 0 & 0 & 0 \\
\vdots & \vdots & \vdots & \vdots \\
B_{n-3} & 0 & 0 & 0 \\
0 & B_{n-2} & 0 & 0 \\
0 & 0 & B_{n-1} & 0 \\
0 & 0 & 0 & B_{n} \\
\end{array}
\right]
\end{eqnarray}
You can multiply each column in $SD$ by your explanatory variable $B_t$ and get the matrix $SDB$ defined above.
Then, you can specify your model as follows:
$$
G_t = Z_t + \beta_{0,s} SD_t + \beta_{1,s} SDB_t \,,
$$
where the index $s$ indicates the season. Observe that we now have four coefficients (12 in your monthly series) $\beta_{1,s}$, one for each column in $SDB$.
The same for the intercept $\beta_0$ except that we must remove one column in $SD$ in order to avoid perfect collinearity. In a monthly series you would include for example the first 11 seasonal intercepts in $SD$.
Fitting the model for example by maximum likelihood will give you one coefficient estimate for each season. You could also test whether $\beta_{0,s}$ are the same for all $s$ or similarly if $\beta_{1,s}$ are constant across seasons. | Is there a way to allow seasonality in regression coefficients?
Edit
(The same idea was proposed by Stephan Kolassa a few minutes before I posted my answer. The answer below can still give you some relevant details.)
You could use seasonal dummies. For simplicity |
34,155 | Is there a way to allow seasonality in regression coefficients? | Certainly there is. Simply include monthly dummies in an interaction with $B_t$. Let $M_{tm}$ denote a dummy that is 1 if time $t$ corresponds to month $m$ and 0 otherwise. Then fit the following regression with ARMA errors:
$$ G_t = \beta M_{t\cdot} + \gamma B_tM_{t\cdot} + Z_t $$
where $Z_t$ is ARMA(p,q) and $\beta$ and $\gamma$ are parameter vectors of length 12.
You can do the actual fitting using R with the nlme package, using the gls() function and specifying a corARMA() correlation structure. | Is there a way to allow seasonality in regression coefficients? | Certainly there is. Simply include monthly dummies in an interaction with $B_t$. Let $M_{tm}$ denote a dummy that is 1 if time $t$ corresponds to month $m$ and 0 otherwise. Then fit the following regr | Is there a way to allow seasonality in regression coefficients?
Certainly there is. Simply include monthly dummies in an interaction with $B_t$. Let $M_{tm}$ denote a dummy that is 1 if time $t$ corresponds to month $m$ and 0 otherwise. Then fit the following regression with ARMA errors:
$$ G_t = \beta M_{t\cdot} + \gamma B_tM_{t\cdot} + Z_t $$
where $Z_t$ is ARMA(p,q) and $\beta$ and $\gamma$ are parameter vectors of length 12.
You can do the actual fitting using R with the nlme package, using the gls() function and specifying a corARMA() correlation structure. | Is there a way to allow seasonality in regression coefficients?
Certainly there is. Simply include monthly dummies in an interaction with $B_t$. Let $M_{tm}$ denote a dummy that is 1 if time $t$ corresponds to month $m$ and 0 otherwise. Then fit the following regr |
34,156 | Is there a way to allow seasonality in regression coefficients? | If you don't want to discretise the seasonal effect, you could assume that the regression coefficients vary in a cyclic manner as a function of the time of year, i.e. $\beta_0(t) = w_0 + w_1\sin nt + w_2\cos nt$ and $\beta_1(t) = w_3 + w_4\sin nt + w_5\cos nt$, then if you substitute these into your linear model, you should get something of the form
$G_t = Z_t + w_o + w_1\sin nt + w_2\cos nt + w_3B_t + w_4B_t\sin nt + w_5B_t\cos nt$
You could fit this model by using OLS regression (or whatever method you are already using) with the additional covariates $\sin nt$, $\cos nt$, $B_t\sin nt$ and $B_t\cos nt$, where $n$ is whatever constant you need to represent a year ($2\pi/365$ for a daily time-series).
This wouldn't introduce any discontinuities in the model as the seasonality in the regression coefficients are smooth functions of time. I suspect if you added sine and cosine components representing harmonics of the annual cycle you could model deviations from simple sinusoidal variation in the regression coefficients (Fourier series type approach).
Caveat: Been a long day, so I may have made a stupid error somewhere. | Is there a way to allow seasonality in regression coefficients? | If you don't want to discretise the seasonal effect, you could assume that the regression coefficients vary in a cyclic manner as a function of the time of year, i.e. $\beta_0(t) = w_0 + w_1\sin nt + | Is there a way to allow seasonality in regression coefficients?
If you don't want to discretise the seasonal effect, you could assume that the regression coefficients vary in a cyclic manner as a function of the time of year, i.e. $\beta_0(t) = w_0 + w_1\sin nt + w_2\cos nt$ and $\beta_1(t) = w_3 + w_4\sin nt + w_5\cos nt$, then if you substitute these into your linear model, you should get something of the form
$G_t = Z_t + w_o + w_1\sin nt + w_2\cos nt + w_3B_t + w_4B_t\sin nt + w_5B_t\cos nt$
You could fit this model by using OLS regression (or whatever method you are already using) with the additional covariates $\sin nt$, $\cos nt$, $B_t\sin nt$ and $B_t\cos nt$, where $n$ is whatever constant you need to represent a year ($2\pi/365$ for a daily time-series).
This wouldn't introduce any discontinuities in the model as the seasonality in the regression coefficients are smooth functions of time. I suspect if you added sine and cosine components representing harmonics of the annual cycle you could model deviations from simple sinusoidal variation in the regression coefficients (Fourier series type approach).
Caveat: Been a long day, so I may have made a stupid error somewhere. | Is there a way to allow seasonality in regression coefficients?
If you don't want to discretise the seasonal effect, you could assume that the regression coefficients vary in a cyclic manner as a function of the time of year, i.e. $\beta_0(t) = w_0 + w_1\sin nt + |
34,157 | Is there a way to allow seasonality in regression coefficients? | Fit the mean and the harmonics of the seasonal cycle to the time series of x and y. These provide the intercept terms. Then, subtract them from x and y to create anomalies. Use these anomalies x' and y' to compute seasonally varying regression slope coefficients: Fit the array product between the x' and y' with the mean and leading harmonics to the seasonal cycle. Do the same for the variance of the x'. Then divide the seasonal cycle fit to the covariance by the seasonal cycle fit to the variance to provide continuously evolving slope coefficients. For details, see
http://onlinelibrary.wiley.com/doi/10.1002/qj.3054/full | Is there a way to allow seasonality in regression coefficients? | Fit the mean and the harmonics of the seasonal cycle to the time series of x and y. These provide the intercept terms. Then, subtract them from x and y to create anomalies. Use these anomalies x' and | Is there a way to allow seasonality in regression coefficients?
Fit the mean and the harmonics of the seasonal cycle to the time series of x and y. These provide the intercept terms. Then, subtract them from x and y to create anomalies. Use these anomalies x' and y' to compute seasonally varying regression slope coefficients: Fit the array product between the x' and y' with the mean and leading harmonics to the seasonal cycle. Do the same for the variance of the x'. Then divide the seasonal cycle fit to the covariance by the seasonal cycle fit to the variance to provide continuously evolving slope coefficients. For details, see
http://onlinelibrary.wiley.com/doi/10.1002/qj.3054/full | Is there a way to allow seasonality in regression coefficients?
Fit the mean and the harmonics of the seasonal cycle to the time series of x and y. These provide the intercept terms. Then, subtract them from x and y to create anomalies. Use these anomalies x' and |
34,158 | Is the sum of a number of ordinal variables still ordinal? | When you say things like 4+1 = 3+2 = 5, -- which you must do when you sum the components -- you (pretty much unavoidably) assumed they were interval at that time.
[If the components weren't interval, in general 4+1 $\neq$ 3+2 ... so you'd certainly have no business calling both of them "5".]
If the components were interval when you summed them, their sum is certainly interval.
[People may well disagree with me on this, but I can't see any basis for saying things like 4+1 = 3+2 = 5 -- along with all the similar statements that must be made -- unless you have assumed an interval scale. What basis would there be for thinking the summed-category-labels are equivalent outside the assumption that all gaps between adjacent values are equi-distant?]
Don't take this as an assertion that people should not add scale-items; in general I think it's a pretty reasonable thing to do. But in any case, once you do it, you shouldn't be uncomfortable about calling the sum interval-scale; you already went there. | Is the sum of a number of ordinal variables still ordinal? | When you say things like 4+1 = 3+2 = 5, -- which you must do when you sum the components -- you (pretty much unavoidably) assumed they were interval at that time.
[If the components weren't interval | Is the sum of a number of ordinal variables still ordinal?
When you say things like 4+1 = 3+2 = 5, -- which you must do when you sum the components -- you (pretty much unavoidably) assumed they were interval at that time.
[If the components weren't interval, in general 4+1 $\neq$ 3+2 ... so you'd certainly have no business calling both of them "5".]
If the components were interval when you summed them, their sum is certainly interval.
[People may well disagree with me on this, but I can't see any basis for saying things like 4+1 = 3+2 = 5 -- along with all the similar statements that must be made -- unless you have assumed an interval scale. What basis would there be for thinking the summed-category-labels are equivalent outside the assumption that all gaps between adjacent values are equi-distant?]
Don't take this as an assertion that people should not add scale-items; in general I think it's a pretty reasonable thing to do. But in any case, once you do it, you shouldn't be uncomfortable about calling the sum interval-scale; you already went there. | Is the sum of a number of ordinal variables still ordinal?
When you say things like 4+1 = 3+2 = 5, -- which you must do when you sum the components -- you (pretty much unavoidably) assumed they were interval at that time.
[If the components weren't interval |
34,159 | Is the sum of a number of ordinal variables still ordinal? | (What a fun question! My answer is a reflection, and others might have interesting opposing viewpoints.)
No. The pairs of ordinal numbers 1 & 4 and 2 & 3 both sum to 5. But suppose such variables were coding, for example, functional mobility in an individual, where 1 indicated no impairment, 2 impairment not requiring assistance, 3 impairment requiring assistance, and 4 immobility. The codes meaningfully represent a progression along a continuum of impairment. But problems obtain:
The idea of summing 'no impairment' and 'immobility' does not necessarily have conceptual validity (beyond two individuals with different experiences).
The substantive meaning of a sum=5 is unclear.
The meaning of an average of these numbers (i.e. a normalized sum), for example 2.5 (the average of 1 and 4, or 2 and 3) means what? Requiring or not requiring assistance in this example?
One of the individuals measured by the 1 and 4 pair will ever complete any kind of race, but both of the 2 and 3 pair will eventually traverse a distance.
Recall also that the many different quantities in ordinal codes will be ordinally identical (i.e. preserve rank), but will be radically different in quantity. For example the same four values above might be coded 0, 1.5, 7 and 92, both the sums and the averages change then, and ordering is not preserved in the resulting sums compared to the 1, 2, 3, 4 codes. | Is the sum of a number of ordinal variables still ordinal? | (What a fun question! My answer is a reflection, and others might have interesting opposing viewpoints.)
No. The pairs of ordinal numbers 1 & 4 and 2 & 3 both sum to 5. But suppose such variables were | Is the sum of a number of ordinal variables still ordinal?
(What a fun question! My answer is a reflection, and others might have interesting opposing viewpoints.)
No. The pairs of ordinal numbers 1 & 4 and 2 & 3 both sum to 5. But suppose such variables were coding, for example, functional mobility in an individual, where 1 indicated no impairment, 2 impairment not requiring assistance, 3 impairment requiring assistance, and 4 immobility. The codes meaningfully represent a progression along a continuum of impairment. But problems obtain:
The idea of summing 'no impairment' and 'immobility' does not necessarily have conceptual validity (beyond two individuals with different experiences).
The substantive meaning of a sum=5 is unclear.
The meaning of an average of these numbers (i.e. a normalized sum), for example 2.5 (the average of 1 and 4, or 2 and 3) means what? Requiring or not requiring assistance in this example?
One of the individuals measured by the 1 and 4 pair will ever complete any kind of race, but both of the 2 and 3 pair will eventually traverse a distance.
Recall also that the many different quantities in ordinal codes will be ordinally identical (i.e. preserve rank), but will be radically different in quantity. For example the same four values above might be coded 0, 1.5, 7 and 92, both the sums and the averages change then, and ordering is not preserved in the resulting sums compared to the 1, 2, 3, 4 codes. | Is the sum of a number of ordinal variables still ordinal?
(What a fun question! My answer is a reflection, and others might have interesting opposing viewpoints.)
No. The pairs of ordinal numbers 1 & 4 and 2 & 3 both sum to 5. But suppose such variables were |
34,160 | Is the sum of a number of ordinal variables still ordinal? | In order to add the numbers of the codification of two ordinal variables you have to make two assumptions:
1- The distance between any two adjacent categories is the same in each variable. That is, if you measure the distance between categories as "the effort it takes to change a customer's mind", then you must consider that changing somebody's mind from "strongly disagree" to "disagree" takes the same effort as changing it from "disagree" to "neutral", etc.
2- The impact of scoring minimum and maximum is the same for each variable. One example in which this would not apply would be these two variables: "Do you like the service given by this company?" and "Do you like the candies on the front desk?". Of course, the impact of each variable on the overall evaluation is much different.
All this problems could be avoided if you tune the score that each category adds to the global punctuation, so for these two variables you could use:
"Do you like the service given by this company?" 100, 90, 30, 5, 0 (You consider "Agree" and "Strongly agree" as nearly the same answer, "Neutral" as a bad outcome, and "Disagree" and "Strongly disagree" as VERY BAD)
"Do you like the candies on the front desk?" 5, 4, 3, 2, 1 (In this case you may consider the first assumption as real, but of course this variable contributes much less than the previous one to the global image of your company)
Another BIG problem is how to tune the category scores properly. In this case I can only say... Good luck, and don't forget to tell me how to do it! | Is the sum of a number of ordinal variables still ordinal? | In order to add the numbers of the codification of two ordinal variables you have to make two assumptions:
1- The distance between any two adjacent categories is the same in each variable. That is, if | Is the sum of a number of ordinal variables still ordinal?
In order to add the numbers of the codification of two ordinal variables you have to make two assumptions:
1- The distance between any two adjacent categories is the same in each variable. That is, if you measure the distance between categories as "the effort it takes to change a customer's mind", then you must consider that changing somebody's mind from "strongly disagree" to "disagree" takes the same effort as changing it from "disagree" to "neutral", etc.
2- The impact of scoring minimum and maximum is the same for each variable. One example in which this would not apply would be these two variables: "Do you like the service given by this company?" and "Do you like the candies on the front desk?". Of course, the impact of each variable on the overall evaluation is much different.
All this problems could be avoided if you tune the score that each category adds to the global punctuation, so for these two variables you could use:
"Do you like the service given by this company?" 100, 90, 30, 5, 0 (You consider "Agree" and "Strongly agree" as nearly the same answer, "Neutral" as a bad outcome, and "Disagree" and "Strongly disagree" as VERY BAD)
"Do you like the candies on the front desk?" 5, 4, 3, 2, 1 (In this case you may consider the first assumption as real, but of course this variable contributes much less than the previous one to the global image of your company)
Another BIG problem is how to tune the category scores properly. In this case I can only say... Good luck, and don't forget to tell me how to do it! | Is the sum of a number of ordinal variables still ordinal?
In order to add the numbers of the codification of two ordinal variables you have to make two assumptions:
1- The distance between any two adjacent categories is the same in each variable. That is, if |
34,161 | Is the sum of a number of ordinal variables still ordinal? | I guess there are enough answers that state that sum of ordinal variables is itself not a well defined concept. But the OP mention Likert scales and indeed there are arguments that it is OK to sum up the Likert items (each answer) which results in what can be considered an interval number! See the discussion on scoring and analysis on the wikipedia page of Likert scales | Is the sum of a number of ordinal variables still ordinal? | I guess there are enough answers that state that sum of ordinal variables is itself not a well defined concept. But the OP mention Likert scales and indeed there are arguments that it is OK to sum up | Is the sum of a number of ordinal variables still ordinal?
I guess there are enough answers that state that sum of ordinal variables is itself not a well defined concept. But the OP mention Likert scales and indeed there are arguments that it is OK to sum up the Likert items (each answer) which results in what can be considered an interval number! See the discussion on scoring and analysis on the wikipedia page of Likert scales | Is the sum of a number of ordinal variables still ordinal?
I guess there are enough answers that state that sum of ordinal variables is itself not a well defined concept. But the OP mention Likert scales and indeed there are arguments that it is OK to sum up |
34,162 | Proving Linear Estimator (beta) is BLUE? | $$S_{xx} = \sum_{i = 1}^n (x_i - \bar{x})^2 = \sum_{i = 1}^n (x_i^2 - 2x_i\bar{x} + \bar{x}^2)$$
$$= \left(\sum_{i = 1}^n x_i^2\right) - n\bar{x}^2 = \left(\sum_{i = 1}^n x_i^2\right) - \bar{x}\sum_{i = 1}^nx_i = \sum_{i = 1}^n x_i^2 - \bar{x}x_i = \sum_{i = 1}^n (x_i - \bar{x})x_i$$ | Proving Linear Estimator (beta) is BLUE? | $$S_{xx} = \sum_{i = 1}^n (x_i - \bar{x})^2 = \sum_{i = 1}^n (x_i^2 - 2x_i\bar{x} + \bar{x}^2)$$
$$= \left(\sum_{i = 1}^n x_i^2\right) - n\bar{x}^2 = \left(\sum_{i = 1}^n x_i^2\right) - \bar{x}\sum_{ | Proving Linear Estimator (beta) is BLUE?
$$S_{xx} = \sum_{i = 1}^n (x_i - \bar{x})^2 = \sum_{i = 1}^n (x_i^2 - 2x_i\bar{x} + \bar{x}^2)$$
$$= \left(\sum_{i = 1}^n x_i^2\right) - n\bar{x}^2 = \left(\sum_{i = 1}^n x_i^2\right) - \bar{x}\sum_{i = 1}^nx_i = \sum_{i = 1}^n x_i^2 - \bar{x}x_i = \sum_{i = 1}^n (x_i - \bar{x})x_i$$ | Proving Linear Estimator (beta) is BLUE?
$$S_{xx} = \sum_{i = 1}^n (x_i - \bar{x})^2 = \sum_{i = 1}^n (x_i^2 - 2x_i\bar{x} + \bar{x}^2)$$
$$= \left(\sum_{i = 1}^n x_i^2\right) - n\bar{x}^2 = \left(\sum_{i = 1}^n x_i^2\right) - \bar{x}\sum_{ |
34,163 | Proving Linear Estimator (beta) is BLUE? | If you want to prove that the OLS for $\hat{\beta}$ is BLUE (best linear unbiased estimator) you have to prove the following two things: First that $\hat{\beta}$ is unbiased and second that $Var(\hat{\beta})$ is the smallest among all linear unbiased estimators.
Proof that OLS estimator is unbiased can be found here http://economictheoryblog.com/2015/02/19/ols_estimator/
and proof that $Var(\hat{\beta})$ is the smallest among all linear unbiased estimators can be found here http://economictheoryblog.com/2015/02/26/markov_theorem/ | Proving Linear Estimator (beta) is BLUE? | If you want to prove that the OLS for $\hat{\beta}$ is BLUE (best linear unbiased estimator) you have to prove the following two things: First that $\hat{\beta}$ is unbiased and second that $Var(\hat{ | Proving Linear Estimator (beta) is BLUE?
If you want to prove that the OLS for $\hat{\beta}$ is BLUE (best linear unbiased estimator) you have to prove the following two things: First that $\hat{\beta}$ is unbiased and second that $Var(\hat{\beta})$ is the smallest among all linear unbiased estimators.
Proof that OLS estimator is unbiased can be found here http://economictheoryblog.com/2015/02/19/ols_estimator/
and proof that $Var(\hat{\beta})$ is the smallest among all linear unbiased estimators can be found here http://economictheoryblog.com/2015/02/26/markov_theorem/ | Proving Linear Estimator (beta) is BLUE?
If you want to prove that the OLS for $\hat{\beta}$ is BLUE (best linear unbiased estimator) you have to prove the following two things: First that $\hat{\beta}$ is unbiased and second that $Var(\hat{ |
34,164 | Proving Linear Estimator (beta) is BLUE? | It seems you need to show:
$\sum_{i=1}^n(x_i-\bar{x})x_i=\sum_{i=1}^n(x_i-\bar{x})^2$
Try this: Expand the right hand side out into two terms, one of which is the left hand side.
Then just show the other term is zero.
This then shows you the manipulation required (though in reverse order) for your derivation. | Proving Linear Estimator (beta) is BLUE? | It seems you need to show:
$\sum_{i=1}^n(x_i-\bar{x})x_i=\sum_{i=1}^n(x_i-\bar{x})^2$
Try this: Expand the right hand side out into two terms, one of which is the left hand side.
Then just show the o | Proving Linear Estimator (beta) is BLUE?
It seems you need to show:
$\sum_{i=1}^n(x_i-\bar{x})x_i=\sum_{i=1}^n(x_i-\bar{x})^2$
Try this: Expand the right hand side out into two terms, one of which is the left hand side.
Then just show the other term is zero.
This then shows you the manipulation required (though in reverse order) for your derivation. | Proving Linear Estimator (beta) is BLUE?
It seems you need to show:
$\sum_{i=1}^n(x_i-\bar{x})x_i=\sum_{i=1}^n(x_i-\bar{x})^2$
Try this: Expand the right hand side out into two terms, one of which is the left hand side.
Then just show the o |
34,165 | Calculating PDF given CDF | I am gonna be a bit imprecise, but hopefully intuitive.
Discrete and continuous probability distributions must be treated differently. For any value in a discrete distribution there is a finite probability. With a fair coin, the probability of heads is 0.5, with a fair six sided die, the probability of a 1 is one sixth, etc. However, the probability of any specific value in a continuous distribution is zero, because one specific value is only one value out of an infinite number of possible values, and if specific values had a >0 probability, then they would not sum up to 1. Hence, with continuous distributions we talk about the probability of ranges of values.
"Sum up to" is key in answering your question. If you are at all familiar with calculus and its history, you understand that the integral sign—that elongated 'S': $\int$—is a special kind of summation: one describing the limiting case as we approach summing an infinite number of vanishingly small values between points $a$ and $b$ on some function. If that function is a PDF, we can integrate it (sum up) to produce a CDF, and conversely differentiate (difference) the CDF to obtain the PDF.
In the discrete case, we can simply perform standard arithmetic summation (hence, big '$\Sigma$', rather than the tall 'S' notation) and arithmetic differencing. | Calculating PDF given CDF | I am gonna be a bit imprecise, but hopefully intuitive.
Discrete and continuous probability distributions must be treated differently. For any value in a discrete distribution there is a finite probab | Calculating PDF given CDF
I am gonna be a bit imprecise, but hopefully intuitive.
Discrete and continuous probability distributions must be treated differently. For any value in a discrete distribution there is a finite probability. With a fair coin, the probability of heads is 0.5, with a fair six sided die, the probability of a 1 is one sixth, etc. However, the probability of any specific value in a continuous distribution is zero, because one specific value is only one value out of an infinite number of possible values, and if specific values had a >0 probability, then they would not sum up to 1. Hence, with continuous distributions we talk about the probability of ranges of values.
"Sum up to" is key in answering your question. If you are at all familiar with calculus and its history, you understand that the integral sign—that elongated 'S': $\int$—is a special kind of summation: one describing the limiting case as we approach summing an infinite number of vanishingly small values between points $a$ and $b$ on some function. If that function is a PDF, we can integrate it (sum up) to produce a CDF, and conversely differentiate (difference) the CDF to obtain the PDF.
In the discrete case, we can simply perform standard arithmetic summation (hence, big '$\Sigma$', rather than the tall 'S' notation) and arithmetic differencing. | Calculating PDF given CDF
I am gonna be a bit imprecise, but hopefully intuitive.
Discrete and continuous probability distributions must be treated differently. For any value in a discrete distribution there is a finite probab |
34,166 | Calculating PDF given CDF | The difference is for the convenience and understanding of people who have not had to endure Ph.D. level theory courses where you derive and prove "Integral with respect to Counting Measure". Which shows there really is no difference between discrete and continuous distributions, that a sum is really an integral (and as @Alexis already mentioned, an integral is essentially a sum) and a difference is really a derivative (it is a little simpler to see that a derivative is a difference scaled appropriately).
Textbooks and courses will treat them different because it is simpler to teach/understand early on rather than requiring the math that shows there is not a difference. | Calculating PDF given CDF | The difference is for the convenience and understanding of people who have not had to endure Ph.D. level theory courses where you derive and prove "Integral with respect to Counting Measure". Which s | Calculating PDF given CDF
The difference is for the convenience and understanding of people who have not had to endure Ph.D. level theory courses where you derive and prove "Integral with respect to Counting Measure". Which shows there really is no difference between discrete and continuous distributions, that a sum is really an integral (and as @Alexis already mentioned, an integral is essentially a sum) and a difference is really a derivative (it is a little simpler to see that a derivative is a difference scaled appropriately).
Textbooks and courses will treat them different because it is simpler to teach/understand early on rather than requiring the math that shows there is not a difference. | Calculating PDF given CDF
The difference is for the convenience and understanding of people who have not had to endure Ph.D. level theory courses where you derive and prove "Integral with respect to Counting Measure". Which s |
34,167 | Calculating PDF given CDF | (At least at introductory levels) the term density refers only to continuous random variables.
Discrete random variables have a probability mass function, sometimes called a probability function (pmf or pf, not pdf). This doesn't return density but actual probability.
Some random variables don't have either (but they still have a cdf).
Think about what the definition of a cdf is ($F_X(x) = P(X\leq x)$), and then what happens as $x$ moves a little bit in both cases.
Now consider that any jumps in the cdf imply that a particular value has non-zero probability (that $P(X\leq x)>P(X<x)$ and the difference is $P(X=x)$). That non-zero probability for particular $x$-values is what the pmf records $p_X(x)=P(X=x)$.
(In more advanced treatments, the distinction disappears.) | Calculating PDF given CDF | (At least at introductory levels) the term density refers only to continuous random variables.
Discrete random variables have a probability mass function, sometimes called a probability function (pmf | Calculating PDF given CDF
(At least at introductory levels) the term density refers only to continuous random variables.
Discrete random variables have a probability mass function, sometimes called a probability function (pmf or pf, not pdf). This doesn't return density but actual probability.
Some random variables don't have either (but they still have a cdf).
Think about what the definition of a cdf is ($F_X(x) = P(X\leq x)$), and then what happens as $x$ moves a little bit in both cases.
Now consider that any jumps in the cdf imply that a particular value has non-zero probability (that $P(X\leq x)>P(X<x)$ and the difference is $P(X=x)$). That non-zero probability for particular $x$-values is what the pmf records $p_X(x)=P(X=x)$.
(In more advanced treatments, the distinction disappears.) | Calculating PDF given CDF
(At least at introductory levels) the term density refers only to continuous random variables.
Discrete random variables have a probability mass function, sometimes called a probability function (pmf |
34,168 | Calculating PDF given CDF | Actually, you can treat continuous and discrete distributions similarly, but in order to do this you have introduce Dirac's delta functions, left limits and other "advanced" concepts.
So, the easy way to answer your question is that discrete CDF jumps, it's discontinuous. You can't differentiate it everywhere because of that.
Again, if you know delta function, all is possible! | Calculating PDF given CDF | Actually, you can treat continuous and discrete distributions similarly, but in order to do this you have introduce Dirac's delta functions, left limits and other "advanced" concepts.
So, the easy way | Calculating PDF given CDF
Actually, you can treat continuous and discrete distributions similarly, but in order to do this you have introduce Dirac's delta functions, left limits and other "advanced" concepts.
So, the easy way to answer your question is that discrete CDF jumps, it's discontinuous. You can't differentiate it everywhere because of that.
Again, if you know delta function, all is possible! | Calculating PDF given CDF
Actually, you can treat continuous and discrete distributions similarly, but in order to do this you have introduce Dirac's delta functions, left limits and other "advanced" concepts.
So, the easy way |
34,169 | Clusterings that can be caused by K-means | To put some more meat on Peter Flom's answer, k-means clustering looks for k groups in data. The method assumes that Each cluster has a centroid at a certain (x,y). The k-means algorithm minimizes the distance of each point to the centroid (this could be euclidian or manhattan distance depending on your data).
To identify the clusters, an initial guess is made of which data points belong in which cluster, and the centroid is calculated for each cluster. The distance metric is then calculated, and then some points are swapped between clusters to see if the fit improves. There are lots of variations on the details, but fundamentally k-means is a brute force solution that is dependent on the initial conditions, as there are local minima to the clustering solution.
So, in your case it looks like case A had initial conditions that were widely separated in x and so the clusters resolve because the distances from the centroids to the data are small, and it's a stable solution. Conversely, you can't obtain D because that single red point is closer to the centroid of the blue points than many others, so the red point should have become part of the blue set.
Therefore the only way you could get D is if you interrupt the clustering process before it's finished (or the code that made the clusters is broken). | Clusterings that can be caused by K-means | To put some more meat on Peter Flom's answer, k-means clustering looks for k groups in data. The method assumes that Each cluster has a centroid at a certain (x,y). The k-means algorithm minimizes the | Clusterings that can be caused by K-means
To put some more meat on Peter Flom's answer, k-means clustering looks for k groups in data. The method assumes that Each cluster has a centroid at a certain (x,y). The k-means algorithm minimizes the distance of each point to the centroid (this could be euclidian or manhattan distance depending on your data).
To identify the clusters, an initial guess is made of which data points belong in which cluster, and the centroid is calculated for each cluster. The distance metric is then calculated, and then some points are swapped between clusters to see if the fit improves. There are lots of variations on the details, but fundamentally k-means is a brute force solution that is dependent on the initial conditions, as there are local minima to the clustering solution.
So, in your case it looks like case A had initial conditions that were widely separated in x and so the clusters resolve because the distances from the centroids to the data are small, and it's a stable solution. Conversely, you can't obtain D because that single red point is closer to the centroid of the blue points than many others, so the red point should have become part of the blue set.
Therefore the only way you could get D is if you interrupt the clustering process before it's finished (or the code that made the clusters is broken). | Clusterings that can be caused by K-means
To put some more meat on Peter Flom's answer, k-means clustering looks for k groups in data. The method assumes that Each cluster has a centroid at a certain (x,y). The k-means algorithm minimizes the |
34,170 | Clusterings that can be caused by K-means | Because the circled point in D is not far from other points in either PC1 dimension, PC2 dimension or the Euclidean distance combining them.
In A, the single point is far from the others on PC1
In B and C there are two large groups that are easily separable. Indeed, B and C are the same clustering (unless I am missing a dot) they only vary in terms of label | Clusterings that can be caused by K-means | Because the circled point in D is not far from other points in either PC1 dimension, PC2 dimension or the Euclidean distance combining them.
In A, the single point is far from the others on PC1
In B | Clusterings that can be caused by K-means
Because the circled point in D is not far from other points in either PC1 dimension, PC2 dimension or the Euclidean distance combining them.
In A, the single point is far from the others on PC1
In B and C there are two large groups that are easily separable. Indeed, B and C are the same clustering (unless I am missing a dot) they only vary in terms of label | Clusterings that can be caused by K-means
Because the circled point in D is not far from other points in either PC1 dimension, PC2 dimension or the Euclidean distance combining them.
In A, the single point is far from the others on PC1
In B |
34,171 | Clusterings that can be caused by K-means | Since D contains a single point only, its center is exactly at this point.
For the remainder of the data, the center must be close to 0,0 in this projection.
At least one of the blue points is substantially closer to the red center than to the blue in the first two principal components. The result does not appear to be produced by Voronoi cells. | Clusterings that can be caused by K-means | Since D contains a single point only, its center is exactly at this point.
For the remainder of the data, the center must be close to 0,0 in this projection.
At least one of the blue points is substan | Clusterings that can be caused by K-means
Since D contains a single point only, its center is exactly at this point.
For the remainder of the data, the center must be close to 0,0 in this projection.
At least one of the blue points is substantially closer to the red center than to the blue in the first two principal components. The result does not appear to be produced by Voronoi cells. | Clusterings that can be caused by K-means
Since D contains a single point only, its center is exactly at this point.
For the remainder of the data, the center must be close to 0,0 in this projection.
At least one of the blue points is substan |
34,172 | Clusterings that can be caused by K-means | This is not a direct answer to your question, but I don't understand how the set-up your teacher suggests, i.e. first applying PCA then looking for clusters, makes sense:
If the dataset has a clustered structure, the dimensional reduction obtained through PCA is not guaranteed to respect this structure whatsoever. In your figures, PC1 and PC2 will only give you the variables (or linear combinations of variables) that capture the most variation in the data.
Put differently: if you hypothesise from the onset that the dataset contains clusters, the most important features are clearly the ones that discriminate between clusters, which, in general do not coincide with the directions of great variations in the whole dataset.
In such a scenario what makes more sense is to first cluster (without any dimensionality reduction) and then perform LDA or XCA, or something similar that preserves the class/cluster discriminatory information. | Clusterings that can be caused by K-means | This is not a direct answer to your question, but I don't understand how the set-up your teacher suggests, i.e. first applying PCA then looking for clusters, makes sense:
If the dataset has a cluster | Clusterings that can be caused by K-means
This is not a direct answer to your question, but I don't understand how the set-up your teacher suggests, i.e. first applying PCA then looking for clusters, makes sense:
If the dataset has a clustered structure, the dimensional reduction obtained through PCA is not guaranteed to respect this structure whatsoever. In your figures, PC1 and PC2 will only give you the variables (or linear combinations of variables) that capture the most variation in the data.
Put differently: if you hypothesise from the onset that the dataset contains clusters, the most important features are clearly the ones that discriminate between clusters, which, in general do not coincide with the directions of great variations in the whole dataset.
In such a scenario what makes more sense is to first cluster (without any dimensionality reduction) and then perform LDA or XCA, or something similar that preserves the class/cluster discriminatory information. | Clusterings that can be caused by K-means
This is not a direct answer to your question, but I don't understand how the set-up your teacher suggests, i.e. first applying PCA then looking for clusters, makes sense:
If the dataset has a cluster |
34,173 | what if the residual series from arima() not looks normal? | When you use MLE a distributional assumption is applied, in this case probably Gaussian. So, if your Gaussian assumption doe not hold, then your likelihood function is messed up, and MLE is not reliable.
The QQ plot does not look good, it shows fatter tails than a normal distribution would have. You can test normality assumption using a number of tests such as Jarque Bera test. I bet they'll all reject the normality.
The first and the simplest thing to try is log-transform. The look of your QQ-plot reminds me of lognormal distribution. You could look at the histogram of residuals and lognormal fit, or simply take the log of the variable re-fit ARIMA, then look at the residuals, I bet they'll look much more normal.
I know some people on this board will suggest to ignore the non-normality of residuals, act as if you never cared for it "because you have a lot of (1200) observations". My stance on this is that if you use normality in any way, such as in your likelihood function, and normality assumption does not hold then you can't use the model.
I suggest you use the models, which do not assume normality, in this case. For example, you could try to fit t-distributed errors. In MATLAB there's an option to use t-distribution in arima class, there could be an option in R too. In any case it would be easy to modify R code, all you need is a new likelihood function, which can be found in a number of places such as MATLAB help.
Another option is to represent ARIMA in state-space form, see e.g. Shumway and Stoffer chapter 6, then use non-Gaussian errors, which is explained in section 6.10, particularly Example 6.23. | what if the residual series from arima() not looks normal? | When you use MLE a distributional assumption is applied, in this case probably Gaussian. So, if your Gaussian assumption doe not hold, then your likelihood function is messed up, and MLE is not reliab | what if the residual series from arima() not looks normal?
When you use MLE a distributional assumption is applied, in this case probably Gaussian. So, if your Gaussian assumption doe not hold, then your likelihood function is messed up, and MLE is not reliable.
The QQ plot does not look good, it shows fatter tails than a normal distribution would have. You can test normality assumption using a number of tests such as Jarque Bera test. I bet they'll all reject the normality.
The first and the simplest thing to try is log-transform. The look of your QQ-plot reminds me of lognormal distribution. You could look at the histogram of residuals and lognormal fit, or simply take the log of the variable re-fit ARIMA, then look at the residuals, I bet they'll look much more normal.
I know some people on this board will suggest to ignore the non-normality of residuals, act as if you never cared for it "because you have a lot of (1200) observations". My stance on this is that if you use normality in any way, such as in your likelihood function, and normality assumption does not hold then you can't use the model.
I suggest you use the models, which do not assume normality, in this case. For example, you could try to fit t-distributed errors. In MATLAB there's an option to use t-distribution in arima class, there could be an option in R too. In any case it would be easy to modify R code, all you need is a new likelihood function, which can be found in a number of places such as MATLAB help.
Another option is to represent ARIMA in state-space form, see e.g. Shumway and Stoffer chapter 6, then use non-Gaussian errors, which is explained in section 6.10, particularly Example 6.23. | what if the residual series from arima() not looks normal?
When you use MLE a distributional assumption is applied, in this case probably Gaussian. So, if your Gaussian assumption doe not hold, then your likelihood function is messed up, and MLE is not reliab |
34,174 | what if the residual series from arima() not looks normal? | You might need to identify Intervention Variables like Pulses, Seasonal Pulses, Level Shifts or Local Time trends. If these are untreated they inflate the variance of the errors and you get a downwards bias in the ACF of the errors, incorrectly suggesting randomness. Additionally you might need to incorporate lags of your predictors to properly account for their impact. Additionally you might need to use GLS (weighted least squares) or a power transform to deal with non-constant error variance. Finally the parameters of your model might be changing over time requiring segmentation of your data as suggested by the Chow Test.
Commercial software is available to do these things or you might want to write it yourself if you have enough time and skills. One more thing there may may be day-of-the-week-effects or other deterministic structure like a particular day-of-the-month or a particular week-of-the-month effect that needs to be incorporated to make the test for randomness more correct. | what if the residual series from arima() not looks normal? | You might need to identify Intervention Variables like Pulses, Seasonal Pulses, Level Shifts or Local Time trends. If these are untreated they inflate the variance of the errors and you get a downward | what if the residual series from arima() not looks normal?
You might need to identify Intervention Variables like Pulses, Seasonal Pulses, Level Shifts or Local Time trends. If these are untreated they inflate the variance of the errors and you get a downwards bias in the ACF of the errors, incorrectly suggesting randomness. Additionally you might need to incorporate lags of your predictors to properly account for their impact. Additionally you might need to use GLS (weighted least squares) or a power transform to deal with non-constant error variance. Finally the parameters of your model might be changing over time requiring segmentation of your data as suggested by the Chow Test.
Commercial software is available to do these things or you might want to write it yourself if you have enough time and skills. One more thing there may may be day-of-the-week-effects or other deterministic structure like a particular day-of-the-month or a particular week-of-the-month effect that needs to be incorporated to make the test for randomness more correct. | what if the residual series from arima() not looks normal?
You might need to identify Intervention Variables like Pulses, Seasonal Pulses, Level Shifts or Local Time trends. If these are untreated they inflate the variance of the errors and you get a downward |
34,175 | what if the residual series from arima() not looks normal? | You should check out the "rugarch" package, and in particular the "ARFIMA" class of fits. This allows you to specify a broad class of distributions included those with skew and heavy tails:
http://cran.r-project.org/web/packages/rugarch/rugarch.pdf | what if the residual series from arima() not looks normal? | You should check out the "rugarch" package, and in particular the "ARFIMA" class of fits. This allows you to specify a broad class of distributions included those with skew and heavy tails:
http://cr | what if the residual series from arima() not looks normal?
You should check out the "rugarch" package, and in particular the "ARFIMA" class of fits. This allows you to specify a broad class of distributions included those with skew and heavy tails:
http://cran.r-project.org/web/packages/rugarch/rugarch.pdf | what if the residual series from arima() not looks normal?
You should check out the "rugarch" package, and in particular the "ARFIMA" class of fits. This allows you to specify a broad class of distributions included those with skew and heavy tails:
http://cr |
34,176 | Deriving the optimal value for the intercept term in SVM | I have geometric explanation. Think of SVM as a maximum margin classifier. In that sense we seek separating hyperplane which will be equidistant from all negative and all positive examples. This includes that the distance from hyperplane from the closest to it's negative example would be as large as the distance to the closest positive. Let $w^*$ be known, then
$$\max_{i: y^{(i)}=-1} w^{*T}x^{(i)}$$
is the closest (worst case) distance from all possible negative examples. Similarly
$$\min_{i: y^{(i)}=1} w^{*T}x^{(i)}$$
is the closest (worst case) distance from all possible positive examples. How can we choose intercept so that the worst case distance for all (worst case) examples is maximum? Yes, we take the average of two.
The '-' sign.
Strictly speaking, $\max_{i: y^{(i)}=-1} w^{*T}x^{(i)}$ is not a distance because it is negative, while $\min_{i: y^{(i)}=1} w^{*T}x^{(i)}>0$. So in order to bring hyperplane from the worst negative to the worst positive direction we need the '-' sign. | Deriving the optimal value for the intercept term in SVM | I have geometric explanation. Think of SVM as a maximum margin classifier. In that sense we seek separating hyperplane which will be equidistant from all negative and all positive examples. This inclu | Deriving the optimal value for the intercept term in SVM
I have geometric explanation. Think of SVM as a maximum margin classifier. In that sense we seek separating hyperplane which will be equidistant from all negative and all positive examples. This includes that the distance from hyperplane from the closest to it's negative example would be as large as the distance to the closest positive. Let $w^*$ be known, then
$$\max_{i: y^{(i)}=-1} w^{*T}x^{(i)}$$
is the closest (worst case) distance from all possible negative examples. Similarly
$$\min_{i: y^{(i)}=1} w^{*T}x^{(i)}$$
is the closest (worst case) distance from all possible positive examples. How can we choose intercept so that the worst case distance for all (worst case) examples is maximum? Yes, we take the average of two.
The '-' sign.
Strictly speaking, $\max_{i: y^{(i)}=-1} w^{*T}x^{(i)}$ is not a distance because it is negative, while $\min_{i: y^{(i)}=1} w^{*T}x^{(i)}>0$. So in order to bring hyperplane from the worst negative to the worst positive direction we need the '-' sign. | Deriving the optimal value for the intercept term in SVM
I have geometric explanation. Think of SVM as a maximum margin classifier. In that sense we seek separating hyperplane which will be equidistant from all negative and all positive examples. This inclu |
34,177 | Deriving the optimal value for the intercept term in SVM | First, for support vectors the decision boundaries are given by $\omega^{*T}x^{(i)} + b = \pm 1$, and $\frac{-b}{||\omega||}$ is the distance from the origin to the hyperplane.
The closest positive and negative examples to the separating hyperplane are,
$argmax_{i:y^{(i)} = -1} \omega^{*T}x^{(i)}$, resp. $argmin_{i:y^{(i)} = 1} \omega^{*T}x^{(i)}$
These verify (because the must be support vectors) the equations for the decision boundaries, that is,
$max_{i:y^{(i)} = -1} \omega^{*T}x^{(i)} + b = -1$, resp. $min_{i:y^{(i)} = 1} \omega^{*T}x^{(i)} + b = 1$
Add the two and solve for $b$.
P.S. why is $\frac{-b}{||\omega||}$ is the distance from the origin to the hyperplane?
We could solve it with some algebra (like here), or as a optimization problem :)
The distance to a line is the norm of the vector point closest to the origin. That is, we would like to solve,
$$
min ||x||^{2}
$$ subject to $\omega^{T}x + b = 0$. By introducing Lagrange multipliers we get,
$$
L = \frac{1}{2}||x||^{2}-\lambda(\omega^{T}x + b)
$$
If we derive with respect to $x$, equal to zero and solve for $x$, we get $x=\lambda \omega$. Subtitute back in the constraint and find $\lambda = \frac{-b}{||\omega||^{2}}$. | Deriving the optimal value for the intercept term in SVM | First, for support vectors the decision boundaries are given by $\omega^{*T}x^{(i)} + b = \pm 1$, and $\frac{-b}{||\omega||}$ is the distance from the origin to the hyperplane.
The closest positive an | Deriving the optimal value for the intercept term in SVM
First, for support vectors the decision boundaries are given by $\omega^{*T}x^{(i)} + b = \pm 1$, and $\frac{-b}{||\omega||}$ is the distance from the origin to the hyperplane.
The closest positive and negative examples to the separating hyperplane are,
$argmax_{i:y^{(i)} = -1} \omega^{*T}x^{(i)}$, resp. $argmin_{i:y^{(i)} = 1} \omega^{*T}x^{(i)}$
These verify (because the must be support vectors) the equations for the decision boundaries, that is,
$max_{i:y^{(i)} = -1} \omega^{*T}x^{(i)} + b = -1$, resp. $min_{i:y^{(i)} = 1} \omega^{*T}x^{(i)} + b = 1$
Add the two and solve for $b$.
P.S. why is $\frac{-b}{||\omega||}$ is the distance from the origin to the hyperplane?
We could solve it with some algebra (like here), or as a optimization problem :)
The distance to a line is the norm of the vector point closest to the origin. That is, we would like to solve,
$$
min ||x||^{2}
$$ subject to $\omega^{T}x + b = 0$. By introducing Lagrange multipliers we get,
$$
L = \frac{1}{2}||x||^{2}-\lambda(\omega^{T}x + b)
$$
If we derive with respect to $x$, equal to zero and solve for $x$, we get $x=\lambda \omega$. Subtitute back in the constraint and find $\lambda = \frac{-b}{||\omega||^{2}}$. | Deriving the optimal value for the intercept term in SVM
First, for support vectors the decision boundaries are given by $\omega^{*T}x^{(i)} + b = \pm 1$, and $\frac{-b}{||\omega||}$ is the distance from the origin to the hyperplane.
The closest positive an |
34,178 | Deriving the optimal value for the intercept term in SVM | I know it's late but just in case it helps I'll give an equivalent explanation to the earlier responses which may also help.
Firstly, our primal problem here is:
$$ \min_w \frac{1}{2}\lVert{w}\rVert^2$$
$$ s.t. \rightarrow y^i(w^Tx^i+b)\geq1=\hat{\gamma}$$
From this primal problem and just like jpmuc says, the closest data points ($x^i$) of the training set to the decision boundary will satisfy:
$$\min_{y^i=1} (w^{*T}x^i) + b^*= 1 \iff y^i=1$$
and
$$\max_{y^i=-1}(w^{*T}x^i) + b^*= -1 \iff y^i=-1$$
This is because we have earlier set the functional margin of the whole dataset ($\hat{\gamma}$) to $1$.
Now, we know that the margin of the positive points to the decision boundary (hyperplane) has to be equal to the margin of the negative points to the hyperplane. Otherwise the margin of one set of the points (negative or positive) wouldn't be equally maximized.
Given this, and the two latter equations (from the primal problem) we can arrive to the desired value $b^*$ by adding them up and solving for $b^*$:
$$b^*=-\frac{\min_{y^i=1} (w^{*T}x^i) + \max_{y^i=-1} (w^{*T}x^i)}{2}$$ | Deriving the optimal value for the intercept term in SVM | I know it's late but just in case it helps I'll give an equivalent explanation to the earlier responses which may also help.
Firstly, our primal problem here is:
$$ \min_w \frac{1}{2}\lVert{w}\rVert^2 | Deriving the optimal value for the intercept term in SVM
I know it's late but just in case it helps I'll give an equivalent explanation to the earlier responses which may also help.
Firstly, our primal problem here is:
$$ \min_w \frac{1}{2}\lVert{w}\rVert^2$$
$$ s.t. \rightarrow y^i(w^Tx^i+b)\geq1=\hat{\gamma}$$
From this primal problem and just like jpmuc says, the closest data points ($x^i$) of the training set to the decision boundary will satisfy:
$$\min_{y^i=1} (w^{*T}x^i) + b^*= 1 \iff y^i=1$$
and
$$\max_{y^i=-1}(w^{*T}x^i) + b^*= -1 \iff y^i=-1$$
This is because we have earlier set the functional margin of the whole dataset ($\hat{\gamma}$) to $1$.
Now, we know that the margin of the positive points to the decision boundary (hyperplane) has to be equal to the margin of the negative points to the hyperplane. Otherwise the margin of one set of the points (negative or positive) wouldn't be equally maximized.
Given this, and the two latter equations (from the primal problem) we can arrive to the desired value $b^*$ by adding them up and solving for $b^*$:
$$b^*=-\frac{\min_{y^i=1} (w^{*T}x^i) + \max_{y^i=-1} (w^{*T}x^i)}{2}$$ | Deriving the optimal value for the intercept term in SVM
I know it's late but just in case it helps I'll give an equivalent explanation to the earlier responses which may also help.
Firstly, our primal problem here is:
$$ \min_w \frac{1}{2}\lVert{w}\rVert^2 |
34,179 | Variables lack correlation, but have pattern | Consider flipping your questions around.
Begin with uncorrelated data - I generated this data randomly, so these variables are independent; my y is normal and my x is log(1+X1) where X1 is a mixture of several geometric distributions chosen to give a roughly similar appearance to your plot:
The y variable is symmetric and the x-variable is mildly skew, but critically, neither of these variables is very long-tailed.
You then get many cases of relatively large values of X and Y together, because the probability that either is above its midrange (the center of the plot) is high, so the probability that both will be is also reasonably high (say, somewhere around 0.15-0.25), the product in this case of 0.5 for the y-variable and something a bit less that 0.5 for the x-variable.
What happens if you exponentiate two such variables, which are simply independent, shortish-tailed variables:
You get something broadly similar to your first plot. It makes both variables - though still independent - strongly right skew (long tailed to the right), ... and that's where the appearance comes from.
Why does it look "L" shaped? Simply because high values of the X and Y variables are both relatively rare, and the combination of the two (due to their independence) rarer still. Because for each variable, almost all the other variable's values are far below its midrange, an extreme X or Y is likely to be associated with values of the other variable below/left-of the middle of the plot.
e.g. if 5% of each distribution is above the midrange, then about 0.25% of values (i.e. not quite 1 on average) will be in the upper right quadrant.
You see pretty much the same phenomenon with any two sufficiently right-skew variables that are independent, and in many that are close to independent. Here are two independent random variables (the absolute values of t-distributed random variables with 1.5 d.f. and different scales): | Variables lack correlation, but have pattern | Consider flipping your questions around.
Begin with uncorrelated data - I generated this data randomly, so these variables are independent; my y is normal and my x is log(1+X1) where X1 is a mixture o | Variables lack correlation, but have pattern
Consider flipping your questions around.
Begin with uncorrelated data - I generated this data randomly, so these variables are independent; my y is normal and my x is log(1+X1) where X1 is a mixture of several geometric distributions chosen to give a roughly similar appearance to your plot:
The y variable is symmetric and the x-variable is mildly skew, but critically, neither of these variables is very long-tailed.
You then get many cases of relatively large values of X and Y together, because the probability that either is above its midrange (the center of the plot) is high, so the probability that both will be is also reasonably high (say, somewhere around 0.15-0.25), the product in this case of 0.5 for the y-variable and something a bit less that 0.5 for the x-variable.
What happens if you exponentiate two such variables, which are simply independent, shortish-tailed variables:
You get something broadly similar to your first plot. It makes both variables - though still independent - strongly right skew (long tailed to the right), ... and that's where the appearance comes from.
Why does it look "L" shaped? Simply because high values of the X and Y variables are both relatively rare, and the combination of the two (due to their independence) rarer still. Because for each variable, almost all the other variable's values are far below its midrange, an extreme X or Y is likely to be associated with values of the other variable below/left-of the middle of the plot.
e.g. if 5% of each distribution is above the midrange, then about 0.25% of values (i.e. not quite 1 on average) will be in the upper right quadrant.
You see pretty much the same phenomenon with any two sufficiently right-skew variables that are independent, and in many that are close to independent. Here are two independent random variables (the absolute values of t-distributed random variables with 1.5 d.f. and different scales): | Variables lack correlation, but have pattern
Consider flipping your questions around.
Begin with uncorrelated data - I generated this data randomly, so these variables are independent; my y is normal and my x is log(1+X1) where X1 is a mixture o |
34,180 | Drawing from the multivariate Student's t-distribution | The Wikipedia article on multivariate t explains that when $Y$ has a $N(0, \Sigma)$ distribution and independently $U$ has a $\chi_\nu^2$ distribution, then
$$X = \mu + \frac{Y}{\sqrt{\frac{U}{\nu}}} = \mu + Y\sqrt{\frac{\nu}{U}}$$
has a $t_\nu(\mu, \Sigma)$ distribution.
This generalizes the univariate case of Student's t, which is the ratio of a standard Normal and a (scaled) $\chi$ variate: we recognize in this formula the classic ratio of a deviation (expected to be zero) to a standard error, which is predicted by the null hypothesis of the Student t-test.
Whence realizations of $X$ ($p$-vectors) can be had from the same algebraic combination of independent realizations of $Y$ (also $p$-vectors) and $U$ (numbers), at a cost therefore of generating $p+1$ random variates for every $p$ coefficients of $X$: that's reasonably efficient.
This R code illustrates the case $p=2$.
library(MASS) # mvrnorm()
mu <- c(7, 5); sigma <- matrix(c(1, 1/2, 1/2, 1), 2); nu <- 4
n <- 4e3 # Number of draws
y <- t(t(mvrnorm(n, rep(0, length(mu)), sigma) * sqrt(nu / rchisq(n, nu))) + mu)
You can check that colMeans(y) approximates mu, var(y) approximates sigma multiplied by $\nu/(\nu-2)$ (an observation kindly offered by Stéphane Laurent, whose claim is justified because the variance of a Student t distribution is $\nu/(\nu-2)$), and you can plot(y) to see the distribution. | Drawing from the multivariate Student's t-distribution | The Wikipedia article on multivariate t explains that when $Y$ has a $N(0, \Sigma)$ distribution and independently $U$ has a $\chi_\nu^2$ distribution, then
$$X = \mu + \frac{Y}{\sqrt{\frac{U}{\nu}}} | Drawing from the multivariate Student's t-distribution
The Wikipedia article on multivariate t explains that when $Y$ has a $N(0, \Sigma)$ distribution and independently $U$ has a $\chi_\nu^2$ distribution, then
$$X = \mu + \frac{Y}{\sqrt{\frac{U}{\nu}}} = \mu + Y\sqrt{\frac{\nu}{U}}$$
has a $t_\nu(\mu, \Sigma)$ distribution.
This generalizes the univariate case of Student's t, which is the ratio of a standard Normal and a (scaled) $\chi$ variate: we recognize in this formula the classic ratio of a deviation (expected to be zero) to a standard error, which is predicted by the null hypothesis of the Student t-test.
Whence realizations of $X$ ($p$-vectors) can be had from the same algebraic combination of independent realizations of $Y$ (also $p$-vectors) and $U$ (numbers), at a cost therefore of generating $p+1$ random variates for every $p$ coefficients of $X$: that's reasonably efficient.
This R code illustrates the case $p=2$.
library(MASS) # mvrnorm()
mu <- c(7, 5); sigma <- matrix(c(1, 1/2, 1/2, 1), 2); nu <- 4
n <- 4e3 # Number of draws
y <- t(t(mvrnorm(n, rep(0, length(mu)), sigma) * sqrt(nu / rchisq(n, nu))) + mu)
You can check that colMeans(y) approximates mu, var(y) approximates sigma multiplied by $\nu/(\nu-2)$ (an observation kindly offered by Stéphane Laurent, whose claim is justified because the variance of a Student t distribution is $\nu/(\nu-2)$), and you can plot(y) to see the distribution. | Drawing from the multivariate Student's t-distribution
The Wikipedia article on multivariate t explains that when $Y$ has a $N(0, \Sigma)$ distribution and independently $U$ has a $\chi_\nu^2$ distribution, then
$$X = \mu + \frac{Y}{\sqrt{\frac{U}{\nu}}} |
34,181 | Drawing from the multivariate Student's t-distribution | Simulations with four different packages and plot:
# variance-covariance matrix :
Sigma <- matrix(rbind(c(2,1),
c(1,3)),
nrow=2)
# mean
Mu <- c(0,0)
# degrees of freedom
df <- 30
# number of simulations
nsims <- 1000
# sampling function
sampling <- function(pkg){
switch(pkg,
"mnormt" = mnormt::rmt(nsims, mean=Mu, S=Sigma, df=df),
"mvtnorm" = mvtnorm::rmvt(nsims, sigma=Sigma, df=df) +
matrix(rep(Mu,nsims), ncol=2, byrow=TRUE),
"LaplacesDemon" = LaplacesDemon::rmvt(nsims, mu=Mu, S=Sigma, df=df),
"mixAK" = mixAK::rMVT(nsims, df=df, mu=Mu, Sigma=Sigma)$x
)
}
# sampling
pkgs <- c("mnormt", "mvtnorm", "LaplacesDemon", "mixAK")
sims <- vapply(pkgs,
FUN=sampling, FUN.VALUE=matrix(0, nrow=nsims, ncol=2))
# dataframe for ggplot2
dat <- setNames(cbind(rep(pkgs,each=nsims),
data.frame(do.call(rbind, plyr::alply(sims, 3)))),
c("pkg", "x", "y"))
# plot
library(ggplot2)
ggplot(dat, aes(x=x, y=y)) +
geom_point() +
facet_grid(.~pkg)
Note:
mvtnorm::rmvt allows a vector of noncentrality parameters.
Benchmarks
> library(microbenchmark)
> microbenchmark(
+ mnormt = sampling("mnormt"),
+ mvtnorm = sampling("mvtnorm"),
+ LaplacesDemon = sampling("LaplacesDemon"),
+ mixAK = sampling("mixAK"),
+ times=100
+ )
Unit: microseconds
expr min lq mean median uq max neval cld
mnormt 327.989 346.509 402.5122 360.5655 383.9930 3537.376 100 a
mvtnorm 518.982 554.235 615.9864 571.4160 604.8840 3814.493 100 b
LaplacesDemon 375.737 408.536 461.7511 422.5930 437.5425 3646.705 100 a
mixAK 875.530 911.677 938.2057 927.0720 948.2685 1237.434 100 c
Update
I've just discovered the mvnfast package, it is the winner.
df <- 5
p <- 6
Mu <- rep(1, p)
Sigma <- toeplitz(p:1)
sampling <- function(pkg, nsims=1000){
switch(pkg,
"mnormt" = mnormt::rmt(nsims, mean=Mu, S=Sigma, df=df),
"mvtnorm" = sweep(mvtnorm::rmvt(nsims, sigma=Sigma, df=df), 2, Mu, "+"),
"mvnfast" = mvnfast::rmvt(nsims, mu=Mu, sigma=Sigma, df=df)
)
}
> microbenchmark(
+ mnormt = sampling("mnormt"),
+ mvtnorm = sampling("mvtnorm"),
+ mvnfast = sampling("mvnfast"),
+ times=1000
+ )
Unit: microseconds
expr min lq mean median uq max neval
mnormt 757.723 858.573 1156.3124 908.5530 1377.555 5285.759 1000
mvtnorm 1240.112 1408.346 1956.2496 1527.7160 2253.086 98021.043 1000
mvnfast 493.099 528.799 599.8516 554.4585 673.828 3693.114 1000 | Drawing from the multivariate Student's t-distribution | Simulations with four different packages and plot:
# variance-covariance matrix :
Sigma <- matrix(rbind(c(2,1),
c(1,3)),
nrow=2)
# mean
Mu <- c(0,0)
# degrees of | Drawing from the multivariate Student's t-distribution
Simulations with four different packages and plot:
# variance-covariance matrix :
Sigma <- matrix(rbind(c(2,1),
c(1,3)),
nrow=2)
# mean
Mu <- c(0,0)
# degrees of freedom
df <- 30
# number of simulations
nsims <- 1000
# sampling function
sampling <- function(pkg){
switch(pkg,
"mnormt" = mnormt::rmt(nsims, mean=Mu, S=Sigma, df=df),
"mvtnorm" = mvtnorm::rmvt(nsims, sigma=Sigma, df=df) +
matrix(rep(Mu,nsims), ncol=2, byrow=TRUE),
"LaplacesDemon" = LaplacesDemon::rmvt(nsims, mu=Mu, S=Sigma, df=df),
"mixAK" = mixAK::rMVT(nsims, df=df, mu=Mu, Sigma=Sigma)$x
)
}
# sampling
pkgs <- c("mnormt", "mvtnorm", "LaplacesDemon", "mixAK")
sims <- vapply(pkgs,
FUN=sampling, FUN.VALUE=matrix(0, nrow=nsims, ncol=2))
# dataframe for ggplot2
dat <- setNames(cbind(rep(pkgs,each=nsims),
data.frame(do.call(rbind, plyr::alply(sims, 3)))),
c("pkg", "x", "y"))
# plot
library(ggplot2)
ggplot(dat, aes(x=x, y=y)) +
geom_point() +
facet_grid(.~pkg)
Note:
mvtnorm::rmvt allows a vector of noncentrality parameters.
Benchmarks
> library(microbenchmark)
> microbenchmark(
+ mnormt = sampling("mnormt"),
+ mvtnorm = sampling("mvtnorm"),
+ LaplacesDemon = sampling("LaplacesDemon"),
+ mixAK = sampling("mixAK"),
+ times=100
+ )
Unit: microseconds
expr min lq mean median uq max neval cld
mnormt 327.989 346.509 402.5122 360.5655 383.9930 3537.376 100 a
mvtnorm 518.982 554.235 615.9864 571.4160 604.8840 3814.493 100 b
LaplacesDemon 375.737 408.536 461.7511 422.5930 437.5425 3646.705 100 a
mixAK 875.530 911.677 938.2057 927.0720 948.2685 1237.434 100 c
Update
I've just discovered the mvnfast package, it is the winner.
df <- 5
p <- 6
Mu <- rep(1, p)
Sigma <- toeplitz(p:1)
sampling <- function(pkg, nsims=1000){
switch(pkg,
"mnormt" = mnormt::rmt(nsims, mean=Mu, S=Sigma, df=df),
"mvtnorm" = sweep(mvtnorm::rmvt(nsims, sigma=Sigma, df=df), 2, Mu, "+"),
"mvnfast" = mvnfast::rmvt(nsims, mu=Mu, sigma=Sigma, df=df)
)
}
> microbenchmark(
+ mnormt = sampling("mnormt"),
+ mvtnorm = sampling("mvtnorm"),
+ mvnfast = sampling("mvnfast"),
+ times=1000
+ )
Unit: microseconds
expr min lq mean median uq max neval
mnormt 757.723 858.573 1156.3124 908.5530 1377.555 5285.759 1000
mvtnorm 1240.112 1408.346 1956.2496 1527.7160 2253.086 98021.043 1000
mvnfast 493.099 528.799 599.8516 554.4585 673.828 3693.114 1000 | Drawing from the multivariate Student's t-distribution
Simulations with four different packages and plot:
# variance-covariance matrix :
Sigma <- matrix(rbind(c(2,1),
c(1,3)),
nrow=2)
# mean
Mu <- c(0,0)
# degrees of |
34,182 | Why do I get same results for OLS and GLS in R? | You got the same results because you didn't specify a special variance or correlation structure in the gls function. Without such options, a GLS behaves like a OLS. The advantage of a GLS model over a normal regression is the ability to specify a correlation structure (option correlation) or allowing the residual variance to differ (option weights). Let me show this with an example.
library(nlme)
set.seed(1500)
x <- rnorm(10000,100,12) # generate x with arbitrary values
y1 <- 10 + 15*x + rnorm(10000,0,5) # the first half of the dataset
y2 <- -2 - 5*x + rnorm(10000,0,15) # the 2nd half of the data set with 3 times larger residual SD (15 vs. 5)
y <- c(y1, y2)
x.new <- c(x, x)
dummy.var <- c(rep(0, length(y1)), rep(1, length(y2))) # dummy variable to distinguish the first half of the dataset (y1) from the second (y2)
# Calculate a normal regression model
lm.mod <- lm(y~x.new*dummy.var)
summary(lm.mod)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 10.27215 0.94237 10.900 <2e-16 ***
x.new 14.99691 0.00935 1603.886 <2e-16 ***
dummy.var -12.07076 1.33272 -9.057 <2e-16 ***
x.new:dummy.var -19.99891 0.01322 -1512.387 <2e-16 ***
# Calculate a GLS without any options
gls.mod.1 <- gls(y~x.new*dummy.var)
summary(gls.mod.1)
Coefficients:
Value Std.Error t-value p-value
(Intercept) 10.27215 0.9423749 10.9003 0
x.new 14.99691 0.0093504 1603.8857 0
dummy.var -12.07076 1.3327194 -9.0572 0
x.new:dummy.var -19.99891 0.0132234 -1512.3868 0
# GLS again, but allowing different residual variance for y1 and y2
gls.mod.2 <- gls(y~x.new*dummy.var, weights=varIdent(form=~1|dummy.var))
summary(gls.mod.2)
Parameter estimates:
0 1
1.000000 2.962565
Coefficients:
Value Std.Error t-value p-value
(Intercept) 10.27215 0.4262268 24.100 0
x.new 14.99691 0.0042291 3546.144 0
dummy.var -12.07076 1.3327202 -9.057 0
x.new:dummy.var -19.99891 0.0132234 -1512.386 0
# Perform a likelihood ratio test
anova(gls.mod.1, gls.mod.2)
Model df AIC BIC logLik Test L.Ratio p-value
gls.mod.1 1 5 153319.4 153358.9 -76654.69
gls.mod.2 2 6 143307.2 143354.6 -71647.61 1 vs 2 10014.15 <.0001
The first GLS model (gls.mod.1) and the normal linear regression model (lm.mod) yield exactly the same results. The GLS model allowing for different residual standard deviations (gls.mod.2) estimates the residual SD of y2 to be around 3 times larger than the residual SD of y1 which is exactly what we specified when we generated the data. The regression coefficients are practically the same, but the standard errors have changed. The likelihood ratio test (and AIC) suggests that the GLS model with the different residual variances (gls.mod.2) fits the data better than the normal model (lm.mod or gls.mod.1).
Variance and correlation structures in gls
You can specify several variance structures in the gls function and the option weights. See here for a list. For a list of correlation structures for the option correlation see here. | Why do I get same results for OLS and GLS in R? | You got the same results because you didn't specify a special variance or correlation structure in the gls function. Without such options, a GLS behaves like a OLS. The advantage of a GLS model over a | Why do I get same results for OLS and GLS in R?
You got the same results because you didn't specify a special variance or correlation structure in the gls function. Without such options, a GLS behaves like a OLS. The advantage of a GLS model over a normal regression is the ability to specify a correlation structure (option correlation) or allowing the residual variance to differ (option weights). Let me show this with an example.
library(nlme)
set.seed(1500)
x <- rnorm(10000,100,12) # generate x with arbitrary values
y1 <- 10 + 15*x + rnorm(10000,0,5) # the first half of the dataset
y2 <- -2 - 5*x + rnorm(10000,0,15) # the 2nd half of the data set with 3 times larger residual SD (15 vs. 5)
y <- c(y1, y2)
x.new <- c(x, x)
dummy.var <- c(rep(0, length(y1)), rep(1, length(y2))) # dummy variable to distinguish the first half of the dataset (y1) from the second (y2)
# Calculate a normal regression model
lm.mod <- lm(y~x.new*dummy.var)
summary(lm.mod)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 10.27215 0.94237 10.900 <2e-16 ***
x.new 14.99691 0.00935 1603.886 <2e-16 ***
dummy.var -12.07076 1.33272 -9.057 <2e-16 ***
x.new:dummy.var -19.99891 0.01322 -1512.387 <2e-16 ***
# Calculate a GLS without any options
gls.mod.1 <- gls(y~x.new*dummy.var)
summary(gls.mod.1)
Coefficients:
Value Std.Error t-value p-value
(Intercept) 10.27215 0.9423749 10.9003 0
x.new 14.99691 0.0093504 1603.8857 0
dummy.var -12.07076 1.3327194 -9.0572 0
x.new:dummy.var -19.99891 0.0132234 -1512.3868 0
# GLS again, but allowing different residual variance for y1 and y2
gls.mod.2 <- gls(y~x.new*dummy.var, weights=varIdent(form=~1|dummy.var))
summary(gls.mod.2)
Parameter estimates:
0 1
1.000000 2.962565
Coefficients:
Value Std.Error t-value p-value
(Intercept) 10.27215 0.4262268 24.100 0
x.new 14.99691 0.0042291 3546.144 0
dummy.var -12.07076 1.3327202 -9.057 0
x.new:dummy.var -19.99891 0.0132234 -1512.386 0
# Perform a likelihood ratio test
anova(gls.mod.1, gls.mod.2)
Model df AIC BIC logLik Test L.Ratio p-value
gls.mod.1 1 5 153319.4 153358.9 -76654.69
gls.mod.2 2 6 143307.2 143354.6 -71647.61 1 vs 2 10014.15 <.0001
The first GLS model (gls.mod.1) and the normal linear regression model (lm.mod) yield exactly the same results. The GLS model allowing for different residual standard deviations (gls.mod.2) estimates the residual SD of y2 to be around 3 times larger than the residual SD of y1 which is exactly what we specified when we generated the data. The regression coefficients are practically the same, but the standard errors have changed. The likelihood ratio test (and AIC) suggests that the GLS model with the different residual variances (gls.mod.2) fits the data better than the normal model (lm.mod or gls.mod.1).
Variance and correlation structures in gls
You can specify several variance structures in the gls function and the option weights. See here for a list. For a list of correlation structures for the option correlation see here. | Why do I get same results for OLS and GLS in R?
You got the same results because you didn't specify a special variance or correlation structure in the gls function. Without such options, a GLS behaves like a OLS. The advantage of a GLS model over a |
34,183 | Why do I get same results for OLS and GLS in R? | and to make it clear, in case of serial correlation of the residuals, you can just use the OLS estimation of it, e.g. gls(..., cor=corAR1(0.6)), here the 0.6, as well as the order come from OLS, you can compute them using the ar function for the residuals of OLS | Why do I get same results for OLS and GLS in R? | and to make it clear, in case of serial correlation of the residuals, you can just use the OLS estimation of it, e.g. gls(..., cor=corAR1(0.6)), here the 0.6, as well as the order come from OLS, you c | Why do I get same results for OLS and GLS in R?
and to make it clear, in case of serial correlation of the residuals, you can just use the OLS estimation of it, e.g. gls(..., cor=corAR1(0.6)), here the 0.6, as well as the order come from OLS, you can compute them using the ar function for the residuals of OLS | Why do I get same results for OLS and GLS in R?
and to make it clear, in case of serial correlation of the residuals, you can just use the OLS estimation of it, e.g. gls(..., cor=corAR1(0.6)), here the 0.6, as well as the order come from OLS, you c |
34,184 | Should the predictor variables be normally distributed for Poisson glm? | (1) No regression, Poisson or otherwise, makes any assumption about the distribution of the predictors.
(2) You should check how the residuals vary against the fitted values but they are only asymptotically normal. | Should the predictor variables be normally distributed for Poisson glm? | (1) No regression, Poisson or otherwise, makes any assumption about the distribution of the predictors.
(2) You should check how the residuals vary against the fitted values but they are only asymptot | Should the predictor variables be normally distributed for Poisson glm?
(1) No regression, Poisson or otherwise, makes any assumption about the distribution of the predictors.
(2) You should check how the residuals vary against the fitted values but they are only asymptotically normal. | Should the predictor variables be normally distributed for Poisson glm?
(1) No regression, Poisson or otherwise, makes any assumption about the distribution of the predictors.
(2) You should check how the residuals vary against the fitted values but they are only asymptot |
34,185 | Should the predictor variables be normally distributed for Poisson glm? | (got too long for a comment)
@Scortchi has covered the issues pretty well; though I wanted to make some additional comments
On the use of histograms as a way of assessing distributional assumptions:
look at [it] overall [...] by looking at a histogram of the residuals
Histograms should be used for such a purpose with some degree of caution.
Specifically, imagine you were looking at histograms of residuals for two models where you were assuming normality, and saw these:
What would you conclude about the assumption of normality in each case?
. . .
In fact they're two histograms of the same data set!
That example (with data) comes from here (see that link for more cautionary examples), and suggestions for what to do if you do use histograms. (I subtracted a value close to the mean to
make them looks like 'residuals' for the above display.)
A better choice for checking distributional assumptions may be some form of Q-Q plot, such as residuals against normal scores if you assume normality. In the case of Poisson GLMs it's kind of tricky because the shape changes as your mean changes; R offers a normality plot (qqnorm) for residuals from a GLM but there are other things you could do. | Should the predictor variables be normally distributed for Poisson glm? | (got too long for a comment)
@Scortchi has covered the issues pretty well; though I wanted to make some additional comments
On the use of histograms as a way of assessing distributional assumptions:
| Should the predictor variables be normally distributed for Poisson glm?
(got too long for a comment)
@Scortchi has covered the issues pretty well; though I wanted to make some additional comments
On the use of histograms as a way of assessing distributional assumptions:
look at [it] overall [...] by looking at a histogram of the residuals
Histograms should be used for such a purpose with some degree of caution.
Specifically, imagine you were looking at histograms of residuals for two models where you were assuming normality, and saw these:
What would you conclude about the assumption of normality in each case?
. . .
In fact they're two histograms of the same data set!
That example (with data) comes from here (see that link for more cautionary examples), and suggestions for what to do if you do use histograms. (I subtracted a value close to the mean to
make them looks like 'residuals' for the above display.)
A better choice for checking distributional assumptions may be some form of Q-Q plot, such as residuals against normal scores if you assume normality. In the case of Poisson GLMs it's kind of tricky because the shape changes as your mean changes; R offers a normality plot (qqnorm) for residuals from a GLM but there are other things you could do. | Should the predictor variables be normally distributed for Poisson glm?
(got too long for a comment)
@Scortchi has covered the issues pretty well; though I wanted to make some additional comments
On the use of histograms as a way of assessing distributional assumptions:
|
34,186 | Why must one trade off between bias and variance? | It results as a decomposition of the error function in two terms, representing "two opposing forces", in the sense that in order to reduce the bias error, you need your model to consider more possibilities to fit the data. But this on the other side increases the variance error. Also, the other way around: if your model fits too much (starts to fit noise, which you could see as non-systematic variations on your individual samples), then you need to force your parameters not to vary too wildly, and thus introducing bias.
In more intuitive terms: bias error is being systematically wrong, and variance error is about learning all tiny, accidental variations of the samples.
Take a look at this nice article for details,
http://scott.fortmann-roe.com/docs/BiasVariance.html | Why must one trade off between bias and variance? | It results as a decomposition of the error function in two terms, representing "two opposing forces", in the sense that in order to reduce the bias error, you need your model to consider more possibil | Why must one trade off between bias and variance?
It results as a decomposition of the error function in two terms, representing "two opposing forces", in the sense that in order to reduce the bias error, you need your model to consider more possibilities to fit the data. But this on the other side increases the variance error. Also, the other way around: if your model fits too much (starts to fit noise, which you could see as non-systematic variations on your individual samples), then you need to force your parameters not to vary too wildly, and thus introducing bias.
In more intuitive terms: bias error is being systematically wrong, and variance error is about learning all tiny, accidental variations of the samples.
Take a look at this nice article for details,
http://scott.fortmann-roe.com/docs/BiasVariance.html | Why must one trade off between bias and variance?
It results as a decomposition of the error function in two terms, representing "two opposing forces", in the sense that in order to reduce the bias error, you need your model to consider more possibil |
34,187 | Why must one trade off between bias and variance? | There are some good answers here. Let me fill a small gap by providing a simple answer to the question as stated: "Why must there be a tradeoff between bias and variance?"
The answer is fairly straightforward. Estimates of population parameters based on sample data will vary from sample to sample, because the sample data will vary. This means that there will be a distribution of parameter estimates under repeated sampling. To understand the pros and cons of different algorithms for estimating population parameters, we need to know about the properties of their sampling distributions. Specifically, we want to know if the sampling distribution is centered on the true value (i.e., if it's biased), and we want to know how 'wide' the sampling distribution is (i.e., how far away from the true value the estimates tend to be on average--this is the variance part).
Now it happens that there will be an estimation procedure that will have the smallest variance of all possible estimation procedures that are unbiased, but there will also often be another estimation procedure that will have even smaller variance (but which will be biased). In this situation, the analyst is faced with a decision regarding which procedure they want to use, depending on whether unbiasedness or lower variance is more important to them in that situation.
In sum: there must be a tradeoff between bias and variance anytime there is more than one possible estimation procedure where the one with the minimum variance of all unbiased procedures is not the procedure with the minimum variance overall. | Why must one trade off between bias and variance? | There are some good answers here. Let me fill a small gap by providing a simple answer to the question as stated: "Why must there be a tradeoff between bias and variance?"
The answer is fairly str | Why must one trade off between bias and variance?
There are some good answers here. Let me fill a small gap by providing a simple answer to the question as stated: "Why must there be a tradeoff between bias and variance?"
The answer is fairly straightforward. Estimates of population parameters based on sample data will vary from sample to sample, because the sample data will vary. This means that there will be a distribution of parameter estimates under repeated sampling. To understand the pros and cons of different algorithms for estimating population parameters, we need to know about the properties of their sampling distributions. Specifically, we want to know if the sampling distribution is centered on the true value (i.e., if it's biased), and we want to know how 'wide' the sampling distribution is (i.e., how far away from the true value the estimates tend to be on average--this is the variance part).
Now it happens that there will be an estimation procedure that will have the smallest variance of all possible estimation procedures that are unbiased, but there will also often be another estimation procedure that will have even smaller variance (but which will be biased). In this situation, the analyst is faced with a decision regarding which procedure they want to use, depending on whether unbiasedness or lower variance is more important to them in that situation.
In sum: there must be a tradeoff between bias and variance anytime there is more than one possible estimation procedure where the one with the minimum variance of all unbiased procedures is not the procedure with the minimum variance overall. | Why must one trade off between bias and variance?
There are some good answers here. Let me fill a small gap by providing a simple answer to the question as stated: "Why must there be a tradeoff between bias and variance?"
The answer is fairly str |
34,188 | Why must one trade off between bias and variance? | In general, this is about finding a compromise between a) cases where Hypothesis NULL is true, but is rejected and b) cases where Hypothesis NULL is wrong, but fails to be rejected.
This is a very vague topic, but restricting to Hypothesis-testing, I suggest going through: Type I and Type II errors involved.
And also, if possible do mention what learning algorithms you are referring to. Thanks! | Why must one trade off between bias and variance? | In general, this is about finding a compromise between a) cases where Hypothesis NULL is true, but is rejected and b) cases where Hypothesis NULL is wrong, but fails to be rejected.
This is a very va | Why must one trade off between bias and variance?
In general, this is about finding a compromise between a) cases where Hypothesis NULL is true, but is rejected and b) cases where Hypothesis NULL is wrong, but fails to be rejected.
This is a very vague topic, but restricting to Hypothesis-testing, I suggest going through: Type I and Type II errors involved.
And also, if possible do mention what learning algorithms you are referring to. Thanks! | Why must one trade off between bias and variance?
In general, this is about finding a compromise between a) cases where Hypothesis NULL is true, but is rejected and b) cases where Hypothesis NULL is wrong, but fails to be rejected.
This is a very va |
34,189 | Why must one trade off between bias and variance? | A bias / variance trade off exists anytime a non-parametric model is specified. A machine learning algorithm might be used to determine the bin width for a non-parametric model. To see why there is a bias-variance trade off, think about a toy example where we model weight as a function of calories.
Imagine that your independent variable, calories consumed, is continuously valued and ranges from 2,000 to 4,000 calories.
If we had to guess the average weight for a particular individual drawn at random from the entire sample, our best guess would be the average weight across all levels of calorie consumption in our sample. This guess may not be the most accurate guess we can come up with, because it doesn't take into account any individual characteristics. Although the guess may not be the most accurate (may be biased), it also has a low variance. It may be biased because our prediction for weight is the same regardless of whether we are told that an individual consumes 0 or 1,000,000 calories in a day. The variance is low because adding or removing an observation doesn't change our average weight of the sample by much if our sample size is large.
If we consider calorie consumption, our guess gets a little bit better. Consider running a regression where we model weight as a function of an intercept term and a term describing the daily caloric intake of an individual. The intercept tells us the average weight within the sample. The coefficient on "calories" tells us that our best guess for weight will change by "Beta" for every additional calorie consumed in a day.
But, non-parametric regression goes one step further. Consider this idea: the marginal effect of an additional calorie depends on how many calories the individual usually consumes in a day. Consider two cases - an emaciated adolescent compared with an Olympic Athlete. Perhaps the adolescent is only consuming 1,500 calories in a day. Because this amount is deficient, the marginal effect of an additional calorie is large. Consuming more food in a day for the child means gaining weight (in a possibly healthy way). In the case of the Olympic Athlete, perhaps they burn everything they consume due to rigorous training schedules. In this case, we may consider that consuming an additional calorie has little effect on weight.
So, perhaps increased caloric intake has a diminishing marginal effect on an individual's weight.
If we were to incorporate this into our model, we may create "bins" which partition our independent variable, "daily caloric intake" in a way that better explains our dependent variable, "weight". Usually when creating non-parametric models, we might assume that our data are uniformly and evenly distributed within each bin.
Start by incorporating two bins into our model: one for individuals who are "calorie deficient" (below 2,500 calories / day) and one for individuals who are "calorie sufficient" (above 2,500 calories / day). Regressing weight as a function of caloric intake, as well as indicator variables for "calorie deficient" and "calorie sufficient" may tell us a better story. We may realize there is a new relationship between calories and weight, and that our "Beta" coefficient on "calories" has now changed because we removed some bias. But we also have new marginal effects on top of that. The coefficients on our indicator variables describe how the marginal effect of an additional calorie changes depending on how many calories the individual usually consumes.
By creating bins, we are forcing our model to "predict the average weight within each bin". As the width of the bins decreases (as our bins get smaller and include a smaller range of caloric intake), the average weight in each bin converges to the observed weights in each bin, because the average is based off of fewer data points with a smaller range. However, the smaller number of observations means that this average comes with a higher variance. Changing one observation has a large effect on our average guess within each bin.
At the extreme, we can create bins with only one observation. The average of this bin will be equivalent to the observed level of caloric intake, which implies that our estimator has 0 bias. However, the variance is very large because our sample within each bin is very small (size of 1), and our average is very susceptible to changes in our sample. If we randomly resampled from our population, our estimator for a particular bin would surely be different. Our estimator has lots of variance, but is not biased.
As the width of bins increases (as our bins get larger and include a larger range of caloric intake), the average weight in each bin may have additional bias. We are forcing the marginal effect of a calorie to be the same within a larger group of individuals, when in reality this may not be the case. However, adding or removing an observation within this bin has very little effect on our estimator (the variance of our estimator is very low).
So, in general: non-parametric regressions suffer from a bias-variance trade off. Partitioning data into smaller bins means that our estimators for each bin will have less bias at the cost of our estimators having a high variance, whereas partitioning data into larger bins means that our estimators for each bin will have less variance at the cost of having more bias. Consider the attributes of your average "guess" within each bin and how they will change as the size of the bins changes: 1 data point or observation in a bin implies a "perfect" average which is very susceptible to changes in data (large variance), versus an infinite number of points in a bin which implies an imperfect average (the average doesn't perfectly guess every point in the bin) with very little variance (adding / dropping an observation has little to no effect). | Why must one trade off between bias and variance? | A bias / variance trade off exists anytime a non-parametric model is specified. A machine learning algorithm might be used to determine the bin width for a non-parametric model. To see why there is a | Why must one trade off between bias and variance?
A bias / variance trade off exists anytime a non-parametric model is specified. A machine learning algorithm might be used to determine the bin width for a non-parametric model. To see why there is a bias-variance trade off, think about a toy example where we model weight as a function of calories.
Imagine that your independent variable, calories consumed, is continuously valued and ranges from 2,000 to 4,000 calories.
If we had to guess the average weight for a particular individual drawn at random from the entire sample, our best guess would be the average weight across all levels of calorie consumption in our sample. This guess may not be the most accurate guess we can come up with, because it doesn't take into account any individual characteristics. Although the guess may not be the most accurate (may be biased), it also has a low variance. It may be biased because our prediction for weight is the same regardless of whether we are told that an individual consumes 0 or 1,000,000 calories in a day. The variance is low because adding or removing an observation doesn't change our average weight of the sample by much if our sample size is large.
If we consider calorie consumption, our guess gets a little bit better. Consider running a regression where we model weight as a function of an intercept term and a term describing the daily caloric intake of an individual. The intercept tells us the average weight within the sample. The coefficient on "calories" tells us that our best guess for weight will change by "Beta" for every additional calorie consumed in a day.
But, non-parametric regression goes one step further. Consider this idea: the marginal effect of an additional calorie depends on how many calories the individual usually consumes in a day. Consider two cases - an emaciated adolescent compared with an Olympic Athlete. Perhaps the adolescent is only consuming 1,500 calories in a day. Because this amount is deficient, the marginal effect of an additional calorie is large. Consuming more food in a day for the child means gaining weight (in a possibly healthy way). In the case of the Olympic Athlete, perhaps they burn everything they consume due to rigorous training schedules. In this case, we may consider that consuming an additional calorie has little effect on weight.
So, perhaps increased caloric intake has a diminishing marginal effect on an individual's weight.
If we were to incorporate this into our model, we may create "bins" which partition our independent variable, "daily caloric intake" in a way that better explains our dependent variable, "weight". Usually when creating non-parametric models, we might assume that our data are uniformly and evenly distributed within each bin.
Start by incorporating two bins into our model: one for individuals who are "calorie deficient" (below 2,500 calories / day) and one for individuals who are "calorie sufficient" (above 2,500 calories / day). Regressing weight as a function of caloric intake, as well as indicator variables for "calorie deficient" and "calorie sufficient" may tell us a better story. We may realize there is a new relationship between calories and weight, and that our "Beta" coefficient on "calories" has now changed because we removed some bias. But we also have new marginal effects on top of that. The coefficients on our indicator variables describe how the marginal effect of an additional calorie changes depending on how many calories the individual usually consumes.
By creating bins, we are forcing our model to "predict the average weight within each bin". As the width of the bins decreases (as our bins get smaller and include a smaller range of caloric intake), the average weight in each bin converges to the observed weights in each bin, because the average is based off of fewer data points with a smaller range. However, the smaller number of observations means that this average comes with a higher variance. Changing one observation has a large effect on our average guess within each bin.
At the extreme, we can create bins with only one observation. The average of this bin will be equivalent to the observed level of caloric intake, which implies that our estimator has 0 bias. However, the variance is very large because our sample within each bin is very small (size of 1), and our average is very susceptible to changes in our sample. If we randomly resampled from our population, our estimator for a particular bin would surely be different. Our estimator has lots of variance, but is not biased.
As the width of bins increases (as our bins get larger and include a larger range of caloric intake), the average weight in each bin may have additional bias. We are forcing the marginal effect of a calorie to be the same within a larger group of individuals, when in reality this may not be the case. However, adding or removing an observation within this bin has very little effect on our estimator (the variance of our estimator is very low).
So, in general: non-parametric regressions suffer from a bias-variance trade off. Partitioning data into smaller bins means that our estimators for each bin will have less bias at the cost of our estimators having a high variance, whereas partitioning data into larger bins means that our estimators for each bin will have less variance at the cost of having more bias. Consider the attributes of your average "guess" within each bin and how they will change as the size of the bins changes: 1 data point or observation in a bin implies a "perfect" average which is very susceptible to changes in data (large variance), versus an infinite number of points in a bin which implies an imperfect average (the average doesn't perfectly guess every point in the bin) with very little variance (adding / dropping an observation has little to no effect). | Why must one trade off between bias and variance?
A bias / variance trade off exists anytime a non-parametric model is specified. A machine learning algorithm might be used to determine the bin width for a non-parametric model. To see why there is a |
34,190 | Which the best programming language to handle time series? | Both Python and R are excellent choices for this type of work.
If you are already using Python, then the easiest option might be to start using Numerical Python (NumPy). The tutorial provides a basic introduction. For further pointers, see the top answer to numpy: learning resources.
If you are interested in learning R, the following thread provides lots of pointers: Books for learning the R language. | Which the best programming language to handle time series? | Both Python and R are excellent choices for this type of work.
If you are already using Python, then the easiest option might be to start using Numerical Python (NumPy). The tutorial provides a basic | Which the best programming language to handle time series?
Both Python and R are excellent choices for this type of work.
If you are already using Python, then the easiest option might be to start using Numerical Python (NumPy). The tutorial provides a basic introduction. For further pointers, see the top answer to numpy: learning resources.
If you are interested in learning R, the following thread provides lots of pointers: Books for learning the R language. | Which the best programming language to handle time series?
Both Python and R are excellent choices for this type of work.
If you are already using Python, then the easiest option might be to start using Numerical Python (NumPy). The tutorial provides a basic |
34,191 | Which the best programming language to handle time series? | If you wind up using R, check out the FDA package. It will help you turn those repeat observations into functional data (i.e. smooth curves), opening up a variety of interesting modes of analysis.
http://cran.r-project.org/web/packages/fda/index.html
http://en.wikipedia.org/wiki/Functional_data_analysis | Which the best programming language to handle time series? | If you wind up using R, check out the FDA package. It will help you turn those repeat observations into functional data (i.e. smooth curves), opening up a variety of interesting modes of analysis.
ht | Which the best programming language to handle time series?
If you wind up using R, check out the FDA package. It will help you turn those repeat observations into functional data (i.e. smooth curves), opening up a variety of interesting modes of analysis.
http://cran.r-project.org/web/packages/fda/index.html
http://en.wikipedia.org/wiki/Functional_data_analysis | Which the best programming language to handle time series?
If you wind up using R, check out the FDA package. It will help you turn those repeat observations into functional data (i.e. smooth curves), opening up a variety of interesting modes of analysis.
ht |
34,192 | Dimensionality reduction technique to maximize separation of known clusters? | "a PCA-style rotation of the data that, instead of maximizing overall variance, maximizes inter-cluster separation". Discriminant analysis is exactly such a technique. A principal component maximizes variance along it. A discriminant function maximizes ratio between-cluster-variance/pooled-within-cluster-variance along it. | Dimensionality reduction technique to maximize separation of known clusters? | "a PCA-style rotation of the data that, instead of maximizing overall variance, maximizes inter-cluster separation". Discriminant analysis is exactly such a technique. A principal component maximizes | Dimensionality reduction technique to maximize separation of known clusters?
"a PCA-style rotation of the data that, instead of maximizing overall variance, maximizes inter-cluster separation". Discriminant analysis is exactly such a technique. A principal component maximizes variance along it. A discriminant function maximizes ratio between-cluster-variance/pooled-within-cluster-variance along it. | Dimensionality reduction technique to maximize separation of known clusters?
"a PCA-style rotation of the data that, instead of maximizing overall variance, maximizes inter-cluster separation". Discriminant analysis is exactly such a technique. A principal component maximizes |
34,193 | Dimensionality reduction technique to maximize separation of known clusters? | There is two methods that come to my mind which you might be interested in. The first is making use of known clusters and is called 'Neighbourhood components analysis' by Goldberger et al .
The idea is that you learn a mapping (eg affine) from the higher dimensional space to a visualizable space. (eg $A: \mathbb{R}^n \mapsto \mathbb{R}^2$). This mapping is estimated by maximimizing the average number of correct classification if a variation of k-nearest neighbour classification is used. There are some impressive results obtained:
The other one is tSNE, which learns a mapping (eg $A: \mathbb{R}^n \mapsto \mathbb{R}^2$). This mapping does not have any constraints, but the loss optimized (not wrt to some parametrization, but with new points in $\mathbb{R}^2$ itself) is that the new space reflects similar distances to the original space. Similar is rather complicated here, it is based on assuming certain distributions of the points in the space and the corresponding KL-divergence.
For the latter, there is matlab code which you can find at the given link. Here is a visualization of the MNIST dataset: | Dimensionality reduction technique to maximize separation of known clusters? | There is two methods that come to my mind which you might be interested in. The first is making use of known clusters and is called 'Neighbourhood components analysis' by Goldberger et al .
The idea i | Dimensionality reduction technique to maximize separation of known clusters?
There is two methods that come to my mind which you might be interested in. The first is making use of known clusters and is called 'Neighbourhood components analysis' by Goldberger et al .
The idea is that you learn a mapping (eg affine) from the higher dimensional space to a visualizable space. (eg $A: \mathbb{R}^n \mapsto \mathbb{R}^2$). This mapping is estimated by maximimizing the average number of correct classification if a variation of k-nearest neighbour classification is used. There are some impressive results obtained:
The other one is tSNE, which learns a mapping (eg $A: \mathbb{R}^n \mapsto \mathbb{R}^2$). This mapping does not have any constraints, but the loss optimized (not wrt to some parametrization, but with new points in $\mathbb{R}^2$ itself) is that the new space reflects similar distances to the original space. Similar is rather complicated here, it is based on assuming certain distributions of the points in the space and the corresponding KL-divergence.
For the latter, there is matlab code which you can find at the given link. Here is a visualization of the MNIST dataset: | Dimensionality reduction technique to maximize separation of known clusters?
There is two methods that come to my mind which you might be interested in. The first is making use of known clusters and is called 'Neighbourhood components analysis' by Goldberger et al .
The idea i |
34,194 | Dimensionality reduction technique to maximize separation of known clusters? | You might want to look at this paper:
G. Sanguinetti, Dimensionality reduction of clustered data sets, IEEE Trans. Pattern Analysis and Machine Intelligence (PAMI) 30(3), 535-540 (2008) (www)
Which describes an unsupervised version of linear discriminant analysis, I have seen some demonstrations of this and it looks like a very useful tool to have in ones toolbox.
If you already know which classes each sample belongs to, then (as ttnphns suggests) you want Linear Discriminant Analysis, Andrew Webb's book on statistical pattern recognition is a good reference book for that kind of thing. | Dimensionality reduction technique to maximize separation of known clusters? | You might want to look at this paper:
G. Sanguinetti, Dimensionality reduction of clustered data sets, IEEE Trans. Pattern Analysis and Machine Intelligence (PAMI) 30(3), 535-540 (2008) (www)
Which de | Dimensionality reduction technique to maximize separation of known clusters?
You might want to look at this paper:
G. Sanguinetti, Dimensionality reduction of clustered data sets, IEEE Trans. Pattern Analysis and Machine Intelligence (PAMI) 30(3), 535-540 (2008) (www)
Which describes an unsupervised version of linear discriminant analysis, I have seen some demonstrations of this and it looks like a very useful tool to have in ones toolbox.
If you already know which classes each sample belongs to, then (as ttnphns suggests) you want Linear Discriminant Analysis, Andrew Webb's book on statistical pattern recognition is a good reference book for that kind of thing. | Dimensionality reduction technique to maximize separation of known clusters?
You might want to look at this paper:
G. Sanguinetti, Dimensionality reduction of clustered data sets, IEEE Trans. Pattern Analysis and Machine Intelligence (PAMI) 30(3), 535-540 (2008) (www)
Which de |
34,195 | Dimensionality reduction technique to maximize separation of known clusters? | The article "A Unified Approach to PCA, PLS, MLR and CCA" (by M Borga et al) provides a compact description about various kind of linear projection methods including PCA and LDA. | Dimensionality reduction technique to maximize separation of known clusters? | The article "A Unified Approach to PCA, PLS, MLR and CCA" (by M Borga et al) provides a compact description about various kind of linear projection methods including PCA and LDA. | Dimensionality reduction technique to maximize separation of known clusters?
The article "A Unified Approach to PCA, PLS, MLR and CCA" (by M Borga et al) provides a compact description about various kind of linear projection methods including PCA and LDA. | Dimensionality reduction technique to maximize separation of known clusters?
The article "A Unified Approach to PCA, PLS, MLR and CCA" (by M Borga et al) provides a compact description about various kind of linear projection methods including PCA and LDA. |
34,196 | Dimensionality reduction technique to maximize separation of known clusters? | Partial Least Squares will do what you want. The "pls" library in R is what I've traditionally used. Here's an example that creates 3 groups of 50 points, assembles them into a data frame with group labels, and runs PLS on them:
library(MASS)
library(pls)
pts1 = mvrnorm(50,c(3,0,3),diag(c(1,1,1)))
pts2 = mvrnorm(50,c(-3,0,3),diag(c(1,1,1)))
pts3 = mvrnorm(50,c(3,3,-3),diag(c(1,1,1)))
pts = as.data.frame(rbind(pts1,pts2,pts3))
pts$labels = c(rep(1,50),rep(2,50),rep(3,50))
plsresult = plsr(labels~.,ncomp=2,data=pts)
plot(plsresult$scores,col=pts$labels) | Dimensionality reduction technique to maximize separation of known clusters? | Partial Least Squares will do what you want. The "pls" library in R is what I've traditionally used. Here's an example that creates 3 groups of 50 points, assembles them into a data frame with group | Dimensionality reduction technique to maximize separation of known clusters?
Partial Least Squares will do what you want. The "pls" library in R is what I've traditionally used. Here's an example that creates 3 groups of 50 points, assembles them into a data frame with group labels, and runs PLS on them:
library(MASS)
library(pls)
pts1 = mvrnorm(50,c(3,0,3),diag(c(1,1,1)))
pts2 = mvrnorm(50,c(-3,0,3),diag(c(1,1,1)))
pts3 = mvrnorm(50,c(3,3,-3),diag(c(1,1,1)))
pts = as.data.frame(rbind(pts1,pts2,pts3))
pts$labels = c(rep(1,50),rep(2,50),rep(3,50))
plsresult = plsr(labels~.,ncomp=2,data=pts)
plot(plsresult$scores,col=pts$labels) | Dimensionality reduction technique to maximize separation of known clusters?
Partial Least Squares will do what you want. The "pls" library in R is what I've traditionally used. Here's an example that creates 3 groups of 50 points, assembles them into a data frame with group |
34,197 | Phillips–Perron unit root test instead of ADF test? | A great advantage of Philips-Perron test is that it is non-parametric, i.e. it does not require to select the level of serial correlation as in ADF. It rather takes the same estimation scheme as in DF test, but corrects the statistic to conduct for autocorrelations and heteroscedasticity (HAC type corrections).
The main disadvantage of the PP test is that it is based on asymptotic theory. Therefore it works well only in large samples that are indeed luxury if not it comes for financial time series data. And it also shares disadvantages of ADF tests: sensitivity to structural breaks, poor small sample power too often resulting in unit root conclusions.
It is advisable to make several tests and see if the results match, if not check the properties of the time series (PP is more robust to deviations from "gentleman's" set of properties!). You may also consider Zivot-Andrew test if you believe the data has structural breaks.
I have found this lecture notes Unit Root Testing To Help Model Building by L. Mahadeva and P.Robinson useful to answer the questions. May be it will give more information to you. | Phillips–Perron unit root test instead of ADF test? | A great advantage of Philips-Perron test is that it is non-parametric, i.e. it does not require to select the level of serial correlation as in ADF. It rather takes the same estimation scheme as in DF | Phillips–Perron unit root test instead of ADF test?
A great advantage of Philips-Perron test is that it is non-parametric, i.e. it does not require to select the level of serial correlation as in ADF. It rather takes the same estimation scheme as in DF test, but corrects the statistic to conduct for autocorrelations and heteroscedasticity (HAC type corrections).
The main disadvantage of the PP test is that it is based on asymptotic theory. Therefore it works well only in large samples that are indeed luxury if not it comes for financial time series data. And it also shares disadvantages of ADF tests: sensitivity to structural breaks, poor small sample power too often resulting in unit root conclusions.
It is advisable to make several tests and see if the results match, if not check the properties of the time series (PP is more robust to deviations from "gentleman's" set of properties!). You may also consider Zivot-Andrew test if you believe the data has structural breaks.
I have found this lecture notes Unit Root Testing To Help Model Building by L. Mahadeva and P.Robinson useful to answer the questions. May be it will give more information to you. | Phillips–Perron unit root test instead of ADF test?
A great advantage of Philips-Perron test is that it is non-parametric, i.e. it does not require to select the level of serial correlation as in ADF. It rather takes the same estimation scheme as in DF |
34,198 | Phillips–Perron unit root test instead of ADF test? | Generally, Adf test is used when the errors are homoscedastic and PP test is preferred for hetroscedastic errors. | Phillips–Perron unit root test instead of ADF test? | Generally, Adf test is used when the errors are homoscedastic and PP test is preferred for hetroscedastic errors. | Phillips–Perron unit root test instead of ADF test?
Generally, Adf test is used when the errors are homoscedastic and PP test is preferred for hetroscedastic errors. | Phillips–Perron unit root test instead of ADF test?
Generally, Adf test is used when the errors are homoscedastic and PP test is preferred for hetroscedastic errors. |
34,199 | How can I obtain a confidence interval for the difference between two probabilities from a binary logistic regression model? | The delta method states
$$ \operatorname{Var}(g(X)) = [g'(X)]^2 \operatorname{Var}(X)$$
Because this problem involves two parameters, we can extend this to the multivariate delta method
$$ =\nabla g^T \, \Sigma \, \nabla g $$
Here,
$$ g = \left[e^{\beta_{0}+\beta_{1}}-e^{\beta_{0}}\right] /\left[\left(1+e^{\beta_{0}+\beta_{1}}\right)\left(1+e^{\beta_{0}}\right)\right] $$
and $\Sigma$ is the variance covariance matrix from your model. $\nabla g$ is...gross. I'm not going to do that by hand, and computer algebra while fast yields a mess of symbols. You can however use autodifferentiation compute the gradient. Once you calculate the variance, then its simply your estimate of the difference in probs plus/minus 1.96 times the standard deviation (root of the variance). Caution, this approach will yield answers below 0 or above 1.
We can do this in R in the following way (note you need to install the autodiffr package).
library(autodiffr)
g = function(b) (exp(b[1] + b[2]) - exp(b[1])) / ((1+ exp(b[1] + b[2]))*(1+exp(b[1])))
x = rbinom(100, 1, 0.5)
eta = -0.8 + 0.2*x
p = plogis(eta)
y = rbinom(100, 1, p)
model = glm(y~x, family=binomial())
Bigma = vcov(model)
grad_g = makeGradFunc(g)
nabla_g = grad_g(coef(model))
se = as.numeric(sqrt(nabla_g %*% Bigma %*% nabla_g))
estimate = diff(predict(model, newdata=list(x=c(0, 1)), type='response'))
estimate + c(-1, 1)*1.96*se
Repeating this procedure for this modest example shows that the resulting confidence interval has near nominal coverage, which is a good thing, but I imagine things would become worse as the probabilities approach 0 or 1. | How can I obtain a confidence interval for the difference between two probabilities from a binary lo | The delta method states
$$ \operatorname{Var}(g(X)) = [g'(X)]^2 \operatorname{Var}(X)$$
Because this problem involves two parameters, we can extend this to the multivariate delta method
$$ =\nabla g^T | How can I obtain a confidence interval for the difference between two probabilities from a binary logistic regression model?
The delta method states
$$ \operatorname{Var}(g(X)) = [g'(X)]^2 \operatorname{Var}(X)$$
Because this problem involves two parameters, we can extend this to the multivariate delta method
$$ =\nabla g^T \, \Sigma \, \nabla g $$
Here,
$$ g = \left[e^{\beta_{0}+\beta_{1}}-e^{\beta_{0}}\right] /\left[\left(1+e^{\beta_{0}+\beta_{1}}\right)\left(1+e^{\beta_{0}}\right)\right] $$
and $\Sigma$ is the variance covariance matrix from your model. $\nabla g$ is...gross. I'm not going to do that by hand, and computer algebra while fast yields a mess of symbols. You can however use autodifferentiation compute the gradient. Once you calculate the variance, then its simply your estimate of the difference in probs plus/minus 1.96 times the standard deviation (root of the variance). Caution, this approach will yield answers below 0 or above 1.
We can do this in R in the following way (note you need to install the autodiffr package).
library(autodiffr)
g = function(b) (exp(b[1] + b[2]) - exp(b[1])) / ((1+ exp(b[1] + b[2]))*(1+exp(b[1])))
x = rbinom(100, 1, 0.5)
eta = -0.8 + 0.2*x
p = plogis(eta)
y = rbinom(100, 1, p)
model = glm(y~x, family=binomial())
Bigma = vcov(model)
grad_g = makeGradFunc(g)
nabla_g = grad_g(coef(model))
se = as.numeric(sqrt(nabla_g %*% Bigma %*% nabla_g))
estimate = diff(predict(model, newdata=list(x=c(0, 1)), type='response'))
estimate + c(-1, 1)*1.96*se
Repeating this procedure for this modest example shows that the resulting confidence interval has near nominal coverage, which is a good thing, but I imagine things would become worse as the probabilities approach 0 or 1. | How can I obtain a confidence interval for the difference between two probabilities from a binary lo
The delta method states
$$ \operatorname{Var}(g(X)) = [g'(X)]^2 \operatorname{Var}(X)$$
Because this problem involves two parameters, we can extend this to the multivariate delta method
$$ =\nabla g^T |
34,200 | How can I obtain a confidence interval for the difference between two probabilities from a binary logistic regression model? | There are two principal approaches:
Estimate the variance $\hat{\sigma}^2$ of $\theta=p_{x1}-p_{x0}$ and assume that $\theta$ is normally distributed. Then the confidence interval is $\pm z_{1-\alpha/2} \hat{\sigma}$, where $z_{1-\alpha/2}$ is the quantile of the standard normal distribution (qnorm(1-alpha/2) in R), which is 1.96 for a 95% interval ($\alpha=0.05$).
Directly estimate a non-parametric (and possibly non-symmetrc) confidence interval with the bootstrap method.
The variance for method 1. can be estimated in different ways. One is the solution based on Gauss' error propagation law suggested by @demetri-pananos. Another method would be the Jackknife, which consists in estimating the parameter $\theta_{(i)}$ $n$ times, each time with one observable left out, and compute the Jackknife Variance therefrom:
\begin{align}
\sigma_{JK} &= \sqrt{\frac{n-1}{n}\sum_{i=1}^n \Big(\theta_{(i)}-\theta_{(.)}\Big)^2}\\
\mbox{ with }&\quad \theta_{(.)}=\frac{1}{n}\sum_{i=1}^n\theta_{(i)} \nonumber
\end{align}
Method 2. is similar to the Jackknife, but the parameter is estimated several times from observables drawn with replacement. From these estimates, the confidence interval can be estimated in different ways. In comparative studies, the "Bias Corrected Accelerated Bootstrap" had the best coverage probability. See section 6 of this report for R code how to compute it and different comparative studies (section 5.2 of the same report explains the Jackknife and lists R code how to compute it). | How can I obtain a confidence interval for the difference between two probabilities from a binary lo | There are two principal approaches:
Estimate the variance $\hat{\sigma}^2$ of $\theta=p_{x1}-p_{x0}$ and assume that $\theta$ is normally distributed. Then the confidence interval is $\pm z_{1-\alpha | How can I obtain a confidence interval for the difference between two probabilities from a binary logistic regression model?
There are two principal approaches:
Estimate the variance $\hat{\sigma}^2$ of $\theta=p_{x1}-p_{x0}$ and assume that $\theta$ is normally distributed. Then the confidence interval is $\pm z_{1-\alpha/2} \hat{\sigma}$, where $z_{1-\alpha/2}$ is the quantile of the standard normal distribution (qnorm(1-alpha/2) in R), which is 1.96 for a 95% interval ($\alpha=0.05$).
Directly estimate a non-parametric (and possibly non-symmetrc) confidence interval with the bootstrap method.
The variance for method 1. can be estimated in different ways. One is the solution based on Gauss' error propagation law suggested by @demetri-pananos. Another method would be the Jackknife, which consists in estimating the parameter $\theta_{(i)}$ $n$ times, each time with one observable left out, and compute the Jackknife Variance therefrom:
\begin{align}
\sigma_{JK} &= \sqrt{\frac{n-1}{n}\sum_{i=1}^n \Big(\theta_{(i)}-\theta_{(.)}\Big)^2}\\
\mbox{ with }&\quad \theta_{(.)}=\frac{1}{n}\sum_{i=1}^n\theta_{(i)} \nonumber
\end{align}
Method 2. is similar to the Jackknife, but the parameter is estimated several times from observables drawn with replacement. From these estimates, the confidence interval can be estimated in different ways. In comparative studies, the "Bias Corrected Accelerated Bootstrap" had the best coverage probability. See section 6 of this report for R code how to compute it and different comparative studies (section 5.2 of the same report explains the Jackknife and lists R code how to compute it). | How can I obtain a confidence interval for the difference between two probabilities from a binary lo
There are two principal approaches:
Estimate the variance $\hat{\sigma}^2$ of $\theta=p_{x1}-p_{x0}$ and assume that $\theta$ is normally distributed. Then the confidence interval is $\pm z_{1-\alpha |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.