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 |
|---|---|---|---|---|---|---|
36,001 | Understanding the different formulations for SVM | C-SVM:
$$
\begin{align}
&\text{minimize}
&t(\mathbf w,b,\xi)=
{1\over2}\|\mathbf w\|_2^2+{C\over m}\sum_{i = 1}^{m}\xi_i \\
&\text{subject to}
&\left\{\begin{matrix}
y_i(\langle\Phi(x_i),\mathbf w\rangle+b)\ge1-\xi_i &(\forall i=1,\dots,m)
\\
\xi_i \ge0
\end{matrix}\right.
\end{align}
$$
C-svc is the common SVM. The dual is:
$$
\begin{align}
&\text{minimize}
&t(\alpha)=
{1\over2}\alpha^T\hat Q\alpha-\mathbf1^T \alpha\\
&\text{subject to}
&\left\{\begin{matrix}
y^t\alpha=0
\\
\mathbf 0\le \mathbf\alpha\le {C\over m}\mathbf1
\end{matrix}\right.
\end{align}
$$
With $\hat Q_{ij} \equiv y_iy_j \Phi(x_i)^T\Phi(x_j) $.
C-BSVM:
$$
\begin{align}
&\text{minimize}
&t(\mathbf w,b,\xi)=
{1\over2}\|\mathbf w\|_2^2+{1\over2}b^2+{C\over m}\sum_{i = 1}^{m}\xi_i \\
&\text{subject to}
&\left\{\begin{matrix}
y_i(\langle\Phi(x_i),\mathbf w\rangle+b)\ge1-\xi_i &(\forall i=1,\dots,m)
\\
\xi_i \ge0
\end{matrix}\right.
\end{align}
$$
C-bsvc introduces the offset $b$ in the objective. This simplifies the dual solution, with only bound constraints remaining.
$$
\begin{align}
&\text{minimize}
&t(\alpha)=
{1\over2}\alpha^TQ\alpha-\mathbf1^T \alpha\\
&\text{subject to}
&\mathbf 0\le \mathbf\alpha\le {C\over m}\mathbf1
\end{align}
$$
With $Q_{ij} \equiv (y_iy_j \Phi(x_i)^T\Phi(x_j)+1) $
$\nu$-SVM:
$$
\begin{align}
&\text{minimize}
&t(\mathbf w,b,\xi,\rho)=
{1\over2}\|\mathbf w\|_2^2-\nu\rho+{1\over m}\sum_{i = 1}^{m}\xi_i \\
&\text{subject to}
&\left\{\begin{matrix}
y_i(\langle\Phi(x_i),\mathbf w\rangle+b)\ge\rho-\xi_i &(\forall i=1,\dots,m)
\\
\xi_i \ge0 & \rho\ge0
\end{matrix}\right.
\end{align}
$$
nu-svc has the following dual:
$$
\begin{align}
&\text{minimize}
&t(\alpha)=
{1\over2}\alpha^T\hat Q\alpha\\
&\text{subject to}
&\left\{\begin{matrix}
y^t\alpha=0
\\
\mathbf 0\le \mathbf\alpha\le {1\over m}\mathbf1
\\
\|\alpha\|_1=\sum_{i=1}^n\alpha_i\ge \nu
\end{matrix}\right.
\end{align}
$$
This means that at least $\nu$ elements of the alpha vector will be non-zero. Or, in other words, $\nu$ is a lower bound on the fraction of support vectors.
Karatzoglou, Alexandros, David Meyer, and Kurt Hornik. "Support vector machines in R." (2005).
Niu, Lingfeng, et al. "Two New Decomposition Algorithms for Training Bound-Constrained Support Vector Machines." Foundations of Computing and Decision Sciences 40.1 (2015): 67-86. | Understanding the different formulations for SVM | C-SVM:
$$
\begin{align}
&\text{minimize}
&t(\mathbf w,b,\xi)=
{1\over2}\|\mathbf w\|_2^2+{C\over m}\sum_{i = 1}^{m}\xi_i \\
&\text{subject to}
&\left\{\begin{matrix}
y_i(\langle\Phi(x_i),\mathbf w\ran | Understanding the different formulations for SVM
C-SVM:
$$
\begin{align}
&\text{minimize}
&t(\mathbf w,b,\xi)=
{1\over2}\|\mathbf w\|_2^2+{C\over m}\sum_{i = 1}^{m}\xi_i \\
&\text{subject to}
&\left\{\begin{matrix}
y_i(\langle\Phi(x_i),\mathbf w\rangle+b)\ge1-\xi_i &(\forall i=1,\dots,m)
\\
\xi_i \ge0
\end{matrix}\right.
\end{align}
$$
C-svc is the common SVM. The dual is:
$$
\begin{align}
&\text{minimize}
&t(\alpha)=
{1\over2}\alpha^T\hat Q\alpha-\mathbf1^T \alpha\\
&\text{subject to}
&\left\{\begin{matrix}
y^t\alpha=0
\\
\mathbf 0\le \mathbf\alpha\le {C\over m}\mathbf1
\end{matrix}\right.
\end{align}
$$
With $\hat Q_{ij} \equiv y_iy_j \Phi(x_i)^T\Phi(x_j) $.
C-BSVM:
$$
\begin{align}
&\text{minimize}
&t(\mathbf w,b,\xi)=
{1\over2}\|\mathbf w\|_2^2+{1\over2}b^2+{C\over m}\sum_{i = 1}^{m}\xi_i \\
&\text{subject to}
&\left\{\begin{matrix}
y_i(\langle\Phi(x_i),\mathbf w\rangle+b)\ge1-\xi_i &(\forall i=1,\dots,m)
\\
\xi_i \ge0
\end{matrix}\right.
\end{align}
$$
C-bsvc introduces the offset $b$ in the objective. This simplifies the dual solution, with only bound constraints remaining.
$$
\begin{align}
&\text{minimize}
&t(\alpha)=
{1\over2}\alpha^TQ\alpha-\mathbf1^T \alpha\\
&\text{subject to}
&\mathbf 0\le \mathbf\alpha\le {C\over m}\mathbf1
\end{align}
$$
With $Q_{ij} \equiv (y_iy_j \Phi(x_i)^T\Phi(x_j)+1) $
$\nu$-SVM:
$$
\begin{align}
&\text{minimize}
&t(\mathbf w,b,\xi,\rho)=
{1\over2}\|\mathbf w\|_2^2-\nu\rho+{1\over m}\sum_{i = 1}^{m}\xi_i \\
&\text{subject to}
&\left\{\begin{matrix}
y_i(\langle\Phi(x_i),\mathbf w\rangle+b)\ge\rho-\xi_i &(\forall i=1,\dots,m)
\\
\xi_i \ge0 & \rho\ge0
\end{matrix}\right.
\end{align}
$$
nu-svc has the following dual:
$$
\begin{align}
&\text{minimize}
&t(\alpha)=
{1\over2}\alpha^T\hat Q\alpha\\
&\text{subject to}
&\left\{\begin{matrix}
y^t\alpha=0
\\
\mathbf 0\le \mathbf\alpha\le {1\over m}\mathbf1
\\
\|\alpha\|_1=\sum_{i=1}^n\alpha_i\ge \nu
\end{matrix}\right.
\end{align}
$$
This means that at least $\nu$ elements of the alpha vector will be non-zero. Or, in other words, $\nu$ is a lower bound on the fraction of support vectors.
Karatzoglou, Alexandros, David Meyer, and Kurt Hornik. "Support vector machines in R." (2005).
Niu, Lingfeng, et al. "Two New Decomposition Algorithms for Training Bound-Constrained Support Vector Machines." Foundations of Computing and Decision Sciences 40.1 (2015): 67-86. | Understanding the different formulations for SVM
C-SVM:
$$
\begin{align}
&\text{minimize}
&t(\mathbf w,b,\xi)=
{1\over2}\|\mathbf w\|_2^2+{C\over m}\sum_{i = 1}^{m}\xi_i \\
&\text{subject to}
&\left\{\begin{matrix}
y_i(\langle\Phi(x_i),\mathbf w\ran |
36,002 | How to explain KNN in Bayesian probability? | kNN from a Bayesian viewpoint
Let suppose that we have a data set comprising $N_{k}$ points in class $\mathcal{C}_{k}$ with $N$ total points, so that $\sum_{k}N_{k} = N$.
We want to classify a new point $\mathbf{x}$ by drawing a sphere centred on $\mathbf{x}$ containing precisely $K$ points irrespective of their class. Suppose that such a sphere has volume $V$ and contains $K_{k}$ points from class $\mathcal{C}_{k}$.
Then,
$$ p(\mathbf{x}|\mathcal{C}_{k}) = \frac{K_{k}}{N_{k}V}$$
provides an estimate of the density associated with each class. Similarly, the unconditional density is given by
$$ p(\mathbf{x}) = \frac{K}{NV}, $$
while the class priors are given by
$$ p(\mathcal{C}_{k}) = \frac{N_{k}}{N}. $$
We can now combine the three equations using Bayes' theorem to obtain the posterior probability of class membership
$$ p(\mathcal{C}_{k}|\mathbf{x}) = \frac{ p(\mathbf{x}|\mathcal{C}_{k}) p(\mathcal{C}_{k})}{p(\mathbf{x})} = \frac{K_{k}}{K}. $$
If we wish to minimize the probability of misclassification, we have to assign the test point $\mathbf{x}$ to the class having the largest posterior probability, corresponding to the largest value of $\frac{K_{k}}{K}$. | How to explain KNN in Bayesian probability? | kNN from a Bayesian viewpoint
Let suppose that we have a data set comprising $N_{k}$ points in class $\mathcal{C}_{k}$ with $N$ total points, so that $\sum_{k}N_{k} = N$.
We want to classify a new po | How to explain KNN in Bayesian probability?
kNN from a Bayesian viewpoint
Let suppose that we have a data set comprising $N_{k}$ points in class $\mathcal{C}_{k}$ with $N$ total points, so that $\sum_{k}N_{k} = N$.
We want to classify a new point $\mathbf{x}$ by drawing a sphere centred on $\mathbf{x}$ containing precisely $K$ points irrespective of their class. Suppose that such a sphere has volume $V$ and contains $K_{k}$ points from class $\mathcal{C}_{k}$.
Then,
$$ p(\mathbf{x}|\mathcal{C}_{k}) = \frac{K_{k}}{N_{k}V}$$
provides an estimate of the density associated with each class. Similarly, the unconditional density is given by
$$ p(\mathbf{x}) = \frac{K}{NV}, $$
while the class priors are given by
$$ p(\mathcal{C}_{k}) = \frac{N_{k}}{N}. $$
We can now combine the three equations using Bayes' theorem to obtain the posterior probability of class membership
$$ p(\mathcal{C}_{k}|\mathbf{x}) = \frac{ p(\mathbf{x}|\mathcal{C}_{k}) p(\mathcal{C}_{k})}{p(\mathbf{x})} = \frac{K_{k}}{K}. $$
If we wish to minimize the probability of misclassification, we have to assign the test point $\mathbf{x}$ to the class having the largest posterior probability, corresponding to the largest value of $\frac{K_{k}}{K}$. | How to explain KNN in Bayesian probability?
kNN from a Bayesian viewpoint
Let suppose that we have a data set comprising $N_{k}$ points in class $\mathcal{C}_{k}$ with $N$ total points, so that $\sum_{k}N_{k} = N$.
We want to classify a new po |
36,003 | How to explain KNN in Bayesian probability? | As explained in detail in this other answer, kNN is a discriminative approach. In order to cast it in the Bayesian framework, we need a generative model, i.e. a model that tells how samples are generated. This question is developed in detail in this paper (Revisiting k-means: New Algorithms via Bayesian Nonparametrics).
The approach follows two steps: first finding a smooth version of k-means (GMM) and then use the Dirichlet Process (DP) to model the mixture of Gaussians.
The first step builds upon the asymptotic relationship between kmeans and GMM. This is necessary in order to have an efficient model of the conditional probabilities, for which we have efficient sampling algorithms.
As already said, the DP models the distribution of Gaussian mixtures which could have generated the observed data. Initially one may even have an infinite number of components!. The goal is then to find the likeliest values that could have generated the data. | How to explain KNN in Bayesian probability? | As explained in detail in this other answer, kNN is a discriminative approach. In order to cast it in the Bayesian framework, we need a generative model, i.e. a model that tells how samples are genera | How to explain KNN in Bayesian probability?
As explained in detail in this other answer, kNN is a discriminative approach. In order to cast it in the Bayesian framework, we need a generative model, i.e. a model that tells how samples are generated. This question is developed in detail in this paper (Revisiting k-means: New Algorithms via Bayesian Nonparametrics).
The approach follows two steps: first finding a smooth version of k-means (GMM) and then use the Dirichlet Process (DP) to model the mixture of Gaussians.
The first step builds upon the asymptotic relationship between kmeans and GMM. This is necessary in order to have an efficient model of the conditional probabilities, for which we have efficient sampling algorithms.
As already said, the DP models the distribution of Gaussian mixtures which could have generated the observed data. Initially one may even have an infinite number of components!. The goal is then to find the likeliest values that could have generated the data. | How to explain KNN in Bayesian probability?
As explained in detail in this other answer, kNN is a discriminative approach. In order to cast it in the Bayesian framework, we need a generative model, i.e. a model that tells how samples are genera |
36,004 | What is the intuitive (geometric?) meaning of minimizing the log determinant of a matrix? | Short answer is: The determinant plays a role because it is tied to the jacobian of the multivariate change of variables and the logarithm is tied to taking the log-likelihood.
Long Answer: Let's start with the univariate standard normal density (parameter free) which is $$\frac{1}{\sqrt{2\pi}} \exp\left(-\frac{1}{2}t^2\right).$$
When we extend (parametrize) it to $x=\sigma t + \mu$, the change of variable requires $dt=\frac{1}{\sigma}dx$ making the general normal density
$$\frac{1}{\sqrt{2\pi}} \frac{1}{\sigma}\exp\left(-\frac{1}{2}(\frac{x-\mu}{\sigma})^2\right).$$
Let us also work out the ML estimation of $\mu$ and $\sigma$ simultaneously (when both unknown). The log-likelihood is
$$\text{A constant} - \frac{n}{2}\log(\sigma^2) -\frac{1}{2}\sum_{i=1}^n\left(\frac{x_i-\mu}{\sigma}\right)^2$$ maximization of which is equivalent to minimizing
$$n \log(\sigma^2) + \sum_{i=1}^n\left(\frac{x_i-\mu}{\sigma}\right)^2$$
and both terms involving $\sigma^2$ need to be accounted for in the minimization (with respect to $\sigma^2$).
Multivariate (say number of dimensions = $d$) analogues behave the similar way. Starting with the generating (standard) density
$$\left(\sqrt{2\pi}\right)^{-d} \exp\left(-\frac{1}{2}\mathbf{z}^t\mathbf{z}\right)$$
and the general MVN density is
$$\left(\sqrt{2\pi}\right)^{-d} \left|\boldsymbol{\Sigma}\right|^{-1/2}\exp\left(-\frac{1}{2}\left(\mathbf{x}-\boldsymbol{\mu}\right)^t\boldsymbol{\Sigma}^{-1}\left(\mathbf{x}-\boldsymbol{\mu}\right)\right).$$
Observe that $\left|\boldsymbol{\Sigma}\right|^{-1/2}$ (which is the reciprocal of the square root of the determinant of the covariance matrix $\boldsymbol{\Sigma}$) in the multivariate case does what $1/\sigma$ does in the univariate case and $\boldsymbol{\Sigma}^{-1}$ does what $1/\sigma^2$ does in the univariate case. In simpler terms, $\left|\boldsymbol{\Sigma}\right|^{-1/2}$ is the change of variable "adjustment".
The maximization of likelihood would lead to minimizing (analogous to the univariate case)
$$n \log\left|\boldsymbol{\Sigma}\right| + \sum_{i=1}^n\left(\mathbf{x}-\boldsymbol{\mu}\right)^t\boldsymbol{\Sigma}^{-1}\left(\mathbf{x}-\boldsymbol{\mu}\right)$$
Again, in simpler terms, $n \log\left|\boldsymbol{\Sigma}\right|$ takes the spot of $n \log(\sigma^2)$ which was there in the univariate case. These terms account for corresponding change of variable adjustments in each scenario.
Above is based on taking $\rho(x)=x$ as in the http://arxiv.org/pdf/1206.1386v2 language. Using $\rho(x)=\frac{d}{2}\log x$ (discussed after I.5 on p.2) changes things accordingly (although, as noted in the paper this $\rho(x)$ does not give a valid density). | What is the intuitive (geometric?) meaning of minimizing the log determinant of a matrix? | Short answer is: The determinant plays a role because it is tied to the jacobian of the multivariate change of variables and the logarithm is tied to taking the log-likelihood.
Long Answer: Let's sta | What is the intuitive (geometric?) meaning of minimizing the log determinant of a matrix?
Short answer is: The determinant plays a role because it is tied to the jacobian of the multivariate change of variables and the logarithm is tied to taking the log-likelihood.
Long Answer: Let's start with the univariate standard normal density (parameter free) which is $$\frac{1}{\sqrt{2\pi}} \exp\left(-\frac{1}{2}t^2\right).$$
When we extend (parametrize) it to $x=\sigma t + \mu$, the change of variable requires $dt=\frac{1}{\sigma}dx$ making the general normal density
$$\frac{1}{\sqrt{2\pi}} \frac{1}{\sigma}\exp\left(-\frac{1}{2}(\frac{x-\mu}{\sigma})^2\right).$$
Let us also work out the ML estimation of $\mu$ and $\sigma$ simultaneously (when both unknown). The log-likelihood is
$$\text{A constant} - \frac{n}{2}\log(\sigma^2) -\frac{1}{2}\sum_{i=1}^n\left(\frac{x_i-\mu}{\sigma}\right)^2$$ maximization of which is equivalent to minimizing
$$n \log(\sigma^2) + \sum_{i=1}^n\left(\frac{x_i-\mu}{\sigma}\right)^2$$
and both terms involving $\sigma^2$ need to be accounted for in the minimization (with respect to $\sigma^2$).
Multivariate (say number of dimensions = $d$) analogues behave the similar way. Starting with the generating (standard) density
$$\left(\sqrt{2\pi}\right)^{-d} \exp\left(-\frac{1}{2}\mathbf{z}^t\mathbf{z}\right)$$
and the general MVN density is
$$\left(\sqrt{2\pi}\right)^{-d} \left|\boldsymbol{\Sigma}\right|^{-1/2}\exp\left(-\frac{1}{2}\left(\mathbf{x}-\boldsymbol{\mu}\right)^t\boldsymbol{\Sigma}^{-1}\left(\mathbf{x}-\boldsymbol{\mu}\right)\right).$$
Observe that $\left|\boldsymbol{\Sigma}\right|^{-1/2}$ (which is the reciprocal of the square root of the determinant of the covariance matrix $\boldsymbol{\Sigma}$) in the multivariate case does what $1/\sigma$ does in the univariate case and $\boldsymbol{\Sigma}^{-1}$ does what $1/\sigma^2$ does in the univariate case. In simpler terms, $\left|\boldsymbol{\Sigma}\right|^{-1/2}$ is the change of variable "adjustment".
The maximization of likelihood would lead to minimizing (analogous to the univariate case)
$$n \log\left|\boldsymbol{\Sigma}\right| + \sum_{i=1}^n\left(\mathbf{x}-\boldsymbol{\mu}\right)^t\boldsymbol{\Sigma}^{-1}\left(\mathbf{x}-\boldsymbol{\mu}\right)$$
Again, in simpler terms, $n \log\left|\boldsymbol{\Sigma}\right|$ takes the spot of $n \log(\sigma^2)$ which was there in the univariate case. These terms account for corresponding change of variable adjustments in each scenario.
Above is based on taking $\rho(x)=x$ as in the http://arxiv.org/pdf/1206.1386v2 language. Using $\rho(x)=\frac{d}{2}\log x$ (discussed after I.5 on p.2) changes things accordingly (although, as noted in the paper this $\rho(x)$ does not give a valid density). | What is the intuitive (geometric?) meaning of minimizing the log determinant of a matrix?
Short answer is: The determinant plays a role because it is tied to the jacobian of the multivariate change of variables and the logarithm is tied to taking the log-likelihood.
Long Answer: Let's sta |
36,005 | Censored regression in R | The predict() and fitted() methods for tobit objects compute the estimates for the latent mean $\mu = E[y^*] = x^\top \beta$. Additionally, the scale parameter $\sigma$ is available as $scale in the objects:
mu <- fitted(fit)
sigma <- fit$scale
The probability of a non-zero observation is then $P(y > 0) = \Phi(\mu/\sigma)$, i.e.:
p0 <- pnorm(mu/sigma)
The conditional expectation of the censored $y$ given that it is non-zero is $E[y | y > 0] = \mu + \sigma \cdot \lambda(\mu/\sigma)$, where $\lambda(\cdot)$ is the inverse Mills ratio $\lambda(x) = \phi(x)/\Phi(x)$:
lambda <- function(x) dnorm(x)/pnorm(x)
ey0 <- mu + sigma * lambda(mu/sigma)
Finally, the unconditional expectation is $E[y] = P(y > 0) \cdot E[y | y > 0]$, i.e.:
ey <- p0 * ey0
If you want to visualize everything together in a time series style plot:
plot(y, ylim = my.range)
lines(mu, col = "slategray")
lines(y.star, col = "black")
lines(ey0, col = "green")
lines(ey, col = "blue")
The reason that the predict() method for tobit objects does not provide all of this automatically is that for all the distributions other than the normal / Gaussian, the relationship is not that easy. But maybe we should at least support the normal case. | Censored regression in R | The predict() and fitted() methods for tobit objects compute the estimates for the latent mean $\mu = E[y^*] = x^\top \beta$. Additionally, the scale parameter $\sigma$ is available as $scale in the o | Censored regression in R
The predict() and fitted() methods for tobit objects compute the estimates for the latent mean $\mu = E[y^*] = x^\top \beta$. Additionally, the scale parameter $\sigma$ is available as $scale in the objects:
mu <- fitted(fit)
sigma <- fit$scale
The probability of a non-zero observation is then $P(y > 0) = \Phi(\mu/\sigma)$, i.e.:
p0 <- pnorm(mu/sigma)
The conditional expectation of the censored $y$ given that it is non-zero is $E[y | y > 0] = \mu + \sigma \cdot \lambda(\mu/\sigma)$, where $\lambda(\cdot)$ is the inverse Mills ratio $\lambda(x) = \phi(x)/\Phi(x)$:
lambda <- function(x) dnorm(x)/pnorm(x)
ey0 <- mu + sigma * lambda(mu/sigma)
Finally, the unconditional expectation is $E[y] = P(y > 0) \cdot E[y | y > 0]$, i.e.:
ey <- p0 * ey0
If you want to visualize everything together in a time series style plot:
plot(y, ylim = my.range)
lines(mu, col = "slategray")
lines(y.star, col = "black")
lines(ey0, col = "green")
lines(ey, col = "blue")
The reason that the predict() method for tobit objects does not provide all of this automatically is that for all the distributions other than the normal / Gaussian, the relationship is not that easy. But maybe we should at least support the normal case. | Censored regression in R
The predict() and fitted() methods for tobit objects compute the estimates for the latent mean $\mu = E[y^*] = x^\top \beta$. Additionally, the scale parameter $\sigma$ is available as $scale in the o |
36,006 | Multicollinearity in polynomial regression | Don't use polynomial transformations "as such", because they will be collinear, as you note. Instead, transform them into orthogonal polynomials. In R, use the poly() command.
Even better, don't use higher order polynomials at all, since they will become unstable at the boundaries of your data space. Instead, use splines. In R, look at the splines package. For more information, look at Frank Harrell's Regression Modeling Strategies. | Multicollinearity in polynomial regression | Don't use polynomial transformations "as such", because they will be collinear, as you note. Instead, transform them into orthogonal polynomials. In R, use the poly() command.
Even better, don't use h | Multicollinearity in polynomial regression
Don't use polynomial transformations "as such", because they will be collinear, as you note. Instead, transform them into orthogonal polynomials. In R, use the poly() command.
Even better, don't use higher order polynomials at all, since they will become unstable at the boundaries of your data space. Instead, use splines. In R, look at the splines package. For more information, look at Frank Harrell's Regression Modeling Strategies. | Multicollinearity in polynomial regression
Don't use polynomial transformations "as such", because they will be collinear, as you note. Instead, transform them into orthogonal polynomials. In R, use the poly() command.
Even better, don't use h |
36,007 | Cauchy distribution (likelihood and Fisher information) | The Fisher information for one observation is given by\begin{align*}I(\theta) &= -\mathbb{E}_\theta\left[\frac{\partial^2 \log f(X;\theta)}{\partial\theta^2}\right]\\ &=\mathbb{E}_\theta\left[ \frac{\partial^2 \log \{1+(X-\theta)^2\}}{\partial\theta^2}\right]\\
&=2\mathbb{E}_\theta\left[ -\frac{\partial }{\partial\theta}\frac{(X-\theta)}{1+(X-\theta)^2}\right]\\
&=2\mathbb{E}_\theta\left[\frac{1}{1+(X-\theta)^2}-\frac{2(X-\theta)^2}{[1+(X-\theta)^2]^2}\right]\\
&= \frac{2}{\pi}\int_\mathbb{R} \frac{1}{[1+(x-\theta)^2]^2}-\frac{2(x-\theta)^2}{[1+(x-\theta)^2]^3} \text{d}x\\
&= \frac{2}{\pi}\int_\mathbb{R} \frac{1}{[1+x^2]^2}-\frac{2x^2}{[1+x^2]^3} \text{d}x\\
&= \frac{2}{\pi}\int_\mathbb{R} \frac{1}{[1+x^2]^2}-\frac{2}{[1+x^2]^2}+\frac{2}{[1+x^2]^3} \text{d}x\\
&= \frac{2}{\pi}\int_\mathbb{R} \frac{-1}{[1+x^2]^2}+\frac{2}{[1+x^2]^3} \text{d}x
\end{align*}
because the integral (and the information) is translation invariant.
Now it is easy to establish a recurrence relation on$$I_k=\int_\mathbb{R} \frac{1}{[1+x^2]^k}\text{d}x$$Indeed
\begin{align*}
I_k &= \int_\mathbb{R} \frac{1+x^2}{[1+x^2]^{k+1}}\text{d}x\\
&= I_{k+1} + \int_\mathbb{R} \frac{2kx}{[1+x^2]^{k+1}}\frac{x}{2k}\text{d}x\\
&= I_{k+1} + \frac{1}{2k} \int_\mathbb{R} \frac{1}{[1+x^2]^{k}}\text{d}x
= I_{k+1} + \frac{1}{2k} I_k
\end{align*}
by an integration by parts. Hence
$$I_1=\pi\quad\text{and}\quad I_{k+1}=\frac{2k-1}{2k}I_k\quad k>1$$
which implies
$$I_1=\pi\quad I_2=\frac{\pi}{2}\quad I_3=\frac{3\pi}{8}$$
and which leads to the Fisher information:
$$I(\theta)=\frac{2}{\pi}\left\{-I_2+2I_3\right\}=\frac{2}{\pi}\left\{\frac{-\pi}{2}+\frac{3\pi}{4}\right\}=\frac{1}{2}$$ | Cauchy distribution (likelihood and Fisher information) | The Fisher information for one observation is given by\begin{align*}I(\theta) &= -\mathbb{E}_\theta\left[\frac{\partial^2 \log f(X;\theta)}{\partial\theta^2}\right]\\ &=\mathbb{E}_\theta\left[ \frac{\ | Cauchy distribution (likelihood and Fisher information)
The Fisher information for one observation is given by\begin{align*}I(\theta) &= -\mathbb{E}_\theta\left[\frac{\partial^2 \log f(X;\theta)}{\partial\theta^2}\right]\\ &=\mathbb{E}_\theta\left[ \frac{\partial^2 \log \{1+(X-\theta)^2\}}{\partial\theta^2}\right]\\
&=2\mathbb{E}_\theta\left[ -\frac{\partial }{\partial\theta}\frac{(X-\theta)}{1+(X-\theta)^2}\right]\\
&=2\mathbb{E}_\theta\left[\frac{1}{1+(X-\theta)^2}-\frac{2(X-\theta)^2}{[1+(X-\theta)^2]^2}\right]\\
&= \frac{2}{\pi}\int_\mathbb{R} \frac{1}{[1+(x-\theta)^2]^2}-\frac{2(x-\theta)^2}{[1+(x-\theta)^2]^3} \text{d}x\\
&= \frac{2}{\pi}\int_\mathbb{R} \frac{1}{[1+x^2]^2}-\frac{2x^2}{[1+x^2]^3} \text{d}x\\
&= \frac{2}{\pi}\int_\mathbb{R} \frac{1}{[1+x^2]^2}-\frac{2}{[1+x^2]^2}+\frac{2}{[1+x^2]^3} \text{d}x\\
&= \frac{2}{\pi}\int_\mathbb{R} \frac{-1}{[1+x^2]^2}+\frac{2}{[1+x^2]^3} \text{d}x
\end{align*}
because the integral (and the information) is translation invariant.
Now it is easy to establish a recurrence relation on$$I_k=\int_\mathbb{R} \frac{1}{[1+x^2]^k}\text{d}x$$Indeed
\begin{align*}
I_k &= \int_\mathbb{R} \frac{1+x^2}{[1+x^2]^{k+1}}\text{d}x\\
&= I_{k+1} + \int_\mathbb{R} \frac{2kx}{[1+x^2]^{k+1}}\frac{x}{2k}\text{d}x\\
&= I_{k+1} + \frac{1}{2k} \int_\mathbb{R} \frac{1}{[1+x^2]^{k}}\text{d}x
= I_{k+1} + \frac{1}{2k} I_k
\end{align*}
by an integration by parts. Hence
$$I_1=\pi\quad\text{and}\quad I_{k+1}=\frac{2k-1}{2k}I_k\quad k>1$$
which implies
$$I_1=\pi\quad I_2=\frac{\pi}{2}\quad I_3=\frac{3\pi}{8}$$
and which leads to the Fisher information:
$$I(\theta)=\frac{2}{\pi}\left\{-I_2+2I_3\right\}=\frac{2}{\pi}\left\{\frac{-\pi}{2}+\frac{3\pi}{4}\right\}=\frac{1}{2}$$ | Cauchy distribution (likelihood and Fisher information)
The Fisher information for one observation is given by\begin{align*}I(\theta) &= -\mathbb{E}_\theta\left[\frac{\partial^2 \log f(X;\theta)}{\partial\theta^2}\right]\\ &=\mathbb{E}_\theta\left[ \frac{\ |
36,008 | Optimal number of bins in histogram by the Freedman–Diaconis rule: difference between theoretical rate and actual number | The reason comes from the fact that the histogram function is expected to include all the data, so it must span the range of the data.
The Freedman-Diaconis rule gives a formula for the width of the bins.
The function gives a formula for the number of bins.
The relationship between number of bins and the width of bins will be impacted by the range of the data.
With Gaussian data, the expected range increases with $n$.
Here's the function:
> nclass.FD
function (x)
{
h <- stats::IQR(x)
if (h == 0)
h <- stats::mad(x, constant = 2)
if (h > 0)
ceiling(diff(range(x))/(2 * h * length(x)^(-1/3)))
else 1L
}
<bytecode: 0x086e6938>
<environment: namespace:grDevices>
diff(range(x)) is the range of the data.
So as we see, it divides the range of the data by the FD formula for bin width (and rounds up) to get the number of bins.
It seems I could have been clearer, so here's a more detailed explanation:
The actual Freedman-Diaconis rule is not a rule for the number of bins, but for the bin-width. By their analysis, the bin width should be proportional to $n^{−1/3}$. Since the total width of the histogram must be closely related to the sample range (it may be a bit wider, because of rounding up to nice numbers), and the expected range changes with $n$, the number of bins is not quite inversely proportional to bin-width, but must increase faster than that. So the number of bins should not grow as $n^{1/3}$ - close to it, but a little faster, because of the way the range comes into it.
Looking at data from Tippett's 1925 tables[1], the expected range in standard normal samples seems to grow quite slowly with $n$, though -- slower even than $\log(n)$:
(indeed, amoeba points out in comments below that it should be proportional - or nearly so - to $\sqrt{\log(n)}$, which grows more slowly than your analysis in the question seem to suggest. This makes me wonder whether there's some other issue coming in, but I haven't investigated whether this range effect fully explains your data.)
A quick look at Tippett's numbers (which go up to n=1000) suggest that the expected range in a Gaussian is very close to linear in $\sqrt{\log(n)}$ over $10\leq n\leq 1000$, but it seems to be not actually proportional for values in this range.
[1]: L. H. C. Tippett (1925). "On the Extreme Individuals and the Range of Samples Taken from a Normal Population". Biometrika 17 (3/4): 364–387 | Optimal number of bins in histogram by the Freedman–Diaconis rule: difference between theoretical ra | The reason comes from the fact that the histogram function is expected to include all the data, so it must span the range of the data.
The Freedman-Diaconis rule gives a formula for the width of the | Optimal number of bins in histogram by the Freedman–Diaconis rule: difference between theoretical rate and actual number
The reason comes from the fact that the histogram function is expected to include all the data, so it must span the range of the data.
The Freedman-Diaconis rule gives a formula for the width of the bins.
The function gives a formula for the number of bins.
The relationship between number of bins and the width of bins will be impacted by the range of the data.
With Gaussian data, the expected range increases with $n$.
Here's the function:
> nclass.FD
function (x)
{
h <- stats::IQR(x)
if (h == 0)
h <- stats::mad(x, constant = 2)
if (h > 0)
ceiling(diff(range(x))/(2 * h * length(x)^(-1/3)))
else 1L
}
<bytecode: 0x086e6938>
<environment: namespace:grDevices>
diff(range(x)) is the range of the data.
So as we see, it divides the range of the data by the FD formula for bin width (and rounds up) to get the number of bins.
It seems I could have been clearer, so here's a more detailed explanation:
The actual Freedman-Diaconis rule is not a rule for the number of bins, but for the bin-width. By their analysis, the bin width should be proportional to $n^{−1/3}$. Since the total width of the histogram must be closely related to the sample range (it may be a bit wider, because of rounding up to nice numbers), and the expected range changes with $n$, the number of bins is not quite inversely proportional to bin-width, but must increase faster than that. So the number of bins should not grow as $n^{1/3}$ - close to it, but a little faster, because of the way the range comes into it.
Looking at data from Tippett's 1925 tables[1], the expected range in standard normal samples seems to grow quite slowly with $n$, though -- slower even than $\log(n)$:
(indeed, amoeba points out in comments below that it should be proportional - or nearly so - to $\sqrt{\log(n)}$, which grows more slowly than your analysis in the question seem to suggest. This makes me wonder whether there's some other issue coming in, but I haven't investigated whether this range effect fully explains your data.)
A quick look at Tippett's numbers (which go up to n=1000) suggest that the expected range in a Gaussian is very close to linear in $\sqrt{\log(n)}$ over $10\leq n\leq 1000$, but it seems to be not actually proportional for values in this range.
[1]: L. H. C. Tippett (1925). "On the Extreme Individuals and the Range of Samples Taken from a Normal Population". Biometrika 17 (3/4): 364–387 | Optimal number of bins in histogram by the Freedman–Diaconis rule: difference between theoretical ra
The reason comes from the fact that the histogram function is expected to include all the data, so it must span the range of the data.
The Freedman-Diaconis rule gives a formula for the width of the |
36,009 | Zero-inflated Poisson and Gibbs sampling, proofs and sampling | For the first question, given that you have a hierarchical model, you simply have to start from the higher level and proceed downwards:
$(r_i|p, \lambda )\sim\mathcal{B}(p)$ for $i=1,\ldots,n$
$(x_i|r, \lambda, p)\sim\mathcal{P}(\lambda r_i)$ for $i=1,\ldots,n$
Note that only the $x_i$'s for which $r_i=1$ need to be simulated. As an R code, this can be written as
n=10^2
p=0.3
lam=2
r=as.integer(runif(n)<p)
x=rep(0,n)
x[r==1]=rpois(sum(r==1),lam)
For the second question, the full conditional distributions can be extracted from the joint density$$f(x,r, \lambda, p) = \frac{b^\alpha \lambda^{\alpha-1} e^{-b \lambda}}{\Gamma(\alpha)} \prod_{i=1}^n\frac{e^{-\lambda r_i} (\lambda r_i)^{x_i}}{x_i!} p^{r_i}(1-p)^{1-r_i}$$since the full conditional densities all are proportional to this joint density as functions of $\lambda$, $p$, or the $r_i$'s.
For instance,
$$\pi(\lambda|p,\mathbf{r},\mathbf{x})\propto\lambda^{\alpha-1} e^{-b \lambda}\prod_{i=1}^n e^{-\lambda r_i} (\lambda)^{x_i}\propto\lambda^{\alpha-1} e^{-b \lambda} e^{-\lambda \sum_i r_i} \lambda^{\sum_i x_i}$$ where I only kept the terms that depend on $\lambda$. Hence
$$\pi(\lambda|p,\mathbf{r},\mathbf{x})\propto\lambda^{\alpha-1+\sum_i x_i} e^{-\left[b+\sum_i r_i\right] \lambda}$$ which is proportional to the $$Gamma\left(a+ \sum_{i}x_i, b+ \sum_{i}r_i\right)$$density on $\lambda$.
Similarly$$\pi(p|\lambda,\mathbf{r},\mathbf{x}) \propto \prod_{i=1}^n p^{r_i}(1-p)^{1-r_i}=p^{\sum_i r_i}(1-p)^{n-\sum_i r_i}$$
leading to
$$Beta\left(1+ \sum_{i}r_i, n+1 - \sum_{i}r_i\right)$$as the full conditional posterior on $p$. | Zero-inflated Poisson and Gibbs sampling, proofs and sampling | For the first question, given that you have a hierarchical model, you simply have to start from the higher level and proceed downwards:
$(r_i|p, \lambda )\sim\mathcal{B}(p)$ for $i=1,\ldots,n$
$(x_i| | Zero-inflated Poisson and Gibbs sampling, proofs and sampling
For the first question, given that you have a hierarchical model, you simply have to start from the higher level and proceed downwards:
$(r_i|p, \lambda )\sim\mathcal{B}(p)$ for $i=1,\ldots,n$
$(x_i|r, \lambda, p)\sim\mathcal{P}(\lambda r_i)$ for $i=1,\ldots,n$
Note that only the $x_i$'s for which $r_i=1$ need to be simulated. As an R code, this can be written as
n=10^2
p=0.3
lam=2
r=as.integer(runif(n)<p)
x=rep(0,n)
x[r==1]=rpois(sum(r==1),lam)
For the second question, the full conditional distributions can be extracted from the joint density$$f(x,r, \lambda, p) = \frac{b^\alpha \lambda^{\alpha-1} e^{-b \lambda}}{\Gamma(\alpha)} \prod_{i=1}^n\frac{e^{-\lambda r_i} (\lambda r_i)^{x_i}}{x_i!} p^{r_i}(1-p)^{1-r_i}$$since the full conditional densities all are proportional to this joint density as functions of $\lambda$, $p$, or the $r_i$'s.
For instance,
$$\pi(\lambda|p,\mathbf{r},\mathbf{x})\propto\lambda^{\alpha-1} e^{-b \lambda}\prod_{i=1}^n e^{-\lambda r_i} (\lambda)^{x_i}\propto\lambda^{\alpha-1} e^{-b \lambda} e^{-\lambda \sum_i r_i} \lambda^{\sum_i x_i}$$ where I only kept the terms that depend on $\lambda$. Hence
$$\pi(\lambda|p,\mathbf{r},\mathbf{x})\propto\lambda^{\alpha-1+\sum_i x_i} e^{-\left[b+\sum_i r_i\right] \lambda}$$ which is proportional to the $$Gamma\left(a+ \sum_{i}x_i, b+ \sum_{i}r_i\right)$$density on $\lambda$.
Similarly$$\pi(p|\lambda,\mathbf{r},\mathbf{x}) \propto \prod_{i=1}^n p^{r_i}(1-p)^{1-r_i}=p^{\sum_i r_i}(1-p)^{n-\sum_i r_i}$$
leading to
$$Beta\left(1+ \sum_{i}r_i, n+1 - \sum_{i}r_i\right)$$as the full conditional posterior on $p$. | Zero-inflated Poisson and Gibbs sampling, proofs and sampling
For the first question, given that you have a hierarchical model, you simply have to start from the higher level and proceed downwards:
$(r_i|p, \lambda )\sim\mathcal{B}(p)$ for $i=1,\ldots,n$
$(x_i| |
36,010 | Problems with time series prediction | You are attempting to forecast a compositional time series. That is, you have three components that are all constrained to lie between 0 and 1 and to add up to 1.
You can address this issue using standard exponential smoothing, by using an appropriate generalized logistic transformation. There was a presentation on this by Koehler, Snyder, Ord & Beaumont at the 2010 International Symposium on Forecasting, which turned into a paper (Snyder et al., 2017, International Journal of Forecasting).
Let's walk though this with your data. Read the data into a matrix obs of time series:
obs <- structure(c(0.03333333, 0.03810624, 0, 0.03776683, 0.06606607,
0.03900325, 0.03125, 0, 0.04927885, 0.0610687, 0.03846154, 0,
0.06028636, 0.09646302, 0.04444444, 0.01111111, 0.02309469, 0.03846154,
0.03119869, 0.01201201, 0.02058505, 0.015625, 0, 0.01802885,
0.02290076, 0, 0, 0.03843256, 0.05144695, 0.06666667, 0.9555556,
0.9387991, 0.9615385, 0.9310345, 0.9219219, 0.9404117, 0.953125,
1, 0.9326923, 0.9160305, 0.9615385, 1, 0.9012811, 0.85209, 0.8888889
), .Dim = c(15L, 3L), .Dimnames = list(NULL, c("Series 1", "Series 2",
"Series 3")), .Tsp = c(1, 15, 1), class = c("mts", "ts", "matrix"
))
You can check whether this worked by typing
obs
Now, you have a few zeros in there, which will be a problem once you take logarithms. A simple solution is to set everything that is less than a small $\epsilon$ to that $\epsilon$:
epsilon <- 0.0001
obs[obs<epsilon] <- epsilon
Now the modified rows do not sum to 1 any more. We can rectify that (although I think this might make the forecast worse):
obs <- obs/matrix(rowSums(obs),nrow=nrow(obs),ncol=ncol(obs),byrow=FALSE)
Now we transform the data as per page 35 of the presentation:
zz <- log(obs[,-ncol(obs)]/obs[,ncol(obs)])
colnames(zz) <- head(colnames(obs),-1)
zz
Load the forecast package and set a horizon of 5 time points:
library(forecast)
horizon <- 5
Now model and forecast the transformed data column by column. Here I am simply calling ets(), which will attempt to fit a state space exponential smoothing model. It turns out that it uses single exponential smoothing for all three series, but especially if you have more than 15 time periods, it may select trend models. Or if you have monthly data, explain to R that you have a potential seasonality, by using ts() with frequency=12 - then ets() will look at seasonal models.
baz <- apply(zz,2,function(xx)forecast(ets(xx),horizon=horizon)["mean"])
forecasts.transformed <- cbind(baz[[1]]$mean,baz[[2]]$mean)
Next we backtransform the forecasts as per page 38 of the presentation:
forecasts <- cbind(exp(forecasts.transformed),1)/(1+rowSums(exp(forecasts.transformed)))
Finally, let's plot histories and forecasts:
plot(obs[,1],ylim=c(0,1),xlim=c(1,nrow(obs)+horizon),type="n",ylab="")
for ( ii in 1:ncol(obs) ) {
lines(obs[,ii],type="o",pch=19,col=ii)
lines(forecasts[,ii],type="o",pch=21,col=ii,lty=2)
}
legend("left",inset=.01,lwd=1,col=1:ncol(obs),pch=19,legend=colnames(obs))
EDIT: a paper on compositional time series forecasting just appeared. I haven't read it, but it may be of interest. | Problems with time series prediction | You are attempting to forecast a compositional time series. That is, you have three components that are all constrained to lie between 0 and 1 and to add up to 1.
You can address this issue using stan | Problems with time series prediction
You are attempting to forecast a compositional time series. That is, you have three components that are all constrained to lie between 0 and 1 and to add up to 1.
You can address this issue using standard exponential smoothing, by using an appropriate generalized logistic transformation. There was a presentation on this by Koehler, Snyder, Ord & Beaumont at the 2010 International Symposium on Forecasting, which turned into a paper (Snyder et al., 2017, International Journal of Forecasting).
Let's walk though this with your data. Read the data into a matrix obs of time series:
obs <- structure(c(0.03333333, 0.03810624, 0, 0.03776683, 0.06606607,
0.03900325, 0.03125, 0, 0.04927885, 0.0610687, 0.03846154, 0,
0.06028636, 0.09646302, 0.04444444, 0.01111111, 0.02309469, 0.03846154,
0.03119869, 0.01201201, 0.02058505, 0.015625, 0, 0.01802885,
0.02290076, 0, 0, 0.03843256, 0.05144695, 0.06666667, 0.9555556,
0.9387991, 0.9615385, 0.9310345, 0.9219219, 0.9404117, 0.953125,
1, 0.9326923, 0.9160305, 0.9615385, 1, 0.9012811, 0.85209, 0.8888889
), .Dim = c(15L, 3L), .Dimnames = list(NULL, c("Series 1", "Series 2",
"Series 3")), .Tsp = c(1, 15, 1), class = c("mts", "ts", "matrix"
))
You can check whether this worked by typing
obs
Now, you have a few zeros in there, which will be a problem once you take logarithms. A simple solution is to set everything that is less than a small $\epsilon$ to that $\epsilon$:
epsilon <- 0.0001
obs[obs<epsilon] <- epsilon
Now the modified rows do not sum to 1 any more. We can rectify that (although I think this might make the forecast worse):
obs <- obs/matrix(rowSums(obs),nrow=nrow(obs),ncol=ncol(obs),byrow=FALSE)
Now we transform the data as per page 35 of the presentation:
zz <- log(obs[,-ncol(obs)]/obs[,ncol(obs)])
colnames(zz) <- head(colnames(obs),-1)
zz
Load the forecast package and set a horizon of 5 time points:
library(forecast)
horizon <- 5
Now model and forecast the transformed data column by column. Here I am simply calling ets(), which will attempt to fit a state space exponential smoothing model. It turns out that it uses single exponential smoothing for all three series, but especially if you have more than 15 time periods, it may select trend models. Or if you have monthly data, explain to R that you have a potential seasonality, by using ts() with frequency=12 - then ets() will look at seasonal models.
baz <- apply(zz,2,function(xx)forecast(ets(xx),horizon=horizon)["mean"])
forecasts.transformed <- cbind(baz[[1]]$mean,baz[[2]]$mean)
Next we backtransform the forecasts as per page 38 of the presentation:
forecasts <- cbind(exp(forecasts.transformed),1)/(1+rowSums(exp(forecasts.transformed)))
Finally, let's plot histories and forecasts:
plot(obs[,1],ylim=c(0,1),xlim=c(1,nrow(obs)+horizon),type="n",ylab="")
for ( ii in 1:ncol(obs) ) {
lines(obs[,ii],type="o",pch=19,col=ii)
lines(forecasts[,ii],type="o",pch=21,col=ii,lty=2)
}
legend("left",inset=.01,lwd=1,col=1:ncol(obs),pch=19,legend=colnames(obs))
EDIT: a paper on compositional time series forecasting just appeared. I haven't read it, but it may be of interest. | Problems with time series prediction
You are attempting to forecast a compositional time series. That is, you have three components that are all constrained to lie between 0 and 1 and to add up to 1.
You can address this issue using stan |
36,011 | Does a prediction interval have to contain the mean? | No, a prediction interval need not contain the mean. I think some of your confusion might be mixing prediction intervals and confidence intervals. While the goal of a prediction interval is to contain with some certainty future values of the random variable, the goal of a confidence interval is to contain the true mean of distribution.
As you mentioned in highly skewed distributions these ideas seem to be at odds with each other. The important thing is to recognize the value in each of the statistics provided.
The predictive value of the mean is:
1) Cumulative: As more samples come in, their average will tend toward the true mean. So if the cumulative value is of interest (for instance, if you're gambling and dealing with winnings or losses you're interested in cumulative effects) then the mean is very useful.
2) Minimizes Squared Residuals: While squared residuals are a somewhat arbitrary quantity of interest it is worthwhile to know what your prediction is minimizing.
If however your goal is to minimize the absolute error in your predictions, the mean forecasted value of 6,000,000 is not what I would go with. | Does a prediction interval have to contain the mean? | No, a prediction interval need not contain the mean. I think some of your confusion might be mixing prediction intervals and confidence intervals. While the goal of a prediction interval is to conta | Does a prediction interval have to contain the mean?
No, a prediction interval need not contain the mean. I think some of your confusion might be mixing prediction intervals and confidence intervals. While the goal of a prediction interval is to contain with some certainty future values of the random variable, the goal of a confidence interval is to contain the true mean of distribution.
As you mentioned in highly skewed distributions these ideas seem to be at odds with each other. The important thing is to recognize the value in each of the statistics provided.
The predictive value of the mean is:
1) Cumulative: As more samples come in, their average will tend toward the true mean. So if the cumulative value is of interest (for instance, if you're gambling and dealing with winnings or losses you're interested in cumulative effects) then the mean is very useful.
2) Minimizes Squared Residuals: While squared residuals are a somewhat arbitrary quantity of interest it is worthwhile to know what your prediction is minimizing.
If however your goal is to minimize the absolute error in your predictions, the mean forecasted value of 6,000,000 is not what I would go with. | Does a prediction interval have to contain the mean?
No, a prediction interval need not contain the mean. I think some of your confusion might be mixing prediction intervals and confidence intervals. While the goal of a prediction interval is to conta |
36,012 | Does a prediction interval have to contain the mean? | Consider the distribution of possible returns in the St Petersburg paradox:
Prob(1)=1/2
Prob(2)=1/4
Prob(4)=1/8
...
Prob(2^n)=1/2^(n+1)
The mean diverges and is outside of any reasonable prediction interval. (The median is 1 in this case, but I don't know what I'd use for my point forecast. Maybe Stephan Kolassa, see above, has a suggestion.)
There's another complication: Let's say you want a 95% prediction interval for some distribution (other than the one I just mentioned). Do you go from the 2.5%tile to the 97.5%tile or the 0 to the 95th or the 5th to the 100th or....? The answer probably depends on why you are asking the question. | Does a prediction interval have to contain the mean? | Consider the distribution of possible returns in the St Petersburg paradox:
Prob(1)=1/2
Prob(2)=1/4
Prob(4)=1/8
...
Prob(2^n)=1/2^(n+1)
The mean diverges and is outside of any reasonable prediction i | Does a prediction interval have to contain the mean?
Consider the distribution of possible returns in the St Petersburg paradox:
Prob(1)=1/2
Prob(2)=1/4
Prob(4)=1/8
...
Prob(2^n)=1/2^(n+1)
The mean diverges and is outside of any reasonable prediction interval. (The median is 1 in this case, but I don't know what I'd use for my point forecast. Maybe Stephan Kolassa, see above, has a suggestion.)
There's another complication: Let's say you want a 95% prediction interval for some distribution (other than the one I just mentioned). Do you go from the 2.5%tile to the 97.5%tile or the 0 to the 95th or the 5th to the 100th or....? The answer probably depends on why you are asking the question. | Does a prediction interval have to contain the mean?
Consider the distribution of possible returns in the St Petersburg paradox:
Prob(1)=1/2
Prob(2)=1/4
Prob(4)=1/8
...
Prob(2^n)=1/2^(n+1)
The mean diverges and is outside of any reasonable prediction i |
36,013 | Why is the standard deviation defined using differences^2 instead of differences^4? [duplicate] | It has to do with moment generating functions. Specifically, variance is defined to be the second moment about the mean, and the third moment generating function is called the skewness. All of these things are called shape parameters, because they describe the shape of the distribution. The 4th moment, Kurtosis which (loosely) descibes how tall a distribution gets, but that's not exactly what you're doing.
Update- Thank you @amoeba for pointing out my mean formulas were wrong, they should be expected values not sums.
$E [(X)]$ - Mean
$E [(X-\mu)^2]$ - Variance
$E [(X-\mu)^3]$ - Third moment, leads to Skewness
$E [(X-\mu)^4]$ - Forth moment, leads to Kurtosis
and so on...
Update- Also to @amobea's point, skewness and kurtosis have additional calculations that need to be done. However, the 3rd and 4th moment generating functions are correctly listed (now). Henry's answer is much more concise and may provide better insight.
So you can do what you purpose but you'll need to make another name up for it, because standard deviation has already been defined.
To be clear, people started calling the second moment 'variance' and the name stuck. Then someone else took the square root of that, and started calling it standard deviation, and the name stuck. Other people said, "that's a good measure for what I'm trying to use", so they wrote articles/theses/etc. with regards to standard deviation.
To your point, there are other methods for describing the 'spread' of a distribution. Standard deviation has a straight forward interpretations with properties that many are familiar with, especially when dealing the Normal distribution. To say one measure is summarily better than all others in all cases is, in my opinion, inappropriate.
Like everything else in the world, the right tool to use depends on the job you're trying to do, or in this case the right measure to use depends on what question you're trying to answer.
For example, in my line of work people tend to use MAPE, which doesn't describe the distribution at all, and has a number of issues of its own which make it a poor fit for what they are trying to do, but everyone has been doing it for a while, so that's what will likely continue happening for the foreseeable future. That has more to do with human nature than statistics, but also is somewhat applicable to your question (and maybe the best answer).
One final point: if you're going to do a sum, you need to muliply each x by the probability of x
$$ E[(X-\mu)^4] = \sum_{x\in D}^{ } (x-\mu)^4*p(x)$$
Your 1/N is only valid if each value of x is equally likely (a.k.a. the distribution is uniform). | Why is the standard deviation defined using differences^2 instead of differences^4? [duplicate] | It has to do with moment generating functions. Specifically, variance is defined to be the second moment about the mean, and the third moment generating function is called the skewness. All of these t | Why is the standard deviation defined using differences^2 instead of differences^4? [duplicate]
It has to do with moment generating functions. Specifically, variance is defined to be the second moment about the mean, and the third moment generating function is called the skewness. All of these things are called shape parameters, because they describe the shape of the distribution. The 4th moment, Kurtosis which (loosely) descibes how tall a distribution gets, but that's not exactly what you're doing.
Update- Thank you @amoeba for pointing out my mean formulas were wrong, they should be expected values not sums.
$E [(X)]$ - Mean
$E [(X-\mu)^2]$ - Variance
$E [(X-\mu)^3]$ - Third moment, leads to Skewness
$E [(X-\mu)^4]$ - Forth moment, leads to Kurtosis
and so on...
Update- Also to @amobea's point, skewness and kurtosis have additional calculations that need to be done. However, the 3rd and 4th moment generating functions are correctly listed (now). Henry's answer is much more concise and may provide better insight.
So you can do what you purpose but you'll need to make another name up for it, because standard deviation has already been defined.
To be clear, people started calling the second moment 'variance' and the name stuck. Then someone else took the square root of that, and started calling it standard deviation, and the name stuck. Other people said, "that's a good measure for what I'm trying to use", so they wrote articles/theses/etc. with regards to standard deviation.
To your point, there are other methods for describing the 'spread' of a distribution. Standard deviation has a straight forward interpretations with properties that many are familiar with, especially when dealing the Normal distribution. To say one measure is summarily better than all others in all cases is, in my opinion, inappropriate.
Like everything else in the world, the right tool to use depends on the job you're trying to do, or in this case the right measure to use depends on what question you're trying to answer.
For example, in my line of work people tend to use MAPE, which doesn't describe the distribution at all, and has a number of issues of its own which make it a poor fit for what they are trying to do, but everyone has been doing it for a while, so that's what will likely continue happening for the foreseeable future. That has more to do with human nature than statistics, but also is somewhat applicable to your question (and maybe the best answer).
One final point: if you're going to do a sum, you need to muliply each x by the probability of x
$$ E[(X-\mu)^4] = \sum_{x\in D}^{ } (x-\mu)^4*p(x)$$
Your 1/N is only valid if each value of x is equally likely (a.k.a. the distribution is uniform). | Why is the standard deviation defined using differences^2 instead of differences^4? [duplicate]
It has to do with moment generating functions. Specifically, variance is defined to be the second moment about the mean, and the third moment generating function is called the skewness. All of these t |
36,014 | Why is the standard deviation defined using differences^2 instead of differences^4? [duplicate] | The mean is in a sense the natural partner of the standard deviation: if you want to minimise $\sqrt{\frac{1}{N} \sum_{i=1}^N (x_i - m)^2}$ then this is achieved when $m = \frac{1}{N} \sum_{i=1}^N x_i$. For example, if you have $x_1=1, x_2=6, x_3=2$, then the minimum comes when $m=3$.
This is not true when you have other measures of deviation from the central estimate. The expression ${\frac{1}{N} \sum_{i=1}^N |x_i - m|}$ is minimised by a median, in this example when $m=2$.
Finding $m$ to minimise $\sqrt[4]{\frac{1}{N} \sum_{i=1}^N (x_i - m)^4}$ is harder as it involves solving a cubic equation. In this example it is minimised when $m \approx 3.423$.
So if you want your central estimate to minimise your chosen deviation measure, and you want your central estimate to be the mean, then the natural deviation measure is going to be the standard deviation or some monotonic function of it such as the variance. | Why is the standard deviation defined using differences^2 instead of differences^4? [duplicate] | The mean is in a sense the natural partner of the standard deviation: if you want to minimise $\sqrt{\frac{1}{N} \sum_{i=1}^N (x_i - m)^2}$ then this is achieved when $m = \frac{1}{N} \sum_{i=1}^N x_i | Why is the standard deviation defined using differences^2 instead of differences^4? [duplicate]
The mean is in a sense the natural partner of the standard deviation: if you want to minimise $\sqrt{\frac{1}{N} \sum_{i=1}^N (x_i - m)^2}$ then this is achieved when $m = \frac{1}{N} \sum_{i=1}^N x_i$. For example, if you have $x_1=1, x_2=6, x_3=2$, then the minimum comes when $m=3$.
This is not true when you have other measures of deviation from the central estimate. The expression ${\frac{1}{N} \sum_{i=1}^N |x_i - m|}$ is minimised by a median, in this example when $m=2$.
Finding $m$ to minimise $\sqrt[4]{\frac{1}{N} \sum_{i=1}^N (x_i - m)^4}$ is harder as it involves solving a cubic equation. In this example it is minimised when $m \approx 3.423$.
So if you want your central estimate to minimise your chosen deviation measure, and you want your central estimate to be the mean, then the natural deviation measure is going to be the standard deviation or some monotonic function of it such as the variance. | Why is the standard deviation defined using differences^2 instead of differences^4? [duplicate]
The mean is in a sense the natural partner of the standard deviation: if you want to minimise $\sqrt{\frac{1}{N} \sum_{i=1}^N (x_i - m)^2}$ then this is achieved when $m = \frac{1}{N} \sum_{i=1}^N x_i |
36,015 | What is re-randomization? | Rerandomization, as used by Morgan and Rubin (Annals of Statistics 2012), is a form of restricted randomization. Suppose you had all of your subjects available for randomization, e.g. you are randomizing 20 hospitals into two arms. You would like the two arms to be similar in terms of important covariates, e.g. hospital size, teaching hospital, etc. If you had several covariates, there is a nontrivial chance of imbalance in one or more covariates. In rare but serious occasions, a covariate could be highly imbalanced. If you could check your randomization for balance prior to starting your intervention and found imbalance, you could redo your simple randomization until the first time you got a randomization that had satisfactory balance.
Your statistical tests that do not account for the fact that you used rerandomization will be conservative, e.g. your two-sample t-test will have a p-value that is a little too large on average so the Type I error for this test is a little too low and the Type II error is higher than it has to be. However, a test that adjusted for the covariates you considered when deciding whether to accept a randomization, e.g. a multivariate regression that adjusted for those covariates in the model, will have approximately the correct standard error and "better" error rates.
Rerandomization is one form of restricted randomization, but there are several viable options. Other methods include stratified randomization, matched randomization (see Greevy, Lu, Silber, Rosenbaum Biostatistics 2004; Kapelner and Krieger Biometrics 2014; and others), and minimization (see Pocock and Simon Biometrics 1975; and many others). Matched randomization and minimization have the advantage that they can be used with sequential entry trials, where patients arrive one at a time or in small batches, and they scale nicely in terms of the sample size and the number of covariates, as opposed to ordinary stratified randomization which has trouble performing well with more than a few covariates. Any form of restricted randomization typically offers big gains over simple randomization. | What is re-randomization? | Rerandomization, as used by Morgan and Rubin (Annals of Statistics 2012), is a form of restricted randomization. Suppose you had all of your subjects available for randomization, e.g. you are randomiz | What is re-randomization?
Rerandomization, as used by Morgan and Rubin (Annals of Statistics 2012), is a form of restricted randomization. Suppose you had all of your subjects available for randomization, e.g. you are randomizing 20 hospitals into two arms. You would like the two arms to be similar in terms of important covariates, e.g. hospital size, teaching hospital, etc. If you had several covariates, there is a nontrivial chance of imbalance in one or more covariates. In rare but serious occasions, a covariate could be highly imbalanced. If you could check your randomization for balance prior to starting your intervention and found imbalance, you could redo your simple randomization until the first time you got a randomization that had satisfactory balance.
Your statistical tests that do not account for the fact that you used rerandomization will be conservative, e.g. your two-sample t-test will have a p-value that is a little too large on average so the Type I error for this test is a little too low and the Type II error is higher than it has to be. However, a test that adjusted for the covariates you considered when deciding whether to accept a randomization, e.g. a multivariate regression that adjusted for those covariates in the model, will have approximately the correct standard error and "better" error rates.
Rerandomization is one form of restricted randomization, but there are several viable options. Other methods include stratified randomization, matched randomization (see Greevy, Lu, Silber, Rosenbaum Biostatistics 2004; Kapelner and Krieger Biometrics 2014; and others), and minimization (see Pocock and Simon Biometrics 1975; and many others). Matched randomization and minimization have the advantage that they can be used with sequential entry trials, where patients arrive one at a time or in small batches, and they scale nicely in terms of the sample size and the number of covariates, as opposed to ordinary stratified randomization which has trouble performing well with more than a few covariates. Any form of restricted randomization typically offers big gains over simple randomization. | What is re-randomization?
Rerandomization, as used by Morgan and Rubin (Annals of Statistics 2012), is a form of restricted randomization. Suppose you had all of your subjects available for randomization, e.g. you are randomiz |
36,016 | Stepwise Model Selection in Logistic Regression in R | Using stepwise selection to find a model is a very bad thing to do. Your hypothesis tests will be invalid, and your out of sample predictive accuracy will be very poor due to overfitting. To understand these points more fully, it may help you to read my answer here: Algorithms for automatic model selection.
The stepAIC function is selecting a model based on the AIC, not whether individual coefficients are above or below some threshold as SPSS does. However, the AIC can be understood as using a specific alpha, just not .05. Instead, it's approximately .157. For more on that, see @Glen_b's answers here: Stepwise regression in R – Critical p-value. | Stepwise Model Selection in Logistic Regression in R | Using stepwise selection to find a model is a very bad thing to do. Your hypothesis tests will be invalid, and your out of sample predictive accuracy will be very poor due to overfitting. To underst | Stepwise Model Selection in Logistic Regression in R
Using stepwise selection to find a model is a very bad thing to do. Your hypothesis tests will be invalid, and your out of sample predictive accuracy will be very poor due to overfitting. To understand these points more fully, it may help you to read my answer here: Algorithms for automatic model selection.
The stepAIC function is selecting a model based on the AIC, not whether individual coefficients are above or below some threshold as SPSS does. However, the AIC can be understood as using a specific alpha, just not .05. Instead, it's approximately .157. For more on that, see @Glen_b's answers here: Stepwise regression in R – Critical p-value. | Stepwise Model Selection in Logistic Regression in R
Using stepwise selection to find a model is a very bad thing to do. Your hypothesis tests will be invalid, and your out of sample predictive accuracy will be very poor due to overfitting. To underst |
36,017 | CV for model parameter tuning AND then model evaluation | The simple rule is that data used for evaluating the performance of a model should not have been used to optimize the model in any way. If you split all of the available data into k disjoint subsets to use to tune the hyper-parameters of a model (e.g. the kernel and regularization parameters of an SVM), then you cannot perform unbiased performance estimation as all of the data has influenced the selection of the hyper-parameters. This means that both (1) and (2) are likely to be optimistically biased.
The solution is to use nested cross-validation, where the outer cross-validation is used for performance evaluation. The key point is that we want to estimate the performance of the whole procedure for fitting the model, which includes tuning the hyper-parameters. So you need to include in each fold of the outer cross-validation all of the steps used to tune the model, which in this case includes using cross-validation to tune the hyper-parameters independently in each fold. I wrote a paper on this topic, which you can find here, section 5.3 gives an example of why performing cross-validation for both model selection and performance evaluation is a bad idea. | CV for model parameter tuning AND then model evaluation | The simple rule is that data used for evaluating the performance of a model should not have been used to optimize the model in any way. If you split all of the available data into k disjoint subsets | CV for model parameter tuning AND then model evaluation
The simple rule is that data used for evaluating the performance of a model should not have been used to optimize the model in any way. If you split all of the available data into k disjoint subsets to use to tune the hyper-parameters of a model (e.g. the kernel and regularization parameters of an SVM), then you cannot perform unbiased performance estimation as all of the data has influenced the selection of the hyper-parameters. This means that both (1) and (2) are likely to be optimistically biased.
The solution is to use nested cross-validation, where the outer cross-validation is used for performance evaluation. The key point is that we want to estimate the performance of the whole procedure for fitting the model, which includes tuning the hyper-parameters. So you need to include in each fold of the outer cross-validation all of the steps used to tune the model, which in this case includes using cross-validation to tune the hyper-parameters independently in each fold. I wrote a paper on this topic, which you can find here, section 5.3 gives an example of why performing cross-validation for both model selection and performance evaluation is a bad idea. | CV for model parameter tuning AND then model evaluation
The simple rule is that data used for evaluating the performance of a model should not have been used to optimize the model in any way. If you split all of the available data into k disjoint subsets |
36,018 | Self-study: Finding the maximum likelihood estimates of the parameters of a density function - UPDATED | [Note: This is my answer to the Dec. 19, 2014, version of the question.]
If you operate the change of variable $y=x^2$ in your density
$$f_X(x|\alpha,\beta,\sigma)=\frac{1}{\Gamma \left( \alpha \right)\beta^{\alpha}}\exp\left\{{-\frac{x^2}{2\sigma^{2}}\frac{1}{\beta}}\right\}\frac{x^{2\alpha-1}}{2^{\alpha-1}\sigma^{2\alpha}}\mathbb{I}_{{\mathbb{R}}^{+}}(x)
$$ the Jacobian is given by $\dfrac{\text{d}y}{\text{d}x}= 2x = 2y^{1/2}$ and hence
\begin{align*}
f_Y(y|\alpha,\beta,\sigma)&=\frac{1}{\Gamma \left( \alpha \right)\beta^{\alpha}}\exp\left\{{-\frac{y}{2\sigma^{2}}\frac{1}{\beta}}\right\}\frac{y^{\frac{2\alpha-1}{2}}}{2^{\alpha-1}\sigma^{2\alpha}}\frac{1}{2 y^{1/2}}\mathbb{I}_{{\mathbb{R}}^{+}}(y)\\
&=\frac{1}{\Gamma \left( \alpha \right)\beta^{\alpha}}\exp\left\{{-\frac{y}{2\sigma^{2}}\frac{1}{\beta}}\right\}\frac{y^{{\alpha-1}}}{2^{\alpha}\sigma^{2\alpha}}\mathbb{I}_{{\mathbb{R}}^{+}}(y)
\end{align*}
This shows that
This is a standard $\mathcal{G}(\alpha,2\sigma^2\beta)$ model, i.e. you observe $$(x_1^2,\ldots,x_n^2)=(y_1,\ldots,y_n)\stackrel{\text{iid}}{\sim}\mathcal{G}(\alpha,\eta);$$
the model is over-parametrised since only $\eta=2\sigma^2\beta$ can be identified;
EM is not necessary to find the MLE of $(\alpha,\eta)$, which is not available in closed form but solution of$$\hat\eta^{-1}=\bar{y}/\hat{\alpha}n\qquad\log(\hat{\alpha})-\psi(\hat{\alpha})=\log(\bar{y})-\frac{1}{n}\sum_{i=1}^n\log(y_i)$$ where $\psi(\cdot)$ is the di-gamma function. This paper by Thomas Minka indicates fast approximations to the resolution of the above equation. | Self-study: Finding the maximum likelihood estimates of the parameters of a density function - UPDAT | [Note: This is my answer to the Dec. 19, 2014, version of the question.]
If you operate the change of variable $y=x^2$ in your density
$$f_X(x|\alpha,\beta,\sigma)=\frac{1}{\Gamma \left( \alpha \right | Self-study: Finding the maximum likelihood estimates of the parameters of a density function - UPDATED
[Note: This is my answer to the Dec. 19, 2014, version of the question.]
If you operate the change of variable $y=x^2$ in your density
$$f_X(x|\alpha,\beta,\sigma)=\frac{1}{\Gamma \left( \alpha \right)\beta^{\alpha}}\exp\left\{{-\frac{x^2}{2\sigma^{2}}\frac{1}{\beta}}\right\}\frac{x^{2\alpha-1}}{2^{\alpha-1}\sigma^{2\alpha}}\mathbb{I}_{{\mathbb{R}}^{+}}(x)
$$ the Jacobian is given by $\dfrac{\text{d}y}{\text{d}x}= 2x = 2y^{1/2}$ and hence
\begin{align*}
f_Y(y|\alpha,\beta,\sigma)&=\frac{1}{\Gamma \left( \alpha \right)\beta^{\alpha}}\exp\left\{{-\frac{y}{2\sigma^{2}}\frac{1}{\beta}}\right\}\frac{y^{\frac{2\alpha-1}{2}}}{2^{\alpha-1}\sigma^{2\alpha}}\frac{1}{2 y^{1/2}}\mathbb{I}_{{\mathbb{R}}^{+}}(y)\\
&=\frac{1}{\Gamma \left( \alpha \right)\beta^{\alpha}}\exp\left\{{-\frac{y}{2\sigma^{2}}\frac{1}{\beta}}\right\}\frac{y^{{\alpha-1}}}{2^{\alpha}\sigma^{2\alpha}}\mathbb{I}_{{\mathbb{R}}^{+}}(y)
\end{align*}
This shows that
This is a standard $\mathcal{G}(\alpha,2\sigma^2\beta)$ model, i.e. you observe $$(x_1^2,\ldots,x_n^2)=(y_1,\ldots,y_n)\stackrel{\text{iid}}{\sim}\mathcal{G}(\alpha,\eta);$$
the model is over-parametrised since only $\eta=2\sigma^2\beta$ can be identified;
EM is not necessary to find the MLE of $(\alpha,\eta)$, which is not available in closed form but solution of$$\hat\eta^{-1}=\bar{y}/\hat{\alpha}n\qquad\log(\hat{\alpha})-\psi(\hat{\alpha})=\log(\bar{y})-\frac{1}{n}\sum_{i=1}^n\log(y_i)$$ where $\psi(\cdot)$ is the di-gamma function. This paper by Thomas Minka indicates fast approximations to the resolution of the above equation. | Self-study: Finding the maximum likelihood estimates of the parameters of a density function - UPDAT
[Note: This is my answer to the Dec. 19, 2014, version of the question.]
If you operate the change of variable $y=x^2$ in your density
$$f_X(x|\alpha,\beta,\sigma)=\frac{1}{\Gamma \left( \alpha \right |
36,019 | Self-study: Finding the maximum likelihood estimates of the parameters of a density function - UPDATED | In the case of the EM algorithm, the initial values can be set arbitrarily since the iterations are guaranteed to converge to the maximum:
We have seen that both the E and the M steps of the EM algorithm are increasing
the value of a well-defined bound on the log likelihood function and that the complete EM cycle will change the model parameters in such a way as to cause the log likelihood to increase (unless it is already at a maximum, in which case the parameters remain unchanged).
There are several strategies to pick the initial values that will improve the overall performance of the algorithms:
Note that the EM algorithm takes many more iterations to reach (approximate)
convergence compared with the K-means algorithm, and that each cycle requires
significantly more computation. It is therefore common to run the K-means algorithm
in order to find a suitable initialization for a Gaussian mixture model that is
subsequently adapted using EM. The covariance matrices can conveniently be initialized
to the sample covariances of the clusters found by the K-means algorithm,
and the mixing coefficients can be set to the fractions of data points assigned to the
respective clusters.
Bishop, C. M. (2006). Pattern recognition and machine learning (Vol. 1, p. 740). New York: springer.
You can read on this in chapter 9 of the book.
Using EM to estimate latent variables in the context of Gaussian Mixture Models with two components ($\Delta_i = 0$ and $\Delta_i = 1$), loglikelihood is given by
(I'm sorry I'm in a hurry and can't type this myself)
ESLII gives some advice on how to select the initial values:
A good way to construct initial guesses for $\mu_1$ and $\mu_2$ is simply to choose two of the $y_i$ at random. Both $\sigma_1^2$ and $\sigma_2^2$ can be set equal to the overall sample variance. The mixing proportion $\hat{\pi}$ can be started at the value 0.5.
Hastie, T., Tibshirani, R.,, Friedman, J. (2008). The elements of statistical learning: data mining, inference and prediction. Springer.
I insist, you can pick any arbitrary initial values, but some will converge faster. | Self-study: Finding the maximum likelihood estimates of the parameters of a density function - UPDAT | In the case of the EM algorithm, the initial values can be set arbitrarily since the iterations are guaranteed to converge to the maximum:
We have seen that both the E and the M steps of the EM algor | Self-study: Finding the maximum likelihood estimates of the parameters of a density function - UPDATED
In the case of the EM algorithm, the initial values can be set arbitrarily since the iterations are guaranteed to converge to the maximum:
We have seen that both the E and the M steps of the EM algorithm are increasing
the value of a well-defined bound on the log likelihood function and that the complete EM cycle will change the model parameters in such a way as to cause the log likelihood to increase (unless it is already at a maximum, in which case the parameters remain unchanged).
There are several strategies to pick the initial values that will improve the overall performance of the algorithms:
Note that the EM algorithm takes many more iterations to reach (approximate)
convergence compared with the K-means algorithm, and that each cycle requires
significantly more computation. It is therefore common to run the K-means algorithm
in order to find a suitable initialization for a Gaussian mixture model that is
subsequently adapted using EM. The covariance matrices can conveniently be initialized
to the sample covariances of the clusters found by the K-means algorithm,
and the mixing coefficients can be set to the fractions of data points assigned to the
respective clusters.
Bishop, C. M. (2006). Pattern recognition and machine learning (Vol. 1, p. 740). New York: springer.
You can read on this in chapter 9 of the book.
Using EM to estimate latent variables in the context of Gaussian Mixture Models with two components ($\Delta_i = 0$ and $\Delta_i = 1$), loglikelihood is given by
(I'm sorry I'm in a hurry and can't type this myself)
ESLII gives some advice on how to select the initial values:
A good way to construct initial guesses for $\mu_1$ and $\mu_2$ is simply to choose two of the $y_i$ at random. Both $\sigma_1^2$ and $\sigma_2^2$ can be set equal to the overall sample variance. The mixing proportion $\hat{\pi}$ can be started at the value 0.5.
Hastie, T., Tibshirani, R.,, Friedman, J. (2008). The elements of statistical learning: data mining, inference and prediction. Springer.
I insist, you can pick any arbitrary initial values, but some will converge faster. | Self-study: Finding the maximum likelihood estimates of the parameters of a density function - UPDAT
In the case of the EM algorithm, the initial values can be set arbitrarily since the iterations are guaranteed to converge to the maximum:
We have seen that both the E and the M steps of the EM algor |
36,020 | In Max. Likelihood the expected score is zero for the true values. Is it also true for any other values? | Verbal formulation: "the expected value of the derivative of the log-likelihood of the sample evaluated (the derivative) at the true value, equals zero".
Innocent question-crucial remark: what is the "expected value" of a function? (informal) A: it is an integral through which we weigh a function using as weight the true density of the random variables that appear in the function.
Assume we have a sample of size $n$ and we have specified the joint density $g(\mathbf z;\xi$), which may, or may not, be the true joint density which is $f(\mathbf z;\theta_0)$.
We then examine the (multiple) integral
$$E\left(\frac {\partial \log g(\mathbf z;\xi)}{\partial \xi}\Big |\xi=\xi_0\right) = \int f(\mathbf z;\theta_0) \cdot \left(\frac {\partial g(\mathbf z;\xi)/\partial \xi}{g(\mathbf z;\xi)}\Big |\xi=\xi_0\right)\text {d}\mathbf z$$
Note carefully which components of the integrand are evaluated at $\xi_0$ and which are not: only the derivative of the specified log-likelihood is, while the true density is not "evaluated" -by construction, it contains the true parameter $\theta_0$, irrespective of what we have specified for our sample.
Now, If $g(\cdot ;\xi) = f(\cdot ;\theta)$ then the above becomes
$$= \int f(\mathbf z;\theta_0) \frac {\partial f(\mathbf z;\theta_0)/\partial\theta}{f(\mathbf z;\theta_0)}\text {d}\mathbf z = \frac {\partial}{\partial \theta} \int f(\mathbf z;\theta_0) \text {d}\mathbf z = \frac {\partial}{\partial \theta} \big(1\big) = 0$$
The integral equals unity (i.e. it is constant) so its derivative w.r.t to $\theta$ will be equal to zero.
So, first conclusion: misspecification with respect to the distribution family destroys the result (*). But assume that you have specified the distribution family correctly, and let's evaluate the expression at some point $\theta_1$:
$$E\left(\frac {\partial \log f(\mathbf z;\theta)}{\partial \theta}\Big |\theta=\theta_1\right) = \int f(\mathbf z;\theta_0) \cdot \frac {\partial f(\mathbf z;\theta_1)/\partial\theta}{f(\mathbf z;\theta_1)}\text {d}\mathbf z$$
Here, the ratio $f(\mathbf z;\theta_0) /f(\mathbf z;\theta_1)$ no longer cancels, and so we cannot interchange the order of integration and differentiation to obtain the result as before (because then we would subject to differentiation the ratio that doesn't cancel also). Therefore, even though $f(\mathbf z;\theta_1)$ is also a density that integrates to unity, we cannot "leave it alone" inside the integral and exploit this property.
So, only at the true value does the result hold, because, the expected value is taken with respect to the true and unknown density, irrespective of our sample specifications.
--
(*) It also destroys the "Information Matrix Equality", see this short exposition of mine, https://alecospapadopoulos.wordpress.com/2014/05/13/information-matrix-equality/ | In Max. Likelihood the expected score is zero for the true values. Is it also true for any other val | Verbal formulation: "the expected value of the derivative of the log-likelihood of the sample evaluated (the derivative) at the true value, equals zero".
Innocent question-crucial remark: what is the | In Max. Likelihood the expected score is zero for the true values. Is it also true for any other values?
Verbal formulation: "the expected value of the derivative of the log-likelihood of the sample evaluated (the derivative) at the true value, equals zero".
Innocent question-crucial remark: what is the "expected value" of a function? (informal) A: it is an integral through which we weigh a function using as weight the true density of the random variables that appear in the function.
Assume we have a sample of size $n$ and we have specified the joint density $g(\mathbf z;\xi$), which may, or may not, be the true joint density which is $f(\mathbf z;\theta_0)$.
We then examine the (multiple) integral
$$E\left(\frac {\partial \log g(\mathbf z;\xi)}{\partial \xi}\Big |\xi=\xi_0\right) = \int f(\mathbf z;\theta_0) \cdot \left(\frac {\partial g(\mathbf z;\xi)/\partial \xi}{g(\mathbf z;\xi)}\Big |\xi=\xi_0\right)\text {d}\mathbf z$$
Note carefully which components of the integrand are evaluated at $\xi_0$ and which are not: only the derivative of the specified log-likelihood is, while the true density is not "evaluated" -by construction, it contains the true parameter $\theta_0$, irrespective of what we have specified for our sample.
Now, If $g(\cdot ;\xi) = f(\cdot ;\theta)$ then the above becomes
$$= \int f(\mathbf z;\theta_0) \frac {\partial f(\mathbf z;\theta_0)/\partial\theta}{f(\mathbf z;\theta_0)}\text {d}\mathbf z = \frac {\partial}{\partial \theta} \int f(\mathbf z;\theta_0) \text {d}\mathbf z = \frac {\partial}{\partial \theta} \big(1\big) = 0$$
The integral equals unity (i.e. it is constant) so its derivative w.r.t to $\theta$ will be equal to zero.
So, first conclusion: misspecification with respect to the distribution family destroys the result (*). But assume that you have specified the distribution family correctly, and let's evaluate the expression at some point $\theta_1$:
$$E\left(\frac {\partial \log f(\mathbf z;\theta)}{\partial \theta}\Big |\theta=\theta_1\right) = \int f(\mathbf z;\theta_0) \cdot \frac {\partial f(\mathbf z;\theta_1)/\partial\theta}{f(\mathbf z;\theta_1)}\text {d}\mathbf z$$
Here, the ratio $f(\mathbf z;\theta_0) /f(\mathbf z;\theta_1)$ no longer cancels, and so we cannot interchange the order of integration and differentiation to obtain the result as before (because then we would subject to differentiation the ratio that doesn't cancel also). Therefore, even though $f(\mathbf z;\theta_1)$ is also a density that integrates to unity, we cannot "leave it alone" inside the integral and exploit this property.
So, only at the true value does the result hold, because, the expected value is taken with respect to the true and unknown density, irrespective of our sample specifications.
--
(*) It also destroys the "Information Matrix Equality", see this short exposition of mine, https://alecospapadopoulos.wordpress.com/2014/05/13/information-matrix-equality/ | In Max. Likelihood the expected score is zero for the true values. Is it also true for any other val
Verbal formulation: "the expected value of the derivative of the log-likelihood of the sample evaluated (the derivative) at the true value, equals zero".
Innocent question-crucial remark: what is the |
36,021 | Chi-squared Vs Mutual information | They are related, so I don't suspect there to be a big difference (hence, go for mutual information if it's easier to calculate).
I haven't seen a formal argument for this, but my logic is:
A g-test is a derivate of mutual information ($G=2\cdot N \cdot MI(r,c)$, cfr. wiki link)
A Chi-squared leads
to the same conclusion as a g-test for reasonably sized samples
Therefore, Chi-squared and MI lead to more or less the same results for reasonably sized samples. In other cases, it will deterministically depend on the dataset properties. | Chi-squared Vs Mutual information | They are related, so I don't suspect there to be a big difference (hence, go for mutual information if it's easier to calculate).
I haven't seen a formal argument for this, but my logic is:
A g-test | Chi-squared Vs Mutual information
They are related, so I don't suspect there to be a big difference (hence, go for mutual information if it's easier to calculate).
I haven't seen a formal argument for this, but my logic is:
A g-test is a derivate of mutual information ($G=2\cdot N \cdot MI(r,c)$, cfr. wiki link)
A Chi-squared leads
to the same conclusion as a g-test for reasonably sized samples
Therefore, Chi-squared and MI lead to more or less the same results for reasonably sized samples. In other cases, it will deterministically depend on the dataset properties. | Chi-squared Vs Mutual information
They are related, so I don't suspect there to be a big difference (hence, go for mutual information if it's easier to calculate).
I haven't seen a formal argument for this, but my logic is:
A g-test |
36,022 | Chi-squared Vs Mutual information | Just as a follow up to @ciri answer, the same arguments have been developed in the following paper:
Richter et al., 2018 | Chi-squared Vs Mutual information | Just as a follow up to @ciri answer, the same arguments have been developed in the following paper:
Richter et al., 2018 | Chi-squared Vs Mutual information
Just as a follow up to @ciri answer, the same arguments have been developed in the following paper:
Richter et al., 2018 | Chi-squared Vs Mutual information
Just as a follow up to @ciri answer, the same arguments have been developed in the following paper:
Richter et al., 2018 |
36,023 | A person repeatedly selects the two most similar items out of three. How to model/estimate a perceptual distance between the items? | A good approach to this kind of problem can be found in section 4 of the paper The Bayesian Image Retrieval System, PicHunter by Cox et al (2000). The data is a set of integer outcomes $A_1, ..., A_N$ where $N$ is the number of trials. In your case, there are 3 possible outcomes per trial. I will let $A_i$ be the index of the face that was left out. The idea is to postulate a generative model for the outcome given some model parameters, and then estimate the parameters by maximum-likelihood. If we show faces $(X_1,X_2,X_3)$ and the participant says that $(X_2,X_3)$ are the most similar, then the outcome is $A=1$, with probability
$$
p(A = 1 ~|~ X_1, X_2, X_3) \propto \exp(-d(X_2,X_3)/\sigma)
$$
where $d(X_2,X_3)$ is the distance between faces 2 and 3, and $\sigma$ is a parameter for the amount of "noise" (i.e. how consistent the participants are). Since you want an embedding in Euclidean space, your distance measure would be:
$$
d(x,y) = \sqrt{\sum_k (\theta_{xk} - \theta_{yk})^2}
$$
where $\theta_x$ is the (unknown) embedding of face $x$. The parameters of this model are $\theta$ and $\sigma$, which you can estimate from data via maximum-likelihood. The paper used gradient ascent to find the maximum.
The model in the paper was slightly different since the paper used known attributes of the images to compute distance, rather than an unknown embedding. To learn an embedding you would need a much larger dataset, in which each face was shown multiple times.
This basic model assumes that all trials are independent and all participants are the same. A nice benefit of this approach is that you can easily embellish the model to include non-independence, participant effects, or other covariates. | A person repeatedly selects the two most similar items out of three. How to model/estimate a percept | A good approach to this kind of problem can be found in section 4 of the paper The Bayesian Image Retrieval System, PicHunter by Cox et al (2000). The data is a set of integer outcomes $A_1, ..., A_N | A person repeatedly selects the two most similar items out of three. How to model/estimate a perceptual distance between the items?
A good approach to this kind of problem can be found in section 4 of the paper The Bayesian Image Retrieval System, PicHunter by Cox et al (2000). The data is a set of integer outcomes $A_1, ..., A_N$ where $N$ is the number of trials. In your case, there are 3 possible outcomes per trial. I will let $A_i$ be the index of the face that was left out. The idea is to postulate a generative model for the outcome given some model parameters, and then estimate the parameters by maximum-likelihood. If we show faces $(X_1,X_2,X_3)$ and the participant says that $(X_2,X_3)$ are the most similar, then the outcome is $A=1$, with probability
$$
p(A = 1 ~|~ X_1, X_2, X_3) \propto \exp(-d(X_2,X_3)/\sigma)
$$
where $d(X_2,X_3)$ is the distance between faces 2 and 3, and $\sigma$ is a parameter for the amount of "noise" (i.e. how consistent the participants are). Since you want an embedding in Euclidean space, your distance measure would be:
$$
d(x,y) = \sqrt{\sum_k (\theta_{xk} - \theta_{yk})^2}
$$
where $\theta_x$ is the (unknown) embedding of face $x$. The parameters of this model are $\theta$ and $\sigma$, which you can estimate from data via maximum-likelihood. The paper used gradient ascent to find the maximum.
The model in the paper was slightly different since the paper used known attributes of the images to compute distance, rather than an unknown embedding. To learn an embedding you would need a much larger dataset, in which each face was shown multiple times.
This basic model assumes that all trials are independent and all participants are the same. A nice benefit of this approach is that you can easily embellish the model to include non-independence, participant effects, or other covariates. | A person repeatedly selects the two most similar items out of three. How to model/estimate a percept
A good approach to this kind of problem can be found in section 4 of the paper The Bayesian Image Retrieval System, PicHunter by Cox et al (2000). The data is a set of integer outcomes $A_1, ..., A_N |
36,024 | A person repeatedly selects the two most similar items out of three. How to model/estimate a perceptual distance between the items? | Thought:
I think eigenfaces is a decent way to convert what can be million-dimensional spaces to a few tens of dimensions.
Premise:
So lets assume that you are using a decent eigenfaces tool, or one that:
does preprocessing to align appropriate features
handles colors in an appropriate way
makes sure the pictures used are all the same size
This means you don't have "pictures" as much as you have vectors of length O(n=50) elements in size where the elements are weights for each eigen-face comprising the basis.
Analysis:
First I would create 150-element vectors (concatenation of weight) as inputs and 1-element vectors (elements of closest match) as outputs. If element 1 and 2 were closest then the output value would be "12". If elements 1 and 3 were closest then the output would be "13". If elements 2 and 3 were closest then output would be "23". Given that there are only 3 unique outputs, I could re-map them to case 1 for "12", case 2 for "13" and case 3 for "23.
Second I would want to throw away as much meaningless data as possible. This means that I would try to use something like random forests to determine which of the ~150 columns were not informative. There is also a "random evil twin method" but I don't have it at my fingertips the way R gives me with random forests. (If you know a good R library for this, I invite you to put it in the comments).
Third, in my personal experience, if you have decent sample sizes, and decent basis a random forest can usually drop you down to the ~30 variables of interest, even from as much as 15k columns. This is where you have to consider what is the general form of the answer.
You could try a dozen breeds of transforms of these variables to map the reduced inputs to the outputs:
you could train an RF of the reduced inputs and call it good.
you could train a NN on the reduced inputs if you wanted better smooth interpolation and generalization than an RF
you could use some sort of linear transformation on the inputs
there are a few dozen other ML hammers to hit it with, but when you are a hammer every problem looks like a nail.
More thoughts:
I would be curious about which of the eigenfaces the reduced set references. I would just like to see that data and let it talk to me.
I'm quite curious about your sample sizes and the nature of your variation. If you are looking at 3 rows, then having 150 columns is not going to be too productive. If you have a few thousand rows then you might be in great shape. A few hundred rows and you might be average. I would hope that you accounted for all sources of variation in terms of ethnicity, facial shape, and such.
Dont be afraid of looking through simple models first. They can be good. Their interpretation and applicability are easily evaluated. Their execution can be tested and confirmed with substantially less effort then complex and highly sensitive methods.
UPDATE:
The "random evil twin" tool is "Boruta". (link) | A person repeatedly selects the two most similar items out of three. How to model/estimate a percept | Thought:
I think eigenfaces is a decent way to convert what can be million-dimensional spaces to a few tens of dimensions.
Premise:
So lets assume that you are using a decent eigenfaces tool, or one t | A person repeatedly selects the two most similar items out of three. How to model/estimate a perceptual distance between the items?
Thought:
I think eigenfaces is a decent way to convert what can be million-dimensional spaces to a few tens of dimensions.
Premise:
So lets assume that you are using a decent eigenfaces tool, or one that:
does preprocessing to align appropriate features
handles colors in an appropriate way
makes sure the pictures used are all the same size
This means you don't have "pictures" as much as you have vectors of length O(n=50) elements in size where the elements are weights for each eigen-face comprising the basis.
Analysis:
First I would create 150-element vectors (concatenation of weight) as inputs and 1-element vectors (elements of closest match) as outputs. If element 1 and 2 were closest then the output value would be "12". If elements 1 and 3 were closest then the output would be "13". If elements 2 and 3 were closest then output would be "23". Given that there are only 3 unique outputs, I could re-map them to case 1 for "12", case 2 for "13" and case 3 for "23.
Second I would want to throw away as much meaningless data as possible. This means that I would try to use something like random forests to determine which of the ~150 columns were not informative. There is also a "random evil twin method" but I don't have it at my fingertips the way R gives me with random forests. (If you know a good R library for this, I invite you to put it in the comments).
Third, in my personal experience, if you have decent sample sizes, and decent basis a random forest can usually drop you down to the ~30 variables of interest, even from as much as 15k columns. This is where you have to consider what is the general form of the answer.
You could try a dozen breeds of transforms of these variables to map the reduced inputs to the outputs:
you could train an RF of the reduced inputs and call it good.
you could train a NN on the reduced inputs if you wanted better smooth interpolation and generalization than an RF
you could use some sort of linear transformation on the inputs
there are a few dozen other ML hammers to hit it with, but when you are a hammer every problem looks like a nail.
More thoughts:
I would be curious about which of the eigenfaces the reduced set references. I would just like to see that data and let it talk to me.
I'm quite curious about your sample sizes and the nature of your variation. If you are looking at 3 rows, then having 150 columns is not going to be too productive. If you have a few thousand rows then you might be in great shape. A few hundred rows and you might be average. I would hope that you accounted for all sources of variation in terms of ethnicity, facial shape, and such.
Dont be afraid of looking through simple models first. They can be good. Their interpretation and applicability are easily evaluated. Their execution can be tested and confirmed with substantially less effort then complex and highly sensitive methods.
UPDATE:
The "random evil twin" tool is "Boruta". (link) | A person repeatedly selects the two most similar items out of three. How to model/estimate a percept
Thought:
I think eigenfaces is a decent way to convert what can be million-dimensional spaces to a few tens of dimensions.
Premise:
So lets assume that you are using a decent eigenfaces tool, or one t |
36,025 | Posterior predictive check following ABC inference for multiple parameters | Great question for a newcomer!!!
Your ABC algorithm provides you with a sample $\theta_1,\ldots,\theta_M$ from the ABC-posterior distribution. For each component of the vector $\theta$, you thus get a sample of size $M$ from the marginal ABC-posterior. For instance here is a toy example about the mean-variance normal posterior, when using median and mad as summaries:
#normal data with 100 observations
x=rnorm(100)
#observed summaries
sumx=c(median(x),mad(x))
#normal x gamma prior
priori=function(N){
return(cbind(rnorm(N,sd=10),1/sqrt(rgamma(N,shape=2,scale=5))))
}
ABC=function(N){
prior=priori(N) #reference table
#pseudo-data
summ=matrix(0,N,2)
for (i in 1:N){
xi=rnorm(100)*prior[i,2]+prior[i,1]
summ[i,]=c(median(xi),mad(xi)) #summaries
}
#normalisation factor for the distance
mads=c(mad(summ[,1]),mad(summ[,2]))
#distance
dist=(abs(sumx[1]-summ[,1])/mads[1])+(abs(sumx[2]-summ[,2])/mads[2])
#selection
posterior=prior[dist<quantile(dist,.05),]
return(posterior)
}
If you plot
res=ABC(10^5);hist(res[,1])
you will get the marginal ABC-posterior for the normal mean.
However, if you want to do a posterior predictive check, you cannot generate one component of your posterior at a time to get pseudo-data and the corresponding summaries. You need both mean and variance to get a new normal sample! So my R code would then be
postsample=res[sample(1:length(res[,1]),10^3),]
to draw a sample from the ABC-posterior and the pseudo-data would then be generated as previously:
#pseudo-data
summ=matrix(0,M,2)
for (i in 1:M){
xi=rnorm(100)*postsample[i,2]+postsample[i,1]
summ[i,]=c(median(xi),mad(xi)) #summaries
} | Posterior predictive check following ABC inference for multiple parameters | Great question for a newcomer!!!
Your ABC algorithm provides you with a sample $\theta_1,\ldots,\theta_M$ from the ABC-posterior distribution. For each component of the vector $\theta$, you thus get a | Posterior predictive check following ABC inference for multiple parameters
Great question for a newcomer!!!
Your ABC algorithm provides you with a sample $\theta_1,\ldots,\theta_M$ from the ABC-posterior distribution. For each component of the vector $\theta$, you thus get a sample of size $M$ from the marginal ABC-posterior. For instance here is a toy example about the mean-variance normal posterior, when using median and mad as summaries:
#normal data with 100 observations
x=rnorm(100)
#observed summaries
sumx=c(median(x),mad(x))
#normal x gamma prior
priori=function(N){
return(cbind(rnorm(N,sd=10),1/sqrt(rgamma(N,shape=2,scale=5))))
}
ABC=function(N){
prior=priori(N) #reference table
#pseudo-data
summ=matrix(0,N,2)
for (i in 1:N){
xi=rnorm(100)*prior[i,2]+prior[i,1]
summ[i,]=c(median(xi),mad(xi)) #summaries
}
#normalisation factor for the distance
mads=c(mad(summ[,1]),mad(summ[,2]))
#distance
dist=(abs(sumx[1]-summ[,1])/mads[1])+(abs(sumx[2]-summ[,2])/mads[2])
#selection
posterior=prior[dist<quantile(dist,.05),]
return(posterior)
}
If you plot
res=ABC(10^5);hist(res[,1])
you will get the marginal ABC-posterior for the normal mean.
However, if you want to do a posterior predictive check, you cannot generate one component of your posterior at a time to get pseudo-data and the corresponding summaries. You need both mean and variance to get a new normal sample! So my R code would then be
postsample=res[sample(1:length(res[,1]),10^3),]
to draw a sample from the ABC-posterior and the pseudo-data would then be generated as previously:
#pseudo-data
summ=matrix(0,M,2)
for (i in 1:M){
xi=rnorm(100)*postsample[i,2]+postsample[i,1]
summ[i,]=c(median(xi),mad(xi)) #summaries
} | Posterior predictive check following ABC inference for multiple parameters
Great question for a newcomer!!!
Your ABC algorithm provides you with a sample $\theta_1,\ldots,\theta_M$ from the ABC-posterior distribution. For each component of the vector $\theta$, you thus get a |
36,026 | $\bar{X}$ versus $\mathbb{E}(\bar{X})$? | First of all, $\bar{X}$ is not an estimator of the Normal distribution. The true mean $\mu$ (as well as the true variance $\sigma^2$) is a parameter of the Normal distribution. $\bar{X}$ is an estimator for $\mu$ and this distinction is extremely important.
It sounds like that your confusion stems from not understanding that estimators themselves have distributions.
Suppose you have a true mean $\mu$ and you try to estimate what that true $\mu$ is. You do this by getting data through an experiment and compute $\bar{X}$. But $\bar{X}$ may not necessarily equal $\mu$; in other words, there is a variance to $\bar{X}$. So although the true $\mu$ may be $10$, your $\bar{X}$ may be $10.1$, or $9.7$ or some other value. So you should think of $\mathbb{E}(\bar{X})$ as the mean of the estimator of the mean. So since $\mathbb{E}(\bar{X}) = \mu$, we know that our realization of the sample mean (the $\bar{X}$) will be drawn from a distribution around $\mu$.
It would be fantastic to plug in $\mathbb{E}(\bar{X})$ to the Normal distribution since it equals $\mu$, but we don't know what $\mathbb{E}(\bar{X})$ is since the data can only tell us the realization of $\bar{X}$.
As to your second question, sometimes people write $\hat{\mu}$ is mean $\bar{X}$. The hat denotes that $\hat{\mu}$ is an estimator for $\mu$, which is what $\bar{X}$ is.
Like above, the $\mathbb{E}(\hat{\sigma}^2)$ (notice the hat) is the expected value of the estimator $\hat{\sigma}^2$, which is an estimator for the parameter $\sigma^2$ as you wrote above. | $\bar{X}$ versus $\mathbb{E}(\bar{X})$? | First of all, $\bar{X}$ is not an estimator of the Normal distribution. The true mean $\mu$ (as well as the true variance $\sigma^2$) is a parameter of the Normal distribution. $\bar{X}$ is an estimat | $\bar{X}$ versus $\mathbb{E}(\bar{X})$?
First of all, $\bar{X}$ is not an estimator of the Normal distribution. The true mean $\mu$ (as well as the true variance $\sigma^2$) is a parameter of the Normal distribution. $\bar{X}$ is an estimator for $\mu$ and this distinction is extremely important.
It sounds like that your confusion stems from not understanding that estimators themselves have distributions.
Suppose you have a true mean $\mu$ and you try to estimate what that true $\mu$ is. You do this by getting data through an experiment and compute $\bar{X}$. But $\bar{X}$ may not necessarily equal $\mu$; in other words, there is a variance to $\bar{X}$. So although the true $\mu$ may be $10$, your $\bar{X}$ may be $10.1$, or $9.7$ or some other value. So you should think of $\mathbb{E}(\bar{X})$ as the mean of the estimator of the mean. So since $\mathbb{E}(\bar{X}) = \mu$, we know that our realization of the sample mean (the $\bar{X}$) will be drawn from a distribution around $\mu$.
It would be fantastic to plug in $\mathbb{E}(\bar{X})$ to the Normal distribution since it equals $\mu$, but we don't know what $\mathbb{E}(\bar{X})$ is since the data can only tell us the realization of $\bar{X}$.
As to your second question, sometimes people write $\hat{\mu}$ is mean $\bar{X}$. The hat denotes that $\hat{\mu}$ is an estimator for $\mu$, which is what $\bar{X}$ is.
Like above, the $\mathbb{E}(\hat{\sigma}^2)$ (notice the hat) is the expected value of the estimator $\hat{\sigma}^2$, which is an estimator for the parameter $\sigma^2$ as you wrote above. | $\bar{X}$ versus $\mathbb{E}(\bar{X})$?
First of all, $\bar{X}$ is not an estimator of the Normal distribution. The true mean $\mu$ (as well as the true variance $\sigma^2$) is a parameter of the Normal distribution. $\bar{X}$ is an estimat |
36,027 | Under what circumstances is the log likelihood function of a point process concave? | This depends on the parameterization of the conditional intensity function. The (regular) point process likelihood is given by,
$L = \left[ \prod_i \lambda^\ast(t_i) \right] \exp\left(-\int \lambda^\ast(u) \,\mathrm{d}u \right) $
with the conditional intensity function $\lambda^\ast(t)$ (from Daley & Vere-Jones, 2002). The main problem is that it is a functional; it is a function of realization history. Therefore, a finite or nonparametric parameterization is needed to practically estimate it.
A successful class of estimators assume a linear form of dependence from the history. In the neuroscience community, it is (unfortunately) known as GLM due to its resemblance to (Poisson) generalized linear models when time is discretized. Here the conditional likelihood is parametrized as $\lambda^\ast(t) = f(\mathbf{h}^\top \mathbf{r})$ where $\mathbf{r}$ is the discretized finite history of the process, $\mathbf{h}$ is the (finite vector) parameter, and $f(\cdot)$ is a (pointwise) nonlinear function. It can be shown that when $f$ is convex and log-concave, the log-likelihood is concave. See (Paninski 2004).
Paninski, L. (2004). Maximum likelihood estimation of cascade point-process neural encoding models. Network: Comput. Neural Syst., 15(04):243-262. | Under what circumstances is the log likelihood function of a point process concave? | This depends on the parameterization of the conditional intensity function. The (regular) point process likelihood is given by,
$L = \left[ \prod_i \lambda^\ast(t_i) \right] \exp\left(-\int \lambda^\a | Under what circumstances is the log likelihood function of a point process concave?
This depends on the parameterization of the conditional intensity function. The (regular) point process likelihood is given by,
$L = \left[ \prod_i \lambda^\ast(t_i) \right] \exp\left(-\int \lambda^\ast(u) \,\mathrm{d}u \right) $
with the conditional intensity function $\lambda^\ast(t)$ (from Daley & Vere-Jones, 2002). The main problem is that it is a functional; it is a function of realization history. Therefore, a finite or nonparametric parameterization is needed to practically estimate it.
A successful class of estimators assume a linear form of dependence from the history. In the neuroscience community, it is (unfortunately) known as GLM due to its resemblance to (Poisson) generalized linear models when time is discretized. Here the conditional likelihood is parametrized as $\lambda^\ast(t) = f(\mathbf{h}^\top \mathbf{r})$ where $\mathbf{r}$ is the discretized finite history of the process, $\mathbf{h}$ is the (finite vector) parameter, and $f(\cdot)$ is a (pointwise) nonlinear function. It can be shown that when $f$ is convex and log-concave, the log-likelihood is concave. See (Paninski 2004).
Paninski, L. (2004). Maximum likelihood estimation of cascade point-process neural encoding models. Network: Comput. Neural Syst., 15(04):243-262. | Under what circumstances is the log likelihood function of a point process concave?
This depends on the parameterization of the conditional intensity function. The (regular) point process likelihood is given by,
$L = \left[ \prod_i \lambda^\ast(t_i) \right] \exp\left(-\int \lambda^\a |
36,028 | Under what circumstances is the log likelihood function of a point process concave? | The likelihood function, as a functional form, is also a density. Since we are interested in the logarithm of the likelihood, the issue can be broken in two:
a) Is the density "log-concave"? (is its logarithm a concave function of the random variable?)
b) Is the density (viewed as a function of the paramaters) log-concave in the parameters of interest?
The reason for this two-step approach, is that we have many established results regarding log-concavity of densities (for a list see, http://works.bepress.com/ted_bergstrom/31/).
Then, we can use various other results that provide conditions under which log-concavity is "inherited" when we examine the functional form with respect to the parameters (for example, when the parameters and the variable are linearly connected). In essence, these are "inheritance" rules for concavity/convexity in general.
To apply this approach to the much-more-to-the-point answer by @Memming, the log-likelihood in this case is
$$\ln L = \sum_i \ln \lambda^\ast(t_i) - \int \lambda^\ast(u) \,\mathrm{d}u $$
$$\Rightarrow \ln L = \sum_i \ln f(\mathbf{h}^\top \mathbf{r_i}) - \int f(u) \,\mathrm{d}u $$
If $f()$ is log-concave, then $\ln f()$ is concave in its argument, whatever that may be. Now, this argument is a linear combination of the elements of the parameter vector $\mathbf h$, so, again by established results, $\ln f()$ is also concave if viewed as a function of $\mathbf h$ alone. But then, the sum of concave functions is also concave.
Regarding the other component of the log-likelihood, the integral, we would want it convex so that its negative will be concave. A sufficient condition is that $f$ is non-decreasing, irrespective of whether it is concave or convex... I don't see how convexity of $f$ guarantees convexity of the integral, since a convex function can be decreasing in its argument. If on the other hand $f$ is non-decreasing due to other aspects of the whole setup, assuming convexity appears redundant.
I would welcome any explanation on this point. | Under what circumstances is the log likelihood function of a point process concave? | The likelihood function, as a functional form, is also a density. Since we are interested in the logarithm of the likelihood, the issue can be broken in two:
a) Is the density "log-concave"? (is its l | Under what circumstances is the log likelihood function of a point process concave?
The likelihood function, as a functional form, is also a density. Since we are interested in the logarithm of the likelihood, the issue can be broken in two:
a) Is the density "log-concave"? (is its logarithm a concave function of the random variable?)
b) Is the density (viewed as a function of the paramaters) log-concave in the parameters of interest?
The reason for this two-step approach, is that we have many established results regarding log-concavity of densities (for a list see, http://works.bepress.com/ted_bergstrom/31/).
Then, we can use various other results that provide conditions under which log-concavity is "inherited" when we examine the functional form with respect to the parameters (for example, when the parameters and the variable are linearly connected). In essence, these are "inheritance" rules for concavity/convexity in general.
To apply this approach to the much-more-to-the-point answer by @Memming, the log-likelihood in this case is
$$\ln L = \sum_i \ln \lambda^\ast(t_i) - \int \lambda^\ast(u) \,\mathrm{d}u $$
$$\Rightarrow \ln L = \sum_i \ln f(\mathbf{h}^\top \mathbf{r_i}) - \int f(u) \,\mathrm{d}u $$
If $f()$ is log-concave, then $\ln f()$ is concave in its argument, whatever that may be. Now, this argument is a linear combination of the elements of the parameter vector $\mathbf h$, so, again by established results, $\ln f()$ is also concave if viewed as a function of $\mathbf h$ alone. But then, the sum of concave functions is also concave.
Regarding the other component of the log-likelihood, the integral, we would want it convex so that its negative will be concave. A sufficient condition is that $f$ is non-decreasing, irrespective of whether it is concave or convex... I don't see how convexity of $f$ guarantees convexity of the integral, since a convex function can be decreasing in its argument. If on the other hand $f$ is non-decreasing due to other aspects of the whole setup, assuming convexity appears redundant.
I would welcome any explanation on this point. | Under what circumstances is the log likelihood function of a point process concave?
The likelihood function, as a functional form, is also a density. Since we are interested in the logarithm of the likelihood, the issue can be broken in two:
a) Is the density "log-concave"? (is its l |
36,029 | Simulation involving conditioning on sum of random variables | My comment in the referenced thread suggests one efficient approach: because $X=A+B$ and $Y=A-B$ are jointly Normal with zero covariance, they are independent, whence the simulation only needs to generate $Y$ (which has mean $0$ and variance $2$) and construct $A = (X+Y)/2$. In this example the distribution of $A^2|(A+B=3)$ is examined by means of the histogram of $10^5$ simulated values.
x <- 3
y <- rnorm(1e5, 0, sqrt(2))
a <- (x+y)/2
hist(a^2)
The expectation can be estimated as
mean(a^2)
The answer should be close to $11/4 = 2.75$. | Simulation involving conditioning on sum of random variables | My comment in the referenced thread suggests one efficient approach: because $X=A+B$ and $Y=A-B$ are jointly Normal with zero covariance, they are independent, whence the simulation only needs to gene | Simulation involving conditioning on sum of random variables
My comment in the referenced thread suggests one efficient approach: because $X=A+B$ and $Y=A-B$ are jointly Normal with zero covariance, they are independent, whence the simulation only needs to generate $Y$ (which has mean $0$ and variance $2$) and construct $A = (X+Y)/2$. In this example the distribution of $A^2|(A+B=3)$ is examined by means of the histogram of $10^5$ simulated values.
x <- 3
y <- rnorm(1e5, 0, sqrt(2))
a <- (x+y)/2
hist(a^2)
The expectation can be estimated as
mean(a^2)
The answer should be close to $11/4 = 2.75$. | Simulation involving conditioning on sum of random variables
My comment in the referenced thread suggests one efficient approach: because $X=A+B$ and $Y=A-B$ are jointly Normal with zero covariance, they are independent, whence the simulation only needs to gene |
36,030 | Simulation involving conditioning on sum of random variables | A generic way to solve this problem is to consider the change of variables from $(A,B)$ to $(A,A+B=S)$. The Jacobian of this transform being equal to one (1), the density of $(A,S)$ is
$$f_{A,S}(a,s)=f_A(a)f_B(s-a)$$
Therefore the density of $A$ conditional on $S=s$ is
$$f_{A|S}(a|s)\propto f_A(a)f_B(s-a)$$
with the proportionality term being the inverse of the marginal density of $S$, $f_S(s)^{-1}$. Since $B=S-A$, a deterministic transform, this is also the joint density of $(A,B)$ given $S$$$f_{A,B|S}(a,b|s)\propto f_A(a)f_B(s-a)\mathbb{I}_{a+b=s}$$Generating a realisation from this target can be done directly if the shape is simple enough, or by accept-reject, Metropolis-Hastings, slice sampling, or any other standard simulation method. | Simulation involving conditioning on sum of random variables | A generic way to solve this problem is to consider the change of variables from $(A,B)$ to $(A,A+B=S)$. The Jacobian of this transform being equal to one (1), the density of $(A,S)$ is
$$f_{A,S}(a,s)= | Simulation involving conditioning on sum of random variables
A generic way to solve this problem is to consider the change of variables from $(A,B)$ to $(A,A+B=S)$. The Jacobian of this transform being equal to one (1), the density of $(A,S)$ is
$$f_{A,S}(a,s)=f_A(a)f_B(s-a)$$
Therefore the density of $A$ conditional on $S=s$ is
$$f_{A|S}(a|s)\propto f_A(a)f_B(s-a)$$
with the proportionality term being the inverse of the marginal density of $S$, $f_S(s)^{-1}$. Since $B=S-A$, a deterministic transform, this is also the joint density of $(A,B)$ given $S$$$f_{A,B|S}(a,b|s)\propto f_A(a)f_B(s-a)\mathbb{I}_{a+b=s}$$Generating a realisation from this target can be done directly if the shape is simple enough, or by accept-reject, Metropolis-Hastings, slice sampling, or any other standard simulation method. | Simulation involving conditioning on sum of random variables
A generic way to solve this problem is to consider the change of variables from $(A,B)$ to $(A,A+B=S)$. The Jacobian of this transform being equal to one (1), the density of $(A,S)$ is
$$f_{A,S}(a,s)= |
36,031 | Simulation involving conditioning on sum of random variables | You could solve this problem using bootstrap samples. For example,
n <- 1000000
A <- rnorm(n)
B <- rnorm(n)
AB <- cbind(A,B)
boots <- 100
bootstrap_data <- matrix(NA,nrow=boots*n,ncol=2)
for(i in 1:boots){
index <- sample(1:n,n,replace=TRUE)
bootstrap_data[(i*n-n+1):(i*n),] <- cbind(A[index],B[index])
}
sum_AB <- bootstrap_data[,1] + bootstrap_data[,2]
x <- sum_AB[sample(1:n,1)]
idx <- which(sum_AB == x)
estimate <- mean(bootstrap_data[idx,1]^2)
Running this code for example, I obtain the following
> estimate
[1] 0.7336328
> x
[1] 0.9890429
So when $A+B=0.9890429$ then $E(A^2|A+B=0.9890429)=0.7336328$.
Now to validate that this should be the answer, let's run whuber's code in his solution. So running his code with x<-0.9890429 results in the following:
> x <- 0.9890429
> y <- rnorm(1e5, 0, sqrt(2))
> a <- (x+y)/2
> hist(a^2)
>
> mean(a^2)
[1] 0.745045
And so the two solutions are very close and coincide with one another. However, my approach to the problem should actually allow you to input any distribution you want rather than relying on the fact that the data came from Normal distributions.
A second more so brute force solution that relies on the fact that when the density is relatively large you can easily perform a brute-force calculation is the following
n <- 1000000
x <- 3 #The desired sum to condition on
A <- rnorm(n)
B <- rnorm(n)
sum_AB <- A+B
epsilon <- .01
idx <- which(sum_AB > x-epsilon & sum_AB < x+epsilon)
estimate <- mean(A[idx]^2)
estimate
Running this code we obtain the following
> estimate
[1] 2.757067
Thus running the code for $A+B=3$ results in $E(A^2|A+B=3)=2.757067$ which agrees with the true solution. | Simulation involving conditioning on sum of random variables | You could solve this problem using bootstrap samples. For example,
n <- 1000000
A <- rnorm(n)
B <- rnorm(n)
AB <- cbind(A,B)
boots <- 100
bootstrap_data <- matrix(NA,nrow=boots*n,ncol=2)
for(i i | Simulation involving conditioning on sum of random variables
You could solve this problem using bootstrap samples. For example,
n <- 1000000
A <- rnorm(n)
B <- rnorm(n)
AB <- cbind(A,B)
boots <- 100
bootstrap_data <- matrix(NA,nrow=boots*n,ncol=2)
for(i in 1:boots){
index <- sample(1:n,n,replace=TRUE)
bootstrap_data[(i*n-n+1):(i*n),] <- cbind(A[index],B[index])
}
sum_AB <- bootstrap_data[,1] + bootstrap_data[,2]
x <- sum_AB[sample(1:n,1)]
idx <- which(sum_AB == x)
estimate <- mean(bootstrap_data[idx,1]^2)
Running this code for example, I obtain the following
> estimate
[1] 0.7336328
> x
[1] 0.9890429
So when $A+B=0.9890429$ then $E(A^2|A+B=0.9890429)=0.7336328$.
Now to validate that this should be the answer, let's run whuber's code in his solution. So running his code with x<-0.9890429 results in the following:
> x <- 0.9890429
> y <- rnorm(1e5, 0, sqrt(2))
> a <- (x+y)/2
> hist(a^2)
>
> mean(a^2)
[1] 0.745045
And so the two solutions are very close and coincide with one another. However, my approach to the problem should actually allow you to input any distribution you want rather than relying on the fact that the data came from Normal distributions.
A second more so brute force solution that relies on the fact that when the density is relatively large you can easily perform a brute-force calculation is the following
n <- 1000000
x <- 3 #The desired sum to condition on
A <- rnorm(n)
B <- rnorm(n)
sum_AB <- A+B
epsilon <- .01
idx <- which(sum_AB > x-epsilon & sum_AB < x+epsilon)
estimate <- mean(A[idx]^2)
estimate
Running this code we obtain the following
> estimate
[1] 2.757067
Thus running the code for $A+B=3$ results in $E(A^2|A+B=3)=2.757067$ which agrees with the true solution. | Simulation involving conditioning on sum of random variables
You could solve this problem using bootstrap samples. For example,
n <- 1000000
A <- rnorm(n)
B <- rnorm(n)
AB <- cbind(A,B)
boots <- 100
bootstrap_data <- matrix(NA,nrow=boots*n,ncol=2)
for(i i |
36,032 | Simulation involving conditioning on sum of random variables | it seems to me that the question becomes this:
how to simulate (X,Y) conditional on X+Y=k and then
use monte carlo
to estimate EU(X,Y) for some function U(x,y)
let's start by reviewing importance sampling :
$E V(Z_1) = \int V(z) f_1(z) = \int V(z) \frac{f_1(z)}{f_2(z)} f_2(z) = E V(Z_2)\frac{f_1(Z_2)}{f_2(Z_2)}$
where the first expectations is with respect to random variable $Z_1$ with density $f_1(z)$ and the second one is wrt $Z_2$ with density $f_2(z)$.
Thus if you can randomly simulate $z_i$'s from $f_1$ then estimate using $\frac{1}{n} \sum_i V(z_i)$ or alternatively simulate $z_i$'s from $f_2$ then using $\frac{1}{n} \sum_i V(z_i) \frac{f_1(z_i)}{f_2(z_i)}$
Now let's get back to our case $U(x,y)=x^2$ and $(X,Y)$ are distributed as (X,Y) condition on X+Y=k, i.e. $\frac{f(x,y)}{\int_{x+y=k} f(x,y)}$ and let $A = \int_{x+y=k} f(x,y)$
so now the procedure is :
generate n iid copies from density $g(x)$ - and call them $X_i$
let $Y_i=k-X_i$ note the distribution of this (X,Y) is $g(x)I(x+y=k)$, where $I()$ is indicator function
the estimate is $$\frac{1}{n} \sum_i U(x_i,y_i) \frac{f(x_i,y_i)}{A g(x_i)} $$ | Simulation involving conditioning on sum of random variables | it seems to me that the question becomes this:
how to simulate (X,Y) conditional on X+Y=k and then
use monte carlo
to estimate EU(X,Y) for some function U(x,y)
let's start by reviewing importance s | Simulation involving conditioning on sum of random variables
it seems to me that the question becomes this:
how to simulate (X,Y) conditional on X+Y=k and then
use monte carlo
to estimate EU(X,Y) for some function U(x,y)
let's start by reviewing importance sampling :
$E V(Z_1) = \int V(z) f_1(z) = \int V(z) \frac{f_1(z)}{f_2(z)} f_2(z) = E V(Z_2)\frac{f_1(Z_2)}{f_2(Z_2)}$
where the first expectations is with respect to random variable $Z_1$ with density $f_1(z)$ and the second one is wrt $Z_2$ with density $f_2(z)$.
Thus if you can randomly simulate $z_i$'s from $f_1$ then estimate using $\frac{1}{n} \sum_i V(z_i)$ or alternatively simulate $z_i$'s from $f_2$ then using $\frac{1}{n} \sum_i V(z_i) \frac{f_1(z_i)}{f_2(z_i)}$
Now let's get back to our case $U(x,y)=x^2$ and $(X,Y)$ are distributed as (X,Y) condition on X+Y=k, i.e. $\frac{f(x,y)}{\int_{x+y=k} f(x,y)}$ and let $A = \int_{x+y=k} f(x,y)$
so now the procedure is :
generate n iid copies from density $g(x)$ - and call them $X_i$
let $Y_i=k-X_i$ note the distribution of this (X,Y) is $g(x)I(x+y=k)$, where $I()$ is indicator function
the estimate is $$\frac{1}{n} \sum_i U(x_i,y_i) \frac{f(x_i,y_i)}{A g(x_i)} $$ | Simulation involving conditioning on sum of random variables
it seems to me that the question becomes this:
how to simulate (X,Y) conditional on X+Y=k and then
use monte carlo
to estimate EU(X,Y) for some function U(x,y)
let's start by reviewing importance s |
36,033 | Is there a test/technique/method for comparing principal components decompositions between samples? | So as far as I understood, you imagine that you have two clouds of $n$ points each, in a $d$-dimensional space; you do PCA on each cloud separately and then want to compare the PCA results between clouds, and to test for significant differences in some of the more important PCA features.
I don't think there are any standard tests for this purpose. For any specific question one can probably come up with some method or test, but your question is a bit too broad to try to come up with any possible tests.
Still, one general approach that comes to mind is to use permutation tests. Say, you want to test if PC1 in both sample sets ("clouds") are different. You can compute angle $\theta$ between them. Then you pool all $2n$ points together in one big cloud, randomly split it into two clouds of size $n$ (this is usually called "shuffle the labels"), run two PCAs and compute $\theta$ between two PC1s. Random splits can be performed many times (say, $10\:000$ times), resulting in a distribution of $\theta$ expected under a null hypothesis of no difference between clouds. Then you simply compare your actual $\theta$ to this distribution and obtain a $p$-value.
The same approach can be used to compare e.g. largest eigenvalues. Or smallest eigenvalues. Or actually almost anything you want to compare.
Apart from that, if you want a test statistic for "equality of PCA outcomes" overall, then maybe you should simply use a test comparing two covariance matrices (without doing any PCA at all). E.g. Box's M-test (which is a multivariate generalization of a Bartlett's test for equality of variances). | Is there a test/technique/method for comparing principal components decompositions between samples? | So as far as I understood, you imagine that you have two clouds of $n$ points each, in a $d$-dimensional space; you do PCA on each cloud separately and then want to compare the PCA results between clo | Is there a test/technique/method for comparing principal components decompositions between samples?
So as far as I understood, you imagine that you have two clouds of $n$ points each, in a $d$-dimensional space; you do PCA on each cloud separately and then want to compare the PCA results between clouds, and to test for significant differences in some of the more important PCA features.
I don't think there are any standard tests for this purpose. For any specific question one can probably come up with some method or test, but your question is a bit too broad to try to come up with any possible tests.
Still, one general approach that comes to mind is to use permutation tests. Say, you want to test if PC1 in both sample sets ("clouds") are different. You can compute angle $\theta$ between them. Then you pool all $2n$ points together in one big cloud, randomly split it into two clouds of size $n$ (this is usually called "shuffle the labels"), run two PCAs and compute $\theta$ between two PC1s. Random splits can be performed many times (say, $10\:000$ times), resulting in a distribution of $\theta$ expected under a null hypothesis of no difference between clouds. Then you simply compare your actual $\theta$ to this distribution and obtain a $p$-value.
The same approach can be used to compare e.g. largest eigenvalues. Or smallest eigenvalues. Or actually almost anything you want to compare.
Apart from that, if you want a test statistic for "equality of PCA outcomes" overall, then maybe you should simply use a test comparing two covariance matrices (without doing any PCA at all). E.g. Box's M-test (which is a multivariate generalization of a Bartlett's test for equality of variances). | Is there a test/technique/method for comparing principal components decompositions between samples?
So as far as I understood, you imagine that you have two clouds of $n$ points each, in a $d$-dimensional space; you do PCA on each cloud separately and then want to compare the PCA results between clo |
36,034 | Is there a test/technique/method for comparing principal components decompositions between samples? | say you have the sample set2 1 and 2, and you found their 1 through nth principle components which are able to map out 90% of the information ( n may be different for both, and 90 is arbitrary).
You can calculate how much of the information in set1 can be retained after mapping to their principal components space and back. Set a threshold for how much information you are willing to lose before declaring the new set is different enough to deserve its own principle components. | Is there a test/technique/method for comparing principal components decompositions between samples? | say you have the sample set2 1 and 2, and you found their 1 through nth principle components which are able to map out 90% of the information ( n may be different for both, and 90 is arbitrary).
You | Is there a test/technique/method for comparing principal components decompositions between samples?
say you have the sample set2 1 and 2, and you found their 1 through nth principle components which are able to map out 90% of the information ( n may be different for both, and 90 is arbitrary).
You can calculate how much of the information in set1 can be retained after mapping to their principal components space and back. Set a threshold for how much information you are willing to lose before declaring the new set is different enough to deserve its own principle components. | Is there a test/technique/method for comparing principal components decompositions between samples?
say you have the sample set2 1 and 2, and you found their 1 through nth principle components which are able to map out 90% of the information ( n may be different for both, and 90 is arbitrary).
You |
36,035 | What is sparse regression model | I am working on a research project using Sparse Regression, and what I learned and understood so far is that $\mathbf{A}$ is the input matrix, such that $ \mathbf{A} \in \mathbb{R}^{n \times p}$ where $n$ is number of samples, and $p$ is number of features.
you are trying to find a set of optimal projection vectors $\vec{x_i} \in \mathbb{R}^{p}$ that is mostly zeros, with few nonzero entries, such that the ratio number of nonzero entries and $p$ is your sparseness parameter (typically $s$) such vectors when multiplied by your input matrix $\mathbf{A}$ will discard most of your input features, and will result in a projection $\vec{p_i} = \mathbf{A} \vec{x_i}$ such that, $\vec{p_i} \in \mathbb{R}^{n}$
what I am doing (not sure if this is the standard), is that I find another vector $\vec{\beta}$ to fit a regression model using the projection vectors $\vec{p_i}$ found earlier so that $\hat{y}=\beta_0+\sum_i{\beta_i p_i}$
I hope this helps | What is sparse regression model | I am working on a research project using Sparse Regression, and what I learned and understood so far is that $\mathbf{A}$ is the input matrix, such that $ \mathbf{A} \in \mathbb{R}^{n \times p}$ where | What is sparse regression model
I am working on a research project using Sparse Regression, and what I learned and understood so far is that $\mathbf{A}$ is the input matrix, such that $ \mathbf{A} \in \mathbb{R}^{n \times p}$ where $n$ is number of samples, and $p$ is number of features.
you are trying to find a set of optimal projection vectors $\vec{x_i} \in \mathbb{R}^{p}$ that is mostly zeros, with few nonzero entries, such that the ratio number of nonzero entries and $p$ is your sparseness parameter (typically $s$) such vectors when multiplied by your input matrix $\mathbf{A}$ will discard most of your input features, and will result in a projection $\vec{p_i} = \mathbf{A} \vec{x_i}$ such that, $\vec{p_i} \in \mathbb{R}^{n}$
what I am doing (not sure if this is the standard), is that I find another vector $\vec{\beta}$ to fit a regression model using the projection vectors $\vec{p_i}$ found earlier so that $\hat{y}=\beta_0+\sum_i{\beta_i p_i}$
I hope this helps | What is sparse regression model
I am working on a research project using Sparse Regression, and what I learned and understood so far is that $\mathbf{A}$ is the input matrix, such that $ \mathbf{A} \in \mathbb{R}^{n \times p}$ where |
36,036 | What is sparse regression model | I have been searching for the answer to this question myself and keeping ending up on this thread. I wanted to address your question #2 in case you're still interested or in case others stumble on this post.
I think your understanding of sparse regressions is wrong. I believe that sparse regression is an umbrella term for any regression that penalizes large models and therefore performs variable selection. Examples would be the LASSO, ridge regression, or sparse principal components analysis (which relies on the LASSO).
The "sparse" refers to the fact that the dimension of the parameter vector has been reduced. This is not the same as sparse data! Below is a quote from researchers at Vienna University of Technology:
"The expression 'sparse' should not be mixed up with techniques for sparse data, containing many zero entries. Here, sparsity refers to the estimated parameter vector, which is forced to contain many zeros."
http://www.statistik.tuwien.ac.at/public/filz/papers/2011JChem.pdf | What is sparse regression model | I have been searching for the answer to this question myself and keeping ending up on this thread. I wanted to address your question #2 in case you're still interested or in case others stumble on thi | What is sparse regression model
I have been searching for the answer to this question myself and keeping ending up on this thread. I wanted to address your question #2 in case you're still interested or in case others stumble on this post.
I think your understanding of sparse regressions is wrong. I believe that sparse regression is an umbrella term for any regression that penalizes large models and therefore performs variable selection. Examples would be the LASSO, ridge regression, or sparse principal components analysis (which relies on the LASSO).
The "sparse" refers to the fact that the dimension of the parameter vector has been reduced. This is not the same as sparse data! Below is a quote from researchers at Vienna University of Technology:
"The expression 'sparse' should not be mixed up with techniques for sparse data, containing many zero entries. Here, sparsity refers to the estimated parameter vector, which is forced to contain many zeros."
http://www.statistik.tuwien.ac.at/public/filz/papers/2011JChem.pdf | What is sparse regression model
I have been searching for the answer to this question myself and keeping ending up on this thread. I wanted to address your question #2 in case you're still interested or in case others stumble on thi |
36,037 | $E[e^{cX}]$ where $c < 0$ and $X$ is lognormally distributed | What you want is the moment generating function of a lognormal variable, which is known to be a hard problem. Alternatively, this is the Laplace transform, which is your expression with $c$ replaced by $-c$. You should have a look at https://en.wikipedia.org/wiki/Log-normal_distribution which do have some useful information.
The paper "On the Laplace transform of the lognormal distribution" by Søren Asmussen, Jens Ledet Jensen and Leonardo Rojas-Nandayapa do give the following approximation, which they investigate in detail. Let $X$ be lognormal with parameters $(\mu, \sigma^2)$, which means that $X=e^Y$ with $Y \sim N(\mu, \sigma^2)$. The Laplace transform is
$$
E(\exp(-\theta e^y) = e^{-\theta \mu} E(\exp(-\theta e^{Y_0})
$$
where $Y_0 \sim N(0,\sigma^2)$. So we consider the Laplace transform $L(\theta) = E(\exp(-\theta e^{Y_0})$. Then they give the approximation to $L(\theta)$:
$$
\frac1{\sqrt{1+W(\theta \sigma^2)}}\exp\left\{ -\frac1{2\sigma^2} W(\theta \sigma^2)^2 - \frac1{\sigma^2} W(\theta \sigma^2) \right\}
$$
where $\theta$ is nonnegative. Here $W$ is the Lambert W function, see https://en.wikipedia.org/wiki/Lambert_W_function . (Then the paper looks into the quality of this approximation, and compares it to older approximations). | $E[e^{cX}]$ where $c < 0$ and $X$ is lognormally distributed | What you want is the moment generating function of a lognormal variable, which is known to be a hard problem. Alternatively, this is the Laplace transform, which is your expression with $c$ replaced b | $E[e^{cX}]$ where $c < 0$ and $X$ is lognormally distributed
What you want is the moment generating function of a lognormal variable, which is known to be a hard problem. Alternatively, this is the Laplace transform, which is your expression with $c$ replaced by $-c$. You should have a look at https://en.wikipedia.org/wiki/Log-normal_distribution which do have some useful information.
The paper "On the Laplace transform of the lognormal distribution" by Søren Asmussen, Jens Ledet Jensen and Leonardo Rojas-Nandayapa do give the following approximation, which they investigate in detail. Let $X$ be lognormal with parameters $(\mu, \sigma^2)$, which means that $X=e^Y$ with $Y \sim N(\mu, \sigma^2)$. The Laplace transform is
$$
E(\exp(-\theta e^y) = e^{-\theta \mu} E(\exp(-\theta e^{Y_0})
$$
where $Y_0 \sim N(0,\sigma^2)$. So we consider the Laplace transform $L(\theta) = E(\exp(-\theta e^{Y_0})$. Then they give the approximation to $L(\theta)$:
$$
\frac1{\sqrt{1+W(\theta \sigma^2)}}\exp\left\{ -\frac1{2\sigma^2} W(\theta \sigma^2)^2 - \frac1{\sigma^2} W(\theta \sigma^2) \right\}
$$
where $\theta$ is nonnegative. Here $W$ is the Lambert W function, see https://en.wikipedia.org/wiki/Lambert_W_function . (Then the paper looks into the quality of this approximation, and compares it to older approximations). | $E[e^{cX}]$ where $c < 0$ and $X$ is lognormally distributed
What you want is the moment generating function of a lognormal variable, which is known to be a hard problem. Alternatively, this is the Laplace transform, which is your expression with $c$ replaced b |
36,038 | comparing OLS, ridge and lasso | Since the goal is prediction you can choose some distance measure and then calculate the distance between your predictions $\hat{Y}$ and the true values $Y$, choosing the method with the minimum distance. The most common distance measurement for this setting is the mean squared error: MSE = $\sum_{i=1}^n \left(\hat{Y_i} - Y_i\right)^2$. The hardest part is appropriately choosing your training and testing sets and then performing model selection procedure required by the Lasso and Ridge regularization.
First, split your data into two parts: training $X_{training}$ and testing $X_{testing}$. A common choice is 66% training, 34% testing but the choice of proportion is influenced by the size of your data set. Now forget about the testing set for a while. Train, or fit, the three models using just the training data. Model selection for the regularization parameter $\lambda$ should be chosen via cross-validation since prediction is your goal here. Finally, using the best $\lambda$, perform prediction on the testing data to obtain values for $\hat{Y}$. I haven't used the Lasso2 or MASS implementations of regularized regression but the glmnet package makes the process very straightforward because it provides a cross-validatiion function. Here's some R code to do this on the Prostate data:
require(glmnet)
data(Prostate, package = "lasso2")
## Split into training and test
n_obs = dim(Prostate)[1]
proportion_split = 0.66
train_index = sample(1:n_obs, round(n_obs * proportion_split))
y = Prostate$lpsa
X = as.matrix(Prostate[setdiff(colnames(Prostate), "lpsa")])
Xtr = X[train_index,]
Xte = X[-train_index,]
ytr = y[train_index]
yte = y[-train_index]
## Train models
ols = lm(ytr ~ Xtr)
lasso = cv.glmnet(Xtr, ytr, alpha = 1)
ridge = cv.glmnet(Xtr, ytr, alpha = 0)
## Test models
y_hat_ols = cbind(rep(1, n_obs - length(train_index)), Xte) %*% coef(ols)
y_hat_lasso = predict(lasso, Xte)
y_hat_ridge = predict(ridge, Xte)
## compare
sum((yte - y_hat_ols)^2)
sum((yte - y_hat_lasso)^2)
sum((yte - y_hat_ridge)^2)
Note that the sample() function randomly chooses the rows for training and testing so the MSE will change every time you run it. And since the Prostate data is really just meant as a demonstration dataset, no clear winner is likely to emerge. | comparing OLS, ridge and lasso | Since the goal is prediction you can choose some distance measure and then calculate the distance between your predictions $\hat{Y}$ and the true values $Y$, choosing the method with the minimum dista | comparing OLS, ridge and lasso
Since the goal is prediction you can choose some distance measure and then calculate the distance between your predictions $\hat{Y}$ and the true values $Y$, choosing the method with the minimum distance. The most common distance measurement for this setting is the mean squared error: MSE = $\sum_{i=1}^n \left(\hat{Y_i} - Y_i\right)^2$. The hardest part is appropriately choosing your training and testing sets and then performing model selection procedure required by the Lasso and Ridge regularization.
First, split your data into two parts: training $X_{training}$ and testing $X_{testing}$. A common choice is 66% training, 34% testing but the choice of proportion is influenced by the size of your data set. Now forget about the testing set for a while. Train, or fit, the three models using just the training data. Model selection for the regularization parameter $\lambda$ should be chosen via cross-validation since prediction is your goal here. Finally, using the best $\lambda$, perform prediction on the testing data to obtain values for $\hat{Y}$. I haven't used the Lasso2 or MASS implementations of regularized regression but the glmnet package makes the process very straightforward because it provides a cross-validatiion function. Here's some R code to do this on the Prostate data:
require(glmnet)
data(Prostate, package = "lasso2")
## Split into training and test
n_obs = dim(Prostate)[1]
proportion_split = 0.66
train_index = sample(1:n_obs, round(n_obs * proportion_split))
y = Prostate$lpsa
X = as.matrix(Prostate[setdiff(colnames(Prostate), "lpsa")])
Xtr = X[train_index,]
Xte = X[-train_index,]
ytr = y[train_index]
yte = y[-train_index]
## Train models
ols = lm(ytr ~ Xtr)
lasso = cv.glmnet(Xtr, ytr, alpha = 1)
ridge = cv.glmnet(Xtr, ytr, alpha = 0)
## Test models
y_hat_ols = cbind(rep(1, n_obs - length(train_index)), Xte) %*% coef(ols)
y_hat_lasso = predict(lasso, Xte)
y_hat_ridge = predict(ridge, Xte)
## compare
sum((yte - y_hat_ols)^2)
sum((yte - y_hat_lasso)^2)
sum((yte - y_hat_ridge)^2)
Note that the sample() function randomly chooses the rows for training and testing so the MSE will change every time you run it. And since the Prostate data is really just meant as a demonstration dataset, no clear winner is likely to emerge. | comparing OLS, ridge and lasso
Since the goal is prediction you can choose some distance measure and then calculate the distance between your predictions $\hat{Y}$ and the true values $Y$, choosing the method with the minimum dista |
36,039 | Required: Method of moments fitting routine for the two-parameter generalized Pareto | As the case when $\xi = 0$ simply corresponds to an exponential distribution with scale parameter $\beta$, it is trivial to compute the method of moments estimator given $\overline y$, the first sample raw moment (the second is not needed since there is only one parameter to estimate in this case). For the case $\xi < 1/2$ with $\xi \ne 0$, we can easily calculate $${\rm E}[Y] = \frac{\beta}{1-\xi}, \quad {\rm E}[Y^2] = \frac{2\beta^2}{(1-\xi)(1-2\xi)},$$ which shows that the first and second raw moments of $Y$ are defined only if $\xi < 1/2$. Consequently, setting these to their respective sample moments and solving for the parameters easily yields the closed form solution $$\widehat{\beta} = \frac{\overline y \overline{y^2}}{2(\overline{y^2} - (\overline y)^2)}, \quad \widehat{\xi} = \frac{1}{2} - \frac{(\overline y)^2}{2(\overline{y^2} - (\overline y)^2)},$$ where $\overline{y^2} = \frac{1}{n} \sum_{i=1}^n y_i^2$ is the second sample raw moment. | Required: Method of moments fitting routine for the two-parameter generalized Pareto | As the case when $\xi = 0$ simply corresponds to an exponential distribution with scale parameter $\beta$, it is trivial to compute the method of moments estimator given $\overline y$, the first sampl | Required: Method of moments fitting routine for the two-parameter generalized Pareto
As the case when $\xi = 0$ simply corresponds to an exponential distribution with scale parameter $\beta$, it is trivial to compute the method of moments estimator given $\overline y$, the first sample raw moment (the second is not needed since there is only one parameter to estimate in this case). For the case $\xi < 1/2$ with $\xi \ne 0$, we can easily calculate $${\rm E}[Y] = \frac{\beta}{1-\xi}, \quad {\rm E}[Y^2] = \frac{2\beta^2}{(1-\xi)(1-2\xi)},$$ which shows that the first and second raw moments of $Y$ are defined only if $\xi < 1/2$. Consequently, setting these to their respective sample moments and solving for the parameters easily yields the closed form solution $$\widehat{\beta} = \frac{\overline y \overline{y^2}}{2(\overline{y^2} - (\overline y)^2)}, \quad \widehat{\xi} = \frac{1}{2} - \frac{(\overline y)^2}{2(\overline{y^2} - (\overline y)^2)},$$ where $\overline{y^2} = \frac{1}{n} \sum_{i=1}^n y_i^2$ is the second sample raw moment. | Required: Method of moments fitting routine for the two-parameter generalized Pareto
As the case when $\xi = 0$ simply corresponds to an exponential distribution with scale parameter $\beta$, it is trivial to compute the method of moments estimator given $\overline y$, the first sampl |
36,040 | Background subtraction for signal and error analysis | Estimating that error correctly will be tricky. But I would like to suggest it is more important first to find a better procedure to subtract background. Only once a good procedure is available would it be worthwhile analyzing the amount of error.
In this case, using the mean is biased upwards by the contributions from the signal, which look large enough to be important. Instead use a more robust estimator. A simple one is the median. Moreover, a little more can be squeezed out of these data by adjusting the columns as well as the rows at the same time. This is called "median polish." It is very fast to carry out and is available in some software (such as R).
These figures of simulated data with 793 rows and 200 columns show the result of adjusting background with median polish. (Ignore the labels on the y-axis; they are an artifact of the software used to display the data.)
A very slight bias is still evident in the adjusted data: the top and bottom quarters, where the signal is not present in any column, are slightly greener than the middle half. However, by contrast, merely subtracting row means from the data produces obvious bias:
Scatterplots (not shown here, but produced by the code) of actual background against estimated background confirm the superiority of median polish.
Now, this is somewhat an unfair comparison, because to compute background you have previously selected columns believed not to have a signal. But there are problems with this:
If there are low-level signals present in those areas (which you haven't seen or expected), they will bias the results.
Only a small subset of the data has been used, magnifying the estimation error in background. (Using only one-tenth of the available columns approximately triples the error in estimating background compared to using the nine-tenths of columns that appear to have little or no signal.)
Furthermore, even when you are confident that some columns do not contain signals, you can still apply median polish to those columns. This will protect you from unexpected violations of your expectations (that these are signal-free areas). Moreover, this robustness will allow you to broaden the set of columns used to estimate background, because if you inadvertently include a few with some signal, they will have only a negligible effect.
Additional processing to identify isolated outliers and to estimate and extract the signal can be done, perhaps in the spirit of my answer to a recent related question.
R code:
#
# Create background.
#
set.seed(17)
i <- 1:793
row.sd <- 0.08
row.mean <- log(60) - row.sd^2/2
background <- exp(rnorm(length(i), row.mean, row.sd))
k <- sample.int(length(background), 6)
background[k] <- background[k] * 1.7
par(mfrow=c(1,1))
plot(background, type="l", col="#000080")
#
# Create a signal.
#
j <- 1:200
f <- function(i, j, center, amp=1, hwidth=5, l=0, u=6000) {
0.2*amp*outer(dbeta((i-l)/(u-l), 3, 1.1), pmax(0, 1-((j-center)/hwidth)^4))
}
#curve(f(x, 10, center=10), 0, 6000)
#image(t(f(i,j, center=100,u=600)), col=c("White", rainbow(100)))
u <- 600
signal <- f(i,j, center=10, amp=110, u=u) +
f(i,j, center=90, amp=90, u=u) +
f(i,j, center=130, amp=80, u=u)
#
# Combine signal and background, both with some iid multiplicative error.
#
ccd <- outer(background, j, function(i,j) i) * exp(rnorm(length(signal), sd=0.05)) +
signal * exp(rnorm(length(signal), sd=0.1))
ccd <- matrix(pmin(120, ccd), nrow=length(i))
#image(j, i, t(ccd), col=c(rep("#f8f8f8",20), rainbow(100)),main="CCD")
#
# Compute background via row means (not recommended).
# (Returns $row and $overall to match the values of `medpolish`.)
#
mean.subtract <- function(x) {
row <- apply(x, 1, mean)
overall <- mean(row)
row <- row - overall
return(list(row=row, overall=overall))
}
#
# Estimate background and adjust the image.
#
fit <- medpolish(ccd)
#fit <- mean.subtract(ccd)
ccd.adj <- ccd - outer(fit$row, j, function(i,j) i)
image(j, i, t(ccd.adj), col=c(rep("#f8f8f8",20), rainbow(100)),
main="Background Subtracted")
plot(fit$row + fit$overall, type="l", xlab="i")
plot(background, fit$row)
#
# Plot the results.
#
require(raster)
show <- function(y, nrows, ncols, hillshade=TRUE, aspect=1, ...) {
x <- apply(y, 2, rev)
x <- raster(x, xmn=0, xmx=ncols, ymn=0, ymx=nrows*aspect)
crs(x) <- "+proj=lcc +ellps=WGS84"
if (hillshade) {
slope <- terrain(x, opt='slope')
aspect <- terrain(x, opt='aspect')
hill <- hillShade(slope, aspect, 10, 60)
plot(hill, col=grey(0:100/100), legend=FALSE, ...)
alpha <- 0.5; add <- TRUE
} else {
alpha <- 1; add <- FALSE
}
plot(x, col=rainbow(127, alpha=alpha), add=add, ...)
}
par(mfrow=c(1,2))
asp <- length(j)/length(i) * 6/8
show(ccd, length(i), length(j), aspect=asp, main="Raw Data")
show(ccd.adj, length(i), length(j), aspect=asp, main="Adjusted Data") | Background subtraction for signal and error analysis | Estimating that error correctly will be tricky. But I would like to suggest it is more important first to find a better procedure to subtract background. Only once a good procedure is available woul | Background subtraction for signal and error analysis
Estimating that error correctly will be tricky. But I would like to suggest it is more important first to find a better procedure to subtract background. Only once a good procedure is available would it be worthwhile analyzing the amount of error.
In this case, using the mean is biased upwards by the contributions from the signal, which look large enough to be important. Instead use a more robust estimator. A simple one is the median. Moreover, a little more can be squeezed out of these data by adjusting the columns as well as the rows at the same time. This is called "median polish." It is very fast to carry out and is available in some software (such as R).
These figures of simulated data with 793 rows and 200 columns show the result of adjusting background with median polish. (Ignore the labels on the y-axis; they are an artifact of the software used to display the data.)
A very slight bias is still evident in the adjusted data: the top and bottom quarters, where the signal is not present in any column, are slightly greener than the middle half. However, by contrast, merely subtracting row means from the data produces obvious bias:
Scatterplots (not shown here, but produced by the code) of actual background against estimated background confirm the superiority of median polish.
Now, this is somewhat an unfair comparison, because to compute background you have previously selected columns believed not to have a signal. But there are problems with this:
If there are low-level signals present in those areas (which you haven't seen or expected), they will bias the results.
Only a small subset of the data has been used, magnifying the estimation error in background. (Using only one-tenth of the available columns approximately triples the error in estimating background compared to using the nine-tenths of columns that appear to have little or no signal.)
Furthermore, even when you are confident that some columns do not contain signals, you can still apply median polish to those columns. This will protect you from unexpected violations of your expectations (that these are signal-free areas). Moreover, this robustness will allow you to broaden the set of columns used to estimate background, because if you inadvertently include a few with some signal, they will have only a negligible effect.
Additional processing to identify isolated outliers and to estimate and extract the signal can be done, perhaps in the spirit of my answer to a recent related question.
R code:
#
# Create background.
#
set.seed(17)
i <- 1:793
row.sd <- 0.08
row.mean <- log(60) - row.sd^2/2
background <- exp(rnorm(length(i), row.mean, row.sd))
k <- sample.int(length(background), 6)
background[k] <- background[k] * 1.7
par(mfrow=c(1,1))
plot(background, type="l", col="#000080")
#
# Create a signal.
#
j <- 1:200
f <- function(i, j, center, amp=1, hwidth=5, l=0, u=6000) {
0.2*amp*outer(dbeta((i-l)/(u-l), 3, 1.1), pmax(0, 1-((j-center)/hwidth)^4))
}
#curve(f(x, 10, center=10), 0, 6000)
#image(t(f(i,j, center=100,u=600)), col=c("White", rainbow(100)))
u <- 600
signal <- f(i,j, center=10, amp=110, u=u) +
f(i,j, center=90, amp=90, u=u) +
f(i,j, center=130, amp=80, u=u)
#
# Combine signal and background, both with some iid multiplicative error.
#
ccd <- outer(background, j, function(i,j) i) * exp(rnorm(length(signal), sd=0.05)) +
signal * exp(rnorm(length(signal), sd=0.1))
ccd <- matrix(pmin(120, ccd), nrow=length(i))
#image(j, i, t(ccd), col=c(rep("#f8f8f8",20), rainbow(100)),main="CCD")
#
# Compute background via row means (not recommended).
# (Returns $row and $overall to match the values of `medpolish`.)
#
mean.subtract <- function(x) {
row <- apply(x, 1, mean)
overall <- mean(row)
row <- row - overall
return(list(row=row, overall=overall))
}
#
# Estimate background and adjust the image.
#
fit <- medpolish(ccd)
#fit <- mean.subtract(ccd)
ccd.adj <- ccd - outer(fit$row, j, function(i,j) i)
image(j, i, t(ccd.adj), col=c(rep("#f8f8f8",20), rainbow(100)),
main="Background Subtracted")
plot(fit$row + fit$overall, type="l", xlab="i")
plot(background, fit$row)
#
# Plot the results.
#
require(raster)
show <- function(y, nrows, ncols, hillshade=TRUE, aspect=1, ...) {
x <- apply(y, 2, rev)
x <- raster(x, xmn=0, xmx=ncols, ymn=0, ymx=nrows*aspect)
crs(x) <- "+proj=lcc +ellps=WGS84"
if (hillshade) {
slope <- terrain(x, opt='slope')
aspect <- terrain(x, opt='aspect')
hill <- hillShade(slope, aspect, 10, 60)
plot(hill, col=grey(0:100/100), legend=FALSE, ...)
alpha <- 0.5; add <- TRUE
} else {
alpha <- 1; add <- FALSE
}
plot(x, col=rainbow(127, alpha=alpha), add=add, ...)
}
par(mfrow=c(1,2))
asp <- length(j)/length(i) * 6/8
show(ccd, length(i), length(j), aspect=asp, main="Raw Data")
show(ccd.adj, length(i), length(j), aspect=asp, main="Adjusted Data") | Background subtraction for signal and error analysis
Estimating that error correctly will be tricky. But I would like to suggest it is more important first to find a better procedure to subtract background. Only once a good procedure is available woul |
36,041 | Background subtraction for signal and error analysis | On the background computation:
Since what you are doing is to measure the background by calculating the average of some values with backgroung only, you can use the error on the average ($\sigma_{Bckg}/\sqrt{n_{avg}}$) and this should estimate correctly the background variation, taking into account the variation of the background among the $n_{avg}$ pixels you considered.
You can also calculate the $Z_i$ error, if I understood correctly, and it is given by $\sqrt{N}$, so this is settled to. In order to calculate the covariance between the errors maybe you can use the covariance formula (and take a look here for an example on the covariance between two variables). I am not the most knowledgeable person about it, so I hope this rambling attract more educated people to the discussion. =) | Background subtraction for signal and error analysis | On the background computation:
Since what you are doing is to measure the background by calculating the average of some values with backgroung only, you can use the error on the average ($\sigma_{Bckg | Background subtraction for signal and error analysis
On the background computation:
Since what you are doing is to measure the background by calculating the average of some values with backgroung only, you can use the error on the average ($\sigma_{Bckg}/\sqrt{n_{avg}}$) and this should estimate correctly the background variation, taking into account the variation of the background among the $n_{avg}$ pixels you considered.
You can also calculate the $Z_i$ error, if I understood correctly, and it is given by $\sqrt{N}$, so this is settled to. In order to calculate the covariance between the errors maybe you can use the covariance formula (and take a look here for an example on the covariance between two variables). I am not the most knowledgeable person about it, so I hope this rambling attract more educated people to the discussion. =) | Background subtraction for signal and error analysis
On the background computation:
Since what you are doing is to measure the background by calculating the average of some values with backgroung only, you can use the error on the average ($\sigma_{Bckg |
36,042 | Estimating Failure Rate from Observed Data | This does seem like a good model, implemented correctly in PyMC. There are two Bayesian stats facts that we can use to confirm your answer with another method:
$\textrm{Beta}(1,1)$ is equivalent to the uniform distribution on the interval $[0,1]$;
The beta and binomial distributions are conjugate.
This means that the posterior distribution of $p$ is also a beta distribution, and (if I have got the parameterization correct) $p_{\text{posterior}} \sim \textrm{Beta}(1,1001)$. You can compare the percentiles from this analytically derived distribution with the percentiles that you have found via MCMC thusly:
> p_posterior = np.random.beta(a=1, b=1001, size=1000000)
> print np.percentile(p_posterior, [2.5, 97.5])
[2.5350975458273468e-05, 0.003681783314872197]
Here is a notebook that collects this all up.
By the way, I'm not sure if card-carrying statisticians would call this a confidence interval. There is a lot of subtlety to this issue, but the major practical objection is that you didn't specify how the 1000 devices were selected. For example, if you are a very important purchaser, and you are testing these thousand before ordering a million units, the manufacturer could go to great lengths to ensure you get a good thousand in this batch! | Estimating Failure Rate from Observed Data | This does seem like a good model, implemented correctly in PyMC. There are two Bayesian stats facts that we can use to confirm your answer with another method:
$\textrm{Beta}(1,1)$ is equivalent to | Estimating Failure Rate from Observed Data
This does seem like a good model, implemented correctly in PyMC. There are two Bayesian stats facts that we can use to confirm your answer with another method:
$\textrm{Beta}(1,1)$ is equivalent to the uniform distribution on the interval $[0,1]$;
The beta and binomial distributions are conjugate.
This means that the posterior distribution of $p$ is also a beta distribution, and (if I have got the parameterization correct) $p_{\text{posterior}} \sim \textrm{Beta}(1,1001)$. You can compare the percentiles from this analytically derived distribution with the percentiles that you have found via MCMC thusly:
> p_posterior = np.random.beta(a=1, b=1001, size=1000000)
> print np.percentile(p_posterior, [2.5, 97.5])
[2.5350975458273468e-05, 0.003681783314872197]
Here is a notebook that collects this all up.
By the way, I'm not sure if card-carrying statisticians would call this a confidence interval. There is a lot of subtlety to this issue, but the major practical objection is that you didn't specify how the 1000 devices were selected. For example, if you are a very important purchaser, and you are testing these thousand before ordering a million units, the manufacturer could go to great lengths to ensure you get a good thousand in this batch! | Estimating Failure Rate from Observed Data
This does seem like a good model, implemented correctly in PyMC. There are two Bayesian stats facts that we can use to confirm your answer with another method:
$\textrm{Beta}(1,1)$ is equivalent to |
36,043 | Why is variability measured relative to a point? | Actually, not all measures of dispersion are calculated relative to some central point. Examples include the $Q_n$ and $S_n$ statistics. Your intuition is sharp, as indeed, the calculation of these only relies on pairwise differences.
A downside of these two estimators is that they are less efficient at the gaussian distribution than the classical variance. However, an advantage is that they are more robust. | Why is variability measured relative to a point? | Actually, not all measures of dispersion are calculated relative to some central point. Examples include the $Q_n$ and $S_n$ statistics. Your intuition is sharp, as indeed, the calculation of these on | Why is variability measured relative to a point?
Actually, not all measures of dispersion are calculated relative to some central point. Examples include the $Q_n$ and $S_n$ statistics. Your intuition is sharp, as indeed, the calculation of these only relies on pairwise differences.
A downside of these two estimators is that they are less efficient at the gaussian distribution than the classical variance. However, an advantage is that they are more robust. | Why is variability measured relative to a point?
Actually, not all measures of dispersion are calculated relative to some central point. Examples include the $Q_n$ and $S_n$ statistics. Your intuition is sharp, as indeed, the calculation of these on |
36,044 | What is MA(q) model input in real world? | When the unobserved error terms are autocorrelated, there are at least 4 possible strategies since you can't just add the errors into your model:
Use OLS with a corrected variance-covariance matrix (such as Newey-West)
Transformation of the model
Feasible Generalized Least Squares
Instrumental Variables
(2) is probably most common. OLS and FGLS are appropriate for non-scalar residual variance matrices. IV is good when you have a regressor correlated with the error term. Transformations can be useful for both.
Prais-Winsten and Conchrane-Orcutt are common examples of (3) for first-order autocorrelation. These links will illustrate the mechanics nicely.
This post includes some real world examples. In the coupon example, you might imagine adding them as regressors if you could get the data. In the other examples, that makes less sense and (1)-(4) provide a feasible alternative. | What is MA(q) model input in real world? | When the unobserved error terms are autocorrelated, there are at least 4 possible strategies since you can't just add the errors into your model:
Use OLS with a corrected variance-covariance matrix ( | What is MA(q) model input in real world?
When the unobserved error terms are autocorrelated, there are at least 4 possible strategies since you can't just add the errors into your model:
Use OLS with a corrected variance-covariance matrix (such as Newey-West)
Transformation of the model
Feasible Generalized Least Squares
Instrumental Variables
(2) is probably most common. OLS and FGLS are appropriate for non-scalar residual variance matrices. IV is good when you have a regressor correlated with the error term. Transformations can be useful for both.
Prais-Winsten and Conchrane-Orcutt are common examples of (3) for first-order autocorrelation. These links will illustrate the mechanics nicely.
This post includes some real world examples. In the coupon example, you might imagine adding them as regressors if you could get the data. In the other examples, that makes less sense and (1)-(4) provide a feasible alternative. | What is MA(q) model input in real world?
When the unobserved error terms are autocorrelated, there are at least 4 possible strategies since you can't just add the errors into your model:
Use OLS with a corrected variance-covariance matrix ( |
36,045 | What is MA(q) model input in real world? | When trying to get an intuitive real world picture of MA or AR (or ARMA or ARIMA if you are extending it) I often find it useful to think of carry over effects, that is something happening in one period carries over into the next.
Here's an example: say you are modelling newspaper sales. The noise (random error) in such a model could sensibly incorporate the relatively short lived effect of newspaper headlines while the rest of the model deals with more stable things like trend and seasonality (now I'm assuming an ARIMA model but if you want a pure MA model imagine no trend or seasonality for the paper). Although the newspaper headline effect is modelled as error we might decide that this effect does indeed carry over into the next few days (a good story brings in readers who then fade away again). This would invite the inclusion of an MA term in the model - the carryover of the effect of the previous error term into the current time period.
You can think in the same way about the AR term only what is carried over here is part of the effect of the whole of the previous days sales.
Hope that helps | What is MA(q) model input in real world? | When trying to get an intuitive real world picture of MA or AR (or ARMA or ARIMA if you are extending it) I often find it useful to think of carry over effects, that is something happening in one peri | What is MA(q) model input in real world?
When trying to get an intuitive real world picture of MA or AR (or ARMA or ARIMA if you are extending it) I often find it useful to think of carry over effects, that is something happening in one period carries over into the next.
Here's an example: say you are modelling newspaper sales. The noise (random error) in such a model could sensibly incorporate the relatively short lived effect of newspaper headlines while the rest of the model deals with more stable things like trend and seasonality (now I'm assuming an ARIMA model but if you want a pure MA model imagine no trend or seasonality for the paper). Although the newspaper headline effect is modelled as error we might decide that this effect does indeed carry over into the next few days (a good story brings in readers who then fade away again). This would invite the inclusion of an MA term in the model - the carryover of the effect of the previous error term into the current time period.
You can think in the same way about the AR term only what is carried over here is part of the effect of the whole of the previous days sales.
Hope that helps | What is MA(q) model input in real world?
When trying to get an intuitive real world picture of MA or AR (or ARMA or ARIMA if you are extending it) I often find it useful to think of carry over effects, that is something happening in one peri |
36,046 | What to do when I have expected count <5 warning for a chi squared test? | A lot of the time, you may not need to do anything. The "5" rule is overly conservative, and there are a number of less restrictive (but somewhat more complex) guidelines to be found in the more recent literature (where 'more recent' means 'over the last half century or more').
For example, if all your cells have expected higher than 1 and about 80% are above 5, you're probably safe just treating it as chi-square (in that the p-values will still be roughly correct in instances you'll care to have good accuracy in). If expecteds are close to equal you can go lower.
If you are willing to condition on both margins and have access to something that can generate random tables with fixed margins (such as can be done in R), you can use simulation to estimate p-values without changing anything else. That's often the easiest to do and is built into chi-square testing in R, as an option.
There are a number of other options (some mentioned in other answers), but my usual preference is to simulate if the null distribution of the test statistic won't be adequately described by the chi-square. | What to do when I have expected count <5 warning for a chi squared test? | A lot of the time, you may not need to do anything. The "5" rule is overly conservative, and there are a number of less restrictive (but somewhat more complex) guidelines to be found in the more recen | What to do when I have expected count <5 warning for a chi squared test?
A lot of the time, you may not need to do anything. The "5" rule is overly conservative, and there are a number of less restrictive (but somewhat more complex) guidelines to be found in the more recent literature (where 'more recent' means 'over the last half century or more').
For example, if all your cells have expected higher than 1 and about 80% are above 5, you're probably safe just treating it as chi-square (in that the p-values will still be roughly correct in instances you'll care to have good accuracy in). If expecteds are close to equal you can go lower.
If you are willing to condition on both margins and have access to something that can generate random tables with fixed margins (such as can be done in R), you can use simulation to estimate p-values without changing anything else. That's often the easiest to do and is built into chi-square testing in R, as an option.
There are a number of other options (some mentioned in other answers), but my usual preference is to simulate if the null distribution of the test statistic won't be adequately described by the chi-square. | What to do when I have expected count <5 warning for a chi squared test?
A lot of the time, you may not need to do anything. The "5" rule is overly conservative, and there are a number of less restrictive (but somewhat more complex) guidelines to be found in the more recen |
36,047 | What to do when I have expected count <5 warning for a chi squared test? | First let me try to clarify the question:
You have a bunch of chi-square tests to run, specifically 12 answers to questions against several different demographic variables. All the demographic variables are nominal, with different numbers of levels (e.g. could be 2 (Male vs. female), 5 for race (or fewer depending on how you classify race) etc.
In most of your tests you get a warning about small expected cell sizes.
If that's the case, the natural thing to do is use an exact test. In SAS there is an EXACT statement in PROC FREQ. In R there is fisher.test in the stats package.
If your questions have ordinal answers there may be better methods. | What to do when I have expected count <5 warning for a chi squared test? | First let me try to clarify the question:
You have a bunch of chi-square tests to run, specifically 12 answers to questions against several different demographic variables. All the demographic variab | What to do when I have expected count <5 warning for a chi squared test?
First let me try to clarify the question:
You have a bunch of chi-square tests to run, specifically 12 answers to questions against several different demographic variables. All the demographic variables are nominal, with different numbers of levels (e.g. could be 2 (Male vs. female), 5 for race (or fewer depending on how you classify race) etc.
In most of your tests you get a warning about small expected cell sizes.
If that's the case, the natural thing to do is use an exact test. In SAS there is an EXACT statement in PROC FREQ. In R there is fisher.test in the stats package.
If your questions have ordinal answers there may be better methods. | What to do when I have expected count <5 warning for a chi squared test?
First let me try to clarify the question:
You have a bunch of chi-square tests to run, specifically 12 answers to questions against several different demographic variables. All the demographic variab |
36,048 | What to do when I have expected count <5 warning for a chi squared test? | You have two options:
ignore the warning
combine/merge the bins | What to do when I have expected count <5 warning for a chi squared test? | You have two options:
ignore the warning
combine/merge the bins | What to do when I have expected count <5 warning for a chi squared test?
You have two options:
ignore the warning
combine/merge the bins | What to do when I have expected count <5 warning for a chi squared test?
You have two options:
ignore the warning
combine/merge the bins |
36,049 | Standardizing inputs for CART | My answer at this stage is based on my intuitive understanding of how CART works, so take it face value.
Standardization does not add or subtract information contained in a given variable and does not distort its relationship to a target variable. For example, if you had a variable "age" which was a predictor for "purchase car". By changing age to (age - mean / sd ) is not going to change its relationship to purchase car, it merely maps it to a new space.
When CART looks for the best splits, it going to use entropy or gini to calculate information gain, this is not dependent on the scale of your predictor variable, rather on the resultant purity of the variable "purchase car".
So long story cut short, standardization should have no influence on your final solution. To verify this, simply run your model twice. Once on the standardized version of data and once with the original. If all goes well, you should see the same variables and order of selection, just different cut off points.
Edit: I've appended two images for your reference for a tree with and without standardized inputs. | Standardizing inputs for CART | My answer at this stage is based on my intuitive understanding of how CART works, so take it face value.
Standardization does not add or subtract information contained in a given variable and does not | Standardizing inputs for CART
My answer at this stage is based on my intuitive understanding of how CART works, so take it face value.
Standardization does not add or subtract information contained in a given variable and does not distort its relationship to a target variable. For example, if you had a variable "age" which was a predictor for "purchase car". By changing age to (age - mean / sd ) is not going to change its relationship to purchase car, it merely maps it to a new space.
When CART looks for the best splits, it going to use entropy or gini to calculate information gain, this is not dependent on the scale of your predictor variable, rather on the resultant purity of the variable "purchase car".
So long story cut short, standardization should have no influence on your final solution. To verify this, simply run your model twice. Once on the standardized version of data and once with the original. If all goes well, you should see the same variables and order of selection, just different cut off points.
Edit: I've appended two images for your reference for a tree with and without standardized inputs. | Standardizing inputs for CART
My answer at this stage is based on my intuitive understanding of how CART works, so take it face value.
Standardization does not add or subtract information contained in a given variable and does not |
36,050 | Standardizing inputs for CART | I will try to give a formal proof here to clarify things.
Step 1
We denote with $x = {x_1, x_2, .., x_n}$ a vector, and with $var(x)=\frac{1}{n}\sum_{i=1}^{n}(x_i-\frac{1}{n}\sum_{j=1}^{n}x_j)^2$ the biased sample variance.
We denote with $y = \frac{x-m}{sd}$ the scaled version.
We work out a formula for $var(y)$ in terms of $var(x),m,sd$.
$$var(y)=\frac{1}{n}\sum_{i=1}^{n}(y_i-\frac{1}{n}\sum_{j=1}^{n}y_j)^2
= \frac{1}{n}\sum_{i=1}^{n}(\frac{x_i-m}{sd}-\frac{1}{n}\sum_{j=1}^{n}\frac{x_j-m}{sd})^2
$$
$$= \frac{1}{n sd^2}\sum_{i=1}^{n}(x_i-m-\frac{1}{n}\sum_{j=1}^{n}(x_j-m))^2$$
$$
= \frac{1}{n sd^2}\sum_{i=1}^{n}(x_i-m-\frac{1}{n}\sum_{j=1}^{n}x_j+\frac{1}{n}\sum_{j=1}^{n}m)^2
$$
$$
= \frac{1}{n sd^2}\sum_{i=1}^{n}(x_i-m-\frac{1}{n}\sum_{j=1}^{n}x_j+m)^2
= \frac{1}{n sd^2}\sum_{i=1}^{n}(x_i-\frac{1}{n}\sum_{j=1}^{n}x_j)^2
$$
$$
= \frac{1}{sd^2}var(x)
$$
So we know that the variance of the scaled version is proportional with the variance of the unscaled version.
$$var(y)=\frac{1}{sd^2}var(x)$$
Step 2
For CART regression we know that the split test is evaluated with a formula like $var(x_{left})+var(x_{right})$, where $x_{left}$ consists of all observation values of the target variable which are less than or equal some threshold value on the test variable.
In order to show that various tests preserves the same order after scaling I think there is enough to say something like:
For any given two binary splits of the values of the target variables, if the evaluation function for the first split is less than the evaluation function for the second split on the unscaled variable implies that the evaluation function for the first split is less than evaluation function for the second split on scaled variable.
In plain English comparison between splits is the same for scaled and unscaled variables.
Demonstration is trivial since the evaluation function is $split(x_{left},x_{x_right})=var(x_{left})+var(x_{right})$, and we know that variance for unscaled version is proportional with variance for scaled version and this property is preserved on addition.
Final comments
Based on intuition, I agreed with @ArunJose from the begining. However, I wanted a solid proof. So, no offense, @ArunJose, I just wanted to be sure. | Standardizing inputs for CART | I will try to give a formal proof here to clarify things.
Step 1
We denote with $x = {x_1, x_2, .., x_n}$ a vector, and with $var(x)=\frac{1}{n}\sum_{i=1}^{n}(x_i-\frac{1}{n}\sum_{j=1}^{n}x_j)^2$ the | Standardizing inputs for CART
I will try to give a formal proof here to clarify things.
Step 1
We denote with $x = {x_1, x_2, .., x_n}$ a vector, and with $var(x)=\frac{1}{n}\sum_{i=1}^{n}(x_i-\frac{1}{n}\sum_{j=1}^{n}x_j)^2$ the biased sample variance.
We denote with $y = \frac{x-m}{sd}$ the scaled version.
We work out a formula for $var(y)$ in terms of $var(x),m,sd$.
$$var(y)=\frac{1}{n}\sum_{i=1}^{n}(y_i-\frac{1}{n}\sum_{j=1}^{n}y_j)^2
= \frac{1}{n}\sum_{i=1}^{n}(\frac{x_i-m}{sd}-\frac{1}{n}\sum_{j=1}^{n}\frac{x_j-m}{sd})^2
$$
$$= \frac{1}{n sd^2}\sum_{i=1}^{n}(x_i-m-\frac{1}{n}\sum_{j=1}^{n}(x_j-m))^2$$
$$
= \frac{1}{n sd^2}\sum_{i=1}^{n}(x_i-m-\frac{1}{n}\sum_{j=1}^{n}x_j+\frac{1}{n}\sum_{j=1}^{n}m)^2
$$
$$
= \frac{1}{n sd^2}\sum_{i=1}^{n}(x_i-m-\frac{1}{n}\sum_{j=1}^{n}x_j+m)^2
= \frac{1}{n sd^2}\sum_{i=1}^{n}(x_i-\frac{1}{n}\sum_{j=1}^{n}x_j)^2
$$
$$
= \frac{1}{sd^2}var(x)
$$
So we know that the variance of the scaled version is proportional with the variance of the unscaled version.
$$var(y)=\frac{1}{sd^2}var(x)$$
Step 2
For CART regression we know that the split test is evaluated with a formula like $var(x_{left})+var(x_{right})$, where $x_{left}$ consists of all observation values of the target variable which are less than or equal some threshold value on the test variable.
In order to show that various tests preserves the same order after scaling I think there is enough to say something like:
For any given two binary splits of the values of the target variables, if the evaluation function for the first split is less than the evaluation function for the second split on the unscaled variable implies that the evaluation function for the first split is less than evaluation function for the second split on scaled variable.
In plain English comparison between splits is the same for scaled and unscaled variables.
Demonstration is trivial since the evaluation function is $split(x_{left},x_{x_right})=var(x_{left})+var(x_{right})$, and we know that variance for unscaled version is proportional with variance for scaled version and this property is preserved on addition.
Final comments
Based on intuition, I agreed with @ArunJose from the begining. However, I wanted a solid proof. So, no offense, @ArunJose, I just wanted to be sure. | Standardizing inputs for CART
I will try to give a formal proof here to clarify things.
Step 1
We denote with $x = {x_1, x_2, .., x_n}$ a vector, and with $var(x)=\frac{1}{n}\sum_{i=1}^{n}(x_i-\frac{1}{n}\sum_{j=1}^{n}x_j)^2$ the |
36,051 | Statistics Modelling Question | Quick Intuitive Solution
The best approach is to accept any offer exceeding a threshold $t$ to be determined.
The expected value of such offers is $(1+t)/2$ while the expected waiting time before such an offer is seen is $1/(1-t)$, which is multiplied by the daily cost $c$. Thus we must find $t$ that maximizes the net $e(t) = (1+t)/2 - c/(1-t).$ The optimum threshold (answering the question) is $$t^{*}(c) = \max\{0, 1-\sqrt{2c}\}$$ with expected net value $$e(t^{*})=t^{*} + (t^{*}-1)^2/2 = \max\{1/2, 1-\sqrt{2c} + c\}$$
which ranges from $1/2$ (when $c\ge 1/2$) to $1$ (when $c=0$).
The strategy depends on $c$ as suggested in the question, but the number of days within which the cost will exceed $1$ (equal approximately to $1/c$) is irrelevant to the decision strategy and therefore should play no role in the solution, either. (In the real world, one might conclude after awhile that the advertising is worthless and withdraw the house for sale on that basis--but such considerations are not part of this simplified model.)
Rigorous Demonstration
When confronted with an offer of $x$ your options are to accept it (which is worth $x$) or to wait a day, when (a) you will earn $-c$ and (b) will receive the value of a random offer $X$ with distribution $F$ (which is always uniform). That expected value is independent of whatever happened in the past. Your decision procedure therefore does not vary over time and consequently can be represented as a function
$$d:[0,1]\to\{\text{accept}, \text{reject}\}$$
where $d(x)$ stipulates what to do upon receiving offer $x$. Equivalently, an optimal decision procedure amounts to a decomposition of the possible values of $x$ into two sets, $A = d^{-1}(\text{accept})$ and $R = d^{-1}(\text{reject}),$ where the offer is accepted if and only if $x\in A.$
If we accept an offer $x$ then we would certainly accept any better offer $y\gt x$, making it clear that every element of $R$ is less than every element of $A$. Therefore an optimal decision procedure amounts to choosing a threshold $t = \sup(R) = \inf(A)$ once and for all; an offer $x$ is accepted if and only if $x\ge t.$
Because the optimal choice (between acceptance and rejection) is always the one worth more, the value $v(x)$ of an offer $x$ is $x$ if $x\ge t$ and otherwise is the expected value of the sale ($e$) minus the cost of prolonging the sale a day ($c$). Whence, breaking the calculation of the expectation into two disjoint cases according to the decision options,
$$e = \mathbb{E}(v(X)) = \mathbb{E}(X | X \ge t)\Pr(X \ge t) + \mathbb{E}(e - c | X \lt t)\Pr(X \lt t).$$
Taking expectations with respect the uniform distribution of $X$,
$$e = (1-t^2)/2 + t(e-c)$$
with unique solution
$$e(t) = \frac{1/2 - c t - t^2/2}{1-t}$$
(equalling the value of $(1+t)/2 - c/(1-t)$ found intuitively.)
The $t$ in $[0,1]$ which maximizes this expectation $e(t)$ is $t^{*}(c) = 1 - \sqrt{2 c}$ provided $0 \le c \le 1/2$ and otherwise it equals $0$. In the former case $e^{*} = e(t^{*}) = 1 - \sqrt{2 c} + c$ and in the latter case $e^{*}=1/2$ (because we will pick the first offer we see, which has an expectation of $1/2$).
The optimal threshold for $c = 0.1$ is $t^{*} = 1 - \sqrt{0.2} \approx 0.553,$ with expected value $e^{*} = 1 - \sqrt{0.2} + 0.1 \approx 0.653.$ This makes sense intuitively: by accepting only offers greater than $0.553$, we would hope to receive something in the middle of $[0.553, 1]$ on average, or about $0.78$. We would, however, expect to wait a little more than a day on average before seeing such an offer, thereby costing us a little more than $0.10$
If one pays up front for each day of advertising, $c$ is added to $e^{*}$ but the optimal solution is not changed (except when $c\gt 1$, in which case it obviously is optimal not to advertise at all). Now $e^{*} = t^{*},$ which is an interesting result: the optimal threshold equals the expected value of the sale. | Statistics Modelling Question | Quick Intuitive Solution
The best approach is to accept any offer exceeding a threshold $t$ to be determined.
The expected value of such offers is $(1+t)/2$ while the expected waiting time before such | Statistics Modelling Question
Quick Intuitive Solution
The best approach is to accept any offer exceeding a threshold $t$ to be determined.
The expected value of such offers is $(1+t)/2$ while the expected waiting time before such an offer is seen is $1/(1-t)$, which is multiplied by the daily cost $c$. Thus we must find $t$ that maximizes the net $e(t) = (1+t)/2 - c/(1-t).$ The optimum threshold (answering the question) is $$t^{*}(c) = \max\{0, 1-\sqrt{2c}\}$$ with expected net value $$e(t^{*})=t^{*} + (t^{*}-1)^2/2 = \max\{1/2, 1-\sqrt{2c} + c\}$$
which ranges from $1/2$ (when $c\ge 1/2$) to $1$ (when $c=0$).
The strategy depends on $c$ as suggested in the question, but the number of days within which the cost will exceed $1$ (equal approximately to $1/c$) is irrelevant to the decision strategy and therefore should play no role in the solution, either. (In the real world, one might conclude after awhile that the advertising is worthless and withdraw the house for sale on that basis--but such considerations are not part of this simplified model.)
Rigorous Demonstration
When confronted with an offer of $x$ your options are to accept it (which is worth $x$) or to wait a day, when (a) you will earn $-c$ and (b) will receive the value of a random offer $X$ with distribution $F$ (which is always uniform). That expected value is independent of whatever happened in the past. Your decision procedure therefore does not vary over time and consequently can be represented as a function
$$d:[0,1]\to\{\text{accept}, \text{reject}\}$$
where $d(x)$ stipulates what to do upon receiving offer $x$. Equivalently, an optimal decision procedure amounts to a decomposition of the possible values of $x$ into two sets, $A = d^{-1}(\text{accept})$ and $R = d^{-1}(\text{reject}),$ where the offer is accepted if and only if $x\in A.$
If we accept an offer $x$ then we would certainly accept any better offer $y\gt x$, making it clear that every element of $R$ is less than every element of $A$. Therefore an optimal decision procedure amounts to choosing a threshold $t = \sup(R) = \inf(A)$ once and for all; an offer $x$ is accepted if and only if $x\ge t.$
Because the optimal choice (between acceptance and rejection) is always the one worth more, the value $v(x)$ of an offer $x$ is $x$ if $x\ge t$ and otherwise is the expected value of the sale ($e$) minus the cost of prolonging the sale a day ($c$). Whence, breaking the calculation of the expectation into two disjoint cases according to the decision options,
$$e = \mathbb{E}(v(X)) = \mathbb{E}(X | X \ge t)\Pr(X \ge t) + \mathbb{E}(e - c | X \lt t)\Pr(X \lt t).$$
Taking expectations with respect the uniform distribution of $X$,
$$e = (1-t^2)/2 + t(e-c)$$
with unique solution
$$e(t) = \frac{1/2 - c t - t^2/2}{1-t}$$
(equalling the value of $(1+t)/2 - c/(1-t)$ found intuitively.)
The $t$ in $[0,1]$ which maximizes this expectation $e(t)$ is $t^{*}(c) = 1 - \sqrt{2 c}$ provided $0 \le c \le 1/2$ and otherwise it equals $0$. In the former case $e^{*} = e(t^{*}) = 1 - \sqrt{2 c} + c$ and in the latter case $e^{*}=1/2$ (because we will pick the first offer we see, which has an expectation of $1/2$).
The optimal threshold for $c = 0.1$ is $t^{*} = 1 - \sqrt{0.2} \approx 0.553,$ with expected value $e^{*} = 1 - \sqrt{0.2} + 0.1 \approx 0.653.$ This makes sense intuitively: by accepting only offers greater than $0.553$, we would hope to receive something in the middle of $[0.553, 1]$ on average, or about $0.78$. We would, however, expect to wait a little more than a day on average before seeing such an offer, thereby costing us a little more than $0.10$
If one pays up front for each day of advertising, $c$ is added to $e^{*}$ but the optimal solution is not changed (except when $c\gt 1$, in which case it obviously is optimal not to advertise at all). Now $e^{*} = t^{*},$ which is an interesting result: the optimal threshold equals the expected value of the sale. | Statistics Modelling Question
Quick Intuitive Solution
The best approach is to accept any offer exceeding a threshold $t$ to be determined.
The expected value of such offers is $(1+t)/2$ while the expected waiting time before such |
36,052 | time series dimensionality reduction | You might want to consider forecastable component analysis (ForeCA), which is a dimension reduction technique for time series, specifically designed to obtaina lower dimensional space that is easier to forecast than the original time series.
Let's look at an example of monthly sunspot numbers and for computational efficiency let's just look at the 20th century.
yy <- window(sunspot.month, 1901, 2000)
plot(yy)
Sunspot numbers are only a univariate time series $y_t = (y_1, \ldots, y_T)$, but we can turn this into a multivariate time series by embedding it its lagged $(p+1)$-dimensional feature space $X_t = \left(y_t, y_{t-1}, \ldots, y_{t-p}\right)$. This is a common technique in non-linear time series analysis.
XX <- embed(yy, 24)
XX <- ts(XX, end = end(yy), freq = 12)
dim(XX)
## [1] 1166 24
In R you can use the ForeCA package to do the estimation. Note that this requires the multivariate spectrum of a $K$-dimensional time series with $T$ observations, which is stored in a $T \times K \times K$ array (one can use symmetry/Hermitian property to half the size). Hence it takes considerably longer to compute than iid dimension reduction techniques (such as PCA or ICA).
So here we take the 24-dimensional time series of embedded sunspot numbers and try to find a 6-dimensional subspace that has interesting patterns that can be easily forecasted.
library(ForeCA)
# this can take several seconds
mod.foreca <- foreca(XX, n.comp = 4,
spectrum.control = list(method = "wosa"))
mod.foreca
## ForeCA found the top 4 ForeCs of 'XX' (24 time series).
## Out of the top 4 ForeCs, 0 are white noise.
##
## Omega(ForeC 1) = 53% vs. maximum Omega(XX) = 43%.
## This is an absolute increase of 9.9 percentage points (relative: 23%) in forecastability.
##
## * * * * * * * * * *
## Use plot(), biplot(), and summary() for more details.
plot(mod.foreca)
The biplot shows that the first component all points in the same direction, which is telling us that this component will be the overall/average pattern. The barplots on the right show how the forecastable components (ForeCs) have indeed decreasing forecastability, and the first component is more forecastable than the original series. In this example, all original series have the same forecastability, as we used the embedding. For general multivariate time series, this is not the case.
Now what do these series look like?
mod.foreca$scores <- ts(mod.foreca$scores, start = start(XX),
freq = frequency(XX))
plot(mod.foreca$scores)
Indeed, the first component is more forecastable than the original series, since it is less noisy. The remaining series also show very interesting patterns, that are not visible in the original series. Note that all ForeCs are orthogonal to each other, i.e., they are uncorrelated.
round(cor(mod.foreca$scores), 3)
## ForeC1 ForeC2 ForeC3 ForeC4
## ForeC1 1 0 0 0
## ForeC2 0 1 0 0
## ForeC3 0 0 1 0
## ForeC4 0 0 0 1
The spectrum of each series also gives a good idea of the different ForeCs [sic!] in sunspot activity.
spec <- mvspectrum(mod.foreca$scores, "wosa")
plot(spec) | time series dimensionality reduction | You might want to consider forecastable component analysis (ForeCA), which is a dimension reduction technique for time series, specifically designed to obtaina lower dimensional space that is easier t | time series dimensionality reduction
You might want to consider forecastable component analysis (ForeCA), which is a dimension reduction technique for time series, specifically designed to obtaina lower dimensional space that is easier to forecast than the original time series.
Let's look at an example of monthly sunspot numbers and for computational efficiency let's just look at the 20th century.
yy <- window(sunspot.month, 1901, 2000)
plot(yy)
Sunspot numbers are only a univariate time series $y_t = (y_1, \ldots, y_T)$, but we can turn this into a multivariate time series by embedding it its lagged $(p+1)$-dimensional feature space $X_t = \left(y_t, y_{t-1}, \ldots, y_{t-p}\right)$. This is a common technique in non-linear time series analysis.
XX <- embed(yy, 24)
XX <- ts(XX, end = end(yy), freq = 12)
dim(XX)
## [1] 1166 24
In R you can use the ForeCA package to do the estimation. Note that this requires the multivariate spectrum of a $K$-dimensional time series with $T$ observations, which is stored in a $T \times K \times K$ array (one can use symmetry/Hermitian property to half the size). Hence it takes considerably longer to compute than iid dimension reduction techniques (such as PCA or ICA).
So here we take the 24-dimensional time series of embedded sunspot numbers and try to find a 6-dimensional subspace that has interesting patterns that can be easily forecasted.
library(ForeCA)
# this can take several seconds
mod.foreca <- foreca(XX, n.comp = 4,
spectrum.control = list(method = "wosa"))
mod.foreca
## ForeCA found the top 4 ForeCs of 'XX' (24 time series).
## Out of the top 4 ForeCs, 0 are white noise.
##
## Omega(ForeC 1) = 53% vs. maximum Omega(XX) = 43%.
## This is an absolute increase of 9.9 percentage points (relative: 23%) in forecastability.
##
## * * * * * * * * * *
## Use plot(), biplot(), and summary() for more details.
plot(mod.foreca)
The biplot shows that the first component all points in the same direction, which is telling us that this component will be the overall/average pattern. The barplots on the right show how the forecastable components (ForeCs) have indeed decreasing forecastability, and the first component is more forecastable than the original series. In this example, all original series have the same forecastability, as we used the embedding. For general multivariate time series, this is not the case.
Now what do these series look like?
mod.foreca$scores <- ts(mod.foreca$scores, start = start(XX),
freq = frequency(XX))
plot(mod.foreca$scores)
Indeed, the first component is more forecastable than the original series, since it is less noisy. The remaining series also show very interesting patterns, that are not visible in the original series. Note that all ForeCs are orthogonal to each other, i.e., they are uncorrelated.
round(cor(mod.foreca$scores), 3)
## ForeC1 ForeC2 ForeC3 ForeC4
## ForeC1 1 0 0 0
## ForeC2 0 1 0 0
## ForeC3 0 0 1 0
## ForeC4 0 0 0 1
The spectrum of each series also gives a good idea of the different ForeCs [sic!] in sunspot activity.
spec <- mvspectrum(mod.foreca$scores, "wosa")
plot(spec) | time series dimensionality reduction
You might want to consider forecastable component analysis (ForeCA), which is a dimension reduction technique for time series, specifically designed to obtaina lower dimensional space that is easier t |
36,053 | time series dimensionality reduction | We see data like this from a number of fast food franchises that want to predict demand in 15 minute intervals. You can construct a daily model that incorporates day-of-the-week effects, weekly effects, monthly effects , week of the-month effects , day-of-the month effects, weekend effects , holiday lead and lag effects , changes in level effects , changes in trends effects, change in day-of-the-week effects , autoregressive effects and pulse effects along with any user-specified predictor series. The daily forecasts can then be used to help forming 15 minute interval forecasts finalizing in a required reconciliation between daily forecasts and 15 minute forecasts. AUTOBOX (http://www.autobox.com) is a tool that can be helpful in this regard while other major software vendors come up short as do all the "free solutions" to this very interesting problem. In terms of full disclosure , I had a hand in developing some of these solutions for Automatic Forecasting Systems, the makers of AUTOBOX. You might try your hand at doing this in R , if you have enough time and patience to program the required steps. | time series dimensionality reduction | We see data like this from a number of fast food franchises that want to predict demand in 15 minute intervals. You can construct a daily model that incorporates day-of-the-week effects, weekly effect | time series dimensionality reduction
We see data like this from a number of fast food franchises that want to predict demand in 15 minute intervals. You can construct a daily model that incorporates day-of-the-week effects, weekly effects, monthly effects , week of the-month effects , day-of-the month effects, weekend effects , holiday lead and lag effects , changes in level effects , changes in trends effects, change in day-of-the-week effects , autoregressive effects and pulse effects along with any user-specified predictor series. The daily forecasts can then be used to help forming 15 minute interval forecasts finalizing in a required reconciliation between daily forecasts and 15 minute forecasts. AUTOBOX (http://www.autobox.com) is a tool that can be helpful in this regard while other major software vendors come up short as do all the "free solutions" to this very interesting problem. In terms of full disclosure , I had a hand in developing some of these solutions for Automatic Forecasting Systems, the makers of AUTOBOX. You might try your hand at doing this in R , if you have enough time and patience to program the required steps. | time series dimensionality reduction
We see data like this from a number of fast food franchises that want to predict demand in 15 minute intervals. You can construct a daily model that incorporates day-of-the-week effects, weekly effect |
36,054 | What does it mean to sample a probability vector from a Dirichlet distribution? | A Dirichlet distribution is often used to probabilistically categorize events among several categories. Suppose that weather events take a Dirichlet distribution. We might then think that tomorrow's weather has probability of being sunny equal to 0.25, probability of rain equal to 0.5, and probability of snow equal to 0.25. Collecting these values in a vector creates a vector of probabilities.
Another way to think about a Dirichlet distribution is the process of breaking a stick. Imagine a stick of unit length. Break that stick anywhere and retain one of the two pieces. Then break the remaining piece into two pieces and continue this as long as you desire. All of the pieces together must sum to unit length, and allocating pieces of different lengths to different events represents the probability of that event.
If you're familiar with the beta distribution, the Dirichlet distribution might become even more clear. A beta distribution is often used to describe a distribution of probabilities of dichotomous events, so its restricted to the unit interval. For example, for a Bernoulli trial, there is only a parameter $\theta$ describing the probability of a "success." Often we think of $\theta$ as being fixed, but if we are uncertain about the "true" value of $\theta$, we could think about a distribution of all possible $\theta$s, with a larger likelihood for those we consider more plausible, so perhaps $\theta \sim \text{B}(\alpha, \beta)$, where $\alpha>\beta$ concentrates more of the mass near 1 and $\beta > \alpha$ concentrates more of the mass near 0.
One might object that the beta distribution only describes the probability of a single probability, that is, for example, that $P(\theta<0.25)=0.5$, which is a scalar number. But keep in mind that the beta distribution is describing dichotomous outcomes. So by applying Kolmogorov's second axiom, we also know that $P(\theta \ge 0.25)=0.5$ as well. Collecting these results in a vector gives us a vector of probabilities.
Extending the beta distribution into three or more categories gives us the Dirichlet distribution; indeed, the PDF of the Dirichlet for two groups is the exact same as the beta distribution. | What does it mean to sample a probability vector from a Dirichlet distribution? | A Dirichlet distribution is often used to probabilistically categorize events among several categories. Suppose that weather events take a Dirichlet distribution. We might then think that tomorrow's w | What does it mean to sample a probability vector from a Dirichlet distribution?
A Dirichlet distribution is often used to probabilistically categorize events among several categories. Suppose that weather events take a Dirichlet distribution. We might then think that tomorrow's weather has probability of being sunny equal to 0.25, probability of rain equal to 0.5, and probability of snow equal to 0.25. Collecting these values in a vector creates a vector of probabilities.
Another way to think about a Dirichlet distribution is the process of breaking a stick. Imagine a stick of unit length. Break that stick anywhere and retain one of the two pieces. Then break the remaining piece into two pieces and continue this as long as you desire. All of the pieces together must sum to unit length, and allocating pieces of different lengths to different events represents the probability of that event.
If you're familiar with the beta distribution, the Dirichlet distribution might become even more clear. A beta distribution is often used to describe a distribution of probabilities of dichotomous events, so its restricted to the unit interval. For example, for a Bernoulli trial, there is only a parameter $\theta$ describing the probability of a "success." Often we think of $\theta$ as being fixed, but if we are uncertain about the "true" value of $\theta$, we could think about a distribution of all possible $\theta$s, with a larger likelihood for those we consider more plausible, so perhaps $\theta \sim \text{B}(\alpha, \beta)$, where $\alpha>\beta$ concentrates more of the mass near 1 and $\beta > \alpha$ concentrates more of the mass near 0.
One might object that the beta distribution only describes the probability of a single probability, that is, for example, that $P(\theta<0.25)=0.5$, which is a scalar number. But keep in mind that the beta distribution is describing dichotomous outcomes. So by applying Kolmogorov's second axiom, we also know that $P(\theta \ge 0.25)=0.5$ as well. Collecting these results in a vector gives us a vector of probabilities.
Extending the beta distribution into three or more categories gives us the Dirichlet distribution; indeed, the PDF of the Dirichlet for two groups is the exact same as the beta distribution. | What does it mean to sample a probability vector from a Dirichlet distribution?
A Dirichlet distribution is often used to probabilistically categorize events among several categories. Suppose that weather events take a Dirichlet distribution. We might then think that tomorrow's w |
36,055 | Why only the mean value is used in (K-means) clustering method? | There a literally thousands of k-means variations. Including soft assignment, variance and covariance (usually referred to as Gaussian Mixture Modeling or EM algorithm).
However, I'd like to point out a few things:
K-means is not based on Euclidean distance. It's based on variance minimization. Since the variance is the sum of the squared Euclidean distances, the minimum variance assignment is the one that has the smallest squared Euclidean, and the square root function is monotone. For efficiency reasons, it actually is smarter to not compute Euclidean distance (but use the squares)
If you plug in a different distance function into k-means it may stop converging. You need to minimize the same criterion in both steps; the second step is recomputing the means. Estimating the center using the arithmetic mean is a least squares estimator, and it will minimize variance. Since both functions minimize variance, k-means must converge. If you want to ensure convergence with other distances, use PAM (partitioning around medoids. The medoid minimizes the within-cluster distances for arbitrary distance functions.)
But in the end, k-means and all of its variations are IMHO more of an optimization (or more precisely, a vector quantization algorithm) than actually a cluster analysis algorithm. They will not actually "discover" structure. They will massage your data into k partitions. If you give them uniform data, with no structure beyond randomness at all, k-means will still find however many "clusters" you want it to find. k-means is happy with returning results that are essentially random. | Why only the mean value is used in (K-means) clustering method? | There a literally thousands of k-means variations. Including soft assignment, variance and covariance (usually referred to as Gaussian Mixture Modeling or EM algorithm).
However, I'd like to point out | Why only the mean value is used in (K-means) clustering method?
There a literally thousands of k-means variations. Including soft assignment, variance and covariance (usually referred to as Gaussian Mixture Modeling or EM algorithm).
However, I'd like to point out a few things:
K-means is not based on Euclidean distance. It's based on variance minimization. Since the variance is the sum of the squared Euclidean distances, the minimum variance assignment is the one that has the smallest squared Euclidean, and the square root function is monotone. For efficiency reasons, it actually is smarter to not compute Euclidean distance (but use the squares)
If you plug in a different distance function into k-means it may stop converging. You need to minimize the same criterion in both steps; the second step is recomputing the means. Estimating the center using the arithmetic mean is a least squares estimator, and it will minimize variance. Since both functions minimize variance, k-means must converge. If you want to ensure convergence with other distances, use PAM (partitioning around medoids. The medoid minimizes the within-cluster distances for arbitrary distance functions.)
But in the end, k-means and all of its variations are IMHO more of an optimization (or more precisely, a vector quantization algorithm) than actually a cluster analysis algorithm. They will not actually "discover" structure. They will massage your data into k partitions. If you give them uniform data, with no structure beyond randomness at all, k-means will still find however many "clusters" you want it to find. k-means is happy with returning results that are essentially random. | Why only the mean value is used in (K-means) clustering method?
There a literally thousands of k-means variations. Including soft assignment, variance and covariance (usually referred to as Gaussian Mixture Modeling or EM algorithm).
However, I'd like to point out |
36,056 | Why only the mean value is used in (K-means) clustering method? | There are lots of different clustering techniques out there, and K-means is just one approach. As DL Dahly commented, EM algorithms can be used for clustering in much the way you described. It's worth noting that the main difference between K-means and using EM with a guassian mixture model for clustering is the shape of the clusters: the centroid will still closely approximate the mean of the points in the group, but K-means will give a spherical cluster whereas a gaussian kernel will give an ellipsoid.
Hierarchical clustering uses a completely different approach. Density based clustering is motivated by a similar heuristic as mean based clustering, but obviously gives different results. There are plenty of clustering techniques that don't consider any kind of mean.
Really when it comes down to it, the choice of algorithm is a function of the problem domain and experimentation (i.e. seeing what works). | Why only the mean value is used in (K-means) clustering method? | There are lots of different clustering techniques out there, and K-means is just one approach. As DL Dahly commented, EM algorithms can be used for clustering in much the way you described. It's worth | Why only the mean value is used in (K-means) clustering method?
There are lots of different clustering techniques out there, and K-means is just one approach. As DL Dahly commented, EM algorithms can be used for clustering in much the way you described. It's worth noting that the main difference between K-means and using EM with a guassian mixture model for clustering is the shape of the clusters: the centroid will still closely approximate the mean of the points in the group, but K-means will give a spherical cluster whereas a gaussian kernel will give an ellipsoid.
Hierarchical clustering uses a completely different approach. Density based clustering is motivated by a similar heuristic as mean based clustering, but obviously gives different results. There are plenty of clustering techniques that don't consider any kind of mean.
Really when it comes down to it, the choice of algorithm is a function of the problem domain and experimentation (i.e. seeing what works). | Why only the mean value is used in (K-means) clustering method?
There are lots of different clustering techniques out there, and K-means is just one approach. As DL Dahly commented, EM algorithms can be used for clustering in much the way you described. It's worth |
36,057 | Confusion over Lagged Dependent and HAC Standard Errors | Question 3)
In notation to be understood as matrix-vector, assume that the correct specification is
$$y = X\beta + \gamma y_{-1}+ e$$
(where $X$ contains the constant and the $X_1$ variable and $e$ is white noise, and $E(e\mid X) =0$), but you specify and estimate instead
$$y = X\beta + u$$
i.e. without including the LAD, and so in reality $u =\gamma y_{-1}+ e$.
Then OLS estimation will give
$$\hat \beta = (X'X)^{-1}X'y = (X'X)^{-1}X'(X\beta + \gamma y_{-1}+ e) $$
$$= \beta + (X'X)^{-1}X'y_{-1}\gamma +(X'X)^{-1}X'e$$
The expected value of the estimator is
$$E(\hat \beta) = \beta + E\Big[(X'X)^{-1}X'y_{-1}\gamma\Big] +E\Big[(X'X)^{-1}X'e\Big]$$
and using the law of iterated expectations
$$E(\hat \beta) = \beta + E\Big(E\Big[(X'X)^{-1}X'y_{-1}\gamma\Big]\mid X\Big) +E\Big(E\Big[(X'X)^{-1}X'e\Big]\mid X\Big)$$
$$= \beta + E\Big((X'X)^{-1}X'E\Big[y_{-1}\gamma\mid X\Big]\Big) +E\Big((X'X)^{-1}X'E\Big[e\mid X\Big]\Big)$$
$$=\beta + E\Big((X'X)^{-1}X'E\Big[y_{-1}\gamma\mid X\Big]\Big) + 0 $$
the last term being zero per our assumptions. But $E\Big[y_{-1}\gamma\mid X\Big] \neq 0$, because $X$ contains all the regressors (from all time periods), and so there is correlation with the LAD vector. Therefore $E(\hat \beta) \neq \beta$. In other words, ignoring the lag dependent variable will not make the estimator unbiased, as long as $\gamma \neq 0$, i.e. as long as the LAD does belong to the regression.
Question 1)
Assume now that you specify correctly, and denote $Z$ the matrix containing also the LAD.
Here (using the same steps as before)
$$\hat \beta = \beta + (Z'Z)^{-1}Z'e$$
and
$$E(\hat \beta) = \beta + E\Big((Z'Z)^{-1}Z'E\Big[e\mid Z\Big]\Big)$$
But is $e$ (the vector) independent of $Z$? No, because $Z$ contains the LAD from all time periods bar the most recent, while $e$ contains the errors from all time periods bar the first. So even if $e$ is not serially correlated, it is correlated with the vector $y_{-1}$.
So indeed, the last term is not zero and $$E(\hat \beta) \neq \beta$$ the OLS estimator is biased.
But the OLS estimator will be consistent if indeed the inclusion of the LAD eliminates serial correlation, because (using the properties of the plim operator)
$$\operatorname{plim}\hat \beta = \beta + \operatorname{plim}\left(\frac 1{n-1} Z'Z\right)^{-1}\cdot \operatorname{plim}\left(\frac 1{n-1}Z'e\right)$$
Part of the standard assumptions (and rather "easily" satisfied), is that the first plim of the product converges to something finite. The second plim written explicitly is (and using the stationarity assumption to invoke the LLN)
$$\operatorname{plim}\left(\frac 1{n-1}Z'\mathbf e\right) = \left[\begin{matrix}
\operatorname{plim}\frac 1{n-1}\sum_{i=2}^ne_i \\
\operatorname{plim}\frac 1{n-1}\sum_{i=2}^nx_{i}e_i \\
\operatorname{plim}\frac 1{n-1}\sum_{i=2}^ny_{i-1}e_i \\
\end{matrix}\right] \rightarrow\left[\begin{matrix}
E(e_i) \\
E(x_{i}e_i) \\
E(y_{i-1}e_i) \\
\end{matrix}\right]\; \forall i$$
$E(e\mid X) = 0 \Rightarrow E(e_i) = 0$, and also that $E(x_{i}e_i)=0$, for all $i$.
Finally, IF serial correlation has been removed, then $E(y_{i-1}e_i) =0$ also. So this plim goes to zero and therefore
$$\operatorname{plim}\hat \beta = \beta$$
i.e. the OLS estimator is indeed consistent in this case. So the "summary" is correct.
Question 2)
The full sentence from Wooldridge is
"It is also valid to use the SC-robust standard errors in models with lagged dependent variables assuming, of course, that there is good reason for allowing serial correlation in such models".
meaning, when we have good reasons to believe that the inclusion of lagged dependent variables does not fully remove autocorrelation. And it seems we got ourselves a Catch-22: if serial correlation (SC) has been removed, why use SC-robust std errors? And if serial correlation has not been removed, our OLS estimator will be inconsistent, so in such a case is it meaningful/useful/appropriate to use asymptotic inference? Well, it appears that if we do suspect that SC still exists, it is better to try to do something about it, regardless. But your comment has merit, and I would suggest to contact Wooldridge directly on the matter, in order to get an authoritative answer. | Confusion over Lagged Dependent and HAC Standard Errors | Question 3)
In notation to be understood as matrix-vector, assume that the correct specification is
$$y = X\beta + \gamma y_{-1}+ e$$
(where $X$ contains the constant and the $X_1$ variable and $e$ i | Confusion over Lagged Dependent and HAC Standard Errors
Question 3)
In notation to be understood as matrix-vector, assume that the correct specification is
$$y = X\beta + \gamma y_{-1}+ e$$
(where $X$ contains the constant and the $X_1$ variable and $e$ is white noise, and $E(e\mid X) =0$), but you specify and estimate instead
$$y = X\beta + u$$
i.e. without including the LAD, and so in reality $u =\gamma y_{-1}+ e$.
Then OLS estimation will give
$$\hat \beta = (X'X)^{-1}X'y = (X'X)^{-1}X'(X\beta + \gamma y_{-1}+ e) $$
$$= \beta + (X'X)^{-1}X'y_{-1}\gamma +(X'X)^{-1}X'e$$
The expected value of the estimator is
$$E(\hat \beta) = \beta + E\Big[(X'X)^{-1}X'y_{-1}\gamma\Big] +E\Big[(X'X)^{-1}X'e\Big]$$
and using the law of iterated expectations
$$E(\hat \beta) = \beta + E\Big(E\Big[(X'X)^{-1}X'y_{-1}\gamma\Big]\mid X\Big) +E\Big(E\Big[(X'X)^{-1}X'e\Big]\mid X\Big)$$
$$= \beta + E\Big((X'X)^{-1}X'E\Big[y_{-1}\gamma\mid X\Big]\Big) +E\Big((X'X)^{-1}X'E\Big[e\mid X\Big]\Big)$$
$$=\beta + E\Big((X'X)^{-1}X'E\Big[y_{-1}\gamma\mid X\Big]\Big) + 0 $$
the last term being zero per our assumptions. But $E\Big[y_{-1}\gamma\mid X\Big] \neq 0$, because $X$ contains all the regressors (from all time periods), and so there is correlation with the LAD vector. Therefore $E(\hat \beta) \neq \beta$. In other words, ignoring the lag dependent variable will not make the estimator unbiased, as long as $\gamma \neq 0$, i.e. as long as the LAD does belong to the regression.
Question 1)
Assume now that you specify correctly, and denote $Z$ the matrix containing also the LAD.
Here (using the same steps as before)
$$\hat \beta = \beta + (Z'Z)^{-1}Z'e$$
and
$$E(\hat \beta) = \beta + E\Big((Z'Z)^{-1}Z'E\Big[e\mid Z\Big]\Big)$$
But is $e$ (the vector) independent of $Z$? No, because $Z$ contains the LAD from all time periods bar the most recent, while $e$ contains the errors from all time periods bar the first. So even if $e$ is not serially correlated, it is correlated with the vector $y_{-1}$.
So indeed, the last term is not zero and $$E(\hat \beta) \neq \beta$$ the OLS estimator is biased.
But the OLS estimator will be consistent if indeed the inclusion of the LAD eliminates serial correlation, because (using the properties of the plim operator)
$$\operatorname{plim}\hat \beta = \beta + \operatorname{plim}\left(\frac 1{n-1} Z'Z\right)^{-1}\cdot \operatorname{plim}\left(\frac 1{n-1}Z'e\right)$$
Part of the standard assumptions (and rather "easily" satisfied), is that the first plim of the product converges to something finite. The second plim written explicitly is (and using the stationarity assumption to invoke the LLN)
$$\operatorname{plim}\left(\frac 1{n-1}Z'\mathbf e\right) = \left[\begin{matrix}
\operatorname{plim}\frac 1{n-1}\sum_{i=2}^ne_i \\
\operatorname{plim}\frac 1{n-1}\sum_{i=2}^nx_{i}e_i \\
\operatorname{plim}\frac 1{n-1}\sum_{i=2}^ny_{i-1}e_i \\
\end{matrix}\right] \rightarrow\left[\begin{matrix}
E(e_i) \\
E(x_{i}e_i) \\
E(y_{i-1}e_i) \\
\end{matrix}\right]\; \forall i$$
$E(e\mid X) = 0 \Rightarrow E(e_i) = 0$, and also that $E(x_{i}e_i)=0$, for all $i$.
Finally, IF serial correlation has been removed, then $E(y_{i-1}e_i) =0$ also. So this plim goes to zero and therefore
$$\operatorname{plim}\hat \beta = \beta$$
i.e. the OLS estimator is indeed consistent in this case. So the "summary" is correct.
Question 2)
The full sentence from Wooldridge is
"It is also valid to use the SC-robust standard errors in models with lagged dependent variables assuming, of course, that there is good reason for allowing serial correlation in such models".
meaning, when we have good reasons to believe that the inclusion of lagged dependent variables does not fully remove autocorrelation. And it seems we got ourselves a Catch-22: if serial correlation (SC) has been removed, why use SC-robust std errors? And if serial correlation has not been removed, our OLS estimator will be inconsistent, so in such a case is it meaningful/useful/appropriate to use asymptotic inference? Well, it appears that if we do suspect that SC still exists, it is better to try to do something about it, regardless. But your comment has merit, and I would suggest to contact Wooldridge directly on the matter, in order to get an authoritative answer. | Confusion over Lagged Dependent and HAC Standard Errors
Question 3)
In notation to be understood as matrix-vector, assume that the correct specification is
$$y = X\beta + \gamma y_{-1}+ e$$
(where $X$ contains the constant and the $X_1$ variable and $e$ i |
36,058 | Does more variables mean tighter confidence intervals? | do I ALWAYS get a tighter confidence interval if I include more variables in my model?
Yes, you do (EDIT: ...basically. Subject to some caveats. See comments below). Here's why: adding more variables reduces the SSE and thereby the variance of the model, on which your confidence and prediction intervals depend. This even happens (to a lesser extent) when the variables you are adding are completely independent of the response:
a=rnorm(100)
b=rnorm(100)
c=rnorm(100)
d=rnorm(100)
e=rnorm(100)
summary(lm(a~b))$sigma # 0.9634881
summary(lm(a~b+c))$sigma # 0.961776
summary(lm(a~b+c+d))$sigma # 0.9640104 (Went up a smidgen)
summary(lm(a~b+c+d+e))$sigma # 0.9588491 (and down we go again...)
But this does not mean you have a better model. In fact, this is how overfitting happens.
Consider the following example: let's say we draw a sample from a quadratic function with noise added.
A first order model will fit this poorly and have very high bias.
A second order model fits well, which is not surprising since this is how the data was generated in the first place.
But let's say we don't know that's how the data was generated, so we fit increasingly higher order models.
As the complexity of the model increases, we're able to capture more of the fluctuations in the data, effectively fitting our model to the noise, to patterns that aren't really there. With enough complexity, we can build a model that will go through each point in our data nearly exactly.
As you can see, as the order of the model increases, so does the fit. We can see this quantitatively by plotting the training error:
But if we draw more points from our generating function, we will observe the test error diverges rapidly.
The moral of the story is to be wary of overfitting your model. Don't just rely on metrics like adjusted-R2, consider validating your model against held out data (a "test" set) or evaluating your model using techniques like cross validation.
For posterity, here's the code for this tutorial:
set.seed(123)
xv = seq(-5,15,length.out=1e4)
X=sample(xv,20)
gen=function(v){v^2 + 7*rnorm(length(v))}
Y=gen(X)
df = data.frame(x=X,y=Y)
plot(X,Y)
lines(xv,xv^2, col="blue") # true model
legend("topleft", "True Model", lty=1, col="blue")
build_formula = function(N){
paste('y~poly(x,',N,',raw=T)')
}
deg=c(1,2,10,20)
formulas = sapply(deg[2:4], build_formula)
formulas = c('y~x', formulas)
pred = lapply(formulas
,function(f){
predict(
lm(f, data=df)
,newdata=list(x=xv))
})
# Progressively add fit lines to the plot
lapply(1:length(pred), function(i){
plot(df, main=paste(deg[i],"-Degree"))
lapply(1:i,function(n){
lines(xv,pred[[n]], col=n)
})
})
# let's actually generate models from poly 1:20 to calculate MSE
deg=seq(1,20)
formulas = sapply(deg, build_formula)
pred.train = lapply(formulas
,function(f){
predict(
lm(f, data=df)
,newdata=list(x=df$x))
})
pred.test = lapply(formulas
,function(f){
predict(
lm(f, data=df)
,newdata=list(x=xv))
})
rmse.train = unlist(lapply(pred.train,function(P){
regr.eval(df$y,P, stats="rmse")
}))
yv=gen(xv)
rmse.test = unlist(lapply(pred.test,function(P){
regr.eval(yv,P, stats="rmse")
}))
plot(rmse.train, type='l', col='blue'
, main="Training Error"
,xlab="Model Complexity")
plot(rmse.test, type='l', col='red'
, main="Train vs. Test Error"
,xlab="Model Complexity")
lines(rmse.train, type='l', col='blue')
legend("topleft", c("Test","Train"), lty=c(1,1), col=c("red","blue")) | Does more variables mean tighter confidence intervals? | do I ALWAYS get a tighter confidence interval if I include more variables in my model?
Yes, you do (EDIT: ...basically. Subject to some caveats. See comments below). Here's why: adding more variables | Does more variables mean tighter confidence intervals?
do I ALWAYS get a tighter confidence interval if I include more variables in my model?
Yes, you do (EDIT: ...basically. Subject to some caveats. See comments below). Here's why: adding more variables reduces the SSE and thereby the variance of the model, on which your confidence and prediction intervals depend. This even happens (to a lesser extent) when the variables you are adding are completely independent of the response:
a=rnorm(100)
b=rnorm(100)
c=rnorm(100)
d=rnorm(100)
e=rnorm(100)
summary(lm(a~b))$sigma # 0.9634881
summary(lm(a~b+c))$sigma # 0.961776
summary(lm(a~b+c+d))$sigma # 0.9640104 (Went up a smidgen)
summary(lm(a~b+c+d+e))$sigma # 0.9588491 (and down we go again...)
But this does not mean you have a better model. In fact, this is how overfitting happens.
Consider the following example: let's say we draw a sample from a quadratic function with noise added.
A first order model will fit this poorly and have very high bias.
A second order model fits well, which is not surprising since this is how the data was generated in the first place.
But let's say we don't know that's how the data was generated, so we fit increasingly higher order models.
As the complexity of the model increases, we're able to capture more of the fluctuations in the data, effectively fitting our model to the noise, to patterns that aren't really there. With enough complexity, we can build a model that will go through each point in our data nearly exactly.
As you can see, as the order of the model increases, so does the fit. We can see this quantitatively by plotting the training error:
But if we draw more points from our generating function, we will observe the test error diverges rapidly.
The moral of the story is to be wary of overfitting your model. Don't just rely on metrics like adjusted-R2, consider validating your model against held out data (a "test" set) or evaluating your model using techniques like cross validation.
For posterity, here's the code for this tutorial:
set.seed(123)
xv = seq(-5,15,length.out=1e4)
X=sample(xv,20)
gen=function(v){v^2 + 7*rnorm(length(v))}
Y=gen(X)
df = data.frame(x=X,y=Y)
plot(X,Y)
lines(xv,xv^2, col="blue") # true model
legend("topleft", "True Model", lty=1, col="blue")
build_formula = function(N){
paste('y~poly(x,',N,',raw=T)')
}
deg=c(1,2,10,20)
formulas = sapply(deg[2:4], build_formula)
formulas = c('y~x', formulas)
pred = lapply(formulas
,function(f){
predict(
lm(f, data=df)
,newdata=list(x=xv))
})
# Progressively add fit lines to the plot
lapply(1:length(pred), function(i){
plot(df, main=paste(deg[i],"-Degree"))
lapply(1:i,function(n){
lines(xv,pred[[n]], col=n)
})
})
# let's actually generate models from poly 1:20 to calculate MSE
deg=seq(1,20)
formulas = sapply(deg, build_formula)
pred.train = lapply(formulas
,function(f){
predict(
lm(f, data=df)
,newdata=list(x=df$x))
})
pred.test = lapply(formulas
,function(f){
predict(
lm(f, data=df)
,newdata=list(x=xv))
})
rmse.train = unlist(lapply(pred.train,function(P){
regr.eval(df$y,P, stats="rmse")
}))
yv=gen(xv)
rmse.test = unlist(lapply(pred.test,function(P){
regr.eval(yv,P, stats="rmse")
}))
plot(rmse.train, type='l', col='blue'
, main="Training Error"
,xlab="Model Complexity")
plot(rmse.test, type='l', col='red'
, main="Train vs. Test Error"
,xlab="Model Complexity")
lines(rmse.train, type='l', col='blue')
legend("topleft", c("Test","Train"), lty=c(1,1), col=c("red","blue")) | Does more variables mean tighter confidence intervals?
do I ALWAYS get a tighter confidence interval if I include more variables in my model?
Yes, you do (EDIT: ...basically. Subject to some caveats. See comments below). Here's why: adding more variables |
36,059 | Question on the consequences of the Kolmogorov axioms | Let X be a standard normal random variable with $S=(-\infty,\infty)$. Here, $P(X=1)=0$ but $\{1\}\neq \emptyset$.
To show that $P(A)=1$ does not imply that $A=S$, consider the following. You flip a coin an infinite number of times. The event of getting all heads $\{H,H,H,H,...\}$ is in the sample space because it is physically possible that tails never appears. Now, let $A = \{\text{flip at least one heads in the infinite flips}\}\neq S$. However, $P(A) = 1 - P(\text{all tails in the infinite flips}) = 1 - (.5)^{\infty} = 1$. | Question on the consequences of the Kolmogorov axioms | Let X be a standard normal random variable with $S=(-\infty,\infty)$. Here, $P(X=1)=0$ but $\{1\}\neq \emptyset$.
To show that $P(A)=1$ does not imply that $A=S$, consider the following. You flip a c | Question on the consequences of the Kolmogorov axioms
Let X be a standard normal random variable with $S=(-\infty,\infty)$. Here, $P(X=1)=0$ but $\{1\}\neq \emptyset$.
To show that $P(A)=1$ does not imply that $A=S$, consider the following. You flip a coin an infinite number of times. The event of getting all heads $\{H,H,H,H,...\}$ is in the sample space because it is physically possible that tails never appears. Now, let $A = \{\text{flip at least one heads in the infinite flips}\}\neq S$. However, $P(A) = 1 - P(\text{all tails in the infinite flips}) = 1 - (.5)^{\infty} = 1$. | Question on the consequences of the Kolmogorov axioms
Let X be a standard normal random variable with $S=(-\infty,\infty)$. Here, $P(X=1)=0$ but $\{1\}\neq \emptyset$.
To show that $P(A)=1$ does not imply that $A=S$, consider the following. You flip a c |
36,060 | Question on the consequences of the Kolmogorov axioms | Following the arguments from @TrynnaDoStat:
Let $X$ be a standard normal random distribution, and therefore $X$ has support on whole $\mathbb{R}$. $P(X=1) = 0$ but $\{1\} \neq \emptyset$
Then using the principle that
$P(\Omega \backslash E) = 1 - P(E)$
$P(X \in \mathbb{R} \backslash ${1}$) = 1 - 0 = 1$, but $\mathbb{R} \backslash \{1\} \neq \mathbb{R}$ | Question on the consequences of the Kolmogorov axioms | Following the arguments from @TrynnaDoStat:
Let $X$ be a standard normal random distribution, and therefore $X$ has support on whole $\mathbb{R}$. $P(X=1) = 0$ but $\{1\} \neq \emptyset$
Then using th | Question on the consequences of the Kolmogorov axioms
Following the arguments from @TrynnaDoStat:
Let $X$ be a standard normal random distribution, and therefore $X$ has support on whole $\mathbb{R}$. $P(X=1) = 0$ but $\{1\} \neq \emptyset$
Then using the principle that
$P(\Omega \backslash E) = 1 - P(E)$
$P(X \in \mathbb{R} \backslash ${1}$) = 1 - 0 = 1$, but $\mathbb{R} \backslash \{1\} \neq \mathbb{R}$ | Question on the consequences of the Kolmogorov axioms
Following the arguments from @TrynnaDoStat:
Let $X$ be a standard normal random distribution, and therefore $X$ has support on whole $\mathbb{R}$. $P(X=1) = 0$ but $\{1\} \neq \emptyset$
Then using th |
36,061 | Question on the consequences of the Kolmogorov axioms | Take the uniform distribution on $S=[0,1]$. Now, $P[S]=1$, but also $P[S\setminus \{1\}]=1$ and $P[S \setminus \{1,1/2,1/3,\ldots\}] = 1$ as well even though both of the latter two are strict subsets of $S$. (Here the notation $A \setminus B$ means all elements belonging to set $A$ and not belonging to $B$.)
To answer the almost surely part of your question:
if P(A)=0 this means that event A is almost never possible and if
P(A)=1 will almost surely occur.
I think you have got it the wrong way round: "almost surely" is defined to be $P(A)=1$.
To fully understand the intricacies and subtleties of the definitions, some familiarity with measure theory is helpful. See, e.g. the Cantor set, which has measure ["length"] zero but contains a uncountably infinite number of points, compared to any interval on the real line $(a,b)$ which has again uncountably infinite number of points but nonzero measure $b-a$.
Given that you are working in Applied statistics, these complicated sets are probably irrelevant to you, so I would not worry about it ( its just something authors like to put in!). | Question on the consequences of the Kolmogorov axioms | Take the uniform distribution on $S=[0,1]$. Now, $P[S]=1$, but also $P[S\setminus \{1\}]=1$ and $P[S \setminus \{1,1/2,1/3,\ldots\}] = 1$ as well even though both of the latter two are strict subsets | Question on the consequences of the Kolmogorov axioms
Take the uniform distribution on $S=[0,1]$. Now, $P[S]=1$, but also $P[S\setminus \{1\}]=1$ and $P[S \setminus \{1,1/2,1/3,\ldots\}] = 1$ as well even though both of the latter two are strict subsets of $S$. (Here the notation $A \setminus B$ means all elements belonging to set $A$ and not belonging to $B$.)
To answer the almost surely part of your question:
if P(A)=0 this means that event A is almost never possible and if
P(A)=1 will almost surely occur.
I think you have got it the wrong way round: "almost surely" is defined to be $P(A)=1$.
To fully understand the intricacies and subtleties of the definitions, some familiarity with measure theory is helpful. See, e.g. the Cantor set, which has measure ["length"] zero but contains a uncountably infinite number of points, compared to any interval on the real line $(a,b)$ which has again uncountably infinite number of points but nonzero measure $b-a$.
Given that you are working in Applied statistics, these complicated sets are probably irrelevant to you, so I would not worry about it ( its just something authors like to put in!). | Question on the consequences of the Kolmogorov axioms
Take the uniform distribution on $S=[0,1]$. Now, $P[S]=1$, but also $P[S\setminus \{1\}]=1$ and $P[S \setminus \{1,1/2,1/3,\ldots\}] = 1$ as well even though both of the latter two are strict subsets |
36,062 | Cause of singularity in matrix for quantile regression | I believe the reason it is coming up as singular is your second reason, that the data are binned. Duplicating observations (for a single x value, multiple responses) increases chances of singularity.
I had the same error message as you with a similarly structured dataset. I have multiple observations for each x value, some of which were identical. I got around it by 'jittering' the data, adding a very small amount of random noise to the response values using rnorm(). This meant that though there were multiple observations for each x value, there were no identical repeats and the rq() function works. As long as the noise you add is small, it won't affect the coefficient and SE estimates from rq noticeably. | Cause of singularity in matrix for quantile regression | I believe the reason it is coming up as singular is your second reason, that the data are binned. Duplicating observations (for a single x value, multiple responses) increases chances of singularity. | Cause of singularity in matrix for quantile regression
I believe the reason it is coming up as singular is your second reason, that the data are binned. Duplicating observations (for a single x value, multiple responses) increases chances of singularity.
I had the same error message as you with a similarly structured dataset. I have multiple observations for each x value, some of which were identical. I got around it by 'jittering' the data, adding a very small amount of random noise to the response values using rnorm(). This meant that though there were multiple observations for each x value, there were no identical repeats and the rq() function works. As long as the noise you add is small, it won't affect the coefficient and SE estimates from rq noticeably. | Cause of singularity in matrix for quantile regression
I believe the reason it is coming up as singular is your second reason, that the data are binned. Duplicating observations (for a single x value, multiple responses) increases chances of singularity. |
36,063 | Cause of singularity in matrix for quantile regression | An alternative to rnorm() proposed by Jack Ballard is using jitter() from the base package. | Cause of singularity in matrix for quantile regression | An alternative to rnorm() proposed by Jack Ballard is using jitter() from the base package. | Cause of singularity in matrix for quantile regression
An alternative to rnorm() proposed by Jack Ballard is using jitter() from the base package. | Cause of singularity in matrix for quantile regression
An alternative to rnorm() proposed by Jack Ballard is using jitter() from the base package. |
36,064 | is Shapiro Wilk test insensitive on the tails? | The situation is complicated, but the results tend to the opposite of this claim: for moderate dataset sizes $n$, the Shapiro-Wilk test is more sensitive in the tails than elsewhere.
Quantifying sensitivity
I take "sensitive" to mean the extent to which the results vary when values in the dataset are perturbed. (Another possible interpretation is that "sensitivity" is meant in terms of the power of the test to detect deviations from the tail behavior of a Normal distribution. However, since "sensitivity" and "power" are common, well-understood statistical terms with distinct meanings, this second interpretation does not seem appropriate.)
Generically, consider the test "results" (which usually would be taken as a p-value) to be some function $f$ of the ordered data $x$. Then we might want to define the sensitivity of $f$ to the $i^\text{th}$ element of $x$ to be
$$\frac{d}{dx_i} f(x_1,x_2,\ldots, x_n).$$
There are a few problems with this, however. First, $f$ might not be differentiable. Second, sensitivity to extremely small changes might be less relevant than sensitivity to larger changes. To cope with these complications we may (1) use directed finite differences to explore changes in $f$ when $x_i$ is separately increased and decreased and (2) obtain these differences for deviations which are appreciable compared to the spread of the data. To this end, given a deviation $\delta\ge 0$ let
$$s_\delta^{\pm i} f = \frac{f(x_1,\ldots,x_{i-1},x_i\pm\delta\sigma, x_{i+1},\ldots, x_n) - f(x_1,x_2,\ldots, x_n)}{\delta\sigma}$$
(where $\sigma$ is a standard measure of the spread of $x$, such as its standard deviation) and define the sensitivity of $f$ to be the vector of absolute difference quotients
$$(|s_{\delta/2}^i| + |s_{\delta/2}^{-i}|, i=1, 2, \ldots, n).$$
That is, each data value is displaced upwards and downwards by amounts $\delta/2$ times the overall spread. The sensitivity is the total absolute relative change, reflecting a net deviation of $\delta\sigma$ centered at the data.
Assessing sensitivity of distributional tests
Sensitivity can vary with the dataset. Should we be assessing it when the data conform to the null hypothesis or when they are far from the null? Both assessments can be informative. But for distributional tests we face the complication that the alternative often is not even parameterizable: although the null hypothesis might be that the data are sampled from a Normal distribution, the alternative would be that they are sampled from any distribution.
A thorough study would look at many alternatives and many sample sizes. Below I report on results for three sample sizes, $n=4, 12, 36$, which are typical of datasets where the Shapiro-Wilk test is used, and for the null (a Normal distribution), a short-tailed alternative (a Uniform distribution), a long-tailed alternative (an Exponential distribution), and a bimodal alternative (a Beta$(2,2)$ distribution). In each case I make the dataset look as much like its parent distribution as possible. This is accomplished by computing the quantiles of the distribution at $n$ probability plotting points (spaced according to Filliben's formulas, aka "Weibull plotting points").
For reference I have applied the same analysis to a variant of the Kolmogorov-Smirnov test. For this variant I first recenter the data, because (at least for the alternatives) the K-S test will not be a realistic comparison. With the recentered data, both tests often produce comparable p-values and those p-values range from $1$ down to $0.0003$, covering a useful range of possibilities.
Results
The sensitivities for $\delta=1$ are plotted on logarithmic axes against the data indexes (ranks). The results for the S-W test are shown in red with filled circles; those for the K-S test are in blue with filled triangles. (Sensitivities of zero are plotted at $10^{-12}$.)
The S-W test tends to be slightly more sensitive to data in the tails (i.e., where the ranks are close to $1$ or to $n$) than in the middle, except for very small datasets. The K-S test, by contrast, tends to be extremely sensitive to a small number of data in one or both tails, at least once the dataset size is sufficiently large. Clearly these tests are telling us different things about the shapes of the datasets.
By and large, the S-W test has substantially larger sensitivities than the K-S test. The reasons for this are complicated, but note especially that two distributional tests cannot be compared based on sensitivity alone: you should also consider the p-values at which these sensitivities are measured.
Code
The R code used to produce these results follows. It is structured to be easily modified to extend the study in any desired direction: different sample sizes, different dataset distributions, and different distributional tests.
filliben <- function(n) {
a <- 2^(-1/n); c(1-a, (2:(n-1) - 0.3175)/(n + 0.365), a)
}
sensitivity <- function(x, f, delta=1, ...) {
s <- delta * sd(x) / 2
e <- function(i) {u <- rep(0, length(x)); u[i] <- s; u}
f.x <- f(x)
sapply(1:length(x), function(i) f(x + e(i)) - f.x) / abs(s)
}
sensitivity.abs <- function(x, f, delta, ...) {
abs(sensitivity(x, f, delta/2, ...)) + abs(sensitivity(x, f, -delta/2, ...))
}
delta <- 1
beta <- function(q) qbeta(q, 1/2, 1/2) # A bimodal distribution
par(mfrow=c(3, 4))
for (n in c(4, 12, 36)) {
x <- filliben(n)
for (f.s in c("qnorm", "qunif", "qexp", "beta")) {
# Perform the tests.
y <- do.call(f.s, list(x))
y <- (y - mean(y))
cat(n, f.s, shapiro.test(y)$p.value, ks.test(y, "pnorm")$p.value, "\n")
# Compute sensitivities.
shapiro.s <- sensitivity.abs(y, function(x) shapiro.test(x)$p.value, delta)
ks.s <- sensitivity.abs(y, function(x) ks.test(x, "pnorm")$p.value, delta)
shapiro.s <- pmax(1e-12, shapiro.s) # Eliminate zeros for log plotting
ks.s <- pmax(1e-12, ks.s) # Eliminate zeros for log plotting
# Plot results.
plot(c(1,n), range(c(shapiro.s, ks.s)), type="n", log="y",
main=f.s, xlab="Rank", ylab=paste0("Sensitivity, n=", n))
points(shapiro.s, pch=16, col="Red")
points(ks.s, pch=24, bg="Blue")
lines(shapiro.s, col="#801010")
lines(ks.s, col="#101080", lty=3)
}
} | is Shapiro Wilk test insensitive on the tails? | The situation is complicated, but the results tend to the opposite of this claim: for moderate dataset sizes $n$, the Shapiro-Wilk test is more sensitive in the tails than elsewhere.
Quantifying sens | is Shapiro Wilk test insensitive on the tails?
The situation is complicated, but the results tend to the opposite of this claim: for moderate dataset sizes $n$, the Shapiro-Wilk test is more sensitive in the tails than elsewhere.
Quantifying sensitivity
I take "sensitive" to mean the extent to which the results vary when values in the dataset are perturbed. (Another possible interpretation is that "sensitivity" is meant in terms of the power of the test to detect deviations from the tail behavior of a Normal distribution. However, since "sensitivity" and "power" are common, well-understood statistical terms with distinct meanings, this second interpretation does not seem appropriate.)
Generically, consider the test "results" (which usually would be taken as a p-value) to be some function $f$ of the ordered data $x$. Then we might want to define the sensitivity of $f$ to the $i^\text{th}$ element of $x$ to be
$$\frac{d}{dx_i} f(x_1,x_2,\ldots, x_n).$$
There are a few problems with this, however. First, $f$ might not be differentiable. Second, sensitivity to extremely small changes might be less relevant than sensitivity to larger changes. To cope with these complications we may (1) use directed finite differences to explore changes in $f$ when $x_i$ is separately increased and decreased and (2) obtain these differences for deviations which are appreciable compared to the spread of the data. To this end, given a deviation $\delta\ge 0$ let
$$s_\delta^{\pm i} f = \frac{f(x_1,\ldots,x_{i-1},x_i\pm\delta\sigma, x_{i+1},\ldots, x_n) - f(x_1,x_2,\ldots, x_n)}{\delta\sigma}$$
(where $\sigma$ is a standard measure of the spread of $x$, such as its standard deviation) and define the sensitivity of $f$ to be the vector of absolute difference quotients
$$(|s_{\delta/2}^i| + |s_{\delta/2}^{-i}|, i=1, 2, \ldots, n).$$
That is, each data value is displaced upwards and downwards by amounts $\delta/2$ times the overall spread. The sensitivity is the total absolute relative change, reflecting a net deviation of $\delta\sigma$ centered at the data.
Assessing sensitivity of distributional tests
Sensitivity can vary with the dataset. Should we be assessing it when the data conform to the null hypothesis or when they are far from the null? Both assessments can be informative. But for distributional tests we face the complication that the alternative often is not even parameterizable: although the null hypothesis might be that the data are sampled from a Normal distribution, the alternative would be that they are sampled from any distribution.
A thorough study would look at many alternatives and many sample sizes. Below I report on results for three sample sizes, $n=4, 12, 36$, which are typical of datasets where the Shapiro-Wilk test is used, and for the null (a Normal distribution), a short-tailed alternative (a Uniform distribution), a long-tailed alternative (an Exponential distribution), and a bimodal alternative (a Beta$(2,2)$ distribution). In each case I make the dataset look as much like its parent distribution as possible. This is accomplished by computing the quantiles of the distribution at $n$ probability plotting points (spaced according to Filliben's formulas, aka "Weibull plotting points").
For reference I have applied the same analysis to a variant of the Kolmogorov-Smirnov test. For this variant I first recenter the data, because (at least for the alternatives) the K-S test will not be a realistic comparison. With the recentered data, both tests often produce comparable p-values and those p-values range from $1$ down to $0.0003$, covering a useful range of possibilities.
Results
The sensitivities for $\delta=1$ are plotted on logarithmic axes against the data indexes (ranks). The results for the S-W test are shown in red with filled circles; those for the K-S test are in blue with filled triangles. (Sensitivities of zero are plotted at $10^{-12}$.)
The S-W test tends to be slightly more sensitive to data in the tails (i.e., where the ranks are close to $1$ or to $n$) than in the middle, except for very small datasets. The K-S test, by contrast, tends to be extremely sensitive to a small number of data in one or both tails, at least once the dataset size is sufficiently large. Clearly these tests are telling us different things about the shapes of the datasets.
By and large, the S-W test has substantially larger sensitivities than the K-S test. The reasons for this are complicated, but note especially that two distributional tests cannot be compared based on sensitivity alone: you should also consider the p-values at which these sensitivities are measured.
Code
The R code used to produce these results follows. It is structured to be easily modified to extend the study in any desired direction: different sample sizes, different dataset distributions, and different distributional tests.
filliben <- function(n) {
a <- 2^(-1/n); c(1-a, (2:(n-1) - 0.3175)/(n + 0.365), a)
}
sensitivity <- function(x, f, delta=1, ...) {
s <- delta * sd(x) / 2
e <- function(i) {u <- rep(0, length(x)); u[i] <- s; u}
f.x <- f(x)
sapply(1:length(x), function(i) f(x + e(i)) - f.x) / abs(s)
}
sensitivity.abs <- function(x, f, delta, ...) {
abs(sensitivity(x, f, delta/2, ...)) + abs(sensitivity(x, f, -delta/2, ...))
}
delta <- 1
beta <- function(q) qbeta(q, 1/2, 1/2) # A bimodal distribution
par(mfrow=c(3, 4))
for (n in c(4, 12, 36)) {
x <- filliben(n)
for (f.s in c("qnorm", "qunif", "qexp", "beta")) {
# Perform the tests.
y <- do.call(f.s, list(x))
y <- (y - mean(y))
cat(n, f.s, shapiro.test(y)$p.value, ks.test(y, "pnorm")$p.value, "\n")
# Compute sensitivities.
shapiro.s <- sensitivity.abs(y, function(x) shapiro.test(x)$p.value, delta)
ks.s <- sensitivity.abs(y, function(x) ks.test(x, "pnorm")$p.value, delta)
shapiro.s <- pmax(1e-12, shapiro.s) # Eliminate zeros for log plotting
ks.s <- pmax(1e-12, ks.s) # Eliminate zeros for log plotting
# Plot results.
plot(c(1,n), range(c(shapiro.s, ks.s)), type="n", log="y",
main=f.s, xlab="Rank", ylab=paste0("Sensitivity, n=", n))
points(shapiro.s, pch=16, col="Red")
points(ks.s, pch=24, bg="Blue")
lines(shapiro.s, col="#801010")
lines(ks.s, col="#101080", lty=3)
}
} | is Shapiro Wilk test insensitive on the tails?
The situation is complicated, but the results tend to the opposite of this claim: for moderate dataset sizes $n$, the Shapiro-Wilk test is more sensitive in the tails than elsewhere.
Quantifying sens |
36,065 | is Shapiro Wilk test insensitive on the tails? | I don't think it's particularly insensitive; I'd say it's more sensitive there than the Lilliefors test, for example, and I'm having trouble thinking of another comparable goodness of fit test in wide use* that I think will be much more sensitive to the tails.
If we look at power comparisons of goodness of fit tests (on which there are numeorus papers), the Shapiro Wilk generally performs very well in a wide variety of situations, including some that I'd regard as relating to "sensitivity to tails".
* well, apart perhaps from the Anderson-Darling$^\dagger$ which might beat it on tail sensitivity in some cases.
Edit: I've been through a number of power comparison studies, including against symmetric heavy tailed alternatives and alternatives with small amounts of contamination by outliers (the two most obvious ways to look at 'sensitivity to tails') and the Shapiro-Wilk does extremely well, generally outperforming even the Anderson-Darling on this task (a task at which the A-D should be expected to excel).
$\dagger$ suitably adapted to the parameter estimation inherent in testing normality without specifying the parameters, of course - see the discussion in the book Goodness of fit techniques by D'Agostino and Stephens
[Do the authors say how this sensitivity was measured or what it was compared to? Does the paper give any justification or context for the claim at all?] | is Shapiro Wilk test insensitive on the tails? | I don't think it's particularly insensitive; I'd say it's more sensitive there than the Lilliefors test, for example, and I'm having trouble thinking of another comparable goodness of fit test in wide | is Shapiro Wilk test insensitive on the tails?
I don't think it's particularly insensitive; I'd say it's more sensitive there than the Lilliefors test, for example, and I'm having trouble thinking of another comparable goodness of fit test in wide use* that I think will be much more sensitive to the tails.
If we look at power comparisons of goodness of fit tests (on which there are numeorus papers), the Shapiro Wilk generally performs very well in a wide variety of situations, including some that I'd regard as relating to "sensitivity to tails".
* well, apart perhaps from the Anderson-Darling$^\dagger$ which might beat it on tail sensitivity in some cases.
Edit: I've been through a number of power comparison studies, including against symmetric heavy tailed alternatives and alternatives with small amounts of contamination by outliers (the two most obvious ways to look at 'sensitivity to tails') and the Shapiro-Wilk does extremely well, generally outperforming even the Anderson-Darling on this task (a task at which the A-D should be expected to excel).
$\dagger$ suitably adapted to the parameter estimation inherent in testing normality without specifying the parameters, of course - see the discussion in the book Goodness of fit techniques by D'Agostino and Stephens
[Do the authors say how this sensitivity was measured or what it was compared to? Does the paper give any justification or context for the claim at all?] | is Shapiro Wilk test insensitive on the tails?
I don't think it's particularly insensitive; I'd say it's more sensitive there than the Lilliefors test, for example, and I'm having trouble thinking of another comparable goodness of fit test in wide |
36,066 | Why do zero differences not enter computation in the Wilcoxon signed ranked test? | It has to do with the assumptions of the test for which the distribution of the test statistic under the null is derived.
The variables are assumed to be continuous.
The probability of a tie is therefore 0 ... and this makes it possible to compute the permutation distribution of the test statistic under the null for given sample size.
Without that assumption being true, you could still do a test, but if you're going to get the null distribution of the test statistic, you'll have to try to compute it conditional on the pattern of tied values (or more easily, simulate).
The easier alternative is to only consider untied values.
Note further that observing ties is not 'evidence in favor of the null', it only contains a lack of evidence against it. With discrete distributions, a range of non-null alternatives are likely to produce ties, not just the null itself.
The 'correct' thing to do is not use a test that assumes continuous distributions on data that don't satisfy the assumptions. If you don't have that, you have to do something to deal with that failure.
I believe that conditioning on the untied data preserves the required properties for the significance level in a way that including ties in some way would not. We might check by simulation. | Why do zero differences not enter computation in the Wilcoxon signed ranked test? | It has to do with the assumptions of the test for which the distribution of the test statistic under the null is derived.
The variables are assumed to be continuous.
The probability of a tie is ther | Why do zero differences not enter computation in the Wilcoxon signed ranked test?
It has to do with the assumptions of the test for which the distribution of the test statistic under the null is derived.
The variables are assumed to be continuous.
The probability of a tie is therefore 0 ... and this makes it possible to compute the permutation distribution of the test statistic under the null for given sample size.
Without that assumption being true, you could still do a test, but if you're going to get the null distribution of the test statistic, you'll have to try to compute it conditional on the pattern of tied values (or more easily, simulate).
The easier alternative is to only consider untied values.
Note further that observing ties is not 'evidence in favor of the null', it only contains a lack of evidence against it. With discrete distributions, a range of non-null alternatives are likely to produce ties, not just the null itself.
The 'correct' thing to do is not use a test that assumes continuous distributions on data that don't satisfy the assumptions. If you don't have that, you have to do something to deal with that failure.
I believe that conditioning on the untied data preserves the required properties for the significance level in a way that including ties in some way would not. We might check by simulation. | Why do zero differences not enter computation in the Wilcoxon signed ranked test?
It has to do with the assumptions of the test for which the distribution of the test statistic under the null is derived.
The variables are assumed to be continuous.
The probability of a tie is ther |
36,067 | Gibbs sampling to produce posterior pdf | I won't belabor the valid points made by @Tomas above so I will just answer with the following: The likelihood for a normal linear model is given by
$$f(y|\beta,\sigma,X)\propto\left(\frac{1}{\sigma^2}\right)^{n/2}\exp\left\{-\frac{1}{2\sigma^2}(y-X\beta)'(y-X\beta)\right\}$$ so now using the standard diffuse prior $$p(\beta,\sigma^2)\propto\frac{1}{\sigma^2}$$
we can obtain draws from the posterior distribution $p(\beta,\sigma^2|y,X)$ in a very simple Gibbs sampler. Note, although your steps above for the Gibbs sampler are not wrong, I would argue that a more efficient decomposition is the following:
$$p(\beta,\sigma^2|y,X)=p(\beta|\sigma^2,y,X)p(\sigma^2|y,X)$$
and so now we want to design a Gibbs sampler to sample from $p(\beta|\sigma^2,y,X)$ and $p(\sigma^2|y,X)$.
After some tedious algebra, we obtain the following:
$$\beta|\sigma^2,y,X\sim N(\hat\beta,\sigma^2(X'X)^{-1})$$
and
$$\sigma^2|y,X\sim\text{Inverse-Gamma}\left(\frac{n-k}{2},\frac{(n-k)\hat\sigma^2}{2}\right)$$
where
$$\hat\beta=(X'X)^{-1}X'y$$
and
$$\hat\sigma^2=\frac{(y-X\hat\beta)'(y-X\hat\beta)}{n-k}$$
Now that we have all that derived, we can obtain samples of $\beta$ and $\sigma^2$ from our Gibbs sampler and at each iteration of the Gibbs sampler we can obtain estimates of $\psi$ by plugging in our estimates of $\beta$ and $\sigma$.
Here is some code that gets at all of this:
library(mvtnorm)
#Pseudo Data
#Sample Size
n = 50
#The response variable
Y = matrix(rnorm(n,20))
#The Design matrix
X = matrix(c(rep(1,n),rnorm(n,3),rnorm(n,10)),nrow=n)
k = ncol(X)
#Number of samples
B = 1100
#Variables to store the samples in
beta = matrix(NA,nrow=B,ncol=k)
sigma = c(1,rep(NA,B))
psi = rep(NA,B)
#The Gibbs Sampler
for(i in 1:B){
#The least square estimators of beta and sigma
V = solve(t(X)%*%X)
bhat = V%*%t(X)%*%Y
sigma.hat = t(Y-X%*%bhat)%*%(Y-X%*%bhat)/(n-k)
#Sample beta from the full conditional
beta[i,] = rmvnorm(1,bhat,sigma[i]*V)
#Sample sigma from the full conditional
sigma[i+1] = 1/rgamma(1,(n-k)/2,(n-k)*sigma.hat/2)
#Obtain the marginal posterior of psi
psi[i] = (beta[i,2]+beta[i,3])/sigma[i+1]
}
#Plot the traces
dev.new()
par(mfrow=c(2,2))
plot(beta[,1],type='l',ylab=expression(beta[1]),main=expression("Plot of "*beta[1]))
plot(beta[,2],type='l',ylab=expression(beta[2]),main=expression("Plot of "*beta[2]))
plot(beta[,3],type='l',ylab=expression(beta[3]),main=expression("Plot of "*beta[2]))
plot(sigma,type='l',ylab=expression(sigma^2),main=expression("Plot of "*sigma^2))
#Burn in the first 100 samples of psi
psi = psi[-(1:100)]
dev.new()
#Plot the marginal posterior density of psi
plot(density(psi),col="red",main=expression("Marginal Posterior Density of "*psi))
Here are the plots it will generate as well
and
FYI, the above trace plots of $\beta$ and $\sigma^2$ are not with burn-in.
Question 2 in response to Edit 2:
If you want the 5% quantile (or any quantile for that matter) for $\psi|y$, all you have to do is the following:
quantile(psi,prob=.05)
If you wanted a 95% confidence interval you could do the following:
lower = quantile(psi,prob=.025)
upper = quantile(psi,prob=.975)
ci = c(lower,upper) | Gibbs sampling to produce posterior pdf | I won't belabor the valid points made by @Tomas above so I will just answer with the following: The likelihood for a normal linear model is given by
$$f(y|\beta,\sigma,X)\propto\left(\frac{1}{\sigma^2 | Gibbs sampling to produce posterior pdf
I won't belabor the valid points made by @Tomas above so I will just answer with the following: The likelihood for a normal linear model is given by
$$f(y|\beta,\sigma,X)\propto\left(\frac{1}{\sigma^2}\right)^{n/2}\exp\left\{-\frac{1}{2\sigma^2}(y-X\beta)'(y-X\beta)\right\}$$ so now using the standard diffuse prior $$p(\beta,\sigma^2)\propto\frac{1}{\sigma^2}$$
we can obtain draws from the posterior distribution $p(\beta,\sigma^2|y,X)$ in a very simple Gibbs sampler. Note, although your steps above for the Gibbs sampler are not wrong, I would argue that a more efficient decomposition is the following:
$$p(\beta,\sigma^2|y,X)=p(\beta|\sigma^2,y,X)p(\sigma^2|y,X)$$
and so now we want to design a Gibbs sampler to sample from $p(\beta|\sigma^2,y,X)$ and $p(\sigma^2|y,X)$.
After some tedious algebra, we obtain the following:
$$\beta|\sigma^2,y,X\sim N(\hat\beta,\sigma^2(X'X)^{-1})$$
and
$$\sigma^2|y,X\sim\text{Inverse-Gamma}\left(\frac{n-k}{2},\frac{(n-k)\hat\sigma^2}{2}\right)$$
where
$$\hat\beta=(X'X)^{-1}X'y$$
and
$$\hat\sigma^2=\frac{(y-X\hat\beta)'(y-X\hat\beta)}{n-k}$$
Now that we have all that derived, we can obtain samples of $\beta$ and $\sigma^2$ from our Gibbs sampler and at each iteration of the Gibbs sampler we can obtain estimates of $\psi$ by plugging in our estimates of $\beta$ and $\sigma$.
Here is some code that gets at all of this:
library(mvtnorm)
#Pseudo Data
#Sample Size
n = 50
#The response variable
Y = matrix(rnorm(n,20))
#The Design matrix
X = matrix(c(rep(1,n),rnorm(n,3),rnorm(n,10)),nrow=n)
k = ncol(X)
#Number of samples
B = 1100
#Variables to store the samples in
beta = matrix(NA,nrow=B,ncol=k)
sigma = c(1,rep(NA,B))
psi = rep(NA,B)
#The Gibbs Sampler
for(i in 1:B){
#The least square estimators of beta and sigma
V = solve(t(X)%*%X)
bhat = V%*%t(X)%*%Y
sigma.hat = t(Y-X%*%bhat)%*%(Y-X%*%bhat)/(n-k)
#Sample beta from the full conditional
beta[i,] = rmvnorm(1,bhat,sigma[i]*V)
#Sample sigma from the full conditional
sigma[i+1] = 1/rgamma(1,(n-k)/2,(n-k)*sigma.hat/2)
#Obtain the marginal posterior of psi
psi[i] = (beta[i,2]+beta[i,3])/sigma[i+1]
}
#Plot the traces
dev.new()
par(mfrow=c(2,2))
plot(beta[,1],type='l',ylab=expression(beta[1]),main=expression("Plot of "*beta[1]))
plot(beta[,2],type='l',ylab=expression(beta[2]),main=expression("Plot of "*beta[2]))
plot(beta[,3],type='l',ylab=expression(beta[3]),main=expression("Plot of "*beta[2]))
plot(sigma,type='l',ylab=expression(sigma^2),main=expression("Plot of "*sigma^2))
#Burn in the first 100 samples of psi
psi = psi[-(1:100)]
dev.new()
#Plot the marginal posterior density of psi
plot(density(psi),col="red",main=expression("Marginal Posterior Density of "*psi))
Here are the plots it will generate as well
and
FYI, the above trace plots of $\beta$ and $\sigma^2$ are not with burn-in.
Question 2 in response to Edit 2:
If you want the 5% quantile (or any quantile for that matter) for $\psi|y$, all you have to do is the following:
quantile(psi,prob=.05)
If you wanted a 95% confidence interval you could do the following:
lower = quantile(psi,prob=.025)
upper = quantile(psi,prob=.975)
ci = c(lower,upper) | Gibbs sampling to produce posterior pdf
I won't belabor the valid points made by @Tomas above so I will just answer with the following: The likelihood for a normal linear model is given by
$$f(y|\beta,\sigma,X)\propto\left(\frac{1}{\sigma^2 |
36,068 | Consecutive Log Transformations | I think it helps here to be concrete, not abstract.
Think about the support of such transformations. ln $x$ requires that $x > 0$, ln ln $x$ requires that $x > 1$, ln ln ln $x$ that $x > e = \exp(1)$, and so forth. Can you think of variables that naturally satisfy such limits? Also, if one limit is natural, the others won't be.
So, while you have a mathematical family here, it is not statistically very useful.
Also, even if by accident or otherwise your data satisfy these limits, these are very severe transformations, even ln repeated twice. They may be the ultimate outlier tamers for large positive values, but they also may have the opposite effect of creating outliers by separating arbitrarily small values just above the lower limits.
If you want something stronger than the logarithm for transforming highly skewed positive values, the (negative) reciprocal is the best candidate. It has the added virtues that its units of measurement are easy to think about and its interpretation is often easy (e.g. times and rates are reciprocals of each other). (A negative sign is optional here if preserving order is important.)
A quite different and much more positive point is that functions such as the loglog $-$ln($-$ln($x$)) and complementary loglog ln($−$ln$ (1−x))$ can be very useful for $0 < x < 1$ and appear as link functions for generalized linear models. | Consecutive Log Transformations | I think it helps here to be concrete, not abstract.
Think about the support of such transformations. ln $x$ requires that $x > 0$, ln ln $x$ requires that $x > 1$, ln ln ln $x$ that $x > e = \exp(1)$ | Consecutive Log Transformations
I think it helps here to be concrete, not abstract.
Think about the support of such transformations. ln $x$ requires that $x > 0$, ln ln $x$ requires that $x > 1$, ln ln ln $x$ that $x > e = \exp(1)$, and so forth. Can you think of variables that naturally satisfy such limits? Also, if one limit is natural, the others won't be.
So, while you have a mathematical family here, it is not statistically very useful.
Also, even if by accident or otherwise your data satisfy these limits, these are very severe transformations, even ln repeated twice. They may be the ultimate outlier tamers for large positive values, but they also may have the opposite effect of creating outliers by separating arbitrarily small values just above the lower limits.
If you want something stronger than the logarithm for transforming highly skewed positive values, the (negative) reciprocal is the best candidate. It has the added virtues that its units of measurement are easy to think about and its interpretation is often easy (e.g. times and rates are reciprocals of each other). (A negative sign is optional here if preserving order is important.)
A quite different and much more positive point is that functions such as the loglog $-$ln($-$ln($x$)) and complementary loglog ln($−$ln$ (1−x))$ can be very useful for $0 < x < 1$ and appear as link functions for generalized linear models. | Consecutive Log Transformations
I think it helps here to be concrete, not abstract.
Think about the support of such transformations. ln $x$ requires that $x > 0$, ln ln $x$ requires that $x > 1$, ln ln ln $x$ that $x > e = \exp(1)$ |
36,069 | Obtaining covariance matrix from correlation matrix | Let $R$ be the correlation matrix and $S$ the vector of standard deviations, so that $S\cdot S$ (where $\cdot$ is the componentwise product) is the vector of variances. Then
$$ \text{diag}(S) R \text{diag}(S) $$ is the covariance matrix. This is fully explained here.
This can be implemented in R as
cor2cov_1 <- function(R,S){
diag(S) %*% R %*% diag(S)
}
but is inefficient. An efficient implementation is
cor2cov <- function(R, S) {
sweep(sweep(R, 1, S, "*"), 2, S, "*")
}
and you can test yourself they give the same result.
TRUTH= 0.8
R <- as.matrix(data.frame(c(1, TRUTH), c(TRUTH, 1)))
S = c(sqrt(1), sqrt(1))
cor2cov_1(R,S)
outer(S,S) * R
smat = as.matrix(S)
R * smat %*% t(smat)
Here is a microbenchmark showing the efficiency of the functions:
library(microbenchmark)
microbenchmark::microbenchmark(outer(S,S) * R ,cor2cov_1(R,S), cor2cov(R,S), R * smat %*% t(smat), times = 10000)
Unit: microseconds
expr min lq mean median uq max neval cld
outer(S, S) * R 1.968 2.214 2.724639 2.337 2.460 3611.362 10000 a
cor2cov_1(R, S) 1.722 1.886 2.778045 1.968 2.091 3743.259 10000 a
cor2cov(R, S) 113.037 116.071 125.844711 118.039 120.663 5462.020 10000 b
R * smat %*% t(smat) 1.066 1.230 1.422712 1.435 1.517 12.177 10000 a | Obtaining covariance matrix from correlation matrix | Let $R$ be the correlation matrix and $S$ the vector of standard deviations, so that $S\cdot S$ (where $\cdot$ is the componentwise product) is the vector of variances. Then
$$ \text{diag}(S) R \text{ | Obtaining covariance matrix from correlation matrix
Let $R$ be the correlation matrix and $S$ the vector of standard deviations, so that $S\cdot S$ (where $\cdot$ is the componentwise product) is the vector of variances. Then
$$ \text{diag}(S) R \text{diag}(S) $$ is the covariance matrix. This is fully explained here.
This can be implemented in R as
cor2cov_1 <- function(R,S){
diag(S) %*% R %*% diag(S)
}
but is inefficient. An efficient implementation is
cor2cov <- function(R, S) {
sweep(sweep(R, 1, S, "*"), 2, S, "*")
}
and you can test yourself they give the same result.
TRUTH= 0.8
R <- as.matrix(data.frame(c(1, TRUTH), c(TRUTH, 1)))
S = c(sqrt(1), sqrt(1))
cor2cov_1(R,S)
outer(S,S) * R
smat = as.matrix(S)
R * smat %*% t(smat)
Here is a microbenchmark showing the efficiency of the functions:
library(microbenchmark)
microbenchmark::microbenchmark(outer(S,S) * R ,cor2cov_1(R,S), cor2cov(R,S), R * smat %*% t(smat), times = 10000)
Unit: microseconds
expr min lq mean median uq max neval cld
outer(S, S) * R 1.968 2.214 2.724639 2.337 2.460 3611.362 10000 a
cor2cov_1(R, S) 1.722 1.886 2.778045 1.968 2.091 3743.259 10000 a
cor2cov(R, S) 113.037 116.071 125.844711 118.039 120.663 5462.020 10000 b
R * smat %*% t(smat) 1.066 1.230 1.422712 1.435 1.517 12.177 10000 a | Obtaining covariance matrix from correlation matrix
Let $R$ be the correlation matrix and $S$ the vector of standard deviations, so that $S\cdot S$ (where $\cdot$ is the componentwise product) is the vector of variances. Then
$$ \text{diag}(S) R \text{ |
36,070 | Image reconstruction using compressed sensing | This article helped me to understand this problem by using the Kronecker product. Here is an excerpt of the article:
Creating the $A$ matrix for 2D image data takes a little more ingenuity than it did in the 1D case. In the derivation that follows, we’ll use the Kronecker product $\otimes$ and the fact that the 2D discrete cosine transform is separable to produce our operator $A$.
Let $X$ be an image in the spectral domain and $D_i=\textit{idct}(I_i)$, where $I_i$ is the identity matrix of size $i$. Then:
$$\begin{align*} \textit{idct2}(X)&=\textit{idct}\left(\textit{idct}\left(X^T\right)^T\right)\\ &=D_m\left(D_nX^T\right)^T\\ &=D_mXD_n^T \end{align*}$$
If $\textit{vec}(X)$ is the vector operator that stacks columns of $X$ on top of each other, then:
$$\begin{align*} \textit{vec}\left(D_mXD_n^T\right)&=\left(D_n\otimes D_m\right)\textit{vec}(X)\\ &=\left(D_n\otimes D_m\right)x\quad\text{where}\ \text{and}\ x\equiv\textit{vec}(X) \end{align*}$$
In the article the library CVXPY is used, but I solved it with the LASSO regularizer:
import numpy as np
import scipy.fftpack as spfft
import scipy.ndimage as spimg
from sklearn.linear_model import Lasso
# read original image and downsize for speed
X = spimg.imread('image.jpg', flatten=True, mode='L') # read in grayscale
ny, nx = X.shape
# extract small sample of signal
k = round(nx * ny * 0.5) # 50% sample
ri = np.random.choice(nx * ny, k, replace=False) # random sample of indices
b = X.T.flat[ri]
b = np.expand_dims(b, axis=1)
# create dct matrix operator using kron (memory errors for large ny*nx)
A = np.kron(
spfft.idct(np.identity(nx), norm='ortho', axis=0),
spfft.idct(np.identity(ny), norm='ortho', axis=0)
)
A = A[ri,:] # same as phi times kron
Now you can apply the LASSO regression
def idct2(x):
return spfft.idct(spfft.idct(x.T, norm='ortho', axis=0).T, norm='ortho', axis=0)
lasso = Lasso(alpha=0.001)
lasso.fit(A, b)
Xat = np.array(lasso.coef_).reshape(nx, ny).T # stack columns
# Get the reconstructed image
Xa = idct2(Xat) | Image reconstruction using compressed sensing | This article helped me to understand this problem by using the Kronecker product. Here is an excerpt of the article:
Creating the $A$ matrix for 2D image data takes a little more ingenuity than it di | Image reconstruction using compressed sensing
This article helped me to understand this problem by using the Kronecker product. Here is an excerpt of the article:
Creating the $A$ matrix for 2D image data takes a little more ingenuity than it did in the 1D case. In the derivation that follows, we’ll use the Kronecker product $\otimes$ and the fact that the 2D discrete cosine transform is separable to produce our operator $A$.
Let $X$ be an image in the spectral domain and $D_i=\textit{idct}(I_i)$, where $I_i$ is the identity matrix of size $i$. Then:
$$\begin{align*} \textit{idct2}(X)&=\textit{idct}\left(\textit{idct}\left(X^T\right)^T\right)\\ &=D_m\left(D_nX^T\right)^T\\ &=D_mXD_n^T \end{align*}$$
If $\textit{vec}(X)$ is the vector operator that stacks columns of $X$ on top of each other, then:
$$\begin{align*} \textit{vec}\left(D_mXD_n^T\right)&=\left(D_n\otimes D_m\right)\textit{vec}(X)\\ &=\left(D_n\otimes D_m\right)x\quad\text{where}\ \text{and}\ x\equiv\textit{vec}(X) \end{align*}$$
In the article the library CVXPY is used, but I solved it with the LASSO regularizer:
import numpy as np
import scipy.fftpack as spfft
import scipy.ndimage as spimg
from sklearn.linear_model import Lasso
# read original image and downsize for speed
X = spimg.imread('image.jpg', flatten=True, mode='L') # read in grayscale
ny, nx = X.shape
# extract small sample of signal
k = round(nx * ny * 0.5) # 50% sample
ri = np.random.choice(nx * ny, k, replace=False) # random sample of indices
b = X.T.flat[ri]
b = np.expand_dims(b, axis=1)
# create dct matrix operator using kron (memory errors for large ny*nx)
A = np.kron(
spfft.idct(np.identity(nx), norm='ortho', axis=0),
spfft.idct(np.identity(ny), norm='ortho', axis=0)
)
A = A[ri,:] # same as phi times kron
Now you can apply the LASSO regression
def idct2(x):
return spfft.idct(spfft.idct(x.T, norm='ortho', axis=0).T, norm='ortho', axis=0)
lasso = Lasso(alpha=0.001)
lasso.fit(A, b)
Xat = np.array(lasso.coef_).reshape(nx, ny).T # stack columns
# Get the reconstructed image
Xa = idct2(Xat) | Image reconstruction using compressed sensing
This article helped me to understand this problem by using the Kronecker product. Here is an excerpt of the article:
Creating the $A$ matrix for 2D image data takes a little more ingenuity than it di |
36,071 | Image reconstruction using compressed sensing | I know that this is an old question but I am answering it in case googles this topic and would like to know the answer.
The problem is the compression matrix and the basis you are doing the sparse reconstruction in are coherent since they are both constructed from the DCT matrix. Do the sparse reconstruction in the DCT basis since the image will sparse/compressible in that basis. For the compression matrix, you need to choose something that will not correlate with the DCT matrix. Noiselets, Random Gaussian will work well. You might try JL-Lemma type matrices as well though I never found them to be very reliable. | Image reconstruction using compressed sensing | I know that this is an old question but I am answering it in case googles this topic and would like to know the answer.
The problem is the compression matrix and the basis you are doing the sparse rec | Image reconstruction using compressed sensing
I know that this is an old question but I am answering it in case googles this topic and would like to know the answer.
The problem is the compression matrix and the basis you are doing the sparse reconstruction in are coherent since they are both constructed from the DCT matrix. Do the sparse reconstruction in the DCT basis since the image will sparse/compressible in that basis. For the compression matrix, you need to choose something that will not correlate with the DCT matrix. Noiselets, Random Gaussian will work well. You might try JL-Lemma type matrices as well though I never found them to be very reliable. | Image reconstruction using compressed sensing
I know that this is an old question but I am answering it in case googles this topic and would like to know the answer.
The problem is the compression matrix and the basis you are doing the sparse rec |
36,072 | What does "principled" mean, as in "principled Bayesian analysis"? | Too long for a comment:
Zhang starts the Bayesian analysis section with the phrase
More principled inferences come from Bayesian analysis.
and later says
There are several advantages of the principled Bayesian analysis.
I don't think "principled Bayesian analysis" is a thing. The word principled is just being used as an adjective to describe the Bayesian analysis, where "principled" means "following a set of principles". This is opposed to an ad-hoc approach based on something like the method of moments. For example, if you were doing a capture-recapture study of animal populations, the Lincoln-Peterson estimator of the true population is an ad-hoc estimate, and a Bayesian estimate would be a more principled approach. Here, Zhang is comparing the Bayesian analysis with some other kind of analysis done in the previous section, which seems to be more specific to this particular problem and therefore less based on general principles.
It is slightly odd to see a "the" there (shouldn't it be "a principled Bayesian analysis"?) but I think this is just because English articles are difficult. You can see that there is a "the" missing from the first sentence at the top of page 93, and there are a few other similar sentences here and there.
Of course, it's perfectly possible that "principled Bayesian analysis" really is a thing, and if that's the case then I would also be interested to know what it is! | What does "principled" mean, as in "principled Bayesian analysis"? | Too long for a comment:
Zhang starts the Bayesian analysis section with the phrase
More principled inferences come from Bayesian analysis.
and later says
There are several advantages of the princip | What does "principled" mean, as in "principled Bayesian analysis"?
Too long for a comment:
Zhang starts the Bayesian analysis section with the phrase
More principled inferences come from Bayesian analysis.
and later says
There are several advantages of the principled Bayesian analysis.
I don't think "principled Bayesian analysis" is a thing. The word principled is just being used as an adjective to describe the Bayesian analysis, where "principled" means "following a set of principles". This is opposed to an ad-hoc approach based on something like the method of moments. For example, if you were doing a capture-recapture study of animal populations, the Lincoln-Peterson estimator of the true population is an ad-hoc estimate, and a Bayesian estimate would be a more principled approach. Here, Zhang is comparing the Bayesian analysis with some other kind of analysis done in the previous section, which seems to be more specific to this particular problem and therefore less based on general principles.
It is slightly odd to see a "the" there (shouldn't it be "a principled Bayesian analysis"?) but I think this is just because English articles are difficult. You can see that there is a "the" missing from the first sentence at the top of page 93, and there are a few other similar sentences here and there.
Of course, it's perfectly possible that "principled Bayesian analysis" really is a thing, and if that's the case then I would also be interested to know what it is! | What does "principled" mean, as in "principled Bayesian analysis"?
Too long for a comment:
Zhang starts the Bayesian analysis section with the phrase
More principled inferences come from Bayesian analysis.
and later says
There are several advantages of the princip |
36,073 | How to incorporate costs (into logit model) of false positive, false negative, true positive, true negative if they are different costs? | This is best thought of, in my opinion, not of a change to the likelihood function, but as a way to translate estimated risk into an optimum decision. We maximize the (standard or standard penalized) likelihood for a reason - to get optimal models. Then optimal decisions are made one individual at a time based on that individual's loss function. As typically loss functions vary from subject to subject, the final decision has to be deferred and cannot be made by an analyst. Most commonly, the loss function is not articulated but is used implicitly by the subject to make her own decision. It will depend on deeply held beliefs as well as prevailing conditions (e.g., resource availability). | How to incorporate costs (into logit model) of false positive, false negative, true positive, true n | This is best thought of, in my opinion, not of a change to the likelihood function, but as a way to translate estimated risk into an optimum decision. We maximize the (standard or standard penalized) | How to incorporate costs (into logit model) of false positive, false negative, true positive, true negative if they are different costs?
This is best thought of, in my opinion, not of a change to the likelihood function, but as a way to translate estimated risk into an optimum decision. We maximize the (standard or standard penalized) likelihood for a reason - to get optimal models. Then optimal decisions are made one individual at a time based on that individual's loss function. As typically loss functions vary from subject to subject, the final decision has to be deferred and cannot be made by an analyst. Most commonly, the loss function is not articulated but is used implicitly by the subject to make her own decision. It will depend on deeply held beliefs as well as prevailing conditions (e.g., resource availability). | How to incorporate costs (into logit model) of false positive, false negative, true positive, true n
This is best thought of, in my opinion, not of a change to the likelihood function, but as a way to translate estimated risk into an optimum decision. We maximize the (standard or standard penalized) |
36,074 | How to incorporate costs (into logit model) of false positive, false negative, true positive, true negative if they are different costs? | There are a few approaches that might get you moving in the right direction. First you could train your logistic regression via iterative learning and this would keep the solution confined to employing the likelihood function to estimate the regression parameters. First, estimate the logistic regression and look at the errors it made. If you want to improve the false positive rate, then assign a higher weight to the observations that the model incorrectly identified as belonging to the positive class. Then rerun the logistic regression using the weighted observations. Do this iteratively until the false positive rate satisfies your objective. See the post on Case weighted logistic regression for a discussion on implementing case weighted logistic regression in R. To be honest, I am not sure how well this approach will work in general, and it is not really an efficient optimization method. It is, however, simple to implement and easy to try.
If you are willing to move outside of relying solely on the likelihood function to control classifications, then you could always optimize the threshold parameter used to partition the observations into negative and positive classes. I believe this threshold parameter is defaulted to 0.5, with any output less than 0.5 being classified as a negative class and any output above 0.5 being classified as a positive class. After the logistic regression weights are estimated you could move onto optimizing this threshold parameter using the true negative rate, true positive rate, precision, recall, F-measure, ect. as your objective function. Practical Neural Network Recipes in C++ has a decent discussion of augmenting the classification threshold to control different error rates (the discussion is about neural nets, but it applies to logistic regression models as well). A variety of optimization techniques could be used to solve this problem. | How to incorporate costs (into logit model) of false positive, false negative, true positive, true n | There are a few approaches that might get you moving in the right direction. First you could train your logistic regression via iterative learning and this would keep the solution confined to employin | How to incorporate costs (into logit model) of false positive, false negative, true positive, true negative if they are different costs?
There are a few approaches that might get you moving in the right direction. First you could train your logistic regression via iterative learning and this would keep the solution confined to employing the likelihood function to estimate the regression parameters. First, estimate the logistic regression and look at the errors it made. If you want to improve the false positive rate, then assign a higher weight to the observations that the model incorrectly identified as belonging to the positive class. Then rerun the logistic regression using the weighted observations. Do this iteratively until the false positive rate satisfies your objective. See the post on Case weighted logistic regression for a discussion on implementing case weighted logistic regression in R. To be honest, I am not sure how well this approach will work in general, and it is not really an efficient optimization method. It is, however, simple to implement and easy to try.
If you are willing to move outside of relying solely on the likelihood function to control classifications, then you could always optimize the threshold parameter used to partition the observations into negative and positive classes. I believe this threshold parameter is defaulted to 0.5, with any output less than 0.5 being classified as a negative class and any output above 0.5 being classified as a positive class. After the logistic regression weights are estimated you could move onto optimizing this threshold parameter using the true negative rate, true positive rate, precision, recall, F-measure, ect. as your objective function. Practical Neural Network Recipes in C++ has a decent discussion of augmenting the classification threshold to control different error rates (the discussion is about neural nets, but it applies to logistic regression models as well). A variety of optimization techniques could be used to solve this problem. | How to incorporate costs (into logit model) of false positive, false negative, true positive, true n
There are a few approaches that might get you moving in the right direction. First you could train your logistic regression via iterative learning and this would keep the solution confined to employin |
36,075 | Is the p-value still uniformly distributed when the null hypothesis is composite? | The answer seems to be 'No' but sometimes 'Yes, asymptotically, depending on the construction of p'. Robins, van der Vaart, and Ventura (2000) go through the details.
The reasoning is basically what @whuber states telegraphically in the comment. The state of nature matters to the nuisance parameters. | Is the p-value still uniformly distributed when the null hypothesis is composite? | The answer seems to be 'No' but sometimes 'Yes, asymptotically, depending on the construction of p'. Robins, van der Vaart, and Ventura (2000) go through the details.
The reasoning is basically what @ | Is the p-value still uniformly distributed when the null hypothesis is composite?
The answer seems to be 'No' but sometimes 'Yes, asymptotically, depending on the construction of p'. Robins, van der Vaart, and Ventura (2000) go through the details.
The reasoning is basically what @whuber states telegraphically in the comment. The state of nature matters to the nuisance parameters. | Is the p-value still uniformly distributed when the null hypothesis is composite?
The answer seems to be 'No' but sometimes 'Yes, asymptotically, depending on the construction of p'. Robins, van der Vaart, and Ventura (2000) go through the details.
The reasoning is basically what @ |
36,076 | Is the p-value still uniformly distributed when the null hypothesis is composite? | First of all let's deal with the simple point hypothesis. It is often claimed (as it is currently in Wikipedia) that the p-value is uniform over [0,1].
This is obviously not the case for discrete outcomes. For example if a coin is tossed 5 times and the test statistic is the number of heads obtained there are only 3 possible p-values under the null hypothesis that the coin is fair. The p-values 0.0625, 0.375 and 1 have probability 0.0625, 0.3125 and 0.625 of occuring arising from outcomes {0,5}, {1,4} and {2,3} respectively.
Perhaps less obvious is that it is not always true for the continuous case. Consider the the null hypothesis that the location of the minute hand on my clock when the battery runs out is uniformly distributed over the range [0,60). All outcomes have the same probability of occuring so the probability of getting an outcome as extreme or more extreme than the observed outcome is unity.
Moving on to composite nulls. No the p-value is not distributed over (0,1) for composite nulls and not just for the reasons given above. Perhaps the p-value has no meaning at all for composite nulls.
Alternatively the p-value is taken to be the p-value for the most favourable member of the composite null for the observed data i.e. the maximum likelihood member of the null. Under this interpretation a p-value of zero may not be possible. Consider the null hypothesis that a coin is fair where fair is defined with a bit of tolerance so that 0.49 < p < 0.51. If zero heads are observed the most likely point hypothesis is p=0.49. But using this member of the null there are more extreme outcomes: in this case all heads would be even less probable. Hence there is a lower bound on the p-value which is not 0.
Note that considering the least favourable member of the null for a given dataset doesn't get you anywhere - for some composite hypotheses it will always be possible to choose a member of the null for which the probability of the observed data is zero whatever the data may be (and therefore a p-value which is always zero). An example is the null that the coin is biased where biased is defined as outside of the above range i.e. p<0.49 or p>0.51. If some heads are observed the point hypothesis p=0 renders this impossible. Conversely if no heads are obtained p=1 renders this impossible. Therefore p-value cannot be defined in terms of least favourable member of the null. | Is the p-value still uniformly distributed when the null hypothesis is composite? | First of all let's deal with the simple point hypothesis. It is often claimed (as it is currently in Wikipedia) that the p-value is uniform over [0,1].
This is obviously not the case for discrete outc | Is the p-value still uniformly distributed when the null hypothesis is composite?
First of all let's deal with the simple point hypothesis. It is often claimed (as it is currently in Wikipedia) that the p-value is uniform over [0,1].
This is obviously not the case for discrete outcomes. For example if a coin is tossed 5 times and the test statistic is the number of heads obtained there are only 3 possible p-values under the null hypothesis that the coin is fair. The p-values 0.0625, 0.375 and 1 have probability 0.0625, 0.3125 and 0.625 of occuring arising from outcomes {0,5}, {1,4} and {2,3} respectively.
Perhaps less obvious is that it is not always true for the continuous case. Consider the the null hypothesis that the location of the minute hand on my clock when the battery runs out is uniformly distributed over the range [0,60). All outcomes have the same probability of occuring so the probability of getting an outcome as extreme or more extreme than the observed outcome is unity.
Moving on to composite nulls. No the p-value is not distributed over (0,1) for composite nulls and not just for the reasons given above. Perhaps the p-value has no meaning at all for composite nulls.
Alternatively the p-value is taken to be the p-value for the most favourable member of the composite null for the observed data i.e. the maximum likelihood member of the null. Under this interpretation a p-value of zero may not be possible. Consider the null hypothesis that a coin is fair where fair is defined with a bit of tolerance so that 0.49 < p < 0.51. If zero heads are observed the most likely point hypothesis is p=0.49. But using this member of the null there are more extreme outcomes: in this case all heads would be even less probable. Hence there is a lower bound on the p-value which is not 0.
Note that considering the least favourable member of the null for a given dataset doesn't get you anywhere - for some composite hypotheses it will always be possible to choose a member of the null for which the probability of the observed data is zero whatever the data may be (and therefore a p-value which is always zero). An example is the null that the coin is biased where biased is defined as outside of the above range i.e. p<0.49 or p>0.51. If some heads are observed the point hypothesis p=0 renders this impossible. Conversely if no heads are obtained p=1 renders this impossible. Therefore p-value cannot be defined in terms of least favourable member of the null. | Is the p-value still uniformly distributed when the null hypothesis is composite?
First of all let's deal with the simple point hypothesis. It is often claimed (as it is currently in Wikipedia) that the p-value is uniform over [0,1].
This is obviously not the case for discrete outc |
36,077 | Is it ok to determine early stopping using the validation set in 10-fold cross-validation? | I am not completely clear of what the question is asking, but I think the answer is no. The thing you need to think hard about with cross-validation is that no part of your algorithm can have any access to the test set. If it does, then your cross-validation results will be tainted and not be an accurate measure of the 'true' error.
From your question, I assume you are using some kind of iterative learning algorithm such as GBM and you are using the validation set as a way of determining when your GBM has enough models in its ensemble and has started to overfit. If this is true, then what you are doing is not optimal.
The way to think of this is that the stopping criteria is part of your learning algorithm. If it is part of the algorithm, then it can't use the test set in any way.
You may need to do nested cross-validation. In your outer loop, you divide into test and training sets, then in your inner loop you further divide the training set into sub test and training sets and proceed as you have. The inner loop cross-validation can be used to learn from that training set when to stop the learning, but to get an accurate generalization error you then need to apply that to the test set from the outer loop that hasn't yet been touched by the inner loop whose aim was to find, from the training data, when the best time to stop is. To be clear, say the inner loop cross-validation found that the best number of iterations was 10. In your outer loop you learn a model using the full outer loop training set, iterating 10 times, then see how that performs on the test set.
Does this make sense?
Note that depending on the models in use and the dataset, this may or may not be a big issue. The downside is that nested cross-validation can be very computationally expensive. Doing things the way you have been may well be an appropriate trade-off between accuracy and computational time in your circumstance. The most rigid answer to your question is no, it is not completely valid cross-validation. Whether it is passable for your circumstances is a different question. | Is it ok to determine early stopping using the validation set in 10-fold cross-validation? | I am not completely clear of what the question is asking, but I think the answer is no. The thing you need to think hard about with cross-validation is that no part of your algorithm can have any acce | Is it ok to determine early stopping using the validation set in 10-fold cross-validation?
I am not completely clear of what the question is asking, but I think the answer is no. The thing you need to think hard about with cross-validation is that no part of your algorithm can have any access to the test set. If it does, then your cross-validation results will be tainted and not be an accurate measure of the 'true' error.
From your question, I assume you are using some kind of iterative learning algorithm such as GBM and you are using the validation set as a way of determining when your GBM has enough models in its ensemble and has started to overfit. If this is true, then what you are doing is not optimal.
The way to think of this is that the stopping criteria is part of your learning algorithm. If it is part of the algorithm, then it can't use the test set in any way.
You may need to do nested cross-validation. In your outer loop, you divide into test and training sets, then in your inner loop you further divide the training set into sub test and training sets and proceed as you have. The inner loop cross-validation can be used to learn from that training set when to stop the learning, but to get an accurate generalization error you then need to apply that to the test set from the outer loop that hasn't yet been touched by the inner loop whose aim was to find, from the training data, when the best time to stop is. To be clear, say the inner loop cross-validation found that the best number of iterations was 10. In your outer loop you learn a model using the full outer loop training set, iterating 10 times, then see how that performs on the test set.
Does this make sense?
Note that depending on the models in use and the dataset, this may or may not be a big issue. The downside is that nested cross-validation can be very computationally expensive. Doing things the way you have been may well be an appropriate trade-off between accuracy and computational time in your circumstance. The most rigid answer to your question is no, it is not completely valid cross-validation. Whether it is passable for your circumstances is a different question. | Is it ok to determine early stopping using the validation set in 10-fold cross-validation?
I am not completely clear of what the question is asking, but I think the answer is no. The thing you need to think hard about with cross-validation is that no part of your algorithm can have any acce |
36,078 | Is it ok to determine early stopping using the validation set in 10-fold cross-validation? | The answer is yes as long as you reserve a test set for scoring in your cross validation. This is typically done by a three way partitioning versus a two way: one for train, one for validation (stop), and one for score (test). The validation set is being used to estimate the error on the test set. Thus the idea is that this stratagem gives the minimum error on the test set. Note that there is no way to inhibit over fitting unless you use the validation set to make your stopping decision, where you have achieved your parameter values by using the training set. | Is it ok to determine early stopping using the validation set in 10-fold cross-validation? | The answer is yes as long as you reserve a test set for scoring in your cross validation. This is typically done by a three way partitioning versus a two way: one for train, one for validation (stop) | Is it ok to determine early stopping using the validation set in 10-fold cross-validation?
The answer is yes as long as you reserve a test set for scoring in your cross validation. This is typically done by a three way partitioning versus a two way: one for train, one for validation (stop), and one for score (test). The validation set is being used to estimate the error on the test set. Thus the idea is that this stratagem gives the minimum error on the test set. Note that there is no way to inhibit over fitting unless you use the validation set to make your stopping decision, where you have achieved your parameter values by using the training set. | Is it ok to determine early stopping using the validation set in 10-fold cross-validation?
The answer is yes as long as you reserve a test set for scoring in your cross validation. This is typically done by a three way partitioning versus a two way: one for train, one for validation (stop) |
36,079 | Extending the Hellinger Distance to multivariate distributions | It's definitely valid. In fact, Hellinger distance between two measure $P$ and $Q$, which are dominated by the same (sigma-finite) measure $\lambda$, is defined as
$$
H^2(P,Q) = \frac{1}{2}\int\left( \sqrt{\frac{dP}{d\lambda}} - \sqrt{\frac{dQ}{d\lambda}} \right)^2 \, d\lambda \, .
$$
Therefore, you're considering the special case when $\lambda$ is two-dimensional Lebesgue measure, and the densities $f$ and $g$ are versions of the Radon-Nikodym derivatives $dP/d\lambda$ and $dQ/d\lambda$. | Extending the Hellinger Distance to multivariate distributions | It's definitely valid. In fact, Hellinger distance between two measure $P$ and $Q$, which are dominated by the same (sigma-finite) measure $\lambda$, is defined as
$$
H^2(P,Q) = \frac{1}{2}\int\left | Extending the Hellinger Distance to multivariate distributions
It's definitely valid. In fact, Hellinger distance between two measure $P$ and $Q$, which are dominated by the same (sigma-finite) measure $\lambda$, is defined as
$$
H^2(P,Q) = \frac{1}{2}\int\left( \sqrt{\frac{dP}{d\lambda}} - \sqrt{\frac{dQ}{d\lambda}} \right)^2 \, d\lambda \, .
$$
Therefore, you're considering the special case when $\lambda$ is two-dimensional Lebesgue measure, and the densities $f$ and $g$ are versions of the Radon-Nikodym derivatives $dP/d\lambda$ and $dQ/d\lambda$. | Extending the Hellinger Distance to multivariate distributions
It's definitely valid. In fact, Hellinger distance between two measure $P$ and $Q$, which are dominated by the same (sigma-finite) measure $\lambda$, is defined as
$$
H^2(P,Q) = \frac{1}{2}\int\left |
36,080 | pivotal statistic versus distribution free statistic | In the first one, the distribution of the quantity involves an unknown parameter or parameters and DOES depend on the distribution of the data. What it doesn't depend on is that parameter or parameters.
So for $X\sim N(\theta,1)$, if we take $Q(\underline{x};\theta) = \bar{x}-\theta$, the distribution of $Q$ is $N(0,1/n)$. This is useful, because you can immediately write down an interval for $Q$ and hence back out an interval for $\theta$.
Note that if $X$ had a different distribution, $Q$ would no longer be $N(0,1/n)$. It's NOT distribution free, its distribution is free of $\theta$ (but note that $Q$ itself is still a function of $\theta$).
In the second one, the distribution of the statistic, $T(\underline{x})$ (which statistic doesn't involve any unknown parameters) - for some specific given value of some population quantities/parameters (so that you're under a null, not an alternative*) - doesn't depend on the distribution of the data.
So, for example, under the null, the distribution of the statistic in a sign test doesn't depend on the distribution the data were drawn from (it's always binomial, as long as the data are continuous, independent, etc). But said distribution sure as heck changes if you change the median difference from zero (i.e. move away from the null).
* if its distribution didn't depend on whatever population quantity or effect the test was trying to pick up under the alternative, it would be useless as a test - the power would always be the significance level
There may well be some circumstances where $Q = T(x-\theta)$ is pivotal at say a large class of location families, and where $T(x)$ is distribution free when $\theta=0$. I think it should work in a variety of circumstances; perhaps the aforementioned sign test would be an obvious place to start. | pivotal statistic versus distribution free statistic | In the first one, the distribution of the quantity involves an unknown parameter or parameters and DOES depend on the distribution of the data. What it doesn't depend on is that parameter or parameter | pivotal statistic versus distribution free statistic
In the first one, the distribution of the quantity involves an unknown parameter or parameters and DOES depend on the distribution of the data. What it doesn't depend on is that parameter or parameters.
So for $X\sim N(\theta,1)$, if we take $Q(\underline{x};\theta) = \bar{x}-\theta$, the distribution of $Q$ is $N(0,1/n)$. This is useful, because you can immediately write down an interval for $Q$ and hence back out an interval for $\theta$.
Note that if $X$ had a different distribution, $Q$ would no longer be $N(0,1/n)$. It's NOT distribution free, its distribution is free of $\theta$ (but note that $Q$ itself is still a function of $\theta$).
In the second one, the distribution of the statistic, $T(\underline{x})$ (which statistic doesn't involve any unknown parameters) - for some specific given value of some population quantities/parameters (so that you're under a null, not an alternative*) - doesn't depend on the distribution of the data.
So, for example, under the null, the distribution of the statistic in a sign test doesn't depend on the distribution the data were drawn from (it's always binomial, as long as the data are continuous, independent, etc). But said distribution sure as heck changes if you change the median difference from zero (i.e. move away from the null).
* if its distribution didn't depend on whatever population quantity or effect the test was trying to pick up under the alternative, it would be useless as a test - the power would always be the significance level
There may well be some circumstances where $Q = T(x-\theta)$ is pivotal at say a large class of location families, and where $T(x)$ is distribution free when $\theta=0$. I think it should work in a variety of circumstances; perhaps the aforementioned sign test would be an obvious place to start. | pivotal statistic versus distribution free statistic
In the first one, the distribution of the quantity involves an unknown parameter or parameters and DOES depend on the distribution of the data. What it doesn't depend on is that parameter or parameter |
36,081 | Obtaining marginal distributions from the bivariate normal | Following up on whuber's comment,
$$\begin{align}
\left.\left.\frac{1}{2(1-\rho^2)}\right(x^2+y^2-2\rho xy\right)
&=\left.\left.\frac{1}{2(1-\rho^2)}\right(x^2-\rho^2x^2+(y^2-2\rho xy + \rho^2x^2)\right)\\
&= \frac{x^2}{2} + \frac{1}{2}\left(\frac{y-\rho x}{\sqrt{1-\rho^2}}\right)^2
\end{align}$$
and so
$$\int_{-\infty}^\infty f_{X,Y}(x,y)\,\mathrm dy = \frac{e^{-x^2/2}}{\sqrt{2\pi}}
\int_{-\infty}^\infty \frac{e^{-(y-\rho x)^2/2(1-\rho^2)}}{\sqrt{1-\rho^2}\sqrt{2\pi}}\,\mathrm dy.$$
I will leave it to the OP to complete
the details and determine whether $\rho$ disappears or not when the integral
is evaluated. | Obtaining marginal distributions from the bivariate normal | Following up on whuber's comment,
$$\begin{align}
\left.\left.\frac{1}{2(1-\rho^2)}\right(x^2+y^2-2\rho xy\right)
&=\left.\left.\frac{1}{2(1-\rho^2)}\right(x^2-\rho^2x^2+(y^2-2\rho xy + \rho^2x^2)\rig | Obtaining marginal distributions from the bivariate normal
Following up on whuber's comment,
$$\begin{align}
\left.\left.\frac{1}{2(1-\rho^2)}\right(x^2+y^2-2\rho xy\right)
&=\left.\left.\frac{1}{2(1-\rho^2)}\right(x^2-\rho^2x^2+(y^2-2\rho xy + \rho^2x^2)\right)\\
&= \frac{x^2}{2} + \frac{1}{2}\left(\frac{y-\rho x}{\sqrt{1-\rho^2}}\right)^2
\end{align}$$
and so
$$\int_{-\infty}^\infty f_{X,Y}(x,y)\,\mathrm dy = \frac{e^{-x^2/2}}{\sqrt{2\pi}}
\int_{-\infty}^\infty \frac{e^{-(y-\rho x)^2/2(1-\rho^2)}}{\sqrt{1-\rho^2}\sqrt{2\pi}}\,\mathrm dy.$$
I will leave it to the OP to complete
the details and determine whether $\rho$ disappears or not when the integral
is evaluated. | Obtaining marginal distributions from the bivariate normal
Following up on whuber's comment,
$$\begin{align}
\left.\left.\frac{1}{2(1-\rho^2)}\right(x^2+y^2-2\rho xy\right)
&=\left.\left.\frac{1}{2(1-\rho^2)}\right(x^2-\rho^2x^2+(y^2-2\rho xy + \rho^2x^2)\rig |
36,082 | Diagnosing why MICE is crashing R when attempting to impute multilevel data | I occasionally have problems with the 2l methods for large data, but have never seen R itself crash on it. My guess would be that they are related to sparse data (very small clusters). How many predictors do you have relative to cluster size?
Some suggestions:
In your data, you have several covariates that have incomplete data but that are not imputed. Please check whether mice removes them before imputation by setting maxit = 0 and inspects imp$log. If you want to use these as predictors, you should specify an imputation method for them.
The mice package does not use any own fortran or C code, but pan may (I don't know). If you are really determined to find the source of the problem, I suggest that you consult the book by Matloff, which contains chapter on advanced debugging techniques.
The obvious other route is to try to simplify the model. Remove superfluous predictors, use a flat file (e.g. pmm) with cluster allocation as a fixed factor, and check whether the intra-class correlations of the observed and impute data are similar.
The intercept term is automatically added by `mice.impute.2l.pan', so you do not need that.
Hope this helps. | Diagnosing why MICE is crashing R when attempting to impute multilevel data | I occasionally have problems with the 2l methods for large data, but have never seen R itself crash on it. My guess would be that they are related to sparse data (very small clusters). How many predic | Diagnosing why MICE is crashing R when attempting to impute multilevel data
I occasionally have problems with the 2l methods for large data, but have never seen R itself crash on it. My guess would be that they are related to sparse data (very small clusters). How many predictors do you have relative to cluster size?
Some suggestions:
In your data, you have several covariates that have incomplete data but that are not imputed. Please check whether mice removes them before imputation by setting maxit = 0 and inspects imp$log. If you want to use these as predictors, you should specify an imputation method for them.
The mice package does not use any own fortran or C code, but pan may (I don't know). If you are really determined to find the source of the problem, I suggest that you consult the book by Matloff, which contains chapter on advanced debugging techniques.
The obvious other route is to try to simplify the model. Remove superfluous predictors, use a flat file (e.g. pmm) with cluster allocation as a fixed factor, and check whether the intra-class correlations of the observed and impute data are similar.
The intercept term is automatically added by `mice.impute.2l.pan', so you do not need that.
Hope this helps. | Diagnosing why MICE is crashing R when attempting to impute multilevel data
I occasionally have problems with the 2l methods for large data, but have never seen R itself crash on it. My guess would be that they are related to sparse data (very small clusters). How many predic |
36,083 | Diagnosing why MICE is crashing R when attempting to impute multilevel data | I found what is causing the crash - there was one missing value in grp (which was not being imputed). Still, it does not seem quite right that it crashes R ! After running
dt.fail <- dt.fail[!is.na(dt.fail$grp),]
it no longer crashes, but instead generates the following error:
Error in order(dfr$group) : argument 1 is not a vector
I will post a seperate question about that. | Diagnosing why MICE is crashing R when attempting to impute multilevel data | I found what is causing the crash - there was one missing value in grp (which was not being imputed). Still, it does not seem quite right that it crashes R ! After running
dt.fail <- dt.fail[!is.na(d | Diagnosing why MICE is crashing R when attempting to impute multilevel data
I found what is causing the crash - there was one missing value in grp (which was not being imputed). Still, it does not seem quite right that it crashes R ! After running
dt.fail <- dt.fail[!is.na(dt.fail$grp),]
it no longer crashes, but instead generates the following error:
Error in order(dfr$group) : argument 1 is not a vector
I will post a seperate question about that. | Diagnosing why MICE is crashing R when attempting to impute multilevel data
I found what is causing the crash - there was one missing value in grp (which was not being imputed). Still, it does not seem quite right that it crashes R ! After running
dt.fail <- dt.fail[!is.na(d |
36,084 | Smoothing 2D data | You need a to specify a model that separates the signal from the noise.
There is the component of noise at the measurement level that you assume gaussian.
The other components, dependent across measurements:
"This noise, for a fixed frequency, can probably be modelled as random with gaussian distribution". Needs clarification — is the noise component common to all timepoints, given the frequency? Is the standard deviation same for all frequencies? Etc.
"At a fixed time, however, the data shows a different kind of noise, with large spurious spikes and fast oscillations" How do you separate that from the signal, for assumably you are interested on variation of the intensity across the frequency. Is the interesting variation somehow different from the uninteresting variation, and if so, how?
Spurious oscillatioins or non-gaussian noise in general is not a big problem, if you have a realistic idea of its characteristics. It can be modeled by transforming the data (and then using a gaussian model) or by explicitly using a non-gaussian error distribution. Modeling noise that is correlated over measurements is more challenging.
Depending on how your noise and data model are, you might be able to model the data with a general-purpose tool like the GAMs in the mgcv package, or you may need a more flexible tool, which easily leads to a quite customized bayesian setup. There are tools for such models, but if you are not a statistician, learning to use them will take a while.
I guess either a solution specific to spectral analysis or the mgcv package are your best bets. | Smoothing 2D data | You need a to specify a model that separates the signal from the noise.
There is the component of noise at the measurement level that you assume gaussian.
The other components, dependent across meas | Smoothing 2D data
You need a to specify a model that separates the signal from the noise.
There is the component of noise at the measurement level that you assume gaussian.
The other components, dependent across measurements:
"This noise, for a fixed frequency, can probably be modelled as random with gaussian distribution". Needs clarification — is the noise component common to all timepoints, given the frequency? Is the standard deviation same for all frequencies? Etc.
"At a fixed time, however, the data shows a different kind of noise, with large spurious spikes and fast oscillations" How do you separate that from the signal, for assumably you are interested on variation of the intensity across the frequency. Is the interesting variation somehow different from the uninteresting variation, and if so, how?
Spurious oscillatioins or non-gaussian noise in general is not a big problem, if you have a realistic idea of its characteristics. It can be modeled by transforming the data (and then using a gaussian model) or by explicitly using a non-gaussian error distribution. Modeling noise that is correlated over measurements is more challenging.
Depending on how your noise and data model are, you might be able to model the data with a general-purpose tool like the GAMs in the mgcv package, or you may need a more flexible tool, which easily leads to a quite customized bayesian setup. There are tools for such models, but if you are not a statistician, learning to use them will take a while.
I guess either a solution specific to spectral analysis or the mgcv package are your best bets. | Smoothing 2D data
You need a to specify a model that separates the signal from the noise.
There is the component of noise at the measurement level that you assume gaussian.
The other components, dependent across meas |
36,085 | Smoothing 2D data | A time series of spectra suggests to me a kinetics experiment, and there is a well-established amount of chemometric literature about this.
What do you know about the spectra? What type of spectra are they? Can you reasonably expect that you have only two species, educt and product?
Can you reasonably assume bilinearity, i.e. the measured spectra $\mathbf X$ at a given time are a linear combination of the component concentrations $\mathbf C$ times the pure component spectra $\mathbf S$:
$\mathbf X^{(nspc \times nwl)} = \mathbf C^{(nspc \times ncomp)} \mathbf S^{(ncomp \times nwl)}$
You say that you want to estimate an exponential decay (in the concentrations). This together with bilinearity suggests to me multivariate curve resolution (MCR). This is a technique that allows you to use information you have (e.g. pure component spectra of some substances, or assumptions on the concentration behaviour like the exponential decay) during model fitting.
A good starting point in the literature is:
Anna de Juan, Marcel Maeder, Manuel Martínez Romà Tauler: Combining hard- and soft-modelling to solve kinetic problems, Chemometrics and Intelligent Laboratory Systems 54, 2000. 123–141.
A good starting point in the internet is http://www.mcrals.info/
The UseR! Chemometrics book discusses it at the very end
Implementation in R: package ALS
As far as I know, it is quite common to smooth the concentrations according to some, e.g. kinetic, model but it is far less common to smooth the spectra. However, the algorithm allows to do so. I asked Anna in summer whether they impose smoothness constraints, but she told me they don't (and good spectroscopists hate smoothing instead of measuring good spectra ;-) ). Often, it is not needed, neither, because aggregating the information from all the spectra will already yield good estimates of the pure component spectra.
I did smooth "component spectra" (in fact, principal components) twice lately (Dochow et al.: Raman-on-chip device and detection fibres with fibre Bragg grating for analysis of solutions and particles, LabChip, 2013 and Dochow el al.: Quartz microfluidic chip for tumour cell identification by Raman spectroscopy in combination with optical traps, AnalBioanalChem, accepted) but in these cases my spectroscopic knowledge told me that I'm allowed to do this. I quite regularly apply a downsampling and smoothing interpolation to my Raman spectra (hyperSpec::spc.loess).
How to know what is too much smoothing? I think the only possible answer is "expert knowledge about the type of spectroscopy and experiment".
edit: I reread the question, and you say you want to estimate the decay at each wavelength. However, is that true or do you want to estimate the decay of different species with overlapping spectra? | Smoothing 2D data | A time series of spectra suggests to me a kinetics experiment, and there is a well-established amount of chemometric literature about this.
What do you know about the spectra? What type of spectra ar | Smoothing 2D data
A time series of spectra suggests to me a kinetics experiment, and there is a well-established amount of chemometric literature about this.
What do you know about the spectra? What type of spectra are they? Can you reasonably expect that you have only two species, educt and product?
Can you reasonably assume bilinearity, i.e. the measured spectra $\mathbf X$ at a given time are a linear combination of the component concentrations $\mathbf C$ times the pure component spectra $\mathbf S$:
$\mathbf X^{(nspc \times nwl)} = \mathbf C^{(nspc \times ncomp)} \mathbf S^{(ncomp \times nwl)}$
You say that you want to estimate an exponential decay (in the concentrations). This together with bilinearity suggests to me multivariate curve resolution (MCR). This is a technique that allows you to use information you have (e.g. pure component spectra of some substances, or assumptions on the concentration behaviour like the exponential decay) during model fitting.
A good starting point in the literature is:
Anna de Juan, Marcel Maeder, Manuel Martínez Romà Tauler: Combining hard- and soft-modelling to solve kinetic problems, Chemometrics and Intelligent Laboratory Systems 54, 2000. 123–141.
A good starting point in the internet is http://www.mcrals.info/
The UseR! Chemometrics book discusses it at the very end
Implementation in R: package ALS
As far as I know, it is quite common to smooth the concentrations according to some, e.g. kinetic, model but it is far less common to smooth the spectra. However, the algorithm allows to do so. I asked Anna in summer whether they impose smoothness constraints, but she told me they don't (and good spectroscopists hate smoothing instead of measuring good spectra ;-) ). Often, it is not needed, neither, because aggregating the information from all the spectra will already yield good estimates of the pure component spectra.
I did smooth "component spectra" (in fact, principal components) twice lately (Dochow et al.: Raman-on-chip device and detection fibres with fibre Bragg grating for analysis of solutions and particles, LabChip, 2013 and Dochow el al.: Quartz microfluidic chip for tumour cell identification by Raman spectroscopy in combination with optical traps, AnalBioanalChem, accepted) but in these cases my spectroscopic knowledge told me that I'm allowed to do this. I quite regularly apply a downsampling and smoothing interpolation to my Raman spectra (hyperSpec::spc.loess).
How to know what is too much smoothing? I think the only possible answer is "expert knowledge about the type of spectroscopy and experiment".
edit: I reread the question, and you say you want to estimate the decay at each wavelength. However, is that true or do you want to estimate the decay of different species with overlapping spectra? | Smoothing 2D data
A time series of spectra suggests to me a kinetics experiment, and there is a well-established amount of chemometric literature about this.
What do you know about the spectra? What type of spectra ar |
36,086 | Smoothing 2D data | The data consist of optical spectra (light intensity against frequency) recorded at >varying times. The points were acquired on a regular grid in x (time) , y (frequency).
To me, this sounds very much like a case for functional data analysis (FDA), although I have no idea of the physics behind your problem, and I might be completely wrong. If you can consider the process behind your data to be inherently smooth and continuous, you might want to use a bivariate basis function expansion to capture your measurements in the form $intensity = f(time, frequency)$, with $f$ being a sum of basis functions (e.g. b-splines) and coefficients. A limited set of basis functions directly reduces roughness and therefore cancels a good part of white noise.
I've read things about 2D kernel density estimate, 2D polynomial / spline interpolation,
etc.
...
I use R, for which I see many packages that seem related (MASS (kde2), fields
(smooth.2d), etc.) but I cannot find much advice on which technique to apply here.
You mentioned spline interpolation, but didn't mention the fda package which implements pretty nicely and easily accessible the basis function expansion I mentioned above. The set of simultaneous measurements for time, frequency and intensity (ordered as a threedimensional array) could be captured as one bivariate functional data object, see. e.g. the function 'Data2fd'. Moreover, several smoothing procedures are available in the package which are all designed to cancel white noise or "roughness" in measurements of inherently smooth processes.
The Wikipedia article phrases the problem of white noise in FDA as follows:
The data may be so accurate that error can be ignored, may be subject to substantial measurement error, or even have a complex indirect relationship to the curve that they define. ... daily records of precipitation at a weather station are so variable as to require careful and sophisticated analyses in order to extract something like a mean precipitation curve.
FDA provide the tools for these cases. Doesn't this translate to your case?
...but I'm not familiar with the jargon or the underlying statistical theory...
...but I cannot find much advice on which technique to apply here...
Concerning fda: I wasn't neither but the book of Ramsay and Silverman on FDA (2005) makes the basics very well accessible and Ramsay Hooker and Graves (2009) directly translate the insights from the book into R code. Both volumes should be available as e-books in a university library for statistics, biosciences, climatology or psychology. Google will also bring up some more links that I can't post alltogether here.
Sorry that I can not provide a more direct solution for your problem. However, FDA did help me a lot once I figured out what it is for. | Smoothing 2D data | The data consist of optical spectra (light intensity against frequency) recorded at >varying times. The points were acquired on a regular grid in x (time) , y (frequency).
To me, this sounds very muc | Smoothing 2D data
The data consist of optical spectra (light intensity against frequency) recorded at >varying times. The points were acquired on a regular grid in x (time) , y (frequency).
To me, this sounds very much like a case for functional data analysis (FDA), although I have no idea of the physics behind your problem, and I might be completely wrong. If you can consider the process behind your data to be inherently smooth and continuous, you might want to use a bivariate basis function expansion to capture your measurements in the form $intensity = f(time, frequency)$, with $f$ being a sum of basis functions (e.g. b-splines) and coefficients. A limited set of basis functions directly reduces roughness and therefore cancels a good part of white noise.
I've read things about 2D kernel density estimate, 2D polynomial / spline interpolation,
etc.
...
I use R, for which I see many packages that seem related (MASS (kde2), fields
(smooth.2d), etc.) but I cannot find much advice on which technique to apply here.
You mentioned spline interpolation, but didn't mention the fda package which implements pretty nicely and easily accessible the basis function expansion I mentioned above. The set of simultaneous measurements for time, frequency and intensity (ordered as a threedimensional array) could be captured as one bivariate functional data object, see. e.g. the function 'Data2fd'. Moreover, several smoothing procedures are available in the package which are all designed to cancel white noise or "roughness" in measurements of inherently smooth processes.
The Wikipedia article phrases the problem of white noise in FDA as follows:
The data may be so accurate that error can be ignored, may be subject to substantial measurement error, or even have a complex indirect relationship to the curve that they define. ... daily records of precipitation at a weather station are so variable as to require careful and sophisticated analyses in order to extract something like a mean precipitation curve.
FDA provide the tools for these cases. Doesn't this translate to your case?
...but I'm not familiar with the jargon or the underlying statistical theory...
...but I cannot find much advice on which technique to apply here...
Concerning fda: I wasn't neither but the book of Ramsay and Silverman on FDA (2005) makes the basics very well accessible and Ramsay Hooker and Graves (2009) directly translate the insights from the book into R code. Both volumes should be available as e-books in a university library for statistics, biosciences, climatology or psychology. Google will also bring up some more links that I can't post alltogether here.
Sorry that I can not provide a more direct solution for your problem. However, FDA did help me a lot once I figured out what it is for. | Smoothing 2D data
The data consist of optical spectra (light intensity against frequency) recorded at >varying times. The points were acquired on a regular grid in x (time) , y (frequency).
To me, this sounds very muc |
36,087 | Smoothing 2D data | Being a simple physicist, not a statistics expert, I'd take a simple approach. The two dimensions are of different natures. It would make sense to smooth along time with one algorithm, and smooth along wavelength with another.
The actual algorithms I'd use: for wavelength, Savitzky-Golay with a higher order, 6 maybe 8.
Along time, if that example is typical, that sudden jump up and more or less exponential decline make it tricky. I've had experimental data, and noisy images, just like that. If simple straightforward methods don't help enough, try a Gaussian smoother but suppress its effect near the jump, as detected by an edge detector. Smooth and broaden the edge detector's output, normalize it to go from 0.0 to 1.0, and use it to select between the original image and the Gaussian-smoothed one, pixel by pixel. | Smoothing 2D data | Being a simple physicist, not a statistics expert, I'd take a simple approach. The two dimensions are of different natures. It would make sense to smooth along time with one algorithm, and smooth al | Smoothing 2D data
Being a simple physicist, not a statistics expert, I'd take a simple approach. The two dimensions are of different natures. It would make sense to smooth along time with one algorithm, and smooth along wavelength with another.
The actual algorithms I'd use: for wavelength, Savitzky-Golay with a higher order, 6 maybe 8.
Along time, if that example is typical, that sudden jump up and more or less exponential decline make it tricky. I've had experimental data, and noisy images, just like that. If simple straightforward methods don't help enough, try a Gaussian smoother but suppress its effect near the jump, as detected by an edge detector. Smooth and broaden the edge detector's output, normalize it to go from 0.0 to 1.0, and use it to select between the original image and the Gaussian-smoothed one, pixel by pixel. | Smoothing 2D data
Being a simple physicist, not a statistics expert, I'd take a simple approach. The two dimensions are of different natures. It would make sense to smooth along time with one algorithm, and smooth al |
36,088 | Smoothing 2D data | @baptiste: I'm glad you added the plot like I suggested. It does help a lot:
So, if I understand correctly, your practical goal is to evaluate the exponential decay rate for each wavelength; then let's do just that! Define a function you want to minimize for each wavelength separately, and minimize it.
Let's look at a single given wavelength, like in your lower right plot.
First, for simplicity, let's throw away all of the values prior to 0.2 seconds, because they contain a massive discontinuity (our approach can be augmented to deal with that later).
Then, define the following optimization criterion, which aims to find the decay constant $\tau$:
$$
\hat\tau = arg min_{\tau} \sum_{t_i}||e^{-t_i/\tau }- d_i||^2
$$
You can solve this optimization problem analytically by differentiating w.r.t $\tau$, equating to zero, and solving for $\tau$; or you can use a solver.
Later, if you believe that adjacent wavelength should have similar decay constants, you can incorporate this into a more elaborate optimization criterion.
If anything, I would suggest you read an optimization must-read book: Boyd's convex optimization.
Hope this helps! | Smoothing 2D data | @baptiste: I'm glad you added the plot like I suggested. It does help a lot:
So, if I understand correctly, your practical goal is to evaluate the exponential decay rate for each wavelength; then let' | Smoothing 2D data
@baptiste: I'm glad you added the plot like I suggested. It does help a lot:
So, if I understand correctly, your practical goal is to evaluate the exponential decay rate for each wavelength; then let's do just that! Define a function you want to minimize for each wavelength separately, and minimize it.
Let's look at a single given wavelength, like in your lower right plot.
First, for simplicity, let's throw away all of the values prior to 0.2 seconds, because they contain a massive discontinuity (our approach can be augmented to deal with that later).
Then, define the following optimization criterion, which aims to find the decay constant $\tau$:
$$
\hat\tau = arg min_{\tau} \sum_{t_i}||e^{-t_i/\tau }- d_i||^2
$$
You can solve this optimization problem analytically by differentiating w.r.t $\tau$, equating to zero, and solving for $\tau$; or you can use a solver.
Later, if you believe that adjacent wavelength should have similar decay constants, you can incorporate this into a more elaborate optimization criterion.
If anything, I would suggest you read an optimization must-read book: Boyd's convex optimization.
Hope this helps! | Smoothing 2D data
@baptiste: I'm glad you added the plot like I suggested. It does help a lot:
So, if I understand correctly, your practical goal is to evaluate the exponential decay rate for each wavelength; then let' |
36,089 | Fixed-effects using demeaned data: why different standard errors when using -plm-? | If you look carefully at the output, you'll notice that the degrees of freedom are different. The degrees of freedom is used to compute the standard errors, thus they are wrong for your demeaned lm. When you apply lm to the demeaned data, lm does not know that the means have been subtracted, or equivalently, that you have eliminated the dummies for the cluster levels. If you include the dummies, as in
summary(lm(y ~ x + cluster,data=dat))
the degrees of freedom are accounted for. | Fixed-effects using demeaned data: why different standard errors when using -plm-? | If you look carefully at the output, you'll notice that the degrees of freedom are different. The degrees of freedom is used to compute the standard errors, thus they are wrong for your demeaned lm. W | Fixed-effects using demeaned data: why different standard errors when using -plm-?
If you look carefully at the output, you'll notice that the degrees of freedom are different. The degrees of freedom is used to compute the standard errors, thus they are wrong for your demeaned lm. When you apply lm to the demeaned data, lm does not know that the means have been subtracted, or equivalently, that you have eliminated the dummies for the cluster levels. If you include the dummies, as in
summary(lm(y ~ x + cluster,data=dat))
the degrees of freedom are accounted for. | Fixed-effects using demeaned data: why different standard errors when using -plm-?
If you look carefully at the output, you'll notice that the degrees of freedom are different. The degrees of freedom is used to compute the standard errors, thus they are wrong for your demeaned lm. W |
36,090 | p-value with multimodal PDF of a test statistic | I think all this is way too much "p-value centered".
You have to remember what tests are really about: rejecting a null hypothesis with a given value for the α risk. The $p$-value is just a tool for this. In the most general situation, you have build a statistic $T$ with known distribution under the null hypothesis ; and to chose a rejection region $A$ so that $\mathbb P_0(T \in A) = \alpha$ (or at least $\le \alpha$ is equality is impossible). P-values are just a convenient way to chose $A$ in many situations, saving you the burden of making a choice. It's an easy recipe, that’s why is so popular, but you shouldn’t forget about what’s going on.
As $p$-values are computed from $T$ (with something like $p = F(T)$ they are also statistics, with uniform $\mathcal U(0,1)$ distribution under the null. If they behave well, they tend to have low values under the alternative, and you reject the null when $p \le\alpha$. The rejection region $A$ is then $A = F^{-1}( (0,\alpha) )$.
OK, I waved my hands long enough, it’s time for examples.
A classical situation with a unimodal statistic
Assume that you observe $x$ drawn from $\mathcal N(\mu,1)$, and want to test $\mu = 0$ (two-sided test). The usual solution is to take $t = x^2$. You know $T \sim \chi^2(1)$ under the null, and the p-value is $p = \mathbb P_0( T \ge t)$. This generates the classical symmetrical rejection region shown below for $\alpha = 0.1$.
In most situations, using the $p$-value leads to the "good" choice for the rejection region.
A fancy situation with a bimodal statistic
Assume that $\mu$ is drawn from an unknown distribution, and $x$ is drawn from $\mathcal N(\mu,1)$. Your null hypothesis is that $\mu = -4$ with probability $1\over 2$, and $\mu = 4$ with probability $1\over 2$. Then you have a bimodal distribution of $X$ as displayed below. Now you can't rely on the recipe: if $x$ is close to 0, let’s say $x = 0.001$... you sure want to reject the null hypothesis.
So we have to make a choice here. A simple choice will be to take a rejection region of the shape
$$ A = (-\infty, -4-a) \cup (-4+a, 4-a) \cup (4+a, \infty) $$
width $0< a$, as displayed below (with the convention that if $a \ge 4$, the central interval is empty). The natural choice is in fact to take a rejection region of the form $A = \{ x \>:\> f(x) < c \}$ where $f$ is the density of $X$, but here it is almost the same.
After a few computations, we have
$\newcommand{\erf}{F}$
$$\mathbb P( X \in A ) = \erf(-a)+\erf(-8-a) + \mathbf 1_{\{a<4\}} \left( \erf(8-a)-\erf(a)\right) $$
where $F$ is the cdf of a standard gaussian variable. This allows to find an appropriate threshold $a$ for any value of $\alpha$.
Now to retrieve a $p$-value that give an equivalent test, from an observation $x$, one take $a = \min( |4-x|, |-4-x| )$, so that $x$ is at the border of the corresponding rejection region ; and $p = \mathbb P( X \in A )$, with the above formula.
Post-Scriptum If you let $T = \min( |4-X|, |-4-X| )$, you transform $X$ into a unimodal statistic, and you can take the $p$-value as usual. | p-value with multimodal PDF of a test statistic | I think all this is way too much "p-value centered".
You have to remember what tests are really about: rejecting a null hypothesis with a given value for the α risk. The $p$-value is just a tool for | p-value with multimodal PDF of a test statistic
I think all this is way too much "p-value centered".
You have to remember what tests are really about: rejecting a null hypothesis with a given value for the α risk. The $p$-value is just a tool for this. In the most general situation, you have build a statistic $T$ with known distribution under the null hypothesis ; and to chose a rejection region $A$ so that $\mathbb P_0(T \in A) = \alpha$ (or at least $\le \alpha$ is equality is impossible). P-values are just a convenient way to chose $A$ in many situations, saving you the burden of making a choice. It's an easy recipe, that’s why is so popular, but you shouldn’t forget about what’s going on.
As $p$-values are computed from $T$ (with something like $p = F(T)$ they are also statistics, with uniform $\mathcal U(0,1)$ distribution under the null. If they behave well, they tend to have low values under the alternative, and you reject the null when $p \le\alpha$. The rejection region $A$ is then $A = F^{-1}( (0,\alpha) )$.
OK, I waved my hands long enough, it’s time for examples.
A classical situation with a unimodal statistic
Assume that you observe $x$ drawn from $\mathcal N(\mu,1)$, and want to test $\mu = 0$ (two-sided test). The usual solution is to take $t = x^2$. You know $T \sim \chi^2(1)$ under the null, and the p-value is $p = \mathbb P_0( T \ge t)$. This generates the classical symmetrical rejection region shown below for $\alpha = 0.1$.
In most situations, using the $p$-value leads to the "good" choice for the rejection region.
A fancy situation with a bimodal statistic
Assume that $\mu$ is drawn from an unknown distribution, and $x$ is drawn from $\mathcal N(\mu,1)$. Your null hypothesis is that $\mu = -4$ with probability $1\over 2$, and $\mu = 4$ with probability $1\over 2$. Then you have a bimodal distribution of $X$ as displayed below. Now you can't rely on the recipe: if $x$ is close to 0, let’s say $x = 0.001$... you sure want to reject the null hypothesis.
So we have to make a choice here. A simple choice will be to take a rejection region of the shape
$$ A = (-\infty, -4-a) \cup (-4+a, 4-a) \cup (4+a, \infty) $$
width $0< a$, as displayed below (with the convention that if $a \ge 4$, the central interval is empty). The natural choice is in fact to take a rejection region of the form $A = \{ x \>:\> f(x) < c \}$ where $f$ is the density of $X$, but here it is almost the same.
After a few computations, we have
$\newcommand{\erf}{F}$
$$\mathbb P( X \in A ) = \erf(-a)+\erf(-8-a) + \mathbf 1_{\{a<4\}} \left( \erf(8-a)-\erf(a)\right) $$
where $F$ is the cdf of a standard gaussian variable. This allows to find an appropriate threshold $a$ for any value of $\alpha$.
Now to retrieve a $p$-value that give an equivalent test, from an observation $x$, one take $a = \min( |4-x|, |-4-x| )$, so that $x$ is at the border of the corresponding rejection region ; and $p = \mathbb P( X \in A )$, with the above formula.
Post-Scriptum If you let $T = \min( |4-X|, |-4-X| )$, you transform $X$ into a unimodal statistic, and you can take the $p$-value as usual. | p-value with multimodal PDF of a test statistic
I think all this is way too much "p-value centered".
You have to remember what tests are really about: rejecting a null hypothesis with a given value for the α risk. The $p$-value is just a tool for |
36,091 | p-value with multimodal PDF of a test statistic | Actually both of you definitions work in different cases, it depends on how you define your null hypothesis (which is often affected by the way you state your alternative hypothesis, so it does matter).
If your null hypothesis is strictly that the parameter(s) equal a given value (or set of values, 1 per parameter), e.g. $H_0: \mu=\mu_0$ then your first definition works (well with $f(x) \le f(x_0)$). This is the 2-tailed test in the traditional simple statistics cases.
But often we are interested only in the alternative being in a certain direction, the one-tailed test case. E.g. If I want to prove that my new pain reliever is better than aspirin (takes less time for the headache to go away on average) then I am only interested in 1 tail and my alternative would be $H_a: \mu < \mu_0$ (if I prove that my new medicine takes longer then it will not help my advertising). This leads to the null hypothesis being $H_0: \mu \ge \mu_0$ even though we often write it as $H_0: \mu = \mu_0$. In this case we only want to look at the possible $x$ values in a certain region, so more like definition 2.
In practice, most common test statistics follow a unimodal distribution (or are close enough) under the null hypothesis, so both definitions are the same. The only common case I know of where all possible cases with lower likelihood are included in the p-value is Fisher's exact test for tables biger than $2\times2$.
So to sum up. Your thinking is generally correct, cases that you suggest are just rare enough that most books/classes only present the simpler version. | p-value with multimodal PDF of a test statistic | Actually both of you definitions work in different cases, it depends on how you define your null hypothesis (which is often affected by the way you state your alternative hypothesis, so it does matter | p-value with multimodal PDF of a test statistic
Actually both of you definitions work in different cases, it depends on how you define your null hypothesis (which is often affected by the way you state your alternative hypothesis, so it does matter).
If your null hypothesis is strictly that the parameter(s) equal a given value (or set of values, 1 per parameter), e.g. $H_0: \mu=\mu_0$ then your first definition works (well with $f(x) \le f(x_0)$). This is the 2-tailed test in the traditional simple statistics cases.
But often we are interested only in the alternative being in a certain direction, the one-tailed test case. E.g. If I want to prove that my new pain reliever is better than aspirin (takes less time for the headache to go away on average) then I am only interested in 1 tail and my alternative would be $H_a: \mu < \mu_0$ (if I prove that my new medicine takes longer then it will not help my advertising). This leads to the null hypothesis being $H_0: \mu \ge \mu_0$ even though we often write it as $H_0: \mu = \mu_0$. In this case we only want to look at the possible $x$ values in a certain region, so more like definition 2.
In practice, most common test statistics follow a unimodal distribution (or are close enough) under the null hypothesis, so both definitions are the same. The only common case I know of where all possible cases with lower likelihood are included in the p-value is Fisher's exact test for tables biger than $2\times2$.
So to sum up. Your thinking is generally correct, cases that you suggest are just rare enough that most books/classes only present the simpler version. | p-value with multimodal PDF of a test statistic
Actually both of you definitions work in different cases, it depends on how you define your null hypothesis (which is often affected by the way you state your alternative hypothesis, so it does matter |
36,092 | p-value with multimodal PDF of a test statistic | This is really two questions:
(1) What is the definition of a p-value?
Answer: Definition 2—the probability under the null hypothesis of getting a value of the test statistic greater than or equal to that observed. (As @whuber pointed out, it needs some qualification: in the case of a composite null hypothesis the probability involved is the maximum probability over every point null in that set; the probability of what's sometimes called the proximal null hypothesis.)
(2) Should a test statistic strictly increase with decreasing probability under the null hypothesis ?
I have tried to answer this in responses to your previous post. (Answer: not always.) Hope someone can explain more clearly if needed. At least note here that many commonly used test statistics don't. You have ...
(a) test statistics ordered by the probability under the null: Fisher's Exact Test, as Greg Snow notes, & the test for a binomial parameter given by Zag.
(b) test statistics ordered by likelihood ratio (sometimes but not always giving the same ordering as (a)): my binomial goodness-of-fit test example.
(c) test statistics chosen for maximum power against specified alternatives (sometimes but not always giving the same ordering as (a) and/or (b), as I think RobertF was getting at): 'The Emperor's new tests', Perlman & Wu (1999), together with the comments & rejoinder, is very interesting (though difficult).
If you read the paper by Christensen that Zag linked to, you will see that in the first example he writes "With only this information, one must use the density itself to determine which data values seem weird and which do not". The clear implication is that with more information you needn't necessarily use the density itself to determine which data values seem weird and which do not.
In response to @whuber's comment ...
The likelihood ratio test is in fact a good example of Defn 2's being used. The p-value in this case is just the probability (under the null) of the the likelihood ratio's being larger or equal to that observed.
As an elementary example, you can test two hypotheses for the probability of success in a Bernoulli trial :
$$H_0: \theta = 0.55$$
$$H_1: \theta = 0.35$$
Nine independent trials give $t$ successes:
$$\newcommand{\pr}{\mathrm{Pr}}\begin{array}{cccc}
t & \pr(t|H_0) & \pr(t|H_1) & \frac{\pr(t|H_1)}{\pr(t|H_0)}=x\\
0 & 0.00076 & 0.02071 & 27.372\\
1 & 0.00832 & 0.10037 & 12.060\\
2 & 0.04069 & 0.21619 & 5.3128\\
3 & 0.11605 & 0.27162 & 2.3406\\
4 & 0.21276 & 0.21939 & 1.0312\\
5 & 0.26004 & 0.11813 & 0.4543\\
6 & 0.21188 & 0.04241 & 0.2001\\
7 & 0.11099 & 0.00979 & 0.0882\\
8 & 0.03391 & 0.00132 & 0.0389\\
9 & 0.00461 & 0.00008 & 0.0171
\end{array}$$
The likelihood ratio $x$ is your test statistic.
Using Defn 1 to get a p-value, you have to add up all the probabilities (under the null) for less (or equally) probabable values of $x$ than that observed. So, observing $t = 2$, you'd add up those for $2$, $8$, $1$, $9$, & $0$ successes to give $0.04069 + 0.03391 + 0.00832 + 0.00461 + 0.00076 = 0.08829$
Using Defn 2, you add up all the probabilities (under the null) for values of $x$ larger than (or equal to) that observed. So, observing $t = 2$, $x$ is larger for $0$ & $1$ successes so you add their probability under the null to that of $2$ successes to give a p-value of $0.04069 + 0.00832 + 0.00076 = 0.04977$.
It's clear that the latter procedure is the likelihood ratio test as usually understood, & that defined by the Neyman–Pearson lemma. | p-value with multimodal PDF of a test statistic | This is really two questions:
(1) What is the definition of a p-value?
Answer: Definition 2—the probability under the null hypothesis of getting a value of the test statistic greater than or equal to | p-value with multimodal PDF of a test statistic
This is really two questions:
(1) What is the definition of a p-value?
Answer: Definition 2—the probability under the null hypothesis of getting a value of the test statistic greater than or equal to that observed. (As @whuber pointed out, it needs some qualification: in the case of a composite null hypothesis the probability involved is the maximum probability over every point null in that set; the probability of what's sometimes called the proximal null hypothesis.)
(2) Should a test statistic strictly increase with decreasing probability under the null hypothesis ?
I have tried to answer this in responses to your previous post. (Answer: not always.) Hope someone can explain more clearly if needed. At least note here that many commonly used test statistics don't. You have ...
(a) test statistics ordered by the probability under the null: Fisher's Exact Test, as Greg Snow notes, & the test for a binomial parameter given by Zag.
(b) test statistics ordered by likelihood ratio (sometimes but not always giving the same ordering as (a)): my binomial goodness-of-fit test example.
(c) test statistics chosen for maximum power against specified alternatives (sometimes but not always giving the same ordering as (a) and/or (b), as I think RobertF was getting at): 'The Emperor's new tests', Perlman & Wu (1999), together with the comments & rejoinder, is very interesting (though difficult).
If you read the paper by Christensen that Zag linked to, you will see that in the first example he writes "With only this information, one must use the density itself to determine which data values seem weird and which do not". The clear implication is that with more information you needn't necessarily use the density itself to determine which data values seem weird and which do not.
In response to @whuber's comment ...
The likelihood ratio test is in fact a good example of Defn 2's being used. The p-value in this case is just the probability (under the null) of the the likelihood ratio's being larger or equal to that observed.
As an elementary example, you can test two hypotheses for the probability of success in a Bernoulli trial :
$$H_0: \theta = 0.55$$
$$H_1: \theta = 0.35$$
Nine independent trials give $t$ successes:
$$\newcommand{\pr}{\mathrm{Pr}}\begin{array}{cccc}
t & \pr(t|H_0) & \pr(t|H_1) & \frac{\pr(t|H_1)}{\pr(t|H_0)}=x\\
0 & 0.00076 & 0.02071 & 27.372\\
1 & 0.00832 & 0.10037 & 12.060\\
2 & 0.04069 & 0.21619 & 5.3128\\
3 & 0.11605 & 0.27162 & 2.3406\\
4 & 0.21276 & 0.21939 & 1.0312\\
5 & 0.26004 & 0.11813 & 0.4543\\
6 & 0.21188 & 0.04241 & 0.2001\\
7 & 0.11099 & 0.00979 & 0.0882\\
8 & 0.03391 & 0.00132 & 0.0389\\
9 & 0.00461 & 0.00008 & 0.0171
\end{array}$$
The likelihood ratio $x$ is your test statistic.
Using Defn 1 to get a p-value, you have to add up all the probabilities (under the null) for less (or equally) probabable values of $x$ than that observed. So, observing $t = 2$, you'd add up those for $2$, $8$, $1$, $9$, & $0$ successes to give $0.04069 + 0.03391 + 0.00832 + 0.00461 + 0.00076 = 0.08829$
Using Defn 2, you add up all the probabilities (under the null) for values of $x$ larger than (or equal to) that observed. So, observing $t = 2$, $x$ is larger for $0$ & $1$ successes so you add their probability under the null to that of $2$ successes to give a p-value of $0.04069 + 0.00832 + 0.00076 = 0.04977$.
It's clear that the latter procedure is the likelihood ratio test as usually understood, & that defined by the Neyman–Pearson lemma. | p-value with multimodal PDF of a test statistic
This is really two questions:
(1) What is the definition of a p-value?
Answer: Definition 2—the probability under the null hypothesis of getting a value of the test statistic greater than or equal to |
36,093 | Can sub-optimality of various hierarchical clustering methods be assessed or ranked? | Only single-linkage is optimal. Complete-linkage fails, so your intuition was wrong there. ;-)
As a simple example, consider the one-dimensional data set 1,2,3,4,5,6.
The (unique) optimum solution for complete linkage with two clusters is (1,2,3) and (4,5,6) (complete linkage height 2). The (unique) optimum solution with three clusters is (1,2), (3,4), (5,6), at linkage height 1.
There exists no agglomerative hierarchy that contains both, obviously, because these partitions do not nest. Hence, no hierarchical clustering contains all optimal solutions for complete linkage. I would even expect complete linkage to exhibit among the worst gap between the optimum solution and the agglomerative solution at high levels, based on that example... An this example likely is a counter example for most other schemes (except single linkage, where this data set degenerates).
You may be interested in studying this article:
Gunnar E. Carlsson, Facundo Mémoli:
Characterization, Stability and Convergence of Hierarchical Clustering Methods. Journal of Machine Learning Research 11: 1425-1470 (2010)
and the references contained therein, in particular also:
Kleinberg, Jon M. "An impossibility theorem for clustering." Advances in neural information processing systems. 2003.
These seem to indicate that given some mild stability requirements (which can be interpreted as uncertainty of our distance measurements), only single-linkage clustering remains. Which, unfortunately, is all but usable in most cases... so IMHO for practical purposes the authors overshoot a bit, neglecting usefulness of the result over pretty theory. | Can sub-optimality of various hierarchical clustering methods be assessed or ranked? | Only single-linkage is optimal. Complete-linkage fails, so your intuition was wrong there. ;-)
As a simple example, consider the one-dimensional data set 1,2,3,4,5,6.
The (unique) optimum solution for | Can sub-optimality of various hierarchical clustering methods be assessed or ranked?
Only single-linkage is optimal. Complete-linkage fails, so your intuition was wrong there. ;-)
As a simple example, consider the one-dimensional data set 1,2,3,4,5,6.
The (unique) optimum solution for complete linkage with two clusters is (1,2,3) and (4,5,6) (complete linkage height 2). The (unique) optimum solution with three clusters is (1,2), (3,4), (5,6), at linkage height 1.
There exists no agglomerative hierarchy that contains both, obviously, because these partitions do not nest. Hence, no hierarchical clustering contains all optimal solutions for complete linkage. I would even expect complete linkage to exhibit among the worst gap between the optimum solution and the agglomerative solution at high levels, based on that example... An this example likely is a counter example for most other schemes (except single linkage, where this data set degenerates).
You may be interested in studying this article:
Gunnar E. Carlsson, Facundo Mémoli:
Characterization, Stability and Convergence of Hierarchical Clustering Methods. Journal of Machine Learning Research 11: 1425-1470 (2010)
and the references contained therein, in particular also:
Kleinberg, Jon M. "An impossibility theorem for clustering." Advances in neural information processing systems. 2003.
These seem to indicate that given some mild stability requirements (which can be interpreted as uncertainty of our distance measurements), only single-linkage clustering remains. Which, unfortunately, is all but usable in most cases... so IMHO for practical purposes the authors overshoot a bit, neglecting usefulness of the result over pretty theory. | Can sub-optimality of various hierarchical clustering methods be assessed or ranked?
Only single-linkage is optimal. Complete-linkage fails, so your intuition was wrong there. ;-)
As a simple example, consider the one-dimensional data set 1,2,3,4,5,6.
The (unique) optimum solution for |
36,094 | Can sub-optimality of various hierarchical clustering methods be assessed or ranked? | A partial answer to your question follows. Single linkage clustering is equivalent to the computation of a minimal spanning tree (references are easy to find). If we disregard ties the result is garantueed to be an optimal solution, or one among a set of optimal solutions, in that the total branch length will be minimal. I think the naive construction process also garantuees the property that you ask for (when cutting a dendrogram). As for complete link clustering, I do not know, and I think it is a good question. A famous reference in this field is the book by Jardine and Simpson, mathematical taxonomy. They conclude that single linkage clustering, for all its shortcomings, is mathematically and conceptually the stand-out method and consider it the most appealing. I don't agree with that, but the book is a very good read. Perhaps their results might imply that the property you seek does not hold for complete link clustering, but this is speculation. | Can sub-optimality of various hierarchical clustering methods be assessed or ranked? | A partial answer to your question follows. Single linkage clustering is equivalent to the computation of a minimal spanning tree (references are easy to find). If we disregard ties the result is garan | Can sub-optimality of various hierarchical clustering methods be assessed or ranked?
A partial answer to your question follows. Single linkage clustering is equivalent to the computation of a minimal spanning tree (references are easy to find). If we disregard ties the result is garantueed to be an optimal solution, or one among a set of optimal solutions, in that the total branch length will be minimal. I think the naive construction process also garantuees the property that you ask for (when cutting a dendrogram). As for complete link clustering, I do not know, and I think it is a good question. A famous reference in this field is the book by Jardine and Simpson, mathematical taxonomy. They conclude that single linkage clustering, for all its shortcomings, is mathematically and conceptually the stand-out method and consider it the most appealing. I don't agree with that, but the book is a very good read. Perhaps their results might imply that the property you seek does not hold for complete link clustering, but this is speculation. | Can sub-optimality of various hierarchical clustering methods be assessed or ranked?
A partial answer to your question follows. Single linkage clustering is equivalent to the computation of a minimal spanning tree (references are easy to find). If we disregard ties the result is garan |
36,095 | Number of needed samples for entropy estimation | Entropy estimation is a surprisingly difficult problem. The fundamental issue is that your estimate is heavily biased by "unobserved" events (which nevertheless have nonzero probability).
There are quite a few different entropy estimators designed specifically to address this problem. For instance, see the BUB esimator by Liam Paninski, the NSB estimator by Nemenman et al, the coverage-adjusted estimator by Vu et al (also see Chao et al, 2003), and the PYM estimator by Archer et al.
There are many other papers that address the problem. Each has a somewhat different approach, and some may be more appropriate under different situations. Several of the papers I suggest provide free code online which automatically computes an estimate and measure of confidence. You may also be interested in this and the R package 'entropy'. | Number of needed samples for entropy estimation | Entropy estimation is a surprisingly difficult problem. The fundamental issue is that your estimate is heavily biased by "unobserved" events (which nevertheless have nonzero probability).
There are q | Number of needed samples for entropy estimation
Entropy estimation is a surprisingly difficult problem. The fundamental issue is that your estimate is heavily biased by "unobserved" events (which nevertheless have nonzero probability).
There are quite a few different entropy estimators designed specifically to address this problem. For instance, see the BUB esimator by Liam Paninski, the NSB estimator by Nemenman et al, the coverage-adjusted estimator by Vu et al (also see Chao et al, 2003), and the PYM estimator by Archer et al.
There are many other papers that address the problem. Each has a somewhat different approach, and some may be more appropriate under different situations. Several of the papers I suggest provide free code online which automatically computes an estimate and measure of confidence. You may also be interested in this and the R package 'entropy'. | Number of needed samples for entropy estimation
Entropy estimation is a surprisingly difficult problem. The fundamental issue is that your estimate is heavily biased by "unobserved" events (which nevertheless have nonzero probability).
There are q |
36,096 | Number of needed samples for entropy estimation | You need to apply standard propagation of uncertainty (in the non-linear case) to Poisson distribution (i.e. assuming that each count is independent).
That is, you need to expand $H(p_1+\Delta p_1, \ldots, p_n + \Delta p_n)$ in Taylor series of $n$ variables $(\Delta p_1,\ldots ,\Delta p_n)$ around $(0,\ldots, 0)$, i.e.:
$$H(p_1+\Delta p_1, \ldots, p_n + \Delta p_n)
=H(p_1,\ldots,p_n)-\frac{1}{\ln2}\sum_{i=1}^n (\ln p_i+1)\Delta p_i
-\frac{1}{2\ln2} \sum_{i=1}^n p_i^{-1} \Delta p_i^2 + \ldots$$
Remembering that $p_i = \frac{N_i}{N}$ and calculating appropriate moments to as many terms as you want.
However, it does not work around $p_i=0$, as it has no Taylor expansion here. In such cases the only possibility I know is Monte Carlo - you estimate parameters of distributions, take random distributions and then take random results according to them and look at the distribution of results (here: entropy). | Number of needed samples for entropy estimation | You need to apply standard propagation of uncertainty (in the non-linear case) to Poisson distribution (i.e. assuming that each count is independent).
That is, you need to expand $H(p_1+\Delta p_1, \l | Number of needed samples for entropy estimation
You need to apply standard propagation of uncertainty (in the non-linear case) to Poisson distribution (i.e. assuming that each count is independent).
That is, you need to expand $H(p_1+\Delta p_1, \ldots, p_n + \Delta p_n)$ in Taylor series of $n$ variables $(\Delta p_1,\ldots ,\Delta p_n)$ around $(0,\ldots, 0)$, i.e.:
$$H(p_1+\Delta p_1, \ldots, p_n + \Delta p_n)
=H(p_1,\ldots,p_n)-\frac{1}{\ln2}\sum_{i=1}^n (\ln p_i+1)\Delta p_i
-\frac{1}{2\ln2} \sum_{i=1}^n p_i^{-1} \Delta p_i^2 + \ldots$$
Remembering that $p_i = \frac{N_i}{N}$ and calculating appropriate moments to as many terms as you want.
However, it does not work around $p_i=0$, as it has no Taylor expansion here. In such cases the only possibility I know is Monte Carlo - you estimate parameters of distributions, take random distributions and then take random results according to them and look at the distribution of results (here: entropy). | Number of needed samples for entropy estimation
You need to apply standard propagation of uncertainty (in the non-linear case) to Poisson distribution (i.e. assuming that each count is independent).
That is, you need to expand $H(p_1+\Delta p_1, \l |
36,097 | Chi-squared and repeated measures | Interesting, the general question of repeated measures in chi-square has been asked quite a few times but usually obtusely so that it doesn't come up in a simple search. Mcnemar test is what you want. mcnemar.test in R. | Chi-squared and repeated measures | Interesting, the general question of repeated measures in chi-square has been asked quite a few times but usually obtusely so that it doesn't come up in a simple search. Mcnemar test is what you want | Chi-squared and repeated measures
Interesting, the general question of repeated measures in chi-square has been asked quite a few times but usually obtusely so that it doesn't come up in a simple search. Mcnemar test is what you want. mcnemar.test in R. | Chi-squared and repeated measures
Interesting, the general question of repeated measures in chi-square has been asked quite a few times but usually obtusely so that it doesn't come up in a simple search. Mcnemar test is what you want |
36,098 | Chi-squared and repeated measures | The pooling of litters for an individual set of parents seems reasonable to me. If the data could be put into a kxk contingency table and the male mice could be naturally paired with female mice a generalization of Mc Nemar's test could be given. This is a generalization of the the McNemar test for K>2. This paper points out the generalization which can be credited to both Stuart in a cited 1955 paper and maxwell in a 1970 paper. The authors of this article show how to implement the procedure in SAS and provide some examples.
The three relevant papers are:
[1] Maxwell A.E. (1970). Comparing the classification of subjects by two independent judges. British Journal of Psychiatry, 116: 651 - 655.
[2] McNemar Q. (1947). Note on the sampling error of the difference between correlated proportions or percentages. Psychometrika, 12: 153 - 157.
[3] Stuart A. (1955). A Test for Homogeneity of the Marginal Distributions in a Two-Way Classification. Biometrika, 42: 412 - 416.
I gave this information in my original answer but pairing is by parents and not by the offspring mice. So given this information it appears these test do not apply.
However the design looks like it could represent a series of kx2 contingency tables where each table represents columns for males and females where k is the number of litters in each group and the cells represent the number of males in the litter or females in the litter depending on the colum the cell belongs to. There is one such table for each set of parents. The tables can be looked upon as a stratification of the data stratified by parents. If the value of k is the same for each set of parents (all sets of parents have the same number of litters) there is a test that compares the distribution of male and female mice taking account for the stratification. The test is a generalization of the Cochran-Mantel-Haenszel test describe here for example.
If you could control or have controlled the experiment so that each parent pair produce the same number of litters you can use this test. If not I do not know yet if there is something similar for unequal stratification groups (counts here being number of litters for the ith parent group). | Chi-squared and repeated measures | The pooling of litters for an individual set of parents seems reasonable to me. If the data could be put into a kxk contingency table and the male mice could be naturally paired with female mice a ge | Chi-squared and repeated measures
The pooling of litters for an individual set of parents seems reasonable to me. If the data could be put into a kxk contingency table and the male mice could be naturally paired with female mice a generalization of Mc Nemar's test could be given. This is a generalization of the the McNemar test for K>2. This paper points out the generalization which can be credited to both Stuart in a cited 1955 paper and maxwell in a 1970 paper. The authors of this article show how to implement the procedure in SAS and provide some examples.
The three relevant papers are:
[1] Maxwell A.E. (1970). Comparing the classification of subjects by two independent judges. British Journal of Psychiatry, 116: 651 - 655.
[2] McNemar Q. (1947). Note on the sampling error of the difference between correlated proportions or percentages. Psychometrika, 12: 153 - 157.
[3] Stuart A. (1955). A Test for Homogeneity of the Marginal Distributions in a Two-Way Classification. Biometrika, 42: 412 - 416.
I gave this information in my original answer but pairing is by parents and not by the offspring mice. So given this information it appears these test do not apply.
However the design looks like it could represent a series of kx2 contingency tables where each table represents columns for males and females where k is the number of litters in each group and the cells represent the number of males in the litter or females in the litter depending on the colum the cell belongs to. There is one such table for each set of parents. The tables can be looked upon as a stratification of the data stratified by parents. If the value of k is the same for each set of parents (all sets of parents have the same number of litters) there is a test that compares the distribution of male and female mice taking account for the stratification. The test is a generalization of the Cochran-Mantel-Haenszel test describe here for example.
If you could control or have controlled the experiment so that each parent pair produce the same number of litters you can use this test. If not I do not know yet if there is something similar for unequal stratification groups (counts here being number of litters for the ith parent group). | Chi-squared and repeated measures
The pooling of litters for an individual set of parents seems reasonable to me. If the data could be put into a kxk contingency table and the male mice could be naturally paired with female mice a ge |
36,099 | When has a Bayesian approach been critical to addressing a theory, hypothesis or problem? | In the study of medical devices for approval to use for specific indications the US Food and Drug Adminstration has for at least a decade encouraged the use of Bayesian methods in phase III clinical trials to allow prior information about the device to be incorporated along with the trial data. | When has a Bayesian approach been critical to addressing a theory, hypothesis or problem? | In the study of medical devices for approval to use for specific indications the US Food and Drug Adminstration has for at least a decade encouraged the use of Bayesian methods in phase III clinical t | When has a Bayesian approach been critical to addressing a theory, hypothesis or problem?
In the study of medical devices for approval to use for specific indications the US Food and Drug Adminstration has for at least a decade encouraged the use of Bayesian methods in phase III clinical trials to allow prior information about the device to be incorporated along with the trial data. | When has a Bayesian approach been critical to addressing a theory, hypothesis or problem?
In the study of medical devices for approval to use for specific indications the US Food and Drug Adminstration has for at least a decade encouraged the use of Bayesian methods in phase III clinical t |
36,100 | When has a Bayesian approach been critical to addressing a theory, hypothesis or problem? | A number of papers have been written on using Bayesian methods to estimate diagnostic testing parameters (false-positive, false-negative, ...). The Bayesian method is often preferred due to the fact there are often more parameters than observations. Unlike other common situations, it is nearly impossible to increase the number of observations.
The article below is a nice overview of the problem:
An Application of a Bayesian Approach in Diagnostic Testing Problems in the Absence of a Gold Standard | When has a Bayesian approach been critical to addressing a theory, hypothesis or problem? | A number of papers have been written on using Bayesian methods to estimate diagnostic testing parameters (false-positive, false-negative, ...). The Bayesian method is often preferred due to the fact | When has a Bayesian approach been critical to addressing a theory, hypothesis or problem?
A number of papers have been written on using Bayesian methods to estimate diagnostic testing parameters (false-positive, false-negative, ...). The Bayesian method is often preferred due to the fact there are often more parameters than observations. Unlike other common situations, it is nearly impossible to increase the number of observations.
The article below is a nice overview of the problem:
An Application of a Bayesian Approach in Diagnostic Testing Problems in the Absence of a Gold Standard | When has a Bayesian approach been critical to addressing a theory, hypothesis or problem?
A number of papers have been written on using Bayesian methods to estimate diagnostic testing parameters (false-positive, false-negative, ...). The Bayesian method is often preferred due to the fact |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.