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 |
|---|---|---|---|---|---|---|
20,101 | Do third order asymptotics exist? | It is not possible for a sequence to "converge" to one thing and then to another. The higher-order terms in an asymptotic expansion will go to zero. What they tell you is how close to zero they are for any given value of $n$.
For the Central Limit Theorem (as an example) the appropriate expansion is that of the logarithm of the characteristic function: the cumulant generating function (cgf). Standardization of the distributions fixes the zeroth, first, and second terms of the cgf. The remaining terms, whose coefficients are the cumulants, depend on $n$ in an orderly way. The standardization that occurs in the CLT (dividing the sum of $n$ random variables by something proportional to $n^{1/2}$--without which convergence will not occur) causes the $m^\text{th}$ cumulant--which after all depends on $m^\text{th}$ moments--to be divided by $(n^{1/2})^m = n^{m/2}$, but at the same time because we are summing $n$ terms, the net result is that the $m^\text{th}$ order term is proportional to $n/n^{m/2} = n^{-(m-2)/2}$. Thus the third cumulant of the standardized sum is proportional to $1/n^{1/2}$, the fourth cumulant is proportional to $1/n$, and so on. These are the higher-order terms. (For details, see this paper of Yuval Filmus for example.)
In general, a high negative power of $n$ is much smaller than a low negative power.
We can always be assured of this by taking a sufficiently large value of $n$. Thus, for really large $n$ we can neglect all negative powers of $n$: they converge to zero. Along the way to convergence, departures from the ultimate limit are measured with increasing accuracy by the additional terms: the $1/n^{1/2}$ term is an initial "correction," or departure from the limiting value; the next $1/n$ term is a smaller, more quickly-vanishing correction added to that, and so on. In brief, the additional terms give you a picture of how quickly the sequence converges to its limit.
These additional terms can help us make corrections for finite (usually small) values of $n$. They show up all the time in this regard, such as Chen's modification of the t-test, which exploits the third-order ($1/n^{1/2}$) term. | Do third order asymptotics exist? | It is not possible for a sequence to "converge" to one thing and then to another. The higher-order terms in an asymptotic expansion will go to zero. What they tell you is how close to zero they are | Do third order asymptotics exist?
It is not possible for a sequence to "converge" to one thing and then to another. The higher-order terms in an asymptotic expansion will go to zero. What they tell you is how close to zero they are for any given value of $n$.
For the Central Limit Theorem (as an example) the appropriate expansion is that of the logarithm of the characteristic function: the cumulant generating function (cgf). Standardization of the distributions fixes the zeroth, first, and second terms of the cgf. The remaining terms, whose coefficients are the cumulants, depend on $n$ in an orderly way. The standardization that occurs in the CLT (dividing the sum of $n$ random variables by something proportional to $n^{1/2}$--without which convergence will not occur) causes the $m^\text{th}$ cumulant--which after all depends on $m^\text{th}$ moments--to be divided by $(n^{1/2})^m = n^{m/2}$, but at the same time because we are summing $n$ terms, the net result is that the $m^\text{th}$ order term is proportional to $n/n^{m/2} = n^{-(m-2)/2}$. Thus the third cumulant of the standardized sum is proportional to $1/n^{1/2}$, the fourth cumulant is proportional to $1/n$, and so on. These are the higher-order terms. (For details, see this paper of Yuval Filmus for example.)
In general, a high negative power of $n$ is much smaller than a low negative power.
We can always be assured of this by taking a sufficiently large value of $n$. Thus, for really large $n$ we can neglect all negative powers of $n$: they converge to zero. Along the way to convergence, departures from the ultimate limit are measured with increasing accuracy by the additional terms: the $1/n^{1/2}$ term is an initial "correction," or departure from the limiting value; the next $1/n$ term is a smaller, more quickly-vanishing correction added to that, and so on. In brief, the additional terms give you a picture of how quickly the sequence converges to its limit.
These additional terms can help us make corrections for finite (usually small) values of $n$. They show up all the time in this regard, such as Chen's modification of the t-test, which exploits the third-order ($1/n^{1/2}$) term. | Do third order asymptotics exist?
It is not possible for a sequence to "converge" to one thing and then to another. The higher-order terms in an asymptotic expansion will go to zero. What they tell you is how close to zero they are |
20,102 | Do third order asymptotics exist? | Here is an attempt to answer your insightful question. I have seen the inclusion of the 3rd term of the Taylor series to increase the speed of convergence of the series to the true distribution. However, I haven't seen (in my limited experience) the usage of third and higher moments.
As pointed out by John D. Cook in his blogs (here and here), there hasn't been much work done in this direction, apart from the Berry-Esseen theorem. My guess would be (from the observation in the blog about the approximation error being bounded by $n^{1/2}$), as the asymptotic normality of mle is guaranteed at a rate of converge of $n^{1/2}$ ($n$, being sample size), considering higher moments won't improve on the normality result.
Therefore, I guess, the answer to your question should be no. The asymptotic distribution converges to a normal dist.(by CLT, under regularity conditions of Lindberg's CLT). However, using higher order terms may increase the rate of convergence to the asymptotic distribution. | Do third order asymptotics exist? | Here is an attempt to answer your insightful question. I have seen the inclusion of the 3rd term of the Taylor series to increase the speed of convergence of the series to the true distribution. Howev | Do third order asymptotics exist?
Here is an attempt to answer your insightful question. I have seen the inclusion of the 3rd term of the Taylor series to increase the speed of convergence of the series to the true distribution. However, I haven't seen (in my limited experience) the usage of third and higher moments.
As pointed out by John D. Cook in his blogs (here and here), there hasn't been much work done in this direction, apart from the Berry-Esseen theorem. My guess would be (from the observation in the blog about the approximation error being bounded by $n^{1/2}$), as the asymptotic normality of mle is guaranteed at a rate of converge of $n^{1/2}$ ($n$, being sample size), considering higher moments won't improve on the normality result.
Therefore, I guess, the answer to your question should be no. The asymptotic distribution converges to a normal dist.(by CLT, under regularity conditions of Lindberg's CLT). However, using higher order terms may increase the rate of convergence to the asymptotic distribution. | Do third order asymptotics exist?
Here is an attempt to answer your insightful question. I have seen the inclusion of the 3rd term of the Taylor series to increase the speed of convergence of the series to the true distribution. Howev |
20,103 | Do third order asymptotics exist? | Definitely not my area, but I'm pretty sure third- and higher-order asymptotics exist. Is this any help?
Robert L. Strawderman. Higher-Order Asymptotic Approximation: Laplace, Saddlepoint, and Related Methods Journal of the American Statistical Association Vol. 95, No. 452 (Dec., 2000), pp. 1358-1364 | Do third order asymptotics exist? | Definitely not my area, but I'm pretty sure third- and higher-order asymptotics exist. Is this any help?
Robert L. Strawderman. Higher-Order Asymptotic Approximation: Laplace, Saddlepoint, and Related | Do third order asymptotics exist?
Definitely not my area, but I'm pretty sure third- and higher-order asymptotics exist. Is this any help?
Robert L. Strawderman. Higher-Order Asymptotic Approximation: Laplace, Saddlepoint, and Related Methods Journal of the American Statistical Association Vol. 95, No. 452 (Dec., 2000), pp. 1358-1364 | Do third order asymptotics exist?
Definitely not my area, but I'm pretty sure third- and higher-order asymptotics exist. Is this any help?
Robert L. Strawderman. Higher-Order Asymptotic Approximation: Laplace, Saddlepoint, and Related |
20,104 | Are Mutual Information and KullbackβLeibler divergence equivalent? | Mutual information is not a metric. A metric $d$ satisfies the identity of indiscernibles: $d(x, y) = 0$ if and only if $x = y$. This is not true of mutual information, which behaves in the opposite manner--zero mutual information implies that two random variables are independent (as far from identical as you can get). And, if two random variables are identical, they have maximal mutual information (as far from zero as you can get).
You're correct that KL divergence is not a metric. It's not symmetric and doesn't satisfy the triangle inequality.
Mutual information and KL divergence are not equivalent. However, the mutual information $I(X, Y)$ between random variables $X$ and $Y$ is given by the KL divergence between the joint distribution $p_{XY}$ and the product of the marginal distributions $p_X \otimes p_Y$ (what the joint distribution would be if $X$ and $Y$ were independent).
$$I(X, Y) = D_{KL}(p_{XY} \parallel p_X \otimes p_Y)$$
Although mutual information is not itself a metric, there are metrics based on it. For example, the variation of information:
$$VI(X, Y) = H(X, Y) - I(X, Y) = H(X) + H(Y) - 2 I(X, Y)$$
where $H(X)$ and $H(Y)$ are the marginal entropies and $H(X, Y)$ is the joint entropy. | Are Mutual Information and KullbackβLeibler divergence equivalent? | Mutual information is not a metric. A metric $d$ satisfies the identity of indiscernibles: $d(x, y) = 0$ if and only if $x = y$. This is not true of mutual information, which behaves in the opposite m | Are Mutual Information and KullbackβLeibler divergence equivalent?
Mutual information is not a metric. A metric $d$ satisfies the identity of indiscernibles: $d(x, y) = 0$ if and only if $x = y$. This is not true of mutual information, which behaves in the opposite manner--zero mutual information implies that two random variables are independent (as far from identical as you can get). And, if two random variables are identical, they have maximal mutual information (as far from zero as you can get).
You're correct that KL divergence is not a metric. It's not symmetric and doesn't satisfy the triangle inequality.
Mutual information and KL divergence are not equivalent. However, the mutual information $I(X, Y)$ between random variables $X$ and $Y$ is given by the KL divergence between the joint distribution $p_{XY}$ and the product of the marginal distributions $p_X \otimes p_Y$ (what the joint distribution would be if $X$ and $Y$ were independent).
$$I(X, Y) = D_{KL}(p_{XY} \parallel p_X \otimes p_Y)$$
Although mutual information is not itself a metric, there are metrics based on it. For example, the variation of information:
$$VI(X, Y) = H(X, Y) - I(X, Y) = H(X) + H(Y) - 2 I(X, Y)$$
where $H(X)$ and $H(Y)$ are the marginal entropies and $H(X, Y)$ is the joint entropy. | Are Mutual Information and KullbackβLeibler divergence equivalent?
Mutual information is not a metric. A metric $d$ satisfies the identity of indiscernibles: $d(x, y) = 0$ if and only if $x = y$. This is not true of mutual information, which behaves in the opposite m |
20,105 | Difference between MA and AR | You should consider the $\epsilon_t$ innovations rather than residuals. In the MA case, you average across the recent innovations, whereas in the AR case you average across the recent observations. Even if the models are stationary and have no deterministic terms, the innovations and the observations are different. For example, suppose the $\epsilon_t$ are i.i.d.. Then, in the MA(1) case, the covariance between $x_t$ and $x_{t-1}$ is still positive! However, the covariance between $x_t$ and $x_{t-2}$ will still be zero. In the AR(1) case on the other hand, all autocorrelations are nonzero but decaying exponentially. | Difference between MA and AR | You should consider the $\epsilon_t$ innovations rather than residuals. In the MA case, you average across the recent innovations, whereas in the AR case you average across the recent observations. Ev | Difference between MA and AR
You should consider the $\epsilon_t$ innovations rather than residuals. In the MA case, you average across the recent innovations, whereas in the AR case you average across the recent observations. Even if the models are stationary and have no deterministic terms, the innovations and the observations are different. For example, suppose the $\epsilon_t$ are i.i.d.. Then, in the MA(1) case, the covariance between $x_t$ and $x_{t-1}$ is still positive! However, the covariance between $x_t$ and $x_{t-2}$ will still be zero. In the AR(1) case on the other hand, all autocorrelations are nonzero but decaying exponentially. | Difference between MA and AR
You should consider the $\epsilon_t$ innovations rather than residuals. In the MA case, you average across the recent innovations, whereas in the AR case you average across the recent observations. Ev |
20,106 | Difference between MA and AR | A key difference which I failed to appreciate: the MA model predictions of $x_t$ include $\epsilon_{t-1}$ in its computation whereas the AR model only predicts based on $x_{t-1}$ without (explicit) regard as to whether the prediction at $t-1$ was under- or over-estimating $x_{t-1}$. Fleshing out what @user1587692 highlighted, the MA model averages across innovations ($\epsilon$, i.e., the "novelty" that the MA model failed to catch, even with its lag(1) component). The AR model, on the other hand, average previous observations (residuals, i.e., $x$ when $\mu = 0$) without splitting the time-series part and innovation part.
To make this super clear, I made a small dataset with $\mu = 0$, $\beta_1 = 0.5$ and $\beta_2 = 0.2$ (latter only used for MA(2) and AR(2)). Here, $x$ is called "observed" and $\epsilon$ is called "MA(1) error". The yellow cells are "helpers", typed in to make the predictions work for observation $x_1$.
To me, this also gives a better intuition why:
The covariance between $x_t$ back until $x_{t-order}$ is positive and zero further back. This is due to the i.i.d. residuals (innovations on top of the non-i.i.d. autocorrelation) that contribute within the averaging window but has, by definition of being white noise, no information about $x_t$ further back.
AR models have (positive or negative) autocorrelations further back. This is just the time-series autocorrelation (dampened by the i.i.d. innovations on top).
Why AR and MA can be viewed as re-parameterizations of each other. No information is added or removed in either model. However, you cannot transform one to the other at any particular time ($t$, column in the table above) - you need to look further back to make an estimate. That's why you need a high order AR to estimate a low-order MA. It takes a lot of $x$ to estimate $\epsilon$ if you can't model it directly.
Similarly, it takes a high order MA to estimate a low-order AR if you don't model $x$ directly (condition it out). | Difference between MA and AR | A key difference which I failed to appreciate: the MA model predictions of $x_t$ include $\epsilon_{t-1}$ in its computation whereas the AR model only predicts based on $x_{t-1}$ without (explicit) re | Difference between MA and AR
A key difference which I failed to appreciate: the MA model predictions of $x_t$ include $\epsilon_{t-1}$ in its computation whereas the AR model only predicts based on $x_{t-1}$ without (explicit) regard as to whether the prediction at $t-1$ was under- or over-estimating $x_{t-1}$. Fleshing out what @user1587692 highlighted, the MA model averages across innovations ($\epsilon$, i.e., the "novelty" that the MA model failed to catch, even with its lag(1) component). The AR model, on the other hand, average previous observations (residuals, i.e., $x$ when $\mu = 0$) without splitting the time-series part and innovation part.
To make this super clear, I made a small dataset with $\mu = 0$, $\beta_1 = 0.5$ and $\beta_2 = 0.2$ (latter only used for MA(2) and AR(2)). Here, $x$ is called "observed" and $\epsilon$ is called "MA(1) error". The yellow cells are "helpers", typed in to make the predictions work for observation $x_1$.
To me, this also gives a better intuition why:
The covariance between $x_t$ back until $x_{t-order}$ is positive and zero further back. This is due to the i.i.d. residuals (innovations on top of the non-i.i.d. autocorrelation) that contribute within the averaging window but has, by definition of being white noise, no information about $x_t$ further back.
AR models have (positive or negative) autocorrelations further back. This is just the time-series autocorrelation (dampened by the i.i.d. innovations on top).
Why AR and MA can be viewed as re-parameterizations of each other. No information is added or removed in either model. However, you cannot transform one to the other at any particular time ($t$, column in the table above) - you need to look further back to make an estimate. That's why you need a high order AR to estimate a low-order MA. It takes a lot of $x$ to estimate $\epsilon$ if you can't model it directly.
Similarly, it takes a high order MA to estimate a low-order AR if you don't model $x$ directly (condition it out). | Difference between MA and AR
A key difference which I failed to appreciate: the MA model predictions of $x_t$ include $\epsilon_{t-1}$ in its computation whereas the AR model only predicts based on $x_{t-1}$ without (explicit) re |
20,107 | Difference between MA and AR | A finite AR model can be expressed as an MA model and vice-versa , If one has an ar(1) model with coefficient .333333333 then the models are (nearly) identical .
Consider the case for an ar(1) with coefficient of .3
$x_t=Ο΅_t+.3*x_{tβ1}$
since $x_{t-1}=e_{t-1}+.3*x_{t-2}$ we can substitute for $x_{t-1}$ and get
$x_t=Ο΅_t+.3*[e_{t-1} + .3*x_{t-2}]$
$\implies x_t=Ο΅_t+.3*e_{t-1} + .09*x_{t-2}$
and
$x_t = Ο΅_t+.3*e_{t-1} + .09*e_{t-2} + .027*x_{t-3}]$
etc .
The "reason" for selecting an ar model versus an ma model is simply for parsimony.
They are identical when q=1 and B1=.333333333 and for other cases for q>1
Hope this helps .... | Difference between MA and AR | A finite AR model can be expressed as an MA model and vice-versa , If one has an ar(1) model with coefficient .333333333 then the models are (nearly) identical .
Consider the case for an ar(1) with co | Difference between MA and AR
A finite AR model can be expressed as an MA model and vice-versa , If one has an ar(1) model with coefficient .333333333 then the models are (nearly) identical .
Consider the case for an ar(1) with coefficient of .3
$x_t=Ο΅_t+.3*x_{tβ1}$
since $x_{t-1}=e_{t-1}+.3*x_{t-2}$ we can substitute for $x_{t-1}$ and get
$x_t=Ο΅_t+.3*[e_{t-1} + .3*x_{t-2}]$
$\implies x_t=Ο΅_t+.3*e_{t-1} + .09*x_{t-2}$
and
$x_t = Ο΅_t+.3*e_{t-1} + .09*e_{t-2} + .027*x_{t-3}]$
etc .
The "reason" for selecting an ar model versus an ma model is simply for parsimony.
They are identical when q=1 and B1=.333333333 and for other cases for q>1
Hope this helps .... | Difference between MA and AR
A finite AR model can be expressed as an MA model and vice-versa , If one has an ar(1) model with coefficient .333333333 then the models are (nearly) identical .
Consider the case for an ar(1) with co |
20,108 | scikit-learn IsolationForest anomaly score | So the code that corresponds to IsolationForest in 0.19.1 can be found here. This makes your problem a lot more manageable and a lot less confusing since what currently lives on sklearn's master branch is quite different from the 0.19.1 release.
In this version, we can recover the underlying scores directly, since decision_function gives them to us like this:
/// do the work for calculating the path lengths across the ensemble ///
scores = 2 ** (-depths.mean(axis=1) / _average_path_length(self.max_samples_))
return 0.5 - scores
scores is calculated exactly as you'd expect from the original paper.
To recover what we want, we simply have to do the following:
model = sklearn.ensemble.IsolationForest()
model.fit(data)
sklearn_score_anomalies = model.decision_function(data_to_predict)
original_paper_score = [-1*s + 0.5 for s in sklearn_score_anomalies]
Very important note going forward: this will not be default behavior for decision_function in future releases of scikit-learn, so assess the docs for later releases to see what you have to do to recover the original score from your model!!
Hope this helped! | scikit-learn IsolationForest anomaly score | So the code that corresponds to IsolationForest in 0.19.1 can be found here. This makes your problem a lot more manageable and a lot less confusing since what currently lives on sklearn's master branc | scikit-learn IsolationForest anomaly score
So the code that corresponds to IsolationForest in 0.19.1 can be found here. This makes your problem a lot more manageable and a lot less confusing since what currently lives on sklearn's master branch is quite different from the 0.19.1 release.
In this version, we can recover the underlying scores directly, since decision_function gives them to us like this:
/// do the work for calculating the path lengths across the ensemble ///
scores = 2 ** (-depths.mean(axis=1) / _average_path_length(self.max_samples_))
return 0.5 - scores
scores is calculated exactly as you'd expect from the original paper.
To recover what we want, we simply have to do the following:
model = sklearn.ensemble.IsolationForest()
model.fit(data)
sklearn_score_anomalies = model.decision_function(data_to_predict)
original_paper_score = [-1*s + 0.5 for s in sklearn_score_anomalies]
Very important note going forward: this will not be default behavior for decision_function in future releases of scikit-learn, so assess the docs for later releases to see what you have to do to recover the original score from your model!!
Hope this helped! | scikit-learn IsolationForest anomaly score
So the code that corresponds to IsolationForest in 0.19.1 can be found here. This makes your problem a lot more manageable and a lot less confusing since what currently lives on sklearn's master branc |
20,109 | scikit-learn IsolationForest anomaly score | A shortcut for tm1212 answer could be:
model = sklearn.ensemble.IsolationForest()
model.fit(data)
sklearn_score_anomalies = abs(model.score_samples(data_to_predict)) | scikit-learn IsolationForest anomaly score | A shortcut for tm1212 answer could be:
model = sklearn.ensemble.IsolationForest()
model.fit(data)
sklearn_score_anomalies = abs(model.score_samples(data_to_predict)) | scikit-learn IsolationForest anomaly score
A shortcut for tm1212 answer could be:
model = sklearn.ensemble.IsolationForest()
model.fit(data)
sklearn_score_anomalies = abs(model.score_samples(data_to_predict)) | scikit-learn IsolationForest anomaly score
A shortcut for tm1212 answer could be:
model = sklearn.ensemble.IsolationForest()
model.fit(data)
sklearn_score_anomalies = abs(model.score_samples(data_to_predict)) |
20,110 | scikit-learn IsolationForest anomaly score | the larger of the score, it will be more likely a inlier.
so you can normalized to a probability by
predict = model.score_samples(X)
proba= (predict-predict.min())/(predict.max()-predict.min())
proba = 1-proba | scikit-learn IsolationForest anomaly score | the larger of the score, it will be more likely a inlier.
so you can normalized to a probability by
predict = model.score_samples(X)
proba= (predict-predict.min())/(predict.max()-predict.min())
proba | scikit-learn IsolationForest anomaly score
the larger of the score, it will be more likely a inlier.
so you can normalized to a probability by
predict = model.score_samples(X)
proba= (predict-predict.min())/(predict.max()-predict.min())
proba = 1-proba | scikit-learn IsolationForest anomaly score
the larger of the score, it will be more likely a inlier.
so you can normalized to a probability by
predict = model.score_samples(X)
proba= (predict-predict.min())/(predict.max()-predict.min())
proba |
20,111 | Why don't we use a symmetric cross-entropy loss? | Consider a classification context like you mentioned, where $q(y \mid x)$ is the model distribution over classes, given input $x$. $p(y \mid x)$ is the 'true' distribution, defined as a delta function centered over the true class for each data point:
$$p(y \mid x_i) = \left \{ \begin{array}{cl}
1 & y = y_i \\
0 & \text{Otherwise} \\
\end{array} \right .$$
For the $i$th data point, the cross entropy $H(q, p)$ is:
$$H(q,p) = -\sum_y q(y \mid x_i) \log p(y \mid x_i)$$
Because $p(y \mid x_i) = 0$ when $y \ne y_i$, this requires summing over terms involving $\log(0)$, and $H(q,p)$ will be $-\infty$ or undefined. | Why don't we use a symmetric cross-entropy loss? | Consider a classification context like you mentioned, where $q(y \mid x)$ is the model distribution over classes, given input $x$. $p(y \mid x)$ is the 'true' distribution, defined as a delta function | Why don't we use a symmetric cross-entropy loss?
Consider a classification context like you mentioned, where $q(y \mid x)$ is the model distribution over classes, given input $x$. $p(y \mid x)$ is the 'true' distribution, defined as a delta function centered over the true class for each data point:
$$p(y \mid x_i) = \left \{ \begin{array}{cl}
1 & y = y_i \\
0 & \text{Otherwise} \\
\end{array} \right .$$
For the $i$th data point, the cross entropy $H(q, p)$ is:
$$H(q,p) = -\sum_y q(y \mid x_i) \log p(y \mid x_i)$$
Because $p(y \mid x_i) = 0$ when $y \ne y_i$, this requires summing over terms involving $\log(0)$, and $H(q,p)$ will be $-\infty$ or undefined. | Why don't we use a symmetric cross-entropy loss?
Consider a classification context like you mentioned, where $q(y \mid x)$ is the model distribution over classes, given input $x$. $p(y \mid x)$ is the 'true' distribution, defined as a delta function |
20,112 | Why don't we use a symmetric cross-entropy loss? | For discrete $p$ and $q$, the loss is
$$
{\displaystyle H(p,q)=-\sum _{x}p(x)\,\log q(x).\!} H(p,q)=-\sum _{x}p(x)\,\log q(x).\!
$$
This exactly corresponds to the expected loss under log-loss assumptions. Say you predict that the next symbol will be $x$ with probability $q(x)$, then your loss will be $- \log(q(x))$. The probability that this will happen, under the true probability $p$ is $p(x)$.
The log loss is very natural in cases such as online compression (where Arithmetic coding will use about the log of the inverse probability attributed to the symbol), or online gambling (where the log is the rate of doubling the capital); see here for example. | Why don't we use a symmetric cross-entropy loss? | For discrete $p$ and $q$, the loss is
$$
{\displaystyle H(p,q)=-\sum _{x}p(x)\,\log q(x).\!} H(p,q)=-\sum _{x}p(x)\,\log q(x).\!
$$
This exactly corresponds to the expected loss under log-loss assumpt | Why don't we use a symmetric cross-entropy loss?
For discrete $p$ and $q$, the loss is
$$
{\displaystyle H(p,q)=-\sum _{x}p(x)\,\log q(x).\!} H(p,q)=-\sum _{x}p(x)\,\log q(x).\!
$$
This exactly corresponds to the expected loss under log-loss assumptions. Say you predict that the next symbol will be $x$ with probability $q(x)$, then your loss will be $- \log(q(x))$. The probability that this will happen, under the true probability $p$ is $p(x)$.
The log loss is very natural in cases such as online compression (where Arithmetic coding will use about the log of the inverse probability attributed to the symbol), or online gambling (where the log is the rate of doubling the capital); see here for example. | Why don't we use a symmetric cross-entropy loss?
For discrete $p$ and $q$, the loss is
$$
{\displaystyle H(p,q)=-\sum _{x}p(x)\,\log q(x).\!} H(p,q)=-\sum _{x}p(x)\,\log q(x).\!
$$
This exactly corresponds to the expected loss under log-loss assumpt |
20,113 | Why don't we use a symmetric cross-entropy loss? | Cross-Entropy is one of the methods used to find how good is the predicted probability models.
The minimum value that the cross-entropy of β[π,π] can have is when π=π which is β[π,π], simple the entropy of the distribution π.
While evaluating different built models say π and π', we often need to compare different them, and cross-entropy can be used here.
The more the value is close to β[π,π], the better is our model.
However, if we take symmetric cross entropy, though there is a lower bound here also, but it becomes difficult to compare two different models.
http://www.cs.rochester.edu/u/james/CSC248/Lec6.pdf | Why don't we use a symmetric cross-entropy loss? | Cross-Entropy is one of the methods used to find how good is the predicted probability models.
The minimum value that the cross-entropy of β[π,π] can have is when π=π which is β[π,π], simple the entro | Why don't we use a symmetric cross-entropy loss?
Cross-Entropy is one of the methods used to find how good is the predicted probability models.
The minimum value that the cross-entropy of β[π,π] can have is when π=π which is β[π,π], simple the entropy of the distribution π.
While evaluating different built models say π and π', we often need to compare different them, and cross-entropy can be used here.
The more the value is close to β[π,π], the better is our model.
However, if we take symmetric cross entropy, though there is a lower bound here also, but it becomes difficult to compare two different models.
http://www.cs.rochester.edu/u/james/CSC248/Lec6.pdf | Why don't we use a symmetric cross-entropy loss?
Cross-Entropy is one of the methods used to find how good is the predicted probability models.
The minimum value that the cross-entropy of β[π,π] can have is when π=π which is β[π,π], simple the entro |
20,114 | Neural network for multiple output regression | At first I thought generic_user's comment was a show-stopper, but I just realized it isn't:
If I train d different networks on d different outputs, then each one will be fit to that dimension with no regard for the others.
But if I train one network with d outputs and use all outputs for backpropagation, then each weight in every layer in the network will be adjusted so that all d outputs are more accurate.
That is: Each network parameter will be adjusted by a sum of gradients (how each output varies with a "wiggle" in this parameter) such that adjusting it in the chosen up or down direction causes more accurate output overall--even if adjusting the weight that way causes some dimensions of the output to be less accurate.
So, yes, the thing that ultimately distinguishes each output is just a linear equation encoded in the last layer, but in training one multi-output network every layer will become better at presenting that last layer with something that allows it to do its job better. And so it follows that the relationships between outputs will be accounted for by this architecture.
You might be able to do better than a fully-connected net by making your architecture reflect any known relationships in the output, just as deep networks do better than shallow ones by exploiting "compositional" relationships between inputs. | Neural network for multiple output regression | At first I thought generic_user's comment was a show-stopper, but I just realized it isn't:
If I train d different networks on d different outputs, then each one will be fit to that dimension with no | Neural network for multiple output regression
At first I thought generic_user's comment was a show-stopper, but I just realized it isn't:
If I train d different networks on d different outputs, then each one will be fit to that dimension with no regard for the others.
But if I train one network with d outputs and use all outputs for backpropagation, then each weight in every layer in the network will be adjusted so that all d outputs are more accurate.
That is: Each network parameter will be adjusted by a sum of gradients (how each output varies with a "wiggle" in this parameter) such that adjusting it in the chosen up or down direction causes more accurate output overall--even if adjusting the weight that way causes some dimensions of the output to be less accurate.
So, yes, the thing that ultimately distinguishes each output is just a linear equation encoded in the last layer, but in training one multi-output network every layer will become better at presenting that last layer with something that allows it to do its job better. And so it follows that the relationships between outputs will be accounted for by this architecture.
You might be able to do better than a fully-connected net by making your architecture reflect any known relationships in the output, just as deep networks do better than shallow ones by exploiting "compositional" relationships between inputs. | Neural network for multiple output regression
At first I thought generic_user's comment was a show-stopper, but I just realized it isn't:
If I train d different networks on d different outputs, then each one will be fit to that dimension with no |
20,115 | Neural network for multiple output regression | A neural net with multiple outcomes takes the form
$$
\mathbf{Y} = \mathbf{\gamma} + \mathbf{V}_1\Gamma_1 + \epsilon\\
\mathbf{V}_1 = a\left(\gamma_2 +\mathbf{V}_2\Gamma_2\right)\\
\mathbf{V}_2 = a\left(\gamma_3 +\mathbf{V}_3\Gamma_3\right)\\
\vdots \\
\mathbf{V}_{L-1} = a\left(\gamma_L+ \mathbf{X}\Gamma_L\right)\\
$$
If your outcome has the dimension $N\times 8$, then $[\gamma_1, \Gamma_1]$ will have the dimension $(p_{V1}+1) \times 8$.
Which is to say that you'd be assuming that each outcome shares ALL of the parameters in the hidden layers, and only has different parameters for taking the uppermost derived variable and relating it to the outcome.
Is this a realistic assumption for your context? | Neural network for multiple output regression | A neural net with multiple outcomes takes the form
$$
\mathbf{Y} = \mathbf{\gamma} + \mathbf{V}_1\Gamma_1 + \epsilon\\
\mathbf{V}_1 = a\left(\gamma_2 +\mathbf{V}_2\Gamma_2\right)\\
\mathbf{V}_2 = a\le | Neural network for multiple output regression
A neural net with multiple outcomes takes the form
$$
\mathbf{Y} = \mathbf{\gamma} + \mathbf{V}_1\Gamma_1 + \epsilon\\
\mathbf{V}_1 = a\left(\gamma_2 +\mathbf{V}_2\Gamma_2\right)\\
\mathbf{V}_2 = a\left(\gamma_3 +\mathbf{V}_3\Gamma_3\right)\\
\vdots \\
\mathbf{V}_{L-1} = a\left(\gamma_L+ \mathbf{X}\Gamma_L\right)\\
$$
If your outcome has the dimension $N\times 8$, then $[\gamma_1, \Gamma_1]$ will have the dimension $(p_{V1}+1) \times 8$.
Which is to say that you'd be assuming that each outcome shares ALL of the parameters in the hidden layers, and only has different parameters for taking the uppermost derived variable and relating it to the outcome.
Is this a realistic assumption for your context? | Neural network for multiple output regression
A neural net with multiple outcomes takes the form
$$
\mathbf{Y} = \mathbf{\gamma} + \mathbf{V}_1\Gamma_1 + \epsilon\\
\mathbf{V}_1 = a\left(\gamma_2 +\mathbf{V}_2\Gamma_2\right)\\
\mathbf{V}_2 = a\le |
20,116 | Neural network for multiple output regression | You can do it with only one Neural Network. But your Neural Network should look like this:
Input Layer: 34 Nodes(one per your input column)
Output Layer: 8 Nodes(one per your output column)
You can add as many as and as big as hidden layers you want in the Neural Network. So Neural Network outputs 8 predicted values and each value will be a different regression of the inputs. | Neural network for multiple output regression | You can do it with only one Neural Network. But your Neural Network should look like this:
Input Layer: 34 Nodes(one per your input column)
Output Layer: 8 Nodes(one per your output column)
You can | Neural network for multiple output regression
You can do it with only one Neural Network. But your Neural Network should look like this:
Input Layer: 34 Nodes(one per your input column)
Output Layer: 8 Nodes(one per your output column)
You can add as many as and as big as hidden layers you want in the Neural Network. So Neural Network outputs 8 predicted values and each value will be a different regression of the inputs. | Neural network for multiple output regression
You can do it with only one Neural Network. But your Neural Network should look like this:
Input Layer: 34 Nodes(one per your input column)
Output Layer: 8 Nodes(one per your output column)
You can |
20,117 | Neural network for multiple output regression | I was wondering the same; here are my ideas:
I suppose that if the outputs share some hidden patterns, then training can benefit from simultaneously learning the regression for all the outputs.
It would be interesting to try an architecture where you build a neural network for each output, but all the neural networks share some layers (the first half layers for example). Then you could train each neural network at the same time: inside the learning loop, each neural network is trained one step (with one batch) sequentially.
This would be similar to knowledge transfer, but with the difference that in knowledge transfer each neural network is fully trained before reusing some part of it to train another neural network.
I bet someone has thought about this before, but I have no reference to it. | Neural network for multiple output regression | I was wondering the same; here are my ideas:
I suppose that if the outputs share some hidden patterns, then training can benefit from simultaneously learning the regression for all the outputs.
It wou | Neural network for multiple output regression
I was wondering the same; here are my ideas:
I suppose that if the outputs share some hidden patterns, then training can benefit from simultaneously learning the regression for all the outputs.
It would be interesting to try an architecture where you build a neural network for each output, but all the neural networks share some layers (the first half layers for example). Then you could train each neural network at the same time: inside the learning loop, each neural network is trained one step (with one batch) sequentially.
This would be similar to knowledge transfer, but with the difference that in knowledge transfer each neural network is fully trained before reusing some part of it to train another neural network.
I bet someone has thought about this before, but I have no reference to it. | Neural network for multiple output regression
I was wondering the same; here are my ideas:
I suppose that if the outputs share some hidden patterns, then training can benefit from simultaneously learning the regression for all the outputs.
It wou |
20,118 | What is a stationary time series? What are some examples? | Perhaps a simple example from finance might help intuition. Let $R_t$ be the interest rate for period $t$ (note this is a random variable).
Numerous interest rate models (eg. Vasicek or Cox-Ingersoll-Ross) imply the rate is stationary process. If you earn the interest rate $R_t$ each period and start with $V_0$ dollars, then the quantity of dollars you have at time $t$ is given by:
$$V_t = V_0 \prod_{\tau=1}^t \left(1 + R_\tau \right)$$
The process $\left\{ V_t \right\}$ is NOT stationary. There's no unconditional mean or variance.
Other examples from econ and finance:
Let $Y_t$ be aggregate output (i.e. GDP) of the economy at time $t$.
$y_t = \log(Y_t)$ is almost certainly not a stationary process.
The growth in log output (i.e. $y_t - y_{t-1}$) is typically treated as a stationary process
Let $S_t$ be the price of overall market portfolio.
$s_t = \log(S_t)$ is almost certainly not a stationary process.
The log return $r_t = s_t - s_{t-1}$ of the market portfolio is typically treated as a stationary process.
A random walk or a Wiener process (the continuous time analogue to a random walk) are canonical examples of non-stationary processes. On the other hand, increments of a random walk or a Wiener process are stationary processes.
Temperature
As @kjetil points out, temperature is not a stationary process. For example, the distribution over temperatures in January is not the same as the distribution over temperatures in June. The joint distribution changes when shifted in time.
On the other hand, let $\mathbf{y}_t$ be a 12 by 1 vector for year $t$ where each entry of the vector denotes the average temperature for a month. You might be able to argue that $\mathbf{y}_t$ is a stationary process.
-- Update As @bright-star points out in the comments, this is the basic idea behind cyclostationarity. The temperature on a specific day as $t$ varies across years may be a stationary process.
Sunspots
One of the first time-series models was developed by Yule and Walker to model the 11-year sunspot cycle.
Let $y_t$ be the number of sunspots in year $t$. They modeled the number of sunspots in a year as a stationary process using the AR(2) model:
$$ y_t = a + b y_{t-1} + c y_{t-2} + \epsilon_t $$
A stationary process can have patterns, cycles, etc...
Be aware of the two common definitions of stationarity.
Somewhat loosely:
A process is strictly stationary if the joint distribution is time invariant.
A process is covariance stationary if the unconditional expectation and the autocovariance exist and do not vary over time.
(Perhaps an obscure, technical remark, but strict stationarity does not imply covariance stationarity and covariance stationarity does not imply strict stationarity.) | What is a stationary time series? What are some examples? | Perhaps a simple example from finance might help intuition. Let $R_t$ be the interest rate for period $t$ (note this is a random variable).
Numerous interest rate models (eg. Vasicek or Cox-Ingersoll- | What is a stationary time series? What are some examples?
Perhaps a simple example from finance might help intuition. Let $R_t$ be the interest rate for period $t$ (note this is a random variable).
Numerous interest rate models (eg. Vasicek or Cox-Ingersoll-Ross) imply the rate is stationary process. If you earn the interest rate $R_t$ each period and start with $V_0$ dollars, then the quantity of dollars you have at time $t$ is given by:
$$V_t = V_0 \prod_{\tau=1}^t \left(1 + R_\tau \right)$$
The process $\left\{ V_t \right\}$ is NOT stationary. There's no unconditional mean or variance.
Other examples from econ and finance:
Let $Y_t$ be aggregate output (i.e. GDP) of the economy at time $t$.
$y_t = \log(Y_t)$ is almost certainly not a stationary process.
The growth in log output (i.e. $y_t - y_{t-1}$) is typically treated as a stationary process
Let $S_t$ be the price of overall market portfolio.
$s_t = \log(S_t)$ is almost certainly not a stationary process.
The log return $r_t = s_t - s_{t-1}$ of the market portfolio is typically treated as a stationary process.
A random walk or a Wiener process (the continuous time analogue to a random walk) are canonical examples of non-stationary processes. On the other hand, increments of a random walk or a Wiener process are stationary processes.
Temperature
As @kjetil points out, temperature is not a stationary process. For example, the distribution over temperatures in January is not the same as the distribution over temperatures in June. The joint distribution changes when shifted in time.
On the other hand, let $\mathbf{y}_t$ be a 12 by 1 vector for year $t$ where each entry of the vector denotes the average temperature for a month. You might be able to argue that $\mathbf{y}_t$ is a stationary process.
-- Update As @bright-star points out in the comments, this is the basic idea behind cyclostationarity. The temperature on a specific day as $t$ varies across years may be a stationary process.
Sunspots
One of the first time-series models was developed by Yule and Walker to model the 11-year sunspot cycle.
Let $y_t$ be the number of sunspots in year $t$. They modeled the number of sunspots in a year as a stationary process using the AR(2) model:
$$ y_t = a + b y_{t-1} + c y_{t-2} + \epsilon_t $$
A stationary process can have patterns, cycles, etc...
Be aware of the two common definitions of stationarity.
Somewhat loosely:
A process is strictly stationary if the joint distribution is time invariant.
A process is covariance stationary if the unconditional expectation and the autocovariance exist and do not vary over time.
(Perhaps an obscure, technical remark, but strict stationarity does not imply covariance stationarity and covariance stationarity does not imply strict stationarity.) | What is a stationary time series? What are some examples?
Perhaps a simple example from finance might help intuition. Let $R_t$ be the interest rate for period $t$ (note this is a random variable).
Numerous interest rate models (eg. Vasicek or Cox-Ingersoll- |
20,119 | What is a stationary time series? What are some examples? | A stationary process' distribution does not change over time. An intuitive example: you flip a coin. 50% heads, regardless of whether you flip it today or tomorrow or next year.
A more complex example: by the efficient market hypothesis, excess stock returns should always fluctuate around zero. There is no trend; as soon as they can predict returns, traders exploit the trend until it vanishes. So no matter when you observed excess returns, it would still be distributed WN(0,$\sigma$).
As you said, it would randomly vary according to a white noise process. | What is a stationary time series? What are some examples? | A stationary process' distribution does not change over time. An intuitive example: you flip a coin. 50% heads, regardless of whether you flip it today or tomorrow or next year.
A more complex exampl | What is a stationary time series? What are some examples?
A stationary process' distribution does not change over time. An intuitive example: you flip a coin. 50% heads, regardless of whether you flip it today or tomorrow or next year.
A more complex example: by the efficient market hypothesis, excess stock returns should always fluctuate around zero. There is no trend; as soon as they can predict returns, traders exploit the trend until it vanishes. So no matter when you observed excess returns, it would still be distributed WN(0,$\sigma$).
As you said, it would randomly vary according to a white noise process. | What is a stationary time series? What are some examples?
A stationary process' distribution does not change over time. An intuitive example: you flip a coin. 50% heads, regardless of whether you flip it today or tomorrow or next year.
A more complex exampl |
20,120 | What is probabilistic inference? | Probabilistic inference uses probabilistic models, i.e. models that describe the statistical problems in terms of probability theory and probability distributions. While statistics use probability theory quite heavily, you cannot say that those two disciplines are the same thing (check the discussion in this thread). Notice that many statistical and machine learning methods do not explicitly use probability theory to define the problems, e.g. many clustering algorithms, or classification methods that work by minimizing some loss function etc. But the distinction is not that straightforward, take as example approximate Bayesian computation -- theoretically it is based on Bayesian (probabilistic!) inference, but it deals with cases where we do not have likelihood function, so instead of it we use a distance measure. | What is probabilistic inference? | Probabilistic inference uses probabilistic models, i.e. models that describe the statistical problems in terms of probability theory and probability distributions. While statistics use probability the | What is probabilistic inference?
Probabilistic inference uses probabilistic models, i.e. models that describe the statistical problems in terms of probability theory and probability distributions. While statistics use probability theory quite heavily, you cannot say that those two disciplines are the same thing (check the discussion in this thread). Notice that many statistical and machine learning methods do not explicitly use probability theory to define the problems, e.g. many clustering algorithms, or classification methods that work by minimizing some loss function etc. But the distinction is not that straightforward, take as example approximate Bayesian computation -- theoretically it is based on Bayesian (probabilistic!) inference, but it deals with cases where we do not have likelihood function, so instead of it we use a distance measure. | What is probabilistic inference?
Probabilistic inference uses probabilistic models, i.e. models that describe the statistical problems in terms of probability theory and probability distributions. While statistics use probability the |
20,121 | What is probabilistic inference? | I will answer your questions from my experience in learning Probabilistic Graphical Models (PGM) in university and the way my PGM teacher defined probabilistic inference. Knowing the material of this class was based on [1], I assume you could find more precise answers in this book.
In answer to 2: Probabilistic inference is a type of statistical inference. From [2] and [3], statistical inference makes statistical propositions about a population, which includes point estimate, interval estimate, hypothesis rejection, clustering and classification. "Probabilistic inference" was introduced and roughly defined in the PGM context as any marginalisation task of a probability function, whether it is a marginal probability computation or finding the most probable outcome (for e.g. classification). It thus enters in the definition of statistical inference as making a proposition on the underlying probability distribution of the population.
To illustrate mathematically some marginalisation tasks in the context of PGM, let $\mathcal{X} = \{X_1, \ldots, X_n\}$ be a set of random variables. For a given bayesian network $(\mathscr{G}, \mathbb{P}_{\theta})$ or markovian network $(\mathscr{H}, \mathbb{P}_{\theta})$ with $\mathbb{P}_\theta$, then the following routines are considered probabilistic inferences:
Computing a marginal or conditional probablity: For $\mathbf{E}, \mathbf{X} \subset \mathcal{X}$, we want to answer:
$$\mathbb{P}_\theta(\mathbf{X} = \mathbf{x} \mid \mathbf{E} =
\mathbf{e}) = ~?.$$
Most probable realization: For $\mathbf{E}, \mathbf{X} \subset \mathcal{X}$, we want to answer:
$${\rm arg}\min_{\!\!\!\!\!\!\!\!\mathbf{x}}\mathbb{P}_\theta(\mathbf{X} = \mathbf{x} \mid \mathbf{E} = \mathbf{e}) = ~?.$$
In answer to 1 and 3: It was the first time I had seen this terminology. The term does make sense, since you make inference on questions that are directly related to probabilities. I cannot answer whether it is used solely in CS or the PGM context.
[1] Koller, Daphne, and Nir Friedman. 2009. Probabilistic Graphical Models: Principles and Techniques. MIT Press.
[2] https://en.wikipedia.org/wiki/Statistical_inference
[3] https://encyclopediaofmath.org/wiki/Statistical_inference | What is probabilistic inference? | I will answer your questions from my experience in learning Probabilistic Graphical Models (PGM) in university and the way my PGM teacher defined probabilistic inference. Knowing the material of this | What is probabilistic inference?
I will answer your questions from my experience in learning Probabilistic Graphical Models (PGM) in university and the way my PGM teacher defined probabilistic inference. Knowing the material of this class was based on [1], I assume you could find more precise answers in this book.
In answer to 2: Probabilistic inference is a type of statistical inference. From [2] and [3], statistical inference makes statistical propositions about a population, which includes point estimate, interval estimate, hypothesis rejection, clustering and classification. "Probabilistic inference" was introduced and roughly defined in the PGM context as any marginalisation task of a probability function, whether it is a marginal probability computation or finding the most probable outcome (for e.g. classification). It thus enters in the definition of statistical inference as making a proposition on the underlying probability distribution of the population.
To illustrate mathematically some marginalisation tasks in the context of PGM, let $\mathcal{X} = \{X_1, \ldots, X_n\}$ be a set of random variables. For a given bayesian network $(\mathscr{G}, \mathbb{P}_{\theta})$ or markovian network $(\mathscr{H}, \mathbb{P}_{\theta})$ with $\mathbb{P}_\theta$, then the following routines are considered probabilistic inferences:
Computing a marginal or conditional probablity: For $\mathbf{E}, \mathbf{X} \subset \mathcal{X}$, we want to answer:
$$\mathbb{P}_\theta(\mathbf{X} = \mathbf{x} \mid \mathbf{E} =
\mathbf{e}) = ~?.$$
Most probable realization: For $\mathbf{E}, \mathbf{X} \subset \mathcal{X}$, we want to answer:
$${\rm arg}\min_{\!\!\!\!\!\!\!\!\mathbf{x}}\mathbb{P}_\theta(\mathbf{X} = \mathbf{x} \mid \mathbf{E} = \mathbf{e}) = ~?.$$
In answer to 1 and 3: It was the first time I had seen this terminology. The term does make sense, since you make inference on questions that are directly related to probabilities. I cannot answer whether it is used solely in CS or the PGM context.
[1] Koller, Daphne, and Nir Friedman. 2009. Probabilistic Graphical Models: Principles and Techniques. MIT Press.
[2] https://en.wikipedia.org/wiki/Statistical_inference
[3] https://encyclopediaofmath.org/wiki/Statistical_inference | What is probabilistic inference?
I will answer your questions from my experience in learning Probabilistic Graphical Models (PGM) in university and the way my PGM teacher defined probabilistic inference. Knowing the material of this |
20,122 | Online estimation of variance with limited memory | Nice and simple algorithm for computing variance in online manner was described by Welford (1962). Below you can see C++/Rcpp implementation of it that works offline, but can be easily adapted to online scenario:
List welford_cpp(NumericVector x) {
int n = x.length();
double delta;
double msq = 0;
double mean = x[0];
if (n > 1) {
for (int i = 1; i < n; i++) {
delta = x[i] - mean;
mean += delta / (i+1);
msq += delta * (x[i] - mean);
}
return Rcpp::List::create(Rcpp::Named("mean") = mean,
Rcpp::Named("variance") = msq / (n-1));
}
return Rcpp::List::create(Rcpp::Named("mean") = mean,
Rcpp::Named("variance") = NAN);
}
As you can see, it needs to store only four variables: n, delta, msq and mean and computes mean and variance simultaneously as you wanted.
Welford, B. P. (1962). Note on a method for calculating corrected sums of squares and products. Technometrics 4(3): 419-420. | Online estimation of variance with limited memory | Nice and simple algorithm for computing variance in online manner was described by Welford (1962). Below you can see C++/Rcpp implementation of it that works offline, but can be easily adapted to onli | Online estimation of variance with limited memory
Nice and simple algorithm for computing variance in online manner was described by Welford (1962). Below you can see C++/Rcpp implementation of it that works offline, but can be easily adapted to online scenario:
List welford_cpp(NumericVector x) {
int n = x.length();
double delta;
double msq = 0;
double mean = x[0];
if (n > 1) {
for (int i = 1; i < n; i++) {
delta = x[i] - mean;
mean += delta / (i+1);
msq += delta * (x[i] - mean);
}
return Rcpp::List::create(Rcpp::Named("mean") = mean,
Rcpp::Named("variance") = msq / (n-1));
}
return Rcpp::List::create(Rcpp::Named("mean") = mean,
Rcpp::Named("variance") = NAN);
}
As you can see, it needs to store only four variables: n, delta, msq and mean and computes mean and variance simultaneously as you wanted.
Welford, B. P. (1962). Note on a method for calculating corrected sums of squares and products. Technometrics 4(3): 419-420. | Online estimation of variance with limited memory
Nice and simple algorithm for computing variance in online manner was described by Welford (1962). Below you can see C++/Rcpp implementation of it that works offline, but can be easily adapted to onli |
20,123 | Online estimation of variance with limited memory | The variance can be expressed as proportional to the squared difference between every value and the mean value, or (as many threads here in stats.SE documented, like this answer I wrote to another question) it can alternatively be expressed as proportional to the squared pairwise difference between every sample.
So we know:
$$\text {Var}(x) = \frac{1}{n} \cdot \sum_{i}(X_i-\overline{X})^2 =
\frac{1}{2n^2} \cdot \sum_{i,j}(X_i-X_j)^2$$
Let's say you add another sample, indexed as the last index, $k$. Your previous variance would be:
$$\text {Var}_{old}(x) = \frac{1}{2(n-1)^2} \cdot \sum_{i<k,j<k}(X_i-X_j)^2$$
Your new variance is
$$\text {Var}_{new}(x) = \frac{1}{2n^2} \cdot \sum_{i,j}(X_i-X_j)^2 =
\frac{1}{2n^2} \cdot
\left(
\sum_{i<k,j<k}(X_i-X_j)^2 + \sum_{j<k}(X_k-X_j)^2 + \sum_{i<k}(X_i-X_k)^2
\right)$$
But
$$\sum_{j<k}(X_k-X_j)^2 = \sum_{i<k}(X_i-X_k)^2\\
\sum_{i<k,j<k}(X_i-X_j)^2 = {2(n-1)^2} \cdot \text {Var}_{old}(x)
$$
So
$$\text {Var}_{new}(x) = \left(\frac{n-1}{n}\right)^2
\text{Var}_{old}(x)+
\frac{1}{n^2}
\sum_{j<k}(X_k-X_j)^2
$$
As @MarkL.Stone said in the comments, this still isn't efficient because we must keep every $X_i$. So, let's expand the formula to arrive at something more tractable.
$$\frac{1}{n^2}\sum_{j<k}(X_k-X_j)^2=\\
\frac{1}{n^2}\sum_{j<k}(X_k^2 - 2 \cdot X_j \cdot X_k + X_j^2)=\\
\frac{1}{n^2}\left(\sum_{j<k}X_k^2 - 2 \cdot X_k \cdot \sum_{j<k} X_j + \sum_{j<k} X_j^2\right)=\\
\frac{1}{n^2}\left(k\cdot X_k^2 - 2 \cdot X_k \cdot (k-1) \cdot \overline{X_{old}} + (k-1) \cdot \overline{X^2_{old}}\right)\\
$$
Because
$$\sum_{j<k} X_j = (k-1) \cdot \overline{X_{old}}\\
\sum_{j<k} X_j^2 = (k-1) \cdot \overline{X^2_{old}}$$
The final form is then
$$\text {Var}_{new}(x) = \left(\frac{n-1}{n}\right)^2
\text{Var}_{old}(x)+
\frac{1}{n^2}\left(k\cdot X_k^2 - 2 \cdot X_k \cdot (k-1) \cdot \overline{X_{old}} + (k-1) \cdot \overline{X^2_{old}}\right)
$$
You can use this formula to update the variance effectively memory-wise. You can also complement it to use batches instead of single point updates.
Basically you need to store the average, the average of the squared samples, and the variance every iteration, and use it to update the variance formula.
Further
$$\overline{X^2_{old}} = \text{Var}_{old}(x) + (\overline{X_{old}})^2\\
\therefore\text {Var}_{new}(x) = \left(\frac{n-1}{n}\right)^2
\text{Var}_{old}(x)+
\frac{1}{n^2}\left(k\cdot X_k^2 - 2 \cdot X_k \cdot (k-1) \cdot \overline{X_{old}} + (k-1) \cdot \left(\text{Var}_{old}(x) + (\overline{X_{old}})^2\right)\right)
$$
Which brings the number of quantities that need to be stored down to 2. | Online estimation of variance with limited memory | The variance can be expressed as proportional to the squared difference between every value and the mean value, or (as many threads here in stats.SE documented, like this answer I wrote to another que | Online estimation of variance with limited memory
The variance can be expressed as proportional to the squared difference between every value and the mean value, or (as many threads here in stats.SE documented, like this answer I wrote to another question) it can alternatively be expressed as proportional to the squared pairwise difference between every sample.
So we know:
$$\text {Var}(x) = \frac{1}{n} \cdot \sum_{i}(X_i-\overline{X})^2 =
\frac{1}{2n^2} \cdot \sum_{i,j}(X_i-X_j)^2$$
Let's say you add another sample, indexed as the last index, $k$. Your previous variance would be:
$$\text {Var}_{old}(x) = \frac{1}{2(n-1)^2} \cdot \sum_{i<k,j<k}(X_i-X_j)^2$$
Your new variance is
$$\text {Var}_{new}(x) = \frac{1}{2n^2} \cdot \sum_{i,j}(X_i-X_j)^2 =
\frac{1}{2n^2} \cdot
\left(
\sum_{i<k,j<k}(X_i-X_j)^2 + \sum_{j<k}(X_k-X_j)^2 + \sum_{i<k}(X_i-X_k)^2
\right)$$
But
$$\sum_{j<k}(X_k-X_j)^2 = \sum_{i<k}(X_i-X_k)^2\\
\sum_{i<k,j<k}(X_i-X_j)^2 = {2(n-1)^2} \cdot \text {Var}_{old}(x)
$$
So
$$\text {Var}_{new}(x) = \left(\frac{n-1}{n}\right)^2
\text{Var}_{old}(x)+
\frac{1}{n^2}
\sum_{j<k}(X_k-X_j)^2
$$
As @MarkL.Stone said in the comments, this still isn't efficient because we must keep every $X_i$. So, let's expand the formula to arrive at something more tractable.
$$\frac{1}{n^2}\sum_{j<k}(X_k-X_j)^2=\\
\frac{1}{n^2}\sum_{j<k}(X_k^2 - 2 \cdot X_j \cdot X_k + X_j^2)=\\
\frac{1}{n^2}\left(\sum_{j<k}X_k^2 - 2 \cdot X_k \cdot \sum_{j<k} X_j + \sum_{j<k} X_j^2\right)=\\
\frac{1}{n^2}\left(k\cdot X_k^2 - 2 \cdot X_k \cdot (k-1) \cdot \overline{X_{old}} + (k-1) \cdot \overline{X^2_{old}}\right)\\
$$
Because
$$\sum_{j<k} X_j = (k-1) \cdot \overline{X_{old}}\\
\sum_{j<k} X_j^2 = (k-1) \cdot \overline{X^2_{old}}$$
The final form is then
$$\text {Var}_{new}(x) = \left(\frac{n-1}{n}\right)^2
\text{Var}_{old}(x)+
\frac{1}{n^2}\left(k\cdot X_k^2 - 2 \cdot X_k \cdot (k-1) \cdot \overline{X_{old}} + (k-1) \cdot \overline{X^2_{old}}\right)
$$
You can use this formula to update the variance effectively memory-wise. You can also complement it to use batches instead of single point updates.
Basically you need to store the average, the average of the squared samples, and the variance every iteration, and use it to update the variance formula.
Further
$$\overline{X^2_{old}} = \text{Var}_{old}(x) + (\overline{X_{old}})^2\\
\therefore\text {Var}_{new}(x) = \left(\frac{n-1}{n}\right)^2
\text{Var}_{old}(x)+
\frac{1}{n^2}\left(k\cdot X_k^2 - 2 \cdot X_k \cdot (k-1) \cdot \overline{X_{old}} + (k-1) \cdot \left(\text{Var}_{old}(x) + (\overline{X_{old}})^2\right)\right)
$$
Which brings the number of quantities that need to be stored down to 2. | Online estimation of variance with limited memory
The variance can be expressed as proportional to the squared difference between every value and the mean value, or (as many threads here in stats.SE documented, like this answer I wrote to another que |
20,124 | Online estimation of variance with limited memory | OK Andy W gave the answer. By conserving the $E^2$ average in the same way as the E average, you can use $V = exp(E^2)-exp(E)^2$. | Online estimation of variance with limited memory | OK Andy W gave the answer. By conserving the $E^2$ average in the same way as the E average, you can use $V = exp(E^2)-exp(E)^2$. | Online estimation of variance with limited memory
OK Andy W gave the answer. By conserving the $E^2$ average in the same way as the E average, you can use $V = exp(E^2)-exp(E)^2$. | Online estimation of variance with limited memory
OK Andy W gave the answer. By conserving the $E^2$ average in the same way as the E average, you can use $V = exp(E^2)-exp(E)^2$. |
20,125 | How to draw fitted graph and actual graph of gamma distribution in one plot? | Question 1
The way you calculate the density by hand seems wrong. There's no need for rounding the random numbers from the gamma distribution. As @Pascal noted, you can use a histogram to plot the density of the points. In the example below, I use the function density to estimate the density and plot it as points. I present the fit both with the points and with the histogram:
library(ggplot2)
library(MASS)
# Generate gamma rvs
x <- rgamma(100000, shape = 2, rate = 0.2)
den <- density(x)
dat <- data.frame(x = den$x, y = den$y)
# Plot density as points
ggplot(data = dat, aes(x = x, y = y)) +
geom_point(size = 3) +
theme_classic()
# Fit parameters (to avoid errors, set lower bounds to zero)
fit.params <- fitdistr(x, "gamma", lower = c(0, 0))
# Plot using density points
ggplot(data = dat, aes(x = x,y = y)) +
geom_point(size = 3) +
geom_line(aes(x=dat$x, y=dgamma(dat$x,fit.params$estimate["shape"], fit.params$estimate["rate"])), color="red", size = 1) +
theme_classic()
# Plot using histograms
ggplot(data = dat) +
geom_histogram(data = as.data.frame(x), aes(x=x, y=..density..)) +
geom_line(aes(x=dat$x, y=dgamma(dat$x,fit.params$estimate["shape"], fit.params$estimate["rate"])), color="red", size = 1) +
theme_classic()
Here is the solution that @Pascal provided:
h <- hist(x, 1000, plot = FALSE)
t1 <- data.frame(x = h$mids, y = h$density)
ggplot(data = t1, aes(x = x, y = y)) +
geom_point(size = 3) +
geom_line(aes(x=t1$x, y=dgamma(t1$x,fit.params$estimate["shape"], fit.params$estimate["rate"])), color="red", size = 1) +
theme_classic()
Question 2
To assess the goodness of fit I recommend the package fitdistrplus. Here is how it can be used to fit two distributions and compare their fits graphically and numerically. The command gofstat prints out several measures, such as the AIC, BIC and some gof-statistics such as the KS-Test etc. These are mainly used to compare fits of different distributions (in this case gamma versus Weibull). More information can be found in my answer here:
library(fitdistrplus)
x <- c(37.50,46.79,48.30,46.04,43.40,39.25,38.49,49.51,40.38,36.98,40.00,
38.49,37.74,47.92,44.53,44.91,44.91,40.00,41.51,47.92,36.98,43.40,
42.26,41.89,38.87,43.02,39.25,40.38,42.64,36.98,44.15,44.91,43.40,
49.81,38.87,40.00,52.45,53.13,47.92,52.45,44.91,29.54,27.13,35.60,
45.34,43.37,54.15,42.77,42.88,44.26,27.14,39.31,24.80,16.62,30.30,
36.39,28.60,28.53,35.84,31.10,34.55,52.65,48.81,43.42,52.49,38.00,
38.65,34.54,37.70,38.11,43.05,29.95,32.48,24.63,35.33,41.34)
fit.weibull <- fitdist(x, "weibull")
fit.gamma <- fitdist(x, "gamma", lower = c(0, 0))
# Compare fits
graphically
par(mfrow = c(2, 2))
plot.legend <- c("Weibull", "Gamma")
denscomp(list(fit.weibull, fit.gamma), fitcol = c("red", "blue"), legendtext = plot.legend)
qqcomp(list(fit.weibull, fit.gamma), fitcol = c("red", "blue"), legendtext = plot.legend)
cdfcomp(list(fit.weibull, fit.gamma), fitcol = c("red", "blue"), legendtext = plot.legend)
ppcomp(list(fit.weibull, fit.gamma), fitcol = c("red", "blue"), legendtext = plot.legend)
@NickCox rightfully advises that the QQ-Plot (upper right panel) is the best single graph for judging and comparing fits. Fitted densities are hard to compare. I include the other graphics as well for the sake of completeness.
# Compare goodness of fit
gofstat(list(fit.weibull, fit.gamma))
Goodness-of-fit statistics
1-mle-weibull 2-mle-gamma
Kolmogorov-Smirnov statistic 0.06863193 0.1204876
Cramer-von Mises statistic 0.05673634 0.2060789
Anderson-Darling statistic 0.38619340 1.2031051
Goodness-of-fit criteria
1-mle-weibull 2-mle-gamma
Aikake's Information Criterion 519.8537 531.5180
Bayesian Information Criterion 524.5151 536.1795 | How to draw fitted graph and actual graph of gamma distribution in one plot? | Question 1
The way you calculate the density by hand seems wrong. There's no need for rounding the random numbers from the gamma distribution. As @Pascal noted, you can use a histogram to plot the den | How to draw fitted graph and actual graph of gamma distribution in one plot?
Question 1
The way you calculate the density by hand seems wrong. There's no need for rounding the random numbers from the gamma distribution. As @Pascal noted, you can use a histogram to plot the density of the points. In the example below, I use the function density to estimate the density and plot it as points. I present the fit both with the points and with the histogram:
library(ggplot2)
library(MASS)
# Generate gamma rvs
x <- rgamma(100000, shape = 2, rate = 0.2)
den <- density(x)
dat <- data.frame(x = den$x, y = den$y)
# Plot density as points
ggplot(data = dat, aes(x = x, y = y)) +
geom_point(size = 3) +
theme_classic()
# Fit parameters (to avoid errors, set lower bounds to zero)
fit.params <- fitdistr(x, "gamma", lower = c(0, 0))
# Plot using density points
ggplot(data = dat, aes(x = x,y = y)) +
geom_point(size = 3) +
geom_line(aes(x=dat$x, y=dgamma(dat$x,fit.params$estimate["shape"], fit.params$estimate["rate"])), color="red", size = 1) +
theme_classic()
# Plot using histograms
ggplot(data = dat) +
geom_histogram(data = as.data.frame(x), aes(x=x, y=..density..)) +
geom_line(aes(x=dat$x, y=dgamma(dat$x,fit.params$estimate["shape"], fit.params$estimate["rate"])), color="red", size = 1) +
theme_classic()
Here is the solution that @Pascal provided:
h <- hist(x, 1000, plot = FALSE)
t1 <- data.frame(x = h$mids, y = h$density)
ggplot(data = t1, aes(x = x, y = y)) +
geom_point(size = 3) +
geom_line(aes(x=t1$x, y=dgamma(t1$x,fit.params$estimate["shape"], fit.params$estimate["rate"])), color="red", size = 1) +
theme_classic()
Question 2
To assess the goodness of fit I recommend the package fitdistrplus. Here is how it can be used to fit two distributions and compare their fits graphically and numerically. The command gofstat prints out several measures, such as the AIC, BIC and some gof-statistics such as the KS-Test etc. These are mainly used to compare fits of different distributions (in this case gamma versus Weibull). More information can be found in my answer here:
library(fitdistrplus)
x <- c(37.50,46.79,48.30,46.04,43.40,39.25,38.49,49.51,40.38,36.98,40.00,
38.49,37.74,47.92,44.53,44.91,44.91,40.00,41.51,47.92,36.98,43.40,
42.26,41.89,38.87,43.02,39.25,40.38,42.64,36.98,44.15,44.91,43.40,
49.81,38.87,40.00,52.45,53.13,47.92,52.45,44.91,29.54,27.13,35.60,
45.34,43.37,54.15,42.77,42.88,44.26,27.14,39.31,24.80,16.62,30.30,
36.39,28.60,28.53,35.84,31.10,34.55,52.65,48.81,43.42,52.49,38.00,
38.65,34.54,37.70,38.11,43.05,29.95,32.48,24.63,35.33,41.34)
fit.weibull <- fitdist(x, "weibull")
fit.gamma <- fitdist(x, "gamma", lower = c(0, 0))
# Compare fits
graphically
par(mfrow = c(2, 2))
plot.legend <- c("Weibull", "Gamma")
denscomp(list(fit.weibull, fit.gamma), fitcol = c("red", "blue"), legendtext = plot.legend)
qqcomp(list(fit.weibull, fit.gamma), fitcol = c("red", "blue"), legendtext = plot.legend)
cdfcomp(list(fit.weibull, fit.gamma), fitcol = c("red", "blue"), legendtext = plot.legend)
ppcomp(list(fit.weibull, fit.gamma), fitcol = c("red", "blue"), legendtext = plot.legend)
@NickCox rightfully advises that the QQ-Plot (upper right panel) is the best single graph for judging and comparing fits. Fitted densities are hard to compare. I include the other graphics as well for the sake of completeness.
# Compare goodness of fit
gofstat(list(fit.weibull, fit.gamma))
Goodness-of-fit statistics
1-mle-weibull 2-mle-gamma
Kolmogorov-Smirnov statistic 0.06863193 0.1204876
Cramer-von Mises statistic 0.05673634 0.2060789
Anderson-Darling statistic 0.38619340 1.2031051
Goodness-of-fit criteria
1-mle-weibull 2-mle-gamma
Aikake's Information Criterion 519.8537 531.5180
Bayesian Information Criterion 524.5151 536.1795 | How to draw fitted graph and actual graph of gamma distribution in one plot?
Question 1
The way you calculate the density by hand seems wrong. There's no need for rounding the random numbers from the gamma distribution. As @Pascal noted, you can use a histogram to plot the den |
20,126 | How to draw fitted graph and actual graph of gamma distribution in one plot? | Addition to the answer provided above, but using density and adding some theme bling:
library(fitdistrplus)
library(ggplot2)
library(ggthemes)
fit.gamma <- fitdist(df$y, "gamma", lower=c(0,0), start=list(scale=1,shape=1))
gammas<-round(rgamma(nrow(df), shape = fit.gamma$estimate["shape"], scale = fit.gamma$estimate["scale"]), 1)
gammas %>%
as_tibble() %>%
ggplot(aes(value)) +
geom_histogram(stat = "density") +
stat_function(fun = function(x) {dgamma(x, fit.gamma$estimate["shape"],scale=fit.gamma$estimate["scale"])}, color = "red") +
lims(x = c(0, 15)) +
theme_economist() +
scale_color_economist() | How to draw fitted graph and actual graph of gamma distribution in one plot? | Addition to the answer provided above, but using density and adding some theme bling:
library(fitdistrplus)
library(ggplot2)
library(ggthemes)
fit.gamma <- fitdist(df$y, "gamma", lower=c(0,0), start= | How to draw fitted graph and actual graph of gamma distribution in one plot?
Addition to the answer provided above, but using density and adding some theme bling:
library(fitdistrplus)
library(ggplot2)
library(ggthemes)
fit.gamma <- fitdist(df$y, "gamma", lower=c(0,0), start=list(scale=1,shape=1))
gammas<-round(rgamma(nrow(df), shape = fit.gamma$estimate["shape"], scale = fit.gamma$estimate["scale"]), 1)
gammas %>%
as_tibble() %>%
ggplot(aes(value)) +
geom_histogram(stat = "density") +
stat_function(fun = function(x) {dgamma(x, fit.gamma$estimate["shape"],scale=fit.gamma$estimate["scale"])}, color = "red") +
lims(x = c(0, 15)) +
theme_economist() +
scale_color_economist() | How to draw fitted graph and actual graph of gamma distribution in one plot?
Addition to the answer provided above, but using density and adding some theme bling:
library(fitdistrplus)
library(ggplot2)
library(ggthemes)
fit.gamma <- fitdist(df$y, "gamma", lower=c(0,0), start= |
20,127 | How to simulate censored data | (As a matter of R coding style, it is best not to use T as a variable name, because it is an alias for TRUE, and that practice will inevitably lead to problems.)
Your question is somewhat ambiguous; there are several ways to interpret it. Let's walk through them:
You stipulate that you want to simulate type 1 censoring. That is typically taken to mean that the experiment is run for a period of time, and that whichever study units have not had the event by then are censored. If that is what you meant, then it is not (necessarily) possible to stipulate the shape and scale parameters, and the censoring time and rate simultaneously. Having stipulated any three, the last is necessarily fixed.
(Attempting to) solve for the shape parameter:
This fails; it seems that it is impossible to have a 15% censoring rate at a censoring time of .88 with a Weibull distribution where the scale parameter is held at 1, no matter what the shape parameter is.
optim(.5, fn=function(shp){(pweibull(.88, shape=shp, scale=1, lower.tail=F)-.15)^2})
# $par
# [1] 4.768372e-08
# ...
# There were 46 warnings (use warnings() to see them)
pweibull(.88, shape=4.768372e-08, scale=1, lower.tail=F)
# [1] 0.3678794
optim(.5, fn=function(shp){(pweibull(.88, shape=shp, scale=1, lower.tail=F)-.15)^2},
control=list(reltol=1e-16))
# $par
# [1] 9.769963e-16
# ...
# There were 50 or more warnings (use warnings() to see the first 50)
pweibull(.88, shape=9.769963e-16, scale=1, lower.tail=F)
# [1] 0.3678794
Solving for the scale parameter:
optim(1, fn=function(scl){(pweibull(.88, shape=.5, scale=scl, lower.tail=F)-.15)^2})
# $par
# [1] 0.2445312
# ...
pweibull(.88, shape=.5, scale=0.2445312, lower.tail=F)
# [1] 0.1500135
Solving for the censoring time:
qweibull(.15, shape=.5, scale=1, lower.tail=F)
# [1] 3.599064
Solving for the censoring rate:
pweibull(.88, shape=.5, scale=1, lower.tail=F)
# [1] 0.3913773
On the other hand, we can think of censoring as randomly (and typically independently) occurring throughout the study due to, say, dropout. In that case, the procedure is to simulate two sets of Weibull variates. Then you simply note which came first: you use the lesser value as the endpoint and call that unit censored if the lesser value was the censoring time. For example:
set.seed(0775)
t = rweibull(3, shape=.5, scale=1)
t # [1] 0.7433678 1.1325749 0.2784812
c = rweibull(3, shape=.5, scale=1.5)
c # [1] 3.3242417 2.8866217 0.9779436
time = pmin(t, c)
time # [1] 0.7433678 1.1325749 0.2784812
cens = ifelse(c<t, 1, 0)
cens # [1] 0 0 0 | How to simulate censored data | (As a matter of R coding style, it is best not to use T as a variable name, because it is an alias for TRUE, and that practice will inevitably lead to problems.)
Your question is somewhat ambiguous; | How to simulate censored data
(As a matter of R coding style, it is best not to use T as a variable name, because it is an alias for TRUE, and that practice will inevitably lead to problems.)
Your question is somewhat ambiguous; there are several ways to interpret it. Let's walk through them:
You stipulate that you want to simulate type 1 censoring. That is typically taken to mean that the experiment is run for a period of time, and that whichever study units have not had the event by then are censored. If that is what you meant, then it is not (necessarily) possible to stipulate the shape and scale parameters, and the censoring time and rate simultaneously. Having stipulated any three, the last is necessarily fixed.
(Attempting to) solve for the shape parameter:
This fails; it seems that it is impossible to have a 15% censoring rate at a censoring time of .88 with a Weibull distribution where the scale parameter is held at 1, no matter what the shape parameter is.
optim(.5, fn=function(shp){(pweibull(.88, shape=shp, scale=1, lower.tail=F)-.15)^2})
# $par
# [1] 4.768372e-08
# ...
# There were 46 warnings (use warnings() to see them)
pweibull(.88, shape=4.768372e-08, scale=1, lower.tail=F)
# [1] 0.3678794
optim(.5, fn=function(shp){(pweibull(.88, shape=shp, scale=1, lower.tail=F)-.15)^2},
control=list(reltol=1e-16))
# $par
# [1] 9.769963e-16
# ...
# There were 50 or more warnings (use warnings() to see the first 50)
pweibull(.88, shape=9.769963e-16, scale=1, lower.tail=F)
# [1] 0.3678794
Solving for the scale parameter:
optim(1, fn=function(scl){(pweibull(.88, shape=.5, scale=scl, lower.tail=F)-.15)^2})
# $par
# [1] 0.2445312
# ...
pweibull(.88, shape=.5, scale=0.2445312, lower.tail=F)
# [1] 0.1500135
Solving for the censoring time:
qweibull(.15, shape=.5, scale=1, lower.tail=F)
# [1] 3.599064
Solving for the censoring rate:
pweibull(.88, shape=.5, scale=1, lower.tail=F)
# [1] 0.3913773
On the other hand, we can think of censoring as randomly (and typically independently) occurring throughout the study due to, say, dropout. In that case, the procedure is to simulate two sets of Weibull variates. Then you simply note which came first: you use the lesser value as the endpoint and call that unit censored if the lesser value was the censoring time. For example:
set.seed(0775)
t = rweibull(3, shape=.5, scale=1)
t # [1] 0.7433678 1.1325749 0.2784812
c = rweibull(3, shape=.5, scale=1.5)
c # [1] 3.3242417 2.8866217 0.9779436
time = pmin(t, c)
time # [1] 0.7433678 1.1325749 0.2784812
cens = ifelse(c<t, 1, 0)
cens # [1] 0 0 0 | How to simulate censored data
(As a matter of R coding style, it is best not to use T as a variable name, because it is an alias for TRUE, and that practice will inevitably lead to problems.)
Your question is somewhat ambiguous; |
20,128 | How to simulate censored data | Just to be sure we're talking about the same thing, type-I censoring is when
... an experiment has a set number of subjects or items and stops the experiment at a predetermined time, at which point any subjects remaining are right-censored.
To generate right censored data using censoring time = 0.88, you'd just use the min function:
T <- rweibull(3, shape=.5, scale=1)
censoring_time <- 0.88
T_censored <- min(censoring_time, T)
However, I'm not entirely sure what you mean when you say, "censoring rate = 0.15"... Do you mean to say that 15% of your subjects are right censored? These notes on censorship seem to indicate that the only parameter one needs for Type-I censorship is censoring time, so I'm not sure how this rate factors in. | How to simulate censored data | Just to be sure we're talking about the same thing, type-I censoring is when
... an experiment has a set number of subjects or items and stops the experiment at a predetermined time, at which point a | How to simulate censored data
Just to be sure we're talking about the same thing, type-I censoring is when
... an experiment has a set number of subjects or items and stops the experiment at a predetermined time, at which point any subjects remaining are right-censored.
To generate right censored data using censoring time = 0.88, you'd just use the min function:
T <- rweibull(3, shape=.5, scale=1)
censoring_time <- 0.88
T_censored <- min(censoring_time, T)
However, I'm not entirely sure what you mean when you say, "censoring rate = 0.15"... Do you mean to say that 15% of your subjects are right censored? These notes on censorship seem to indicate that the only parameter one needs for Type-I censorship is censoring time, so I'm not sure how this rate factors in. | How to simulate censored data
Just to be sure we're talking about the same thing, type-I censoring is when
... an experiment has a set number of subjects or items and stops the experiment at a predetermined time, at which point a |
20,129 | How to handle NA values in shrinkage (Lasso) method using glmnet | Omitting cases with NA values could lead to bias. An alternative would be to perform multiple imputations of the missing data, for example with mice, and then do lasso on each of the imputations. Lasso will probably return different sets of selected variables for the imputations, but you could examine how frequently each variable is selected, among the imputed data sets, to identify your best candidate variables.
Imputation, of course, is inapplicable if the probability of a data point being missing is related to its true value. So before doing imputation make sure at least that is unlikely to be the case, based on knowledge of the subject matter. | How to handle NA values in shrinkage (Lasso) method using glmnet | Omitting cases with NA values could lead to bias. An alternative would be to perform multiple imputations of the missing data, for example with mice, and then do lasso on each of the imputations. Lass | How to handle NA values in shrinkage (Lasso) method using glmnet
Omitting cases with NA values could lead to bias. An alternative would be to perform multiple imputations of the missing data, for example with mice, and then do lasso on each of the imputations. Lasso will probably return different sets of selected variables for the imputations, but you could examine how frequently each variable is selected, among the imputed data sets, to identify your best candidate variables.
Imputation, of course, is inapplicable if the probability of a data point being missing is related to its true value. So before doing imputation make sure at least that is unlikely to be the case, based on knowledge of the subject matter. | How to handle NA values in shrinkage (Lasso) method using glmnet
Omitting cases with NA values could lead to bias. An alternative would be to perform multiple imputations of the missing data, for example with mice, and then do lasso on each of the imputations. Lass |
20,130 | How to handle NA values in shrinkage (Lasso) method using glmnet | Use complete.cases and/or na.omit to identify those rows that don't have NAs.
cc <- complete.cases(geno6) & complete.cases(pheno6)
geno61 <- as.matrix(geno6[cc, ])
pheno61 <- pheno6[cc, 1]
glmnet(geno61, pheno61, ...) | How to handle NA values in shrinkage (Lasso) method using glmnet | Use complete.cases and/or na.omit to identify those rows that don't have NAs.
cc <- complete.cases(geno6) & complete.cases(pheno6)
geno61 <- as.matrix(geno6[cc, ])
pheno61 <- pheno6[cc, 1]
glmnet(gen | How to handle NA values in shrinkage (Lasso) method using glmnet
Use complete.cases and/or na.omit to identify those rows that don't have NAs.
cc <- complete.cases(geno6) & complete.cases(pheno6)
geno61 <- as.matrix(geno6[cc, ])
pheno61 <- pheno6[cc, 1]
glmnet(geno61, pheno61, ...) | How to handle NA values in shrinkage (Lasso) method using glmnet
Use complete.cases and/or na.omit to identify those rows that don't have NAs.
cc <- complete.cases(geno6) & complete.cases(pheno6)
geno61 <- as.matrix(geno6[cc, ])
pheno61 <- pheno6[cc, 1]
glmnet(gen |
20,131 | How to handle NA values in shrinkage (Lasso) method using glmnet | I know this is an old question - but I wanted to add, beyond imputation with mice, to get a more reliable list of covariates, lasso could be performed after stacking all the imputed datasets (as if it were 1 dataset) but weight the records by the the fraction of missing variables.
See: Wood et. al. 2008 | How to handle NA values in shrinkage (Lasso) method using glmnet | I know this is an old question - but I wanted to add, beyond imputation with mice, to get a more reliable list of covariates, lasso could be performed after stacking all the imputed datasets (as if it | How to handle NA values in shrinkage (Lasso) method using glmnet
I know this is an old question - but I wanted to add, beyond imputation with mice, to get a more reliable list of covariates, lasso could be performed after stacking all the imputed datasets (as if it were 1 dataset) but weight the records by the the fraction of missing variables.
See: Wood et. al. 2008 | How to handle NA values in shrinkage (Lasso) method using glmnet
I know this is an old question - but I wanted to add, beyond imputation with mice, to get a more reliable list of covariates, lasso could be performed after stacking all the imputed datasets (as if it |
20,132 | mutual information vs normalized mutual information | Mutual Information I(X,Y) yelds values from $0$ (no mutual information - variables X and Y are independent) to $+\infty$. The higher the I(X,Y), the more information is shared between X and Y. However, high values of mutual information might be unintuitive and hard to interpret due to its unbounded range of values $I(X,Y)\in [0...\infty)$.
Normalized Mutual Information measures try to bring the possible values to bounded range $I(X,Y)\in [0...m]$. Specifically, case of $m=1$ is useful due to ease of comparison with commonly used correlation coefficients.
Nice discussion of relations between Mutual Information and Pearson Correlation Coefficient can be found in Materials and Methods section of "Generalized Correlation for Biomolecular Dynamics" paper by Lange and Grubmuller[1]. They also introducte of generalized correlation coefficient that maps values of I(X,Y) onto [0,1] interval, which can be seen as another approach Normalised Mutual Information.
[1] O. F. Lange, H. GrubmΓΌller, Proteins 2006, 62, 1053β1061. | mutual information vs normalized mutual information | Mutual Information I(X,Y) yelds values from $0$ (no mutual information - variables X and Y are independent) to $+\infty$. The higher the I(X,Y), the more information is shared between X and Y. However | mutual information vs normalized mutual information
Mutual Information I(X,Y) yelds values from $0$ (no mutual information - variables X and Y are independent) to $+\infty$. The higher the I(X,Y), the more information is shared between X and Y. However, high values of mutual information might be unintuitive and hard to interpret due to its unbounded range of values $I(X,Y)\in [0...\infty)$.
Normalized Mutual Information measures try to bring the possible values to bounded range $I(X,Y)\in [0...m]$. Specifically, case of $m=1$ is useful due to ease of comparison with commonly used correlation coefficients.
Nice discussion of relations between Mutual Information and Pearson Correlation Coefficient can be found in Materials and Methods section of "Generalized Correlation for Biomolecular Dynamics" paper by Lange and Grubmuller[1]. They also introducte of generalized correlation coefficient that maps values of I(X,Y) onto [0,1] interval, which can be seen as another approach Normalised Mutual Information.
[1] O. F. Lange, H. GrubmΓΌller, Proteins 2006, 62, 1053β1061. | mutual information vs normalized mutual information
Mutual Information I(X,Y) yelds values from $0$ (no mutual information - variables X and Y are independent) to $+\infty$. The higher the I(X,Y), the more information is shared between X and Y. However |
20,133 | mutual information vs normalized mutual information | Unlike correlation, mutual information is not bounded always less then 1. Ie it is the number of bits of information shared between two variables and thus depends on the total information content of each of the variables.
Various measures of normalized Mutual Information are attempts to make it more like correlation by bounding it (ie 1 is good, 0 is bad). | mutual information vs normalized mutual information | Unlike correlation, mutual information is not bounded always less then 1. Ie it is the number of bits of information shared between two variables and thus depends on the total information content of e | mutual information vs normalized mutual information
Unlike correlation, mutual information is not bounded always less then 1. Ie it is the number of bits of information shared between two variables and thus depends on the total information content of each of the variables.
Various measures of normalized Mutual Information are attempts to make it more like correlation by bounding it (ie 1 is good, 0 is bad). | mutual information vs normalized mutual information
Unlike correlation, mutual information is not bounded always less then 1. Ie it is the number of bits of information shared between two variables and thus depends on the total information content of e |
20,134 | Difference between series with drift and series with trend | If I have a new series that exhibit an increasing behavior, how do I know this series is a series with drift or with trend?
You may get some graphical clue about whether an intercept or a deterministic
trend should be considered. Be aware that the drift term in your equation with $\phi=1$ generates a deterministic linear trend in the observed series, while a deterministic trend turns into an exponential pattern in $y_t$.
To see what I mean, you could simulate and plot some series with the R software as shown below.
Simulate a random walk:
n <- 150
eps <- rnorm(n)
x0 <- rep(0, n)
for(i in seq.int(2, n)){
x0[i] <- x0[i-1] + eps[i]
}
plot(ts(x0))
Simulate a random walk with drift:
drift <- 2
x1 <- rep(0, n)
for(i in seq.int(2, n)){
x1[i] <- drift + x1[i-1] + eps[i]
}
plot(ts(x1))
Simulate a random walk with a deterministic trend:
trend <- seq_len(n)
x2 <- rep(0, n)
for(i in seq.int(2, n)){
x2[i] <- trend[i] + x2[i-1] + eps[i]
}
plot(ts(x2))
You can also see this analytically. In this document (pp.22), the effect of deterministic terms in a model with seasonal unit roots are obtained. It is written in Spanish but you may simply follow the derivations of each equation, if you need some clarifications about it you may send me an e-mail.
Can I do two ADF tests: ADF test 1. Null hypothesis is the series is I(1) with drift ADF test 2. Null hypothesis is the series is I(1) with trend. But what if for both tests, the null hypothesis is not rejected?
If the null is rejected in both cases then there isn't evidence supporting the
presence of a unit root. In this case you could test for the significance of the deterministic terms in a stationary autoregressive model or in a model with no autoregressive terms if there is no autocorrelation. | Difference between series with drift and series with trend | If I have a new series that exhibit an increasing behavior, how do I know this series is a series with drift or with trend?
You may get some graphical clue about whether an intercept or a determinist | Difference between series with drift and series with trend
If I have a new series that exhibit an increasing behavior, how do I know this series is a series with drift or with trend?
You may get some graphical clue about whether an intercept or a deterministic
trend should be considered. Be aware that the drift term in your equation with $\phi=1$ generates a deterministic linear trend in the observed series, while a deterministic trend turns into an exponential pattern in $y_t$.
To see what I mean, you could simulate and plot some series with the R software as shown below.
Simulate a random walk:
n <- 150
eps <- rnorm(n)
x0 <- rep(0, n)
for(i in seq.int(2, n)){
x0[i] <- x0[i-1] + eps[i]
}
plot(ts(x0))
Simulate a random walk with drift:
drift <- 2
x1 <- rep(0, n)
for(i in seq.int(2, n)){
x1[i] <- drift + x1[i-1] + eps[i]
}
plot(ts(x1))
Simulate a random walk with a deterministic trend:
trend <- seq_len(n)
x2 <- rep(0, n)
for(i in seq.int(2, n)){
x2[i] <- trend[i] + x2[i-1] + eps[i]
}
plot(ts(x2))
You can also see this analytically. In this document (pp.22), the effect of deterministic terms in a model with seasonal unit roots are obtained. It is written in Spanish but you may simply follow the derivations of each equation, if you need some clarifications about it you may send me an e-mail.
Can I do two ADF tests: ADF test 1. Null hypothesis is the series is I(1) with drift ADF test 2. Null hypothesis is the series is I(1) with trend. But what if for both tests, the null hypothesis is not rejected?
If the null is rejected in both cases then there isn't evidence supporting the
presence of a unit root. In this case you could test for the significance of the deterministic terms in a stationary autoregressive model or in a model with no autoregressive terms if there is no autocorrelation. | Difference between series with drift and series with trend
If I have a new series that exhibit an increasing behavior, how do I know this series is a series with drift or with trend?
You may get some graphical clue about whether an intercept or a determinist |
20,135 | What to do when sample covariance matrix is not invertible? | If your samples dimensionality is less than the vector space dimensionality, singular matrices may arise. If you have less samples than $d+1$ (when $d$ is your dimensionality), this situation will even necessarily arise: $k+1$ samples span at most a $d$ dimensional hyperplane. Given such a small sample, you obviously cannot compute a variance in the orthogonal space.
This is why it's common to not use literal PCA, but instead perform singular value decomposition, which can be used to compute the pseudoinverse of a matrix.
If the matrix is invertible, the pseudoinverse will be the inverse.
However, if you are seeing non-invertible matrixes, chances are that your distance from the cluster will be meaningless if the vector is outside of the hyperplane the cluster repesents, because you do not know the variance in the orthogonal space (you can think of this variance as 0!) SVD can compute the pseudoinverse, but the "variances" will still be not determined by your data.
In this case, you should probably have been doing global dimensionality reduction first. Increasing the sample size will only help when you actually have non-redundant dimensions: no matter how many samples you draw from a distributions with $y=x$, the matrix will always be non-invertible, and you will not be able to judge the deviation $x-y$ with respect to a standard deviation (which is 0).
Furthermore, depending on how you compute the covariance matrix, you might be running into numerical issues due to catastrophic cancellation. The simplest workaround is to always center the data first, to get zero mean. | What to do when sample covariance matrix is not invertible? | If your samples dimensionality is less than the vector space dimensionality, singular matrices may arise. If you have less samples than $d+1$ (when $d$ is your dimensionality), this situation will eve | What to do when sample covariance matrix is not invertible?
If your samples dimensionality is less than the vector space dimensionality, singular matrices may arise. If you have less samples than $d+1$ (when $d$ is your dimensionality), this situation will even necessarily arise: $k+1$ samples span at most a $d$ dimensional hyperplane. Given such a small sample, you obviously cannot compute a variance in the orthogonal space.
This is why it's common to not use literal PCA, but instead perform singular value decomposition, which can be used to compute the pseudoinverse of a matrix.
If the matrix is invertible, the pseudoinverse will be the inverse.
However, if you are seeing non-invertible matrixes, chances are that your distance from the cluster will be meaningless if the vector is outside of the hyperplane the cluster repesents, because you do not know the variance in the orthogonal space (you can think of this variance as 0!) SVD can compute the pseudoinverse, but the "variances" will still be not determined by your data.
In this case, you should probably have been doing global dimensionality reduction first. Increasing the sample size will only help when you actually have non-redundant dimensions: no matter how many samples you draw from a distributions with $y=x$, the matrix will always be non-invertible, and you will not be able to judge the deviation $x-y$ with respect to a standard deviation (which is 0).
Furthermore, depending on how you compute the covariance matrix, you might be running into numerical issues due to catastrophic cancellation. The simplest workaround is to always center the data first, to get zero mean. | What to do when sample covariance matrix is not invertible?
If your samples dimensionality is less than the vector space dimensionality, singular matrices may arise. If you have less samples than $d+1$ (when $d$ is your dimensionality), this situation will eve |
20,136 | What to do when sample covariance matrix is not invertible? | I faced this problem when trying to do KDE using gaussian_kde in Python where the random variables were the 784 pixels of some images. In my case the reason was that many pixels were always (in all the images) zero, so no random at all. To solve this problem I just added some small gaussian noise to the images and voilΓ , now the covariance matrix is invertible. | What to do when sample covariance matrix is not invertible? | I faced this problem when trying to do KDE using gaussian_kde in Python where the random variables were the 784 pixels of some images. In my case the reason was that many pixels were always (in all th | What to do when sample covariance matrix is not invertible?
I faced this problem when trying to do KDE using gaussian_kde in Python where the random variables were the 784 pixels of some images. In my case the reason was that many pixels were always (in all the images) zero, so no random at all. To solve this problem I just added some small gaussian noise to the images and voilΓ , now the covariance matrix is invertible. | What to do when sample covariance matrix is not invertible?
I faced this problem when trying to do KDE using gaussian_kde in Python where the random variables were the 784 pixels of some images. In my case the reason was that many pixels were always (in all th |
20,137 | Analyze proportions | In one dimension, this sounds like a job for beta regression (with or without variable dispersion). This is a regression model with beta-distributed dependent variable, naturally 0-1 constrained. An R package is betareg and a paper describing its use is here.
For more than two proportions the usual extension of the Beta distribution leads to Dirichlet regression. An R package DirichletReg is available, described e.g. here.
There are some reasons not to use logit links and multinomial logistic regression for true compositional data, mostly to do with what strong assumptions they imply for the variance. However, if your data are all actually normalised counts (abundances?), those assumptions may be correct and Peter's suggestion would probably be the way to go. | Analyze proportions | In one dimension, this sounds like a job for beta regression (with or without variable dispersion). This is a regression model with beta-distributed dependent variable, naturally 0-1 constrained. An | Analyze proportions
In one dimension, this sounds like a job for beta regression (with or without variable dispersion). This is a regression model with beta-distributed dependent variable, naturally 0-1 constrained. An R package is betareg and a paper describing its use is here.
For more than two proportions the usual extension of the Beta distribution leads to Dirichlet regression. An R package DirichletReg is available, described e.g. here.
There are some reasons not to use logit links and multinomial logistic regression for true compositional data, mostly to do with what strong assumptions they imply for the variance. However, if your data are all actually normalised counts (abundances?), those assumptions may be correct and Peter's suggestion would probably be the way to go. | Analyze proportions
In one dimension, this sounds like a job for beta regression (with or without variable dispersion). This is a regression model with beta-distributed dependent variable, naturally 0-1 constrained. An |
20,138 | Analyze proportions | I am not sure exactly what you are trying to find out, but what about a multinomial logistic regression with gradient as the independent variable?
In R, one way to do this is the mlogit function in the mlogit library. See this vignette | Analyze proportions | I am not sure exactly what you are trying to find out, but what about a multinomial logistic regression with gradient as the independent variable?
In R, one way to do this is the mlogit function in th | Analyze proportions
I am not sure exactly what you are trying to find out, but what about a multinomial logistic regression with gradient as the independent variable?
In R, one way to do this is the mlogit function in the mlogit library. See this vignette | Analyze proportions
I am not sure exactly what you are trying to find out, but what about a multinomial logistic regression with gradient as the independent variable?
In R, one way to do this is the mlogit function in th |
20,139 | Statistical test for a value being significantly further from the population mean: is it a Z-test or a T-test? | You raise an interesting question. First thing first, if you have an observation of 0.35, a mean of 0.25, and a standard deviation of 1/10^7 (that's how I interpret your e^-7 bit) you really don't need to go into any hypothesis testing exercise. Your 0.35 observation is very different than the mean of 0.25 given that it will be several thousands standard deviation away from the mean and it will probably be several millions standard errors from the mean.
The difference between the Z-test and the t-test refers mainly to sample size. With samples smaller than 120, you should use the t-test to calculate p values. When sample sizes are greater than that, it does not make much difference if at all which one you use. It is fun to calculate it both ways regardless of sample size and observe how little difference there is between the two tests.
As far as calculating things yourself, you can calculate the t stat by dividing the difference between your observation and the mean and divide that by the standard error. The standard error is the standard deviation divided by the square root of the sample size. Now, you have your t stat. To calculate a p value I think there is no alternative than to look up your t value within a t test table. If you accept a simple Excel alternative TDIST(t stat value, DF, 1 or 2 for 1 or 2 tail p value) does the trick. To calculate a p value using Z, the Excel formula for a 1 tail test is: (1 - NORMSDIST (Z value). The Z value being the same as the t stat (or the number of standard error away from the mean).
Just as a caveat, those methods of hypothesis testing can get distorted by sample size. In other words, the larger your sample size the smaller your standard error, the higher your resulting Z value or t stat, the lower the p value, and the higher your statistical significance. As a short cut in this logic, large sample sizes will result in high statistical significance. But, high statistical significance in association with large sample size can be completely immaterial. In other words, statistically significant is a mathematical phrase. It does not necessarily mean significant (per Webster dictionary).
To get away from this large sample size trap, statisticians have moved on to Effect Size methods. The latter use as a unit of statistical distance between two observations the Standard Deviation instead of the Standard Error. With such a framework sample size will have no impact on your statistical significance. Using Effect Size will also tend to move you away from p values and towards Confidence Intervals which can be more meaningful in plain English. | Statistical test for a value being significantly further from the population mean: is it a Z-test or | You raise an interesting question. First thing first, if you have an observation of 0.35, a mean of 0.25, and a standard deviation of 1/10^7 (that's how I interpret your e^-7 bit) you really don't ne | Statistical test for a value being significantly further from the population mean: is it a Z-test or a T-test?
You raise an interesting question. First thing first, if you have an observation of 0.35, a mean of 0.25, and a standard deviation of 1/10^7 (that's how I interpret your e^-7 bit) you really don't need to go into any hypothesis testing exercise. Your 0.35 observation is very different than the mean of 0.25 given that it will be several thousands standard deviation away from the mean and it will probably be several millions standard errors from the mean.
The difference between the Z-test and the t-test refers mainly to sample size. With samples smaller than 120, you should use the t-test to calculate p values. When sample sizes are greater than that, it does not make much difference if at all which one you use. It is fun to calculate it both ways regardless of sample size and observe how little difference there is between the two tests.
As far as calculating things yourself, you can calculate the t stat by dividing the difference between your observation and the mean and divide that by the standard error. The standard error is the standard deviation divided by the square root of the sample size. Now, you have your t stat. To calculate a p value I think there is no alternative than to look up your t value within a t test table. If you accept a simple Excel alternative TDIST(t stat value, DF, 1 or 2 for 1 or 2 tail p value) does the trick. To calculate a p value using Z, the Excel formula for a 1 tail test is: (1 - NORMSDIST (Z value). The Z value being the same as the t stat (or the number of standard error away from the mean).
Just as a caveat, those methods of hypothesis testing can get distorted by sample size. In other words, the larger your sample size the smaller your standard error, the higher your resulting Z value or t stat, the lower the p value, and the higher your statistical significance. As a short cut in this logic, large sample sizes will result in high statistical significance. But, high statistical significance in association with large sample size can be completely immaterial. In other words, statistically significant is a mathematical phrase. It does not necessarily mean significant (per Webster dictionary).
To get away from this large sample size trap, statisticians have moved on to Effect Size methods. The latter use as a unit of statistical distance between two observations the Standard Deviation instead of the Standard Error. With such a framework sample size will have no impact on your statistical significance. Using Effect Size will also tend to move you away from p values and towards Confidence Intervals which can be more meaningful in plain English. | Statistical test for a value being significantly further from the population mean: is it a Z-test or
You raise an interesting question. First thing first, if you have an observation of 0.35, a mean of 0.25, and a standard deviation of 1/10^7 (that's how I interpret your e^-7 bit) you really don't ne |
20,140 | Statistical test for a value being significantly further from the population mean: is it a Z-test or a T-test? | Hypothesis testing always refers to the population. If you want to make a statement about the sample, you do not need to test (just compare what you see).
Frequentists believe in asymptotics, so as long as your sample size is big, do not worry about the distribution of your data.
Z-test and T-test do basically the same in terms of calculating the test statistic, just the critical values are obtained from different distributions (Normal vs Student-T). If your sample size is large, the difference is marginal.
Regarding Q1: Just look it up from the T-distribution with n-1 degrees of freedom, where n is the sample size.
Regarding Q2: You compute the threshold based on your desired significance level for a Z-test, and based on significance level on sample size in case of the T-Test. | Statistical test for a value being significantly further from the population mean: is it a Z-test or | Hypothesis testing always refers to the population. If you want to make a statement about the sample, you do not need to test (just compare what you see).
Frequentists believe in asymptotics, so as lo | Statistical test for a value being significantly further from the population mean: is it a Z-test or a T-test?
Hypothesis testing always refers to the population. If you want to make a statement about the sample, you do not need to test (just compare what you see).
Frequentists believe in asymptotics, so as long as your sample size is big, do not worry about the distribution of your data.
Z-test and T-test do basically the same in terms of calculating the test statistic, just the critical values are obtained from different distributions (Normal vs Student-T). If your sample size is large, the difference is marginal.
Regarding Q1: Just look it up from the T-distribution with n-1 degrees of freedom, where n is the sample size.
Regarding Q2: You compute the threshold based on your desired significance level for a Z-test, and based on significance level on sample size in case of the T-Test. | Statistical test for a value being significantly further from the population mean: is it a Z-test or
Hypothesis testing always refers to the population. If you want to make a statement about the sample, you do not need to test (just compare what you see).
Frequentists believe in asymptotics, so as lo |
20,141 | Etymology of "t" in t-test and t-distribution | It appears to have been done by Fisher as he was developing a more general theory of testing, although perhaps by Student in a letter to Fisher a couple of years before. Originally Student denoted it by $z$, although it wasn't actually in its current form at that time (that had to wait for Fisher.) If you have access, The American Statistician (1979) has a paper on this. If you don't, some brief comments are in http://jeff560.tripod.com/s.html. | Etymology of "t" in t-test and t-distribution | It appears to have been done by Fisher as he was developing a more general theory of testing, although perhaps by Student in a letter to Fisher a couple of years before. Originally Student denoted it | Etymology of "t" in t-test and t-distribution
It appears to have been done by Fisher as he was developing a more general theory of testing, although perhaps by Student in a letter to Fisher a couple of years before. Originally Student denoted it by $z$, although it wasn't actually in its current form at that time (that had to wait for Fisher.) If you have access, The American Statistician (1979) has a paper on this. If you don't, some brief comments are in http://jeff560.tripod.com/s.html. | Etymology of "t" in t-test and t-distribution
It appears to have been done by Fisher as he was developing a more general theory of testing, although perhaps by Student in a letter to Fisher a couple of years before. Originally Student denoted it |
20,142 | Etymology of "t" in t-test and t-distribution | According to H.A. David's paper linked here, "Student's t" and "t" were first used in R.A. Fisher's 1924 paper On a Distribution Yielding the Error Functions of Several Well Known Statistics. The first occurrence is on page 809 where we see Fisher refer to "Student's curves" and uses the variable t. | Etymology of "t" in t-test and t-distribution | According to H.A. David's paper linked here, "Student's t" and "t" were first used in R.A. Fisher's 1924 paper On a Distribution Yielding the Error Functions of Several Well Known Statistics. The fir | Etymology of "t" in t-test and t-distribution
According to H.A. David's paper linked here, "Student's t" and "t" were first used in R.A. Fisher's 1924 paper On a Distribution Yielding the Error Functions of Several Well Known Statistics. The first occurrence is on page 809 where we see Fisher refer to "Student's curves" and uses the variable t. | Etymology of "t" in t-test and t-distribution
According to H.A. David's paper linked here, "Student's t" and "t" were first used in R.A. Fisher's 1924 paper On a Distribution Yielding the Error Functions of Several Well Known Statistics. The fir |
20,143 | Etymology of "t" in t-test and t-distribution | I believe it's because "t" is the last letter of both Gossett and Student, which was his pen name. Why choose the last letter? Search me. | Etymology of "t" in t-test and t-distribution | I believe it's because "t" is the last letter of both Gossett and Student, which was his pen name. Why choose the last letter? Search me. | Etymology of "t" in t-test and t-distribution
I believe it's because "t" is the last letter of both Gossett and Student, which was his pen name. Why choose the last letter? Search me. | Etymology of "t" in t-test and t-distribution
I believe it's because "t" is the last letter of both Gossett and Student, which was his pen name. Why choose the last letter? Search me. |
20,144 | Illustrative datasets and analysis for multilevel modelling | You might want to check out the UCLA multilevel modelling resources.
For example, the UCLA site has
this page that includes datafiles and analysis for several examples from Snijders and Bosker using multiple analysis packages.
This copy of Harvey Goldstein's multilevel modelling text with data files | Illustrative datasets and analysis for multilevel modelling | You might want to check out the UCLA multilevel modelling resources.
For example, the UCLA site has
this page that includes datafiles and analysis for several examples from Snijders and Bosker using | Illustrative datasets and analysis for multilevel modelling
You might want to check out the UCLA multilevel modelling resources.
For example, the UCLA site has
this page that includes datafiles and analysis for several examples from Snijders and Bosker using multiple analysis packages.
This copy of Harvey Goldstein's multilevel modelling text with data files | Illustrative datasets and analysis for multilevel modelling
You might want to check out the UCLA multilevel modelling resources.
For example, the UCLA site has
this page that includes datafiles and analysis for several examples from Snijders and Bosker using |
20,145 | Illustrative datasets and analysis for multilevel modelling | Are you aware of the online resources at the MLwiN site? In particular their free online course. They go through examples in all three software packages you mention (R, Stata, and MLwiN of course), and provide datasets along with them.
One of the modules goes through multi-level models for binary responses, which it sounds like your project would entail.
Currently our mixed-model tag wiki has the community suggested readings for multi-level models. Although I couldn't say off-hand which of those books had accompanying data. | Illustrative datasets and analysis for multilevel modelling | Are you aware of the online resources at the MLwiN site? In particular their free online course. They go through examples in all three software packages you mention (R, Stata, and MLwiN of course), an | Illustrative datasets and analysis for multilevel modelling
Are you aware of the online resources at the MLwiN site? In particular their free online course. They go through examples in all three software packages you mention (R, Stata, and MLwiN of course), and provide datasets along with them.
One of the modules goes through multi-level models for binary responses, which it sounds like your project would entail.
Currently our mixed-model tag wiki has the community suggested readings for multi-level models. Although I couldn't say off-hand which of those books had accompanying data. | Illustrative datasets and analysis for multilevel modelling
Are you aware of the online resources at the MLwiN site? In particular their free online course. They go through examples in all three software packages you mention (R, Stata, and MLwiN of course), an |
20,146 | Illustrative datasets and analysis for multilevel modelling | Stata comes with a bunch of toy data sets that you can take a look at: File -> Example Data Sets -> Manual datasets -> [XT] -> there appears to be some biostat data under xtmepoisson and xtmixed. There are some examples on GLLAMM website with both code and data: http://gllamm.org/examples.html. | Illustrative datasets and analysis for multilevel modelling | Stata comes with a bunch of toy data sets that you can take a look at: File -> Example Data Sets -> Manual datasets -> [XT] -> there appears to be some biostat data under xtmepoisson and xtmixed. Ther | Illustrative datasets and analysis for multilevel modelling
Stata comes with a bunch of toy data sets that you can take a look at: File -> Example Data Sets -> Manual datasets -> [XT] -> there appears to be some biostat data under xtmepoisson and xtmixed. There are some examples on GLLAMM website with both code and data: http://gllamm.org/examples.html. | Illustrative datasets and analysis for multilevel modelling
Stata comes with a bunch of toy data sets that you can take a look at: File -> Example Data Sets -> Manual datasets -> [XT] -> there appears to be some biostat data under xtmepoisson and xtmixed. Ther |
20,147 | What are good resources providing a history of statistics? | Read Stephen Stigler's books, The History of Statistics and Statistics on the Table. This will give you an overview of the field from 1750 through about 1930. For pre-1750 history, Anders Hald is well known (but I haven't read his work).
The edited volumes of seminal papers, Breakthroughs in Statistics, provide reprints of key papers along with short introductions by eminent modern statisticians explaining the meaning and impacts of these papers.
There are incredible primary resources, especially in Europe, for researching statistical history, especially the more difficult-to-find sources prior to 1750. For example, you can find Fermat's collected works, Huygens' 17th century treatise on probability, and high-resolution scans of 16th and 15th century treatises, such as Tartagia's General trattato di numeri, et misure. Be prepared to read old French, old Italian, Latin, and even Dutch. (Those with a modest command of the modern versions of these languages won't have difficulties.)
Additional information can be obtained at the Journal for the History of Probability and Statistics and in early reviews of the history of probability and statistics. But your best bet is to search. Searches turned up all these resources several years ago, and several of them I had to search for again because their URLs had changed. | What are good resources providing a history of statistics? | Read Stephen Stigler's books, The History of Statistics and Statistics on the Table. This will give you an overview of the field from 1750 through about 1930. For pre-1750 history, Anders Hald is we | What are good resources providing a history of statistics?
Read Stephen Stigler's books, The History of Statistics and Statistics on the Table. This will give you an overview of the field from 1750 through about 1930. For pre-1750 history, Anders Hald is well known (but I haven't read his work).
The edited volumes of seminal papers, Breakthroughs in Statistics, provide reprints of key papers along with short introductions by eminent modern statisticians explaining the meaning and impacts of these papers.
There are incredible primary resources, especially in Europe, for researching statistical history, especially the more difficult-to-find sources prior to 1750. For example, you can find Fermat's collected works, Huygens' 17th century treatise on probability, and high-resolution scans of 16th and 15th century treatises, such as Tartagia's General trattato di numeri, et misure. Be prepared to read old French, old Italian, Latin, and even Dutch. (Those with a modest command of the modern versions of these languages won't have difficulties.)
Additional information can be obtained at the Journal for the History of Probability and Statistics and in early reviews of the history of probability and statistics. But your best bet is to search. Searches turned up all these resources several years ago, and several of them I had to search for again because their URLs had changed. | What are good resources providing a history of statistics?
Read Stephen Stigler's books, The History of Statistics and Statistics on the Table. This will give you an overview of the field from 1750 through about 1930. For pre-1750 history, Anders Hald is we |
20,148 | What are good resources providing a history of statistics? | David Salsburg "The Lady Tasting Tea: How Statistics Revolutionized Science in the Twentieth Century" is an easy and entertaining read. It might not be focused on breakthroughs per se, but it tells the story featuring the Pearsons, Gosset, Fisher, Neyman and others. | What are good resources providing a history of statistics? | David Salsburg "The Lady Tasting Tea: How Statistics Revolutionized Science in the Twentieth Century" is an easy and entertaining read. It might not be focused on breakthroughs per se, but it tells th | What are good resources providing a history of statistics?
David Salsburg "The Lady Tasting Tea: How Statistics Revolutionized Science in the Twentieth Century" is an easy and entertaining read. It might not be focused on breakthroughs per se, but it tells the story featuring the Pearsons, Gosset, Fisher, Neyman and others. | What are good resources providing a history of statistics?
David Salsburg "The Lady Tasting Tea: How Statistics Revolutionized Science in the Twentieth Century" is an easy and entertaining read. It might not be focused on breakthroughs per se, but it tells th |
20,149 | What are good resources providing a history of statistics? | I recommend the work of Stephen Stigler. | What are good resources providing a history of statistics? | I recommend the work of Stephen Stigler. | What are good resources providing a history of statistics?
I recommend the work of Stephen Stigler. | What are good resources providing a history of statistics?
I recommend the work of Stephen Stigler. |
20,150 | What are good resources providing a history of statistics? | In addition to Stigler's excellent work, there is a book The Science of Conjecture: Evidence and Probability before Pascal by James Franklin; very interesting, less technical than Stigler's books, at least in part because the material wasn't as technical. | What are good resources providing a history of statistics? | In addition to Stigler's excellent work, there is a book The Science of Conjecture: Evidence and Probability before Pascal by James Franklin; very interesting, less technical than Stigler's books, at | What are good resources providing a history of statistics?
In addition to Stigler's excellent work, there is a book The Science of Conjecture: Evidence and Probability before Pascal by James Franklin; very interesting, less technical than Stigler's books, at least in part because the material wasn't as technical. | What are good resources providing a history of statistics?
In addition to Stigler's excellent work, there is a book The Science of Conjecture: Evidence and Probability before Pascal by James Franklin; very interesting, less technical than Stigler's books, at |
20,151 | What are good resources providing a history of statistics? | The Politics of Large Numbers: A History of Statistical Reasoning By Alain Desrosières.
It covers a wide range of topics, in several countries (France, Germany, Great-Britain, United States), from the 17th/18th centuries to about 1970-1980: the history of institutions collecting and treating statistical data, how statistical methods evolved (probabilities, central limit theorem, regression, survey methodology...), the influence of political or social considerations (epidemics, poverty, unemployment, eugenics...), etc.
It was originally published in 1993 in French, and later translated in English. The most recent edition in French is from 2010, and apparently 2002 for the edition in English. | What are good resources providing a history of statistics? | The Politics of Large Numbers: A History of Statistical Reasoning By Alain Desrosières.
It covers a wide range of topics, in several countries (France, Germany, Great-Britain, United States), from the | What are good resources providing a history of statistics?
The Politics of Large Numbers: A History of Statistical Reasoning By Alain Desrosières.
It covers a wide range of topics, in several countries (France, Germany, Great-Britain, United States), from the 17th/18th centuries to about 1970-1980: the history of institutions collecting and treating statistical data, how statistical methods evolved (probabilities, central limit theorem, regression, survey methodology...), the influence of political or social considerations (epidemics, poverty, unemployment, eugenics...), etc.
It was originally published in 1993 in French, and later translated in English. The most recent edition in French is from 2010, and apparently 2002 for the edition in English. | What are good resources providing a history of statistics?
The Politics of Large Numbers: A History of Statistical Reasoning By Alain Desrosières.
It covers a wide range of topics, in several countries (France, Germany, Great-Britain, United States), from the |
20,152 | What is the Bayesian counterpart to a two-sample t-test with unequal variances? | While you can do this in a Bayesian way, have you considered whether it would actually be better to estimate the difference in the means rather than test whether they are different? This is what Andrew Gelman frequently recommends. I can imagine some possible reasons for wanting to do hypothesis testing, but I don't think they're that common.
I don't think you need something like a t-test, because you can estimate the standard deviation well because you said the groups have very similar standard deviations.
If that's the case then I think this link should be what you need. It shows how to estimate a difference in means or do a hypothesis test (though I don't recommend this). You could also take a look at the part they reference in bolstad's book (you can find electronic copies online). Its possible to incorporate estimating the variances as well but it's more complex, so I suspect you're better off incorporating the prior information you have about the variances in a naive way (for example, using the unbiased Stdev estimator on each of the sets and then averaging them and pretending those are your 'known' stdevs). | What is the Bayesian counterpart to a two-sample t-test with unequal variances? | While you can do this in a Bayesian way, have you considered whether it would actually be better to estimate the difference in the means rather than test whether they are different? This is what Andre | What is the Bayesian counterpart to a two-sample t-test with unequal variances?
While you can do this in a Bayesian way, have you considered whether it would actually be better to estimate the difference in the means rather than test whether they are different? This is what Andrew Gelman frequently recommends. I can imagine some possible reasons for wanting to do hypothesis testing, but I don't think they're that common.
I don't think you need something like a t-test, because you can estimate the standard deviation well because you said the groups have very similar standard deviations.
If that's the case then I think this link should be what you need. It shows how to estimate a difference in means or do a hypothesis test (though I don't recommend this). You could also take a look at the part they reference in bolstad's book (you can find electronic copies online). Its possible to incorporate estimating the variances as well but it's more complex, so I suspect you're better off incorporating the prior information you have about the variances in a naive way (for example, using the unbiased Stdev estimator on each of the sets and then averaging them and pretending those are your 'known' stdevs). | What is the Bayesian counterpart to a two-sample t-test with unequal variances?
While you can do this in a Bayesian way, have you considered whether it would actually be better to estimate the difference in the means rather than test whether they are different? This is what Andre |
20,153 | What is the Bayesian counterpart to a two-sample t-test with unequal variances? | John Kruschke has developed a Bayesian routine that is meant as a drop in replacement for the two-sample t-test. The routine is called BEST (Bayesian Estimation Supersedes the T-test) and is described here. I also made an online javascript version that runs in the browser available here. | What is the Bayesian counterpart to a two-sample t-test with unequal variances? | John Kruschke has developed a Bayesian routine that is meant as a drop in replacement for the two-sample t-test. The routine is called BEST (Bayesian Estimation Supersedes the T-test) and is described | What is the Bayesian counterpart to a two-sample t-test with unequal variances?
John Kruschke has developed a Bayesian routine that is meant as a drop in replacement for the two-sample t-test. The routine is called BEST (Bayesian Estimation Supersedes the T-test) and is described here. I also made an online javascript version that runs in the browser available here. | What is the Bayesian counterpart to a two-sample t-test with unequal variances?
John Kruschke has developed a Bayesian routine that is meant as a drop in replacement for the two-sample t-test. The routine is called BEST (Bayesian Estimation Supersedes the T-test) and is described |
20,154 | How to quickly sample X if exp(X) ~ Gamma? | Consider a small shape parameter $\alpha$ near 0, such as $\alpha = 1/100$. In the range between 0 and $\alpha$, $e^{-\alpha}$ is approximately $1$, so the Gamma pdf is approximately $x^{\alpha-1}dx / \Gamma(\alpha)$. This can be integrated to an approximate CDF, $F_\alpha(x) = \frac{x^\alpha}{\alpha \Gamma(\alpha)}$. Inverting it, we see a $1/\alpha$ power: a huge exponent. For $\alpha = 1/100$ this causes some chance of underflow (a double precision value less than $10^{-300}$, more or less). Here is a plot of the chance of getting underflow as a function of the base-ten logarithm of $\alpha$:
One solution is to exploit this approximation for generating log(Gamma) variates: in effect, try to generate a Gamma variate and if it's too small, generate its logarithm from this approximate power distribution (as shown below). (Do this repeatedly until the log is within the underflow range, so that it is a valid substitute for the original underflowing variate.) For the Dirichlet calculation, subtract the maximum of all the logarithms from each of the log values: this implicitly rescales all the Gamma variates so it won't affect the Dirichlet values. Treat any resulting log that is too small (say, less than -100) as being the log of a true zero. Exponentiate the other logs. Now you can proceed without underflow.
This is going to take even longer than before, but at least it will work!
To generate an approximate log Gamma variate with shape parameter $\alpha$, precompute $C = \log(\Gamma(\alpha)) + \log(\alpha)$. This is easy, because there are algorithms to compute values of log Gamma directly. Generate a uniform random float between 0 and 1, take its logarithm, divide by $\alpha$, and add $C$ to it.
Because the scale parameter merely rescales the variate, there is no problem accommodating it in these procedures. You don't even need it if all scale parameters are the same.
Edit
In another reply the OP describes a method in which the $1/\alpha$ power of a uniform variate (a $B(\alpha)$ variate) is multiplied by a $\Gamma(\alpha+1)$ variate. This works because the pdf of the joint distribution of these two variates equals $\left(\alpha x^{\alpha-1}\right) \left(y^{\alpha}e^{-y}dy/\Gamma(\alpha+1)\right)$. To find the pdf of $z = xy$ we substitute $y \to z/x$, divide by the Jacobean $x$, and integrate out $x$. The integral must range from $z$ to $\infty$ because $0 \le y \le 1$, whence
$$\text{pdf}(z)=\frac{\alpha}{\Gamma(\alpha+1)}\int_z^{\infty}{\left(x^\alpha / x\right) e^{-x} (z/x)^{\alpha-1} dx} dz = \frac{1}{\Gamma(\alpha)}z^{\alpha-1}e^{-z}dz,$$
which is the pdf of a $\Gamma(\alpha)$ distribution.
The whole point is that when $0 \lt \alpha \lt 1$, a value drawn from $\Gamma(\alpha+1)$ is unlikely to underflow and by summing its log and $1/\alpha$ times the log of an independent uniform variate we will have the log of a $\Gamma(\alpha)$ variate. The log is likely to be very negative, but we will have bypassed the construction of its antilog, which will underflow in a floating point representation. | How to quickly sample X if exp(X) ~ Gamma? | Consider a small shape parameter $\alpha$ near 0, such as $\alpha = 1/100$. In the range between 0 and $\alpha$, $e^{-\alpha}$ is approximately $1$, so the Gamma pdf is approximately $x^{\alpha-1}dx | How to quickly sample X if exp(X) ~ Gamma?
Consider a small shape parameter $\alpha$ near 0, such as $\alpha = 1/100$. In the range between 0 and $\alpha$, $e^{-\alpha}$ is approximately $1$, so the Gamma pdf is approximately $x^{\alpha-1}dx / \Gamma(\alpha)$. This can be integrated to an approximate CDF, $F_\alpha(x) = \frac{x^\alpha}{\alpha \Gamma(\alpha)}$. Inverting it, we see a $1/\alpha$ power: a huge exponent. For $\alpha = 1/100$ this causes some chance of underflow (a double precision value less than $10^{-300}$, more or less). Here is a plot of the chance of getting underflow as a function of the base-ten logarithm of $\alpha$:
One solution is to exploit this approximation for generating log(Gamma) variates: in effect, try to generate a Gamma variate and if it's too small, generate its logarithm from this approximate power distribution (as shown below). (Do this repeatedly until the log is within the underflow range, so that it is a valid substitute for the original underflowing variate.) For the Dirichlet calculation, subtract the maximum of all the logarithms from each of the log values: this implicitly rescales all the Gamma variates so it won't affect the Dirichlet values. Treat any resulting log that is too small (say, less than -100) as being the log of a true zero. Exponentiate the other logs. Now you can proceed without underflow.
This is going to take even longer than before, but at least it will work!
To generate an approximate log Gamma variate with shape parameter $\alpha$, precompute $C = \log(\Gamma(\alpha)) + \log(\alpha)$. This is easy, because there are algorithms to compute values of log Gamma directly. Generate a uniform random float between 0 and 1, take its logarithm, divide by $\alpha$, and add $C$ to it.
Because the scale parameter merely rescales the variate, there is no problem accommodating it in these procedures. You don't even need it if all scale parameters are the same.
Edit
In another reply the OP describes a method in which the $1/\alpha$ power of a uniform variate (a $B(\alpha)$ variate) is multiplied by a $\Gamma(\alpha+1)$ variate. This works because the pdf of the joint distribution of these two variates equals $\left(\alpha x^{\alpha-1}\right) \left(y^{\alpha}e^{-y}dy/\Gamma(\alpha+1)\right)$. To find the pdf of $z = xy$ we substitute $y \to z/x$, divide by the Jacobean $x$, and integrate out $x$. The integral must range from $z$ to $\infty$ because $0 \le y \le 1$, whence
$$\text{pdf}(z)=\frac{\alpha}{\Gamma(\alpha+1)}\int_z^{\infty}{\left(x^\alpha / x\right) e^{-x} (z/x)^{\alpha-1} dx} dz = \frac{1}{\Gamma(\alpha)}z^{\alpha-1}e^{-z}dz,$$
which is the pdf of a $\Gamma(\alpha)$ distribution.
The whole point is that when $0 \lt \alpha \lt 1$, a value drawn from $\Gamma(\alpha+1)$ is unlikely to underflow and by summing its log and $1/\alpha$ times the log of an independent uniform variate we will have the log of a $\Gamma(\alpha)$ variate. The log is likely to be very negative, but we will have bypassed the construction of its antilog, which will underflow in a floating point representation. | How to quickly sample X if exp(X) ~ Gamma?
Consider a small shape parameter $\alpha$ near 0, such as $\alpha = 1/100$. In the range between 0 and $\alpha$, $e^{-\alpha}$ is approximately $1$, so the Gamma pdf is approximately $x^{\alpha-1}dx |
20,155 | How to quickly sample X if exp(X) ~ Gamma? | I'm answering my own question, but I found a pretty good solution, even if I do not fully understand it. Looking at the code from the GNU Scientific Library, here is how it samples gamma variables (r is the random number generator, a is $\alpha$ and b is $\beta$):
if (a < 1)
{
double u = gsl_rng_uniform_pos (r);
return gsl_ran_gamma (r, 1.0 + a, b) * pow (u, 1.0 / a);
}
gsl_ran_gamma is the function which returns a gamma random sample (so the above is a recursive call), while gsl_rng_uniform_pos returns a uniformly distributed number in $(0,1)$ (the _pos is for strictly positive as it is guaranteed to not return 0.0).
Therefore, I can take the log of the last expression and use
return log(gsl_ran_gamma(r, 1.0 + a, b)) + log(u)/a;
To get what I wanted. I now have two log() calls (but one less pow()), but the result is probably better. Before, as whuber pointed out, I had something raised to the power of $1/a$, potentially a huge number. Now, in logspace, I'm multiplying by $1/a$. So, it is less likely to underflow. | How to quickly sample X if exp(X) ~ Gamma? | I'm answering my own question, but I found a pretty good solution, even if I do not fully understand it. Looking at the code from the GNU Scientific Library, here is how it samples gamma variables (r | How to quickly sample X if exp(X) ~ Gamma?
I'm answering my own question, but I found a pretty good solution, even if I do not fully understand it. Looking at the code from the GNU Scientific Library, here is how it samples gamma variables (r is the random number generator, a is $\alpha$ and b is $\beta$):
if (a < 1)
{
double u = gsl_rng_uniform_pos (r);
return gsl_ran_gamma (r, 1.0 + a, b) * pow (u, 1.0 / a);
}
gsl_ran_gamma is the function which returns a gamma random sample (so the above is a recursive call), while gsl_rng_uniform_pos returns a uniformly distributed number in $(0,1)$ (the _pos is for strictly positive as it is guaranteed to not return 0.0).
Therefore, I can take the log of the last expression and use
return log(gsl_ran_gamma(r, 1.0 + a, b)) + log(u)/a;
To get what I wanted. I now have two log() calls (but one less pow()), but the result is probably better. Before, as whuber pointed out, I had something raised to the power of $1/a$, potentially a huge number. Now, in logspace, I'm multiplying by $1/a$. So, it is less likely to underflow. | How to quickly sample X if exp(X) ~ Gamma?
I'm answering my own question, but I found a pretty good solution, even if I do not fully understand it. Looking at the code from the GNU Scientific Library, here is how it samples gamma variables (r |
20,156 | GLMNET or LARS for computing LASSO solutions? | In my experience, LARS is faster for small problems, very sparse problems, or very 'wide' problems (much much more features than samples). Indeed, its computational cost is limited by the number of features selected, if you don't compute the full regularization path. On the other hand, for big problems, glmnet (coordinate descent optimization) is faster. Amongst other things, coordinate descent has a good data access pattern (memory-friendly) and it can benefit from redundancy in the data on very large datasets, as it converges with partial fits. In particular, it does not suffer from heavily correlated datasets.
The conclusion that we (the core developers of the scikit-learn) have come too is that, if you do not have strong a priori knowledge of your data, you should rather use glmnet (or coordinate descent optimization, to talk about an algorithm rather than an implementation).
Interesting benchmarks may be compared in Julien Mairal's thesis:
https://lear.inrialpes.fr/people/mairal/resources/pdf/phd_thesis.pdf
Section 1.4, in particular 1.4.5 (page 22)
Julien comes to slightly different conclusions, although his analysis of the problem is similar. I suspect this is because he was very much interested in very wide problems. | GLMNET or LARS for computing LASSO solutions? | In my experience, LARS is faster for small problems, very sparse problems, or very 'wide' problems (much much more features than samples). Indeed, its computational cost is limited by the number of fe | GLMNET or LARS for computing LASSO solutions?
In my experience, LARS is faster for small problems, very sparse problems, or very 'wide' problems (much much more features than samples). Indeed, its computational cost is limited by the number of features selected, if you don't compute the full regularization path. On the other hand, for big problems, glmnet (coordinate descent optimization) is faster. Amongst other things, coordinate descent has a good data access pattern (memory-friendly) and it can benefit from redundancy in the data on very large datasets, as it converges with partial fits. In particular, it does not suffer from heavily correlated datasets.
The conclusion that we (the core developers of the scikit-learn) have come too is that, if you do not have strong a priori knowledge of your data, you should rather use glmnet (or coordinate descent optimization, to talk about an algorithm rather than an implementation).
Interesting benchmarks may be compared in Julien Mairal's thesis:
https://lear.inrialpes.fr/people/mairal/resources/pdf/phd_thesis.pdf
Section 1.4, in particular 1.4.5 (page 22)
Julien comes to slightly different conclusions, although his analysis of the problem is similar. I suspect this is because he was very much interested in very wide problems. | GLMNET or LARS for computing LASSO solutions?
In my experience, LARS is faster for small problems, very sparse problems, or very 'wide' problems (much much more features than samples). Indeed, its computational cost is limited by the number of fe |
20,157 | GLMNET or LARS for computing LASSO solutions? | LASSO is non-unique in the case where multiple features have perfect collinearity. Here's a simple thought experiment to prove it.
Let's say you have three random vectors $y$, $x_1$, $x_2$. You're trying to predict $y$ from $x_1$, $x_2$. Now assume $y$ = $x1$ = $x2$. An optimal LASSO solution would be $\beta_1 = 1 - P$, $\beta_2 = 0$, where $P$ is the effect of LASSO penalty. However, also optimal would be $\beta_1 = 0$, $\beta_2 - 1 - P$. | GLMNET or LARS for computing LASSO solutions? | LASSO is non-unique in the case where multiple features have perfect collinearity. Here's a simple thought experiment to prove it.
Let's say you have three random vectors $y$, $x_1$, $x_2$. You're | GLMNET or LARS for computing LASSO solutions?
LASSO is non-unique in the case where multiple features have perfect collinearity. Here's a simple thought experiment to prove it.
Let's say you have three random vectors $y$, $x_1$, $x_2$. You're trying to predict $y$ from $x_1$, $x_2$. Now assume $y$ = $x1$ = $x2$. An optimal LASSO solution would be $\beta_1 = 1 - P$, $\beta_2 = 0$, where $P$ is the effect of LASSO penalty. However, also optimal would be $\beta_1 = 0$, $\beta_2 - 1 - P$. | GLMNET or LARS for computing LASSO solutions?
LASSO is non-unique in the case where multiple features have perfect collinearity. Here's a simple thought experiment to prove it.
Let's say you have three random vectors $y$, $x_1$, $x_2$. You're |
20,158 | GLMNET or LARS for computing LASSO solutions? | Lars and Glmnet give different solutions for the Lasso problem, as they use slightly different objective functions and different standartisations of the data. You can find details code for reproduction in the related question Why do Lars and Glmnet give different solutions for the Lasso problem? | GLMNET or LARS for computing LASSO solutions? | Lars and Glmnet give different solutions for the Lasso problem, as they use slightly different objective functions and different standartisations of the data. You can find details code for reproductio | GLMNET or LARS for computing LASSO solutions?
Lars and Glmnet give different solutions for the Lasso problem, as they use slightly different objective functions and different standartisations of the data. You can find details code for reproduction in the related question Why do Lars and Glmnet give different solutions for the Lasso problem? | GLMNET or LARS for computing LASSO solutions?
Lars and Glmnet give different solutions for the Lasso problem, as they use slightly different objective functions and different standartisations of the data. You can find details code for reproductio |
20,159 | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$? | My first attempt at an answer was flawed (see below for the flawed answer). The reason it is flawed is that the margin of error (MOE) that is reported applies to a candidate's polling percentage but not to the difference of the percentages. My second attempt explicitly addresses the question posed by the OP a bit better.
Second Attempt
The OP's friend reasons as follows:
Construct the confidence interval for Candidate A and Candidate B separately using the given MOE.
If they overlap we have a statistical dead hear and if they do not then A is currently leading B.
The main issue here is that the first step is invalid. Constructing confidence intervals independently for the two candidates is not a valid step because the polling percentages for the two candidates are dependent random variables. In other words, a voter who decides not to vote for A may potentially decide to vote for B instead. Thus, the correct way to assess if the lead is significant or not is to construct a confidence interval for the difference. See the wiki as to how to compute the standard error for the difference of polling percentages under some assumptions.
Flawed answer below
In my opinion the 'correct' way to think of the polling result is as follows:
In a survey of 500 voters the chances that we will see a difference in lead as high as 8% is greater than 5%.
Whether you believe that 'A leads B' or 'A ties B' is then dependent on the extent to which you are willing to accept 5% as your cut-off criteria. | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$? | My first attempt at an answer was flawed (see below for the flawed answer). The reason it is flawed is that the margin of error (MOE) that is reported applies to a candidate's polling percentage but n | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$?
My first attempt at an answer was flawed (see below for the flawed answer). The reason it is flawed is that the margin of error (MOE) that is reported applies to a candidate's polling percentage but not to the difference of the percentages. My second attempt explicitly addresses the question posed by the OP a bit better.
Second Attempt
The OP's friend reasons as follows:
Construct the confidence interval for Candidate A and Candidate B separately using the given MOE.
If they overlap we have a statistical dead hear and if they do not then A is currently leading B.
The main issue here is that the first step is invalid. Constructing confidence intervals independently for the two candidates is not a valid step because the polling percentages for the two candidates are dependent random variables. In other words, a voter who decides not to vote for A may potentially decide to vote for B instead. Thus, the correct way to assess if the lead is significant or not is to construct a confidence interval for the difference. See the wiki as to how to compute the standard error for the difference of polling percentages under some assumptions.
Flawed answer below
In my opinion the 'correct' way to think of the polling result is as follows:
In a survey of 500 voters the chances that we will see a difference in lead as high as 8% is greater than 5%.
Whether you believe that 'A leads B' or 'A ties B' is then dependent on the extent to which you are willing to accept 5% as your cut-off criteria. | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$?
My first attempt at an answer was flawed (see below for the flawed answer). The reason it is flawed is that the margin of error (MOE) that is reported applies to a candidate's polling percentage but n |
20,160 | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$? | Itβs easier to explain in terms of standard deviations, rather than confidence intervals.
Your friendβs conclusion is basically correct under the simplest model where you have simple random sampling and two candidates. Now the sample proportions satisfy $p_A + p_B = 1$ so that $p_B = 1 - p_A$. Thus,
$$Var(p_A - p_B) = Var(2 p_A - 1) = 4 Var(p_A)$$
and so
$$SD(p_A - p_B) = 2 SD(p_A).$$
What makes this simple relationship possible is that $p_A$ and $p_B$ are perfectly negatively correlated, because in general
$$Var(p_A - p_B) = Var(p_A) + Var(p_B) - 2 Cov(p_A, p_B).$$
Outside this simple model, if $p_A + p_B = 1$ does not hold in general, then you must take into account the correlation between $p_A$ and $p_B$ that is not included in the margin of error. It is possible for $SD(p_A - p_B) \ll 2 SD(p_A)$.
But all this nuance seems to indicate that the polling organizations should report the margin of error on the difference. Whereβs Nate Silver? | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$? | Itβs easier to explain in terms of standard deviations, rather than confidence intervals.
Your friendβs conclusion is basically correct under the simplest model where you have simple random sampling a | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$?
Itβs easier to explain in terms of standard deviations, rather than confidence intervals.
Your friendβs conclusion is basically correct under the simplest model where you have simple random sampling and two candidates. Now the sample proportions satisfy $p_A + p_B = 1$ so that $p_B = 1 - p_A$. Thus,
$$Var(p_A - p_B) = Var(2 p_A - 1) = 4 Var(p_A)$$
and so
$$SD(p_A - p_B) = 2 SD(p_A).$$
What makes this simple relationship possible is that $p_A$ and $p_B$ are perfectly negatively correlated, because in general
$$Var(p_A - p_B) = Var(p_A) + Var(p_B) - 2 Cov(p_A, p_B).$$
Outside this simple model, if $p_A + p_B = 1$ does not hold in general, then you must take into account the correlation between $p_A$ and $p_B$ that is not included in the margin of error. It is possible for $SD(p_A - p_B) \ll 2 SD(p_A)$.
But all this nuance seems to indicate that the polling organizations should report the margin of error on the difference. Whereβs Nate Silver? | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$?
Itβs easier to explain in terms of standard deviations, rather than confidence intervals.
Your friendβs conclusion is basically correct under the simplest model where you have simple random sampling a |
20,161 | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$? | Not only is that a bad way to term things but that's not even a statistical dead heat.
You don't use overlapping confidence intervals that way. If you really wanted to only say that Candidate A was going to win then Candidate A is definitely in the lead. The lead is 8% MOE 6.4%. The confidence interval of that subtraction score is not double the confidence interval of the individual scores. Which is implied by claiming the overlap of CIs (Β±MOE) around each estimate is a dead heat. Assuming equal N and variance, the MOE of the difference is sqrt(2) times 4.5. That's because finding the difference between the values would only double the variance (SD squared). The confidence interval is based on a sqrt of the variance therefore combining them is the average (4.5) * sqrt(2). Since the MOE of your 8% lead is approximately 6.4% then Candidate A is in the lead.
As an aside, MOE's are very conservative and based on the 50% choice value. The formula is sqrt(0.25/n) * 2. There is a formula for calculating standard errors of difference scores that we could use as well. We would apply that using the found values rather than the 50% cutoff and that still gives us a significant lead for Candidate A (7.5% MOE). I believe that, given the questioners comment, and the proximity of that cutoff to the hypothetical one selected, that that was probably what they were looking for.
Any introduction to both confidence intervals and to power would be helpful here. Even the wikipedia article on MOE looks pretty good. | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$? | Not only is that a bad way to term things but that's not even a statistical dead heat.
You don't use overlapping confidence intervals that way. If you really wanted to only say that Candidate A was go | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$?
Not only is that a bad way to term things but that's not even a statistical dead heat.
You don't use overlapping confidence intervals that way. If you really wanted to only say that Candidate A was going to win then Candidate A is definitely in the lead. The lead is 8% MOE 6.4%. The confidence interval of that subtraction score is not double the confidence interval of the individual scores. Which is implied by claiming the overlap of CIs (Β±MOE) around each estimate is a dead heat. Assuming equal N and variance, the MOE of the difference is sqrt(2) times 4.5. That's because finding the difference between the values would only double the variance (SD squared). The confidence interval is based on a sqrt of the variance therefore combining them is the average (4.5) * sqrt(2). Since the MOE of your 8% lead is approximately 6.4% then Candidate A is in the lead.
As an aside, MOE's are very conservative and based on the 50% choice value. The formula is sqrt(0.25/n) * 2. There is a formula for calculating standard errors of difference scores that we could use as well. We would apply that using the found values rather than the 50% cutoff and that still gives us a significant lead for Candidate A (7.5% MOE). I believe that, given the questioners comment, and the proximity of that cutoff to the hypothetical one selected, that that was probably what they were looking for.
Any introduction to both confidence intervals and to power would be helpful here. Even the wikipedia article on MOE looks pretty good. | Can you explain why statistical tie is not naively rejected when $p_1-p_2 < 2 \,\text {MOE}$?
Not only is that a bad way to term things but that's not even a statistical dead heat.
You don't use overlapping confidence intervals that way. If you really wanted to only say that Candidate A was go |
20,162 | Does p-value ever depend on the alternative? | The alternative hypothesis affects the test through the evidentiary ordering
The p-value of a classical hypothesis test depends on the alternative hypothesis only through the evidentiary ordering constructed for the test, which is what tells you what constitutes an "extreme" observation. Any hypothesis test involves specification of an evidentiary ordering which is a total order on the set of all possible outcomes of the observable data. This evidentiary ordering specifies which outcomes are more conducive to the null or alternative hypotheses respectively. Often this ordering is implicit on having defined a "test statistic" for the test, but the only role of the test statistic is to represent this ordering.
Hypothesis testing via an evidentiary ordering: Suppose we want to create a hypothesis test for an unknown parameter $\theta \in \Theta$ using an observable random vector $\mathbf{X} \in \mathscr{X}$ with a distribution that depends on this parameter. For any stipulated null space $\Theta_0$ and alternative space $\Theta_A$ (and any particular logic for how the test works) we contruct a total order $\succeq$ on the outcome space $\mathscr{X}$. The interpretation of the total order is:
$$\mathbf{x} \succeq \mathbf{x}'
\quad \quad \iff \quad \quad
\mathbf{x} \text{ is at least as conducive to } H_A \text{ as } \mathbf{x}'.$$
For brevity, we sometimes say that $\mathbf{x} \succeq \mathbf{x}'$ means that $\mathbf{x}$ is at least as "extreme" as $\mathbf{x}'$. This is a common shorthand, which is okay if you remember that "extreme" means "conducive to the alternative hypothesis" in this context. In practice, the evidentiary ordering for the sample space is often set implicitly by constructing a test statistic and having an ordering for the test statistic.$^\dagger$ This is essentially just the same thing, but removed one-level of abstraction away from the sample space. Now, having set the evidentiary ordering for the test, the p-value function is then defined as:
$$p(\mathbf{x}) \equiv \sup_{\theta \in \Theta_0} \mathbb{P}(\mathbf{X} \succeq \mathbf{x} | \theta)
\quad \quad \quad
\text{for all } \mathbf{x} \in \mathscr{X}.$$
If we denote the probabilistic model by $\mathbb{M} \equiv \{ \mathbb{P}(\cdot | \theta) | \theta \in \Theta \}$ then we can write the p-value function as a function $p = f(\mathbb{M}, \Theta_0, \succeq)$. We can see that the p-value function is fully determined by the model $\mathbb{M}$, the null space $\Theta_0$ and the evidentiary ordering $\succeq$. Observe that the alternative hypothesis only affects this function through its contribution to the evidentiary ordering.
The structure of a classical hypothesis test is shown in the diagram below. This diagram illustrates the elements of the test that lead to the p-value function, which ultimately defines the test. As can be seen in the diagram, the alternative hypothesis has a limited role; combined with the logic of the test it affects the evidentiary ordering for the test, which then flows into determination of the p-value function.
$^\dagger$ Often the evidentiary ordering is set implicitly using a test statistic $T: \mathscr{X} \rightarrow \mathbb{R}$ and then using the ordering defined by the correspondence $\mathbf{x}_0 \succeq \mathbf{x}_1
\iff
T(\mathbf{x}_0) \geqslant T(\mathbf{x}_1)$. In this case the p-value reduces to $p(\mathbf{x}) = \sup_{\theta \in \Theta_0} \mathbb{P}(T(\mathbf{X}) \geqslant T(\mathbf{x}) | \theta)$. | Does p-value ever depend on the alternative? | The alternative hypothesis affects the test through the evidentiary ordering
The p-value of a classical hypothesis test depends on the alternative hypothesis only through the evidentiary ordering cons | Does p-value ever depend on the alternative?
The alternative hypothesis affects the test through the evidentiary ordering
The p-value of a classical hypothesis test depends on the alternative hypothesis only through the evidentiary ordering constructed for the test, which is what tells you what constitutes an "extreme" observation. Any hypothesis test involves specification of an evidentiary ordering which is a total order on the set of all possible outcomes of the observable data. This evidentiary ordering specifies which outcomes are more conducive to the null or alternative hypotheses respectively. Often this ordering is implicit on having defined a "test statistic" for the test, but the only role of the test statistic is to represent this ordering.
Hypothesis testing via an evidentiary ordering: Suppose we want to create a hypothesis test for an unknown parameter $\theta \in \Theta$ using an observable random vector $\mathbf{X} \in \mathscr{X}$ with a distribution that depends on this parameter. For any stipulated null space $\Theta_0$ and alternative space $\Theta_A$ (and any particular logic for how the test works) we contruct a total order $\succeq$ on the outcome space $\mathscr{X}$. The interpretation of the total order is:
$$\mathbf{x} \succeq \mathbf{x}'
\quad \quad \iff \quad \quad
\mathbf{x} \text{ is at least as conducive to } H_A \text{ as } \mathbf{x}'.$$
For brevity, we sometimes say that $\mathbf{x} \succeq \mathbf{x}'$ means that $\mathbf{x}$ is at least as "extreme" as $\mathbf{x}'$. This is a common shorthand, which is okay if you remember that "extreme" means "conducive to the alternative hypothesis" in this context. In practice, the evidentiary ordering for the sample space is often set implicitly by constructing a test statistic and having an ordering for the test statistic.$^\dagger$ This is essentially just the same thing, but removed one-level of abstraction away from the sample space. Now, having set the evidentiary ordering for the test, the p-value function is then defined as:
$$p(\mathbf{x}) \equiv \sup_{\theta \in \Theta_0} \mathbb{P}(\mathbf{X} \succeq \mathbf{x} | \theta)
\quad \quad \quad
\text{for all } \mathbf{x} \in \mathscr{X}.$$
If we denote the probabilistic model by $\mathbb{M} \equiv \{ \mathbb{P}(\cdot | \theta) | \theta \in \Theta \}$ then we can write the p-value function as a function $p = f(\mathbb{M}, \Theta_0, \succeq)$. We can see that the p-value function is fully determined by the model $\mathbb{M}$, the null space $\Theta_0$ and the evidentiary ordering $\succeq$. Observe that the alternative hypothesis only affects this function through its contribution to the evidentiary ordering.
The structure of a classical hypothesis test is shown in the diagram below. This diagram illustrates the elements of the test that lead to the p-value function, which ultimately defines the test. As can be seen in the diagram, the alternative hypothesis has a limited role; combined with the logic of the test it affects the evidentiary ordering for the test, which then flows into determination of the p-value function.
$^\dagger$ Often the evidentiary ordering is set implicitly using a test statistic $T: \mathscr{X} \rightarrow \mathbb{R}$ and then using the ordering defined by the correspondence $\mathbf{x}_0 \succeq \mathbf{x}_1
\iff
T(\mathbf{x}_0) \geqslant T(\mathbf{x}_1)$. In this case the p-value reduces to $p(\mathbf{x}) = \sup_{\theta \in \Theta_0} \mathbb{P}(T(\mathbf{X}) \geqslant T(\mathbf{x}) | \theta)$. | Does p-value ever depend on the alternative?
The alternative hypothesis affects the test through the evidentiary ordering
The p-value of a classical hypothesis test depends on the alternative hypothesis only through the evidentiary ordering cons |
20,163 | Does p-value ever depend on the alternative? | The test statistic ($t$ in your example) and all calculations to reach that point depend only on the null hypothesis $H_0$ and nothing else.
The p-value is affected by the alternative hypothesis $H_1$ as the $H_1$ identifies which values are considered as "extreme" values and the p-value calculates the proximity of the final result (your $t$) to those values.
For instance, in your example of $H_0$ vs $H_1'$ you would reject $H_0$ only if $t>T_\alpha$ and for the example $H_0$ vs $H_1$ you would reject $H_0$ only if $t>T_{\alpha/2}$ or $t<-T_{\alpha/2}$.
Thus the p-value of $H_0$ vs $H_1$ would be the probability of the union of two sets whereas the $H_0$ vs $H_1'$ would be the probability of one set where the cut-off point is higher on the x-axis compared to the previous case.
EDIT: In response to what you mentioned about Fisher, I believe you are referring to the famous lady testing test. Which indeed doesn't have a strictly speaking alternative hypothesis but it is slightly different compared to the hypothesis tests that we usually conduct.
In this example, he only defined the null hypothesis $H_0$: She has no ability to distinguish the tea and he used the combination formula to measure the probability of all possible outcomes given that $H_0$ is true which is essentially the p-value of each data point.
The main difference/trick here that you might be looking for is that in Fisher's eyes, it would only take one incorrect guess to make her a liar and thus he wanted to identify the smallest amount of cups that he needs to give her to taste. In a sense, one might say that he tested the $H_1:$At least one incorrect guess and he looked for the smallest possible sample size for some pre-defined parameters.
This is a slightly different case to the way we usually conduct statistical hypothesis tests as we take sample from a population and we usually "allow" some non-$H_0$ cases. I guess the final answer to your question is that we want an $H_1$ or at least a "loose-definition" of it in order to define what are the "extreme-departures" from the $H_0$ (Even if you are Fisher and you hide it well enough).
Really good question by the way :) | Does p-value ever depend on the alternative? | The test statistic ($t$ in your example) and all calculations to reach that point depend only on the null hypothesis $H_0$ and nothing else.
The p-value is affected by the alternative hypothesis $H_1$ | Does p-value ever depend on the alternative?
The test statistic ($t$ in your example) and all calculations to reach that point depend only on the null hypothesis $H_0$ and nothing else.
The p-value is affected by the alternative hypothesis $H_1$ as the $H_1$ identifies which values are considered as "extreme" values and the p-value calculates the proximity of the final result (your $t$) to those values.
For instance, in your example of $H_0$ vs $H_1'$ you would reject $H_0$ only if $t>T_\alpha$ and for the example $H_0$ vs $H_1$ you would reject $H_0$ only if $t>T_{\alpha/2}$ or $t<-T_{\alpha/2}$.
Thus the p-value of $H_0$ vs $H_1$ would be the probability of the union of two sets whereas the $H_0$ vs $H_1'$ would be the probability of one set where the cut-off point is higher on the x-axis compared to the previous case.
EDIT: In response to what you mentioned about Fisher, I believe you are referring to the famous lady testing test. Which indeed doesn't have a strictly speaking alternative hypothesis but it is slightly different compared to the hypothesis tests that we usually conduct.
In this example, he only defined the null hypothesis $H_0$: She has no ability to distinguish the tea and he used the combination formula to measure the probability of all possible outcomes given that $H_0$ is true which is essentially the p-value of each data point.
The main difference/trick here that you might be looking for is that in Fisher's eyes, it would only take one incorrect guess to make her a liar and thus he wanted to identify the smallest amount of cups that he needs to give her to taste. In a sense, one might say that he tested the $H_1:$At least one incorrect guess and he looked for the smallest possible sample size for some pre-defined parameters.
This is a slightly different case to the way we usually conduct statistical hypothesis tests as we take sample from a population and we usually "allow" some non-$H_0$ cases. I guess the final answer to your question is that we want an $H_1$ or at least a "loose-definition" of it in order to define what are the "extreme-departures" from the $H_0$ (Even if you are Fisher and you hide it well enough).
Really good question by the way :) | Does p-value ever depend on the alternative?
The test statistic ($t$ in your example) and all calculations to reach that point depend only on the null hypothesis $H_0$ and nothing else.
The p-value is affected by the alternative hypothesis $H_1$ |
20,164 | Does p-value ever depend on the alternative? | Here's how I see it.
Generally, the p-value is the probability, under the null hypothesis, to observe a result that is as far or farther away from what would be "typical" under the null hypothesis.
This is informal and imprecise, and in fact decisions need to be made in order to make this precise.
What needs to be chosen is a test statistic, and "far or farther away" needs to be defined. One way of doing this is to specify an alternative, and to ask, how does a test need to look like in order to achieve optimal power under the alternative while respecting the nominal level under the null hypothesis? This is Neyman and Pearson's approach to construct tests. Given the test statistic and the "direction" of the alternative (one-sided or two-sided, although in principle more complex "direction definitions" are conceivable), the p-value is computed using the null hypothesis and not the alternative. However the alternative has its impact through the determination of test statistic and direction.
Alternatively (!) one can choose the test statistic without specifying an alternative based on a (usually heuristic) idea of how to measure "closeness" to the null hypothesis (e.g., Kolmogorov-Smirnov or $\chi^2$-distance from the hypothesised distribution), preferably in such a way that the distribution of the test statistic under the null can be specified. This also requires a "direction", but this seems often trivial (e.g., large KS-distance => evidence against the null). In this case one could argue that there is no alternative and therefore no impact of the alternative on the p-value. One could however also say that a test constructed in this way implicitly defines an alternative, namely "all distributions that tend to generate test statistic values in the rejection direction".
As an example, consider the KS-test for normality. Though counter-intuitive at first sight, it is conceivable to reject normality in case of a too small KS-distance, which makes sense in an application in which it is suspected that researchers faked data in order to make them look "perfectly normal". The alternative to i.i.d. normality is then implicitly the family of distributions that tend to generate samples that look more normal than i.i.d. normal samples, for example because observations are dependent in such a way that a small KS-distance is enforced.
The p-value is then different from the standard KS-test. Not sure whether you'd say "this is because it depends on the alternative" because all these choices could be made without explicitly specifying an alternative, however it can for sure be related to the concept of an "implicit alternative" defined by the test. | Does p-value ever depend on the alternative? | Here's how I see it.
Generally, the p-value is the probability, under the null hypothesis, to observe a result that is as far or farther away from what would be "typical" under the null hypothesis.
Th | Does p-value ever depend on the alternative?
Here's how I see it.
Generally, the p-value is the probability, under the null hypothesis, to observe a result that is as far or farther away from what would be "typical" under the null hypothesis.
This is informal and imprecise, and in fact decisions need to be made in order to make this precise.
What needs to be chosen is a test statistic, and "far or farther away" needs to be defined. One way of doing this is to specify an alternative, and to ask, how does a test need to look like in order to achieve optimal power under the alternative while respecting the nominal level under the null hypothesis? This is Neyman and Pearson's approach to construct tests. Given the test statistic and the "direction" of the alternative (one-sided or two-sided, although in principle more complex "direction definitions" are conceivable), the p-value is computed using the null hypothesis and not the alternative. However the alternative has its impact through the determination of test statistic and direction.
Alternatively (!) one can choose the test statistic without specifying an alternative based on a (usually heuristic) idea of how to measure "closeness" to the null hypothesis (e.g., Kolmogorov-Smirnov or $\chi^2$-distance from the hypothesised distribution), preferably in such a way that the distribution of the test statistic under the null can be specified. This also requires a "direction", but this seems often trivial (e.g., large KS-distance => evidence against the null). In this case one could argue that there is no alternative and therefore no impact of the alternative on the p-value. One could however also say that a test constructed in this way implicitly defines an alternative, namely "all distributions that tend to generate test statistic values in the rejection direction".
As an example, consider the KS-test for normality. Though counter-intuitive at first sight, it is conceivable to reject normality in case of a too small KS-distance, which makes sense in an application in which it is suspected that researchers faked data in order to make them look "perfectly normal". The alternative to i.i.d. normality is then implicitly the family of distributions that tend to generate samples that look more normal than i.i.d. normal samples, for example because observations are dependent in such a way that a small KS-distance is enforced.
The p-value is then different from the standard KS-test. Not sure whether you'd say "this is because it depends on the alternative" because all these choices could be made without explicitly specifying an alternative, however it can for sure be related to the concept of an "implicit alternative" defined by the test. | Does p-value ever depend on the alternative?
Here's how I see it.
Generally, the p-value is the probability, under the null hypothesis, to observe a result that is as far or farther away from what would be "typical" under the null hypothesis.
Th |
20,165 | Does p-value ever depend on the alternative? | My direct answer to the question is that p-values clearly do not depend on the alternative hypothesis, as the alternative is not present in the calculations, but at the same time p-values are dependent on the alternative hypothesis insofar as a one-tailed p-value is different from a two-tailed p-value and we typically use the alternative hypothesis to specify the number of tails.
The difficulties here might be the result of some standard shortcomings of statistical description and definition and so I will address those as I unpack the direct answer a bit.
βHypothesisβ
What is a hypothesis for the purposes of a significance test? Itβs what I call a βstatistical hypothesisβ rather than a hypothesis regarding the real world. To make that distinction clear, consider the hypothesis that the sun rises in the east because of the way that the Earth rotates around its north-south axis. That hypothesis is not one that can be plugged into a t-test, for example. Now consider the hypothesis that the mean number of bubbles in a typical pint of Guinness stout brewed with yeast A is equal to the number of bubbles in a typical pint Guinness brewed with yeast B. That hypothesis can be treated a statistical hypothesis that can be evaluated using a t-test because counts of bubbles from multiple pints can be converted into an observed value of the test statistic, t.
A statistical hypothesis is nothing more than a point or a region within the parameter space of the statistical model chosen for the analysis. For the t-test, the null hypothesis is present in the calculation of the t-value (although it is frequently omitted from textbook formulas, with dire consequences!). Letβs use $\bar{x}_A$ to be the mean of the first group of bubble counts and $\bar{x}_B$ to be the mean of the second, $SED$ to be the standard error of the difference between those means, and $\delta_0$ to be the null hypothesis. The calculation of the observed t-value is then
$$t=\frac{(\bar{x}_A-\bar{x}_A)-\delta_0}{SED}$$
Yes, in this case $\delta_0$ is zero and so it can be left out of the formula without changing the numerical result, but it should never be omitted for two reasons: explicitness helps to reduce confusion, and the null hypothesis is not always zero (the dreaded βnill-nullβ) and so it cannot always be omitted!
The p-value is determined by finding the extremity of the observed t-value compared to the distribution of Studentβs t, and so that equation demonstrates immediately that the p-value depends on the null hypothesis. The absence of the alternative hypothesis similarly demonstrates the irrelevance of the alternative to the p-value. (Yes, itβs relevance is still to come, read on.)
In the previous paragraph I rely on the undefined βextremityβ to do a lot of work and so I need to unpack it a bit. I will say initially that it is the statistical model that defines what is meant by extreme, and it does that by providing a theoretical sampling distribution of the test statistic against which the observed value of test statistic can be calibrated. If the observed test statistic value falls near the centre of that distribution then it is not extreme, but if it falls towards one or other edge of the distribution then it is extreme in some proportion to the nearness to the edge. (Iβm deliberately ignoring the complications of multimodal distributions, and of two-tailed p-value because the evidential interpretation of a neo-Fisherian p-value is assisted by the routine use of one-tailed p-values.)
One way to express the extremeness of an observed test statistic is as the integral of the sampling distribution from the observed value out to the end. That integral is a probability and hence the usual definition of a p-value as a probability. However, because some of the most damaging misconceptions about p-values relate to (or depend on) its probabilistic nature, it can be helpful to think of a p-value as a fractional ranking of extremeness rather than a probability of observing something more extreme. Iβll use a simple permutations test to illustrate that idea.
To perform a permutations test you delineate all possible arrangements of the data (with the statistical model being no more than the assumption of data exchangeability under the null hypothesis), and order those arrangements according to their corresponding test statistic values. (The test statistic is commonly the means, but can be the medians or any other interesting statistic calculated from each data arrangement.) Those ordered values of test statistic define the test statistic sampling distribution under the null hypothesis according to the model.
To get the p-value you simply determine the numerical rank of the test statistic value for the observed data arrangement within that distribution, and divide that rank by the total number of possible arrangements to get the p-value. In other words, the p-value is a fractional ranking and encodes how strange it would be to obtain the observed data arrangement according to the model if the null hypothesis is true.
Alternative hypothesis
There are two different alternative hypotheses that need to be considered. The first is the specific effect size that serves as the alternative hypothesis during the planning stage of a hypothesis test (e.g. the effect size to be plugged into the calculation of statistical power that can be used for sample size determination). That pre-data alternative has no effect on the data actually observed and hence no effect on the observed p-value.
The other alternative hypothesis is the one that the original question refers to. It is the complement of the null hypothesis and, given that a p-value depends on the null hypothesis, one might reasonably consider the p-value also depends on the alternative. However, I prefer to think that it is the null hypothesis that is doing the work, partly because the null appears (should appear!) in the formulation of a test statistic, but also because the alternative hypothesis is usually a range (or ranges) of parameter values in the statistical model whereas the null is usually a single point. | Does p-value ever depend on the alternative? | My direct answer to the question is that p-values clearly do not depend on the alternative hypothesis, as the alternative is not present in the calculations, but at the same time p-values are dependen | Does p-value ever depend on the alternative?
My direct answer to the question is that p-values clearly do not depend on the alternative hypothesis, as the alternative is not present in the calculations, but at the same time p-values are dependent on the alternative hypothesis insofar as a one-tailed p-value is different from a two-tailed p-value and we typically use the alternative hypothesis to specify the number of tails.
The difficulties here might be the result of some standard shortcomings of statistical description and definition and so I will address those as I unpack the direct answer a bit.
βHypothesisβ
What is a hypothesis for the purposes of a significance test? Itβs what I call a βstatistical hypothesisβ rather than a hypothesis regarding the real world. To make that distinction clear, consider the hypothesis that the sun rises in the east because of the way that the Earth rotates around its north-south axis. That hypothesis is not one that can be plugged into a t-test, for example. Now consider the hypothesis that the mean number of bubbles in a typical pint of Guinness stout brewed with yeast A is equal to the number of bubbles in a typical pint Guinness brewed with yeast B. That hypothesis can be treated a statistical hypothesis that can be evaluated using a t-test because counts of bubbles from multiple pints can be converted into an observed value of the test statistic, t.
A statistical hypothesis is nothing more than a point or a region within the parameter space of the statistical model chosen for the analysis. For the t-test, the null hypothesis is present in the calculation of the t-value (although it is frequently omitted from textbook formulas, with dire consequences!). Letβs use $\bar{x}_A$ to be the mean of the first group of bubble counts and $\bar{x}_B$ to be the mean of the second, $SED$ to be the standard error of the difference between those means, and $\delta_0$ to be the null hypothesis. The calculation of the observed t-value is then
$$t=\frac{(\bar{x}_A-\bar{x}_A)-\delta_0}{SED}$$
Yes, in this case $\delta_0$ is zero and so it can be left out of the formula without changing the numerical result, but it should never be omitted for two reasons: explicitness helps to reduce confusion, and the null hypothesis is not always zero (the dreaded βnill-nullβ) and so it cannot always be omitted!
The p-value is determined by finding the extremity of the observed t-value compared to the distribution of Studentβs t, and so that equation demonstrates immediately that the p-value depends on the null hypothesis. The absence of the alternative hypothesis similarly demonstrates the irrelevance of the alternative to the p-value. (Yes, itβs relevance is still to come, read on.)
In the previous paragraph I rely on the undefined βextremityβ to do a lot of work and so I need to unpack it a bit. I will say initially that it is the statistical model that defines what is meant by extreme, and it does that by providing a theoretical sampling distribution of the test statistic against which the observed value of test statistic can be calibrated. If the observed test statistic value falls near the centre of that distribution then it is not extreme, but if it falls towards one or other edge of the distribution then it is extreme in some proportion to the nearness to the edge. (Iβm deliberately ignoring the complications of multimodal distributions, and of two-tailed p-value because the evidential interpretation of a neo-Fisherian p-value is assisted by the routine use of one-tailed p-values.)
One way to express the extremeness of an observed test statistic is as the integral of the sampling distribution from the observed value out to the end. That integral is a probability and hence the usual definition of a p-value as a probability. However, because some of the most damaging misconceptions about p-values relate to (or depend on) its probabilistic nature, it can be helpful to think of a p-value as a fractional ranking of extremeness rather than a probability of observing something more extreme. Iβll use a simple permutations test to illustrate that idea.
To perform a permutations test you delineate all possible arrangements of the data (with the statistical model being no more than the assumption of data exchangeability under the null hypothesis), and order those arrangements according to their corresponding test statistic values. (The test statistic is commonly the means, but can be the medians or any other interesting statistic calculated from each data arrangement.) Those ordered values of test statistic define the test statistic sampling distribution under the null hypothesis according to the model.
To get the p-value you simply determine the numerical rank of the test statistic value for the observed data arrangement within that distribution, and divide that rank by the total number of possible arrangements to get the p-value. In other words, the p-value is a fractional ranking and encodes how strange it would be to obtain the observed data arrangement according to the model if the null hypothesis is true.
Alternative hypothesis
There are two different alternative hypotheses that need to be considered. The first is the specific effect size that serves as the alternative hypothesis during the planning stage of a hypothesis test (e.g. the effect size to be plugged into the calculation of statistical power that can be used for sample size determination). That pre-data alternative has no effect on the data actually observed and hence no effect on the observed p-value.
The other alternative hypothesis is the one that the original question refers to. It is the complement of the null hypothesis and, given that a p-value depends on the null hypothesis, one might reasonably consider the p-value also depends on the alternative. However, I prefer to think that it is the null hypothesis that is doing the work, partly because the null appears (should appear!) in the formulation of a test statistic, but also because the alternative hypothesis is usually a range (or ranges) of parameter values in the statistical model whereas the null is usually a single point. | Does p-value ever depend on the alternative?
My direct answer to the question is that p-values clearly do not depend on the alternative hypothesis, as the alternative is not present in the calculations, but at the same time p-values are dependen |
20,166 | Does p-value ever depend on the alternative? | The reason that results in the wrong direction donβt give small p-values is because they provide terrible evidence in favor of the alternative. Imagine a null hypothesis of a fair coin and an alternative of a bias towards heads. You then flip the coin 100 times and get 99 tails. You have terrible evidence in favor of your alternative hypothesis.
This can apply in other settings. Think of an F-test comparing the variances of two distributions. If you think the distribution with its variance on top has higher variance but wind up with a variance ratio $<1$, you have rather poor evidence that the distribution on top has higher variance than the distribution on the bottom.
$$F_0=s_1^2/s_2^2$$
If $s_1^2<s_2^2$, your evidence is quite poor that $\sigma_1^2>\sigma_2^2$. | Does p-value ever depend on the alternative? | The reason that results in the wrong direction donβt give small p-values is because they provide terrible evidence in favor of the alternative. Imagine a null hypothesis of a fair coin and an alternat | Does p-value ever depend on the alternative?
The reason that results in the wrong direction donβt give small p-values is because they provide terrible evidence in favor of the alternative. Imagine a null hypothesis of a fair coin and an alternative of a bias towards heads. You then flip the coin 100 times and get 99 tails. You have terrible evidence in favor of your alternative hypothesis.
This can apply in other settings. Think of an F-test comparing the variances of two distributions. If you think the distribution with its variance on top has higher variance but wind up with a variance ratio $<1$, you have rather poor evidence that the distribution on top has higher variance than the distribution on the bottom.
$$F_0=s_1^2/s_2^2$$
If $s_1^2<s_2^2$, your evidence is quite poor that $\sigma_1^2>\sigma_2^2$. | Does p-value ever depend on the alternative?
The reason that results in the wrong direction donβt give small p-values is because they provide terrible evidence in favor of the alternative. Imagine a null hypothesis of a fair coin and an alternat |
20,167 | When is NHST appropriate in business? | I will respond to this both as an economist/econometrician and as a decades-long business professional in the private sector.
1) As another answer noted, we should separate in our minds "statistical significance" from "economic significance" (the "size" aspect of the situation).
2) Statistical significance depends on the "amount of risk of being wrong one is willing to take". The established scientific tradition is to be "as conservative and guarded as possible" against claims that a significant difference does exist. This is reflected in the standard 1%, 5%, 10% "significance levels" one is taught to use when running significance testing. But businesses may very well want/decide to accept much more of such risk, so you can go ahead an run significance testing at a any level of significance you choose, say, 40%.
3) Classical statistics and expected values are more suited to decisions about mid-term / repetitive situations. In businesses, we have to make many short-term/one-off decisions. Then, the Baeysian approach to inference may be more well suited, and also, it may make more sense to consider the "most likely" outcomes rather than "expected values".
4) Cost considerations should of course enter a bushiness decision. This boils down to model correctly your loss/payoff function. In traditional statistical testing, the loss/payoff function is implicitly assumed to be symmetric around "zero-difference", because the object of science is accuracy itself, and so the direction of inaccuracy does not matter. But in economic activity such symmetries in costs/payoffs are rarely the case. See my two answers in this post as well as this post. | When is NHST appropriate in business? | I will respond to this both as an economist/econometrician and as a decades-long business professional in the private sector.
1) As another answer noted, we should separate in our minds "statistical s | When is NHST appropriate in business?
I will respond to this both as an economist/econometrician and as a decades-long business professional in the private sector.
1) As another answer noted, we should separate in our minds "statistical significance" from "economic significance" (the "size" aspect of the situation).
2) Statistical significance depends on the "amount of risk of being wrong one is willing to take". The established scientific tradition is to be "as conservative and guarded as possible" against claims that a significant difference does exist. This is reflected in the standard 1%, 5%, 10% "significance levels" one is taught to use when running significance testing. But businesses may very well want/decide to accept much more of such risk, so you can go ahead an run significance testing at a any level of significance you choose, say, 40%.
3) Classical statistics and expected values are more suited to decisions about mid-term / repetitive situations. In businesses, we have to make many short-term/one-off decisions. Then, the Baeysian approach to inference may be more well suited, and also, it may make more sense to consider the "most likely" outcomes rather than "expected values".
4) Cost considerations should of course enter a bushiness decision. This boils down to model correctly your loss/payoff function. In traditional statistical testing, the loss/payoff function is implicitly assumed to be symmetric around "zero-difference", because the object of science is accuracy itself, and so the direction of inaccuracy does not matter. But in economic activity such symmetries in costs/payoffs are rarely the case. See my two answers in this post as well as this post. | When is NHST appropriate in business?
I will respond to this both as an economist/econometrician and as a decades-long business professional in the private sector.
1) As another answer noted, we should separate in our minds "statistical s |
20,168 | When is NHST appropriate in business? | Your concerns are completely legitimate.
1) This gets to the effect size. Given enough data, we can detect tiny differences. However, all we are concluding from getting FROM $\mu_X - \mu_Y = 0.0000001\ne0$ is that the difference between the two means is not zero. While we may be very confident in that conclusion, we reserve the right to say, "Yeah, but we aren't interested in a difference that small."
2) I disagree here. The population with the lower mean may exhibit a higher sample mean. In fact, I will give you an R simulation showing how common this is.
set.seed(2019)
V <- rep(NA,2500)
for (i in 1:length(V)){
x <- rnorm(25,0,1)
y <- rnorm(25,0.25,1)
V[i] <- mean(x) - mean(y)
}
length(V[V>0])/length(V)*100
We expect the entries of V to be less than zero, since the population mean of $Y$ is greater than the population mean of $X$ (0.25 versus 0). However, this simulation gives me $\bar{x} > \bar{y}$ in 19.08% of the cases. In other words, your plan would result in the worse approach being implemented about a fifth of the time. Perhaps you are willing to take that risk, and there are quantitative ways to defend this stance, but you should be aware that it is common. | When is NHST appropriate in business? | Your concerns are completely legitimate.
1) This gets to the effect size. Given enough data, we can detect tiny differences. However, all we are concluding from getting FROM $\mu_X - \mu_Y = 0.0000001 | When is NHST appropriate in business?
Your concerns are completely legitimate.
1) This gets to the effect size. Given enough data, we can detect tiny differences. However, all we are concluding from getting FROM $\mu_X - \mu_Y = 0.0000001\ne0$ is that the difference between the two means is not zero. While we may be very confident in that conclusion, we reserve the right to say, "Yeah, but we aren't interested in a difference that small."
2) I disagree here. The population with the lower mean may exhibit a higher sample mean. In fact, I will give you an R simulation showing how common this is.
set.seed(2019)
V <- rep(NA,2500)
for (i in 1:length(V)){
x <- rnorm(25,0,1)
y <- rnorm(25,0.25,1)
V[i] <- mean(x) - mean(y)
}
length(V[V>0])/length(V)*100
We expect the entries of V to be less than zero, since the population mean of $Y$ is greater than the population mean of $X$ (0.25 versus 0). However, this simulation gives me $\bar{x} > \bar{y}$ in 19.08% of the cases. In other words, your plan would result in the worse approach being implemented about a fifth of the time. Perhaps you are willing to take that risk, and there are quantitative ways to defend this stance, but you should be aware that it is common. | When is NHST appropriate in business?
Your concerns are completely legitimate.
1) This gets to the effect size. Given enough data, we can detect tiny differences. However, all we are concluding from getting FROM $\mu_X - \mu_Y = 0.0000001 |
20,169 | When is NHST appropriate in business? | The concerns are legitimate but I do not think that statistical testing is the end all-be all of decisions in actual business practice. Statistics, correctly used, merely helps frame the information that is available for decision making. As already mentioned, effect-size is a good way of visualizing what it is that you are actually buying when you make a decision to change because you rejected the null hypothesis. Deciding whether or not it is worth it at this point is something that may no longer involve statistics. | When is NHST appropriate in business? | The concerns are legitimate but I do not think that statistical testing is the end all-be all of decisions in actual business practice. Statistics, correctly used, merely helps frame the information t | When is NHST appropriate in business?
The concerns are legitimate but I do not think that statistical testing is the end all-be all of decisions in actual business practice. Statistics, correctly used, merely helps frame the information that is available for decision making. As already mentioned, effect-size is a good way of visualizing what it is that you are actually buying when you make a decision to change because you rejected the null hypothesis. Deciding whether or not it is worth it at this point is something that may no longer involve statistics. | When is NHST appropriate in business?
The concerns are legitimate but I do not think that statistical testing is the end all-be all of decisions in actual business practice. Statistics, correctly used, merely helps frame the information t |
20,170 | How should I standardize input when fine-tuning a CNN? | First of all, VGG-16 may not be the right architecture for you. It has been superseded by various architectures, of which the most commonly used in application is ResNet. However, if you have very few data, transfer learning on VGG-16 may be more efficient than on ResNet. Bottom line, use both and compare them on the validation test.
Coming to your point about standardization: it's true that Simonyan
& Zisserman didn't standardize the RGB intensities, but it's false that they didn't apply any other preprocessing: they applied significant data augmentation. See section 3.1 of their paper. You would need to apply the same data augmentation described there, to your training set.
If you choose to use a ResNet, you want to get this paper:
Han et al., Classification of the Clinical Images for Benign and Malignant Cutaneous Tumors Using a Deep Learning Algorithm, 2018
The model they use is ResNet-152: you might try with a smaller ResNet, if transfer-training for this one proves to be too much of a challenge. ResNets are so ubiquitous that you can find implementations of this architecture in basically all frameworks, e.g.
https://github.com/tensorflow/models/tree/master/official/resnet
https://github.com/pytorch/vision/tree/master/torchvision
https://github.com/keras-team/keras-applications
Standardization for a ResNet model
The paper above is behind a paywall (but I'm sure the authors will send you a copy, if you send them an email), so I cannot say for sure if they used standardization in this specific application: btw, note that they didn't just classify the skin lesion to be benign or malignant, but, to the best of my understanding, they classified it to one of 12 different classes. In general Best Practices for training ResNets do suggest to perform standardization. For example, among the BPs suggested in https://arxiv.org/pdf/1812.01187.pdf, we find:
Scale hue, saturation, and brightness with coefficients uniformly drawn from [0.6, 1.4]
Normalize RGB channels by subtracting 123.68, 116.779, 103.939 and dividing
by 58.393, 57.12, 57.375, respectively, which should be the sample mean & sample standard deviation of each channel, computed on the training set of the ISLVRC2012 dataset (a subset of ImageNet), which has 1.3 million images for training and 1000
classes.
Of course, if you plan to compare the results from the VGG-16 and the ResNet-152 (or ResNet-50: another commonly used ResNet model, which is less data-hungry than ResNet-152), you need to use the same standardization for both.
Concerning your second question (standardize the input relative to ImageNet and your dataset, only to ImageNet, or only to your dataset), option 3 is crazy, because when you feed new data to your NN, these data must be standardized too (since you standardized the training set, the weights of the NN after training are the "right ones" for standardized inputs). Now, to avoid test set leakage, the usual practice is to standardize new data using the sample mean (and sample standard deviation, if you're using ResNet-style normalization) computed on the training set (ISLVRC2012, in this case, because you did most of the training on it). Now, suppose you get a new skin sample image: you have to normalize it before feeding it to your NN. If you normalize it using sample mean & standard deviation based on your new dataset, you'll be doing something completely different from what you did during training, so I wouldn't expect the NN to work very well. When would option 3 make sense? In two cases: either when you train your NN from scratch on your new dataset, or when you unfreeze a lot of layers and retrain them. However, transfer learning is usually performed by unfreezing only the top layer of the NN (the softmax layer).
Choosing between option 1 and 2 depends on how large is your dataset wrt ImageNet (or to be precise, to the ISLVRC2012 dataset, the subset of ImageNet which has been used to train the ResNet), and how "extreme" in term of RGB values your images are wrt those of ISLVRC2012. I suggest you compute the sample mean and sample standard deviation for ISLVRC2012, and ISLVRC2012 + your train set. If, as I suppose, the difference is small, then just use the statistics computed on ISLVRC2012.
Standardization is not what you should really worry about
Finally, since you're doing transfer learning, it will be much more important to perform proper data augmentation, rather than to concentrate on the proper normalization. For obvious reasons, skin sample images will be scarce, and the dataset will be unbalanced (i.e., you will likely have much more images of benign lesions, than of malignant lesions). Since your question didn't ask about data augmentation, I won't touch the topic, but I suggest you read also:
https://www.nature.com/articles/nature21056
https://academic.oup.com/annonc/article/29/8/1836/5004443
https://www.jmir.org/2018/10/e11936
https://arxiv.org/pdf/1812.02316.pdf | How should I standardize input when fine-tuning a CNN? | First of all, VGG-16 may not be the right architecture for you. It has been superseded by various architectures, of which the most commonly used in application is ResNet. However, if you have very few | How should I standardize input when fine-tuning a CNN?
First of all, VGG-16 may not be the right architecture for you. It has been superseded by various architectures, of which the most commonly used in application is ResNet. However, if you have very few data, transfer learning on VGG-16 may be more efficient than on ResNet. Bottom line, use both and compare them on the validation test.
Coming to your point about standardization: it's true that Simonyan
& Zisserman didn't standardize the RGB intensities, but it's false that they didn't apply any other preprocessing: they applied significant data augmentation. See section 3.1 of their paper. You would need to apply the same data augmentation described there, to your training set.
If you choose to use a ResNet, you want to get this paper:
Han et al., Classification of the Clinical Images for Benign and Malignant Cutaneous Tumors Using a Deep Learning Algorithm, 2018
The model they use is ResNet-152: you might try with a smaller ResNet, if transfer-training for this one proves to be too much of a challenge. ResNets are so ubiquitous that you can find implementations of this architecture in basically all frameworks, e.g.
https://github.com/tensorflow/models/tree/master/official/resnet
https://github.com/pytorch/vision/tree/master/torchvision
https://github.com/keras-team/keras-applications
Standardization for a ResNet model
The paper above is behind a paywall (but I'm sure the authors will send you a copy, if you send them an email), so I cannot say for sure if they used standardization in this specific application: btw, note that they didn't just classify the skin lesion to be benign or malignant, but, to the best of my understanding, they classified it to one of 12 different classes. In general Best Practices for training ResNets do suggest to perform standardization. For example, among the BPs suggested in https://arxiv.org/pdf/1812.01187.pdf, we find:
Scale hue, saturation, and brightness with coefficients uniformly drawn from [0.6, 1.4]
Normalize RGB channels by subtracting 123.68, 116.779, 103.939 and dividing
by 58.393, 57.12, 57.375, respectively, which should be the sample mean & sample standard deviation of each channel, computed on the training set of the ISLVRC2012 dataset (a subset of ImageNet), which has 1.3 million images for training and 1000
classes.
Of course, if you plan to compare the results from the VGG-16 and the ResNet-152 (or ResNet-50: another commonly used ResNet model, which is less data-hungry than ResNet-152), you need to use the same standardization for both.
Concerning your second question (standardize the input relative to ImageNet and your dataset, only to ImageNet, or only to your dataset), option 3 is crazy, because when you feed new data to your NN, these data must be standardized too (since you standardized the training set, the weights of the NN after training are the "right ones" for standardized inputs). Now, to avoid test set leakage, the usual practice is to standardize new data using the sample mean (and sample standard deviation, if you're using ResNet-style normalization) computed on the training set (ISLVRC2012, in this case, because you did most of the training on it). Now, suppose you get a new skin sample image: you have to normalize it before feeding it to your NN. If you normalize it using sample mean & standard deviation based on your new dataset, you'll be doing something completely different from what you did during training, so I wouldn't expect the NN to work very well. When would option 3 make sense? In two cases: either when you train your NN from scratch on your new dataset, or when you unfreeze a lot of layers and retrain them. However, transfer learning is usually performed by unfreezing only the top layer of the NN (the softmax layer).
Choosing between option 1 and 2 depends on how large is your dataset wrt ImageNet (or to be precise, to the ISLVRC2012 dataset, the subset of ImageNet which has been used to train the ResNet), and how "extreme" in term of RGB values your images are wrt those of ISLVRC2012. I suggest you compute the sample mean and sample standard deviation for ISLVRC2012, and ISLVRC2012 + your train set. If, as I suppose, the difference is small, then just use the statistics computed on ISLVRC2012.
Standardization is not what you should really worry about
Finally, since you're doing transfer learning, it will be much more important to perform proper data augmentation, rather than to concentrate on the proper normalization. For obvious reasons, skin sample images will be scarce, and the dataset will be unbalanced (i.e., you will likely have much more images of benign lesions, than of malignant lesions). Since your question didn't ask about data augmentation, I won't touch the topic, but I suggest you read also:
https://www.nature.com/articles/nature21056
https://academic.oup.com/annonc/article/29/8/1836/5004443
https://www.jmir.org/2018/10/e11936
https://arxiv.org/pdf/1812.02316.pdf | How should I standardize input when fine-tuning a CNN?
First of all, VGG-16 may not be the right architecture for you. It has been superseded by various architectures, of which the most commonly used in application is ResNet. However, if you have very few |
20,171 | Why are random effects assumed to follow a normal distribution in (G)LMMs? | Some points:
The choice of a normal distribution for the random effects in linear mixed models (i.e., normally distributed) outcome is typically done for mathematical convenience. That is, the normal distribution of $[Y \mid b]$ works nicely with the normal distribution for the random effects $[b]$, and you get a marginal distribution that for the outcome $[Y]$ that is multivariate normal.
In that regard it helps to see a mixed model as a hierarchical Bayesian model. Namely, in the linear mixed model assuming a normal distribution for the random effects is a conjugate prior that gives you back a posterior in closed-form. Hence, you can do the same for other distributions. If you have Binomial outcome data, the conjugate prior for the random effects is a Beta distribution, and you get the Beta-Binomial model. Likewise if you have Poisson outcome data, the conjugate prior for the random effects is a Gamma distribution, and you get the Gamma-Poisson model. Just to make clear here that in the previously mentioned examples, the distribution of the random effects was on the scale of the mean of the outcome conditional on the random effects not on the scale of the linear predictor (e.g., in the Gamma-Poisson example, on the linear predictor scale the assumed distribution would be a log-Gamma distribution).
There is nothing stoping you changing the distribution. For example, in the linear mixed model you could use a Studentβs t distribution for the random effects, or in categorical outcomes to use a normal distribution. But then you lose the computational advantage of having a closed-form posterior. There is considerable literature looking into the impact of changing the random-effects distribution. Many people have proposed flexible models for it; for example, using splines or mixtures to be able to capture random-effects distributions that are multi-modal. However, the general consensus has been that the normal distribution works pretty well. Namely, even if you simulate data from a bimodal or skewed distribution for the random effects, and you assume in your mixed model that it is normal, the results (i.e., parameter estimates and standard errors) are almost identical to when you fit a flexible model that captures this distribution more appropriately.
Hence, the choice of the normal distribution has dominated, even though other options do exist. With regard to your point on whether the choice of a normal distribution is defensible for categorical data, as Ben mentioned, note that the distribution of the random effects is placed not on the outcome but rather on the transformed mean of the outcome. For example, for Poisson data you assume a normal distribution for the random effects for $\log(\mu)$ where $\mu$ denotes the expected counts of the outcome variable $Y$ which is the observed counts. | Why are random effects assumed to follow a normal distribution in (G)LMMs? | Some points:
The choice of a normal distribution for the random effects in linear mixed models (i.e., normally distributed) outcome is typically done for mathematical convenience. That is, the normal | Why are random effects assumed to follow a normal distribution in (G)LMMs?
Some points:
The choice of a normal distribution for the random effects in linear mixed models (i.e., normally distributed) outcome is typically done for mathematical convenience. That is, the normal distribution of $[Y \mid b]$ works nicely with the normal distribution for the random effects $[b]$, and you get a marginal distribution that for the outcome $[Y]$ that is multivariate normal.
In that regard it helps to see a mixed model as a hierarchical Bayesian model. Namely, in the linear mixed model assuming a normal distribution for the random effects is a conjugate prior that gives you back a posterior in closed-form. Hence, you can do the same for other distributions. If you have Binomial outcome data, the conjugate prior for the random effects is a Beta distribution, and you get the Beta-Binomial model. Likewise if you have Poisson outcome data, the conjugate prior for the random effects is a Gamma distribution, and you get the Gamma-Poisson model. Just to make clear here that in the previously mentioned examples, the distribution of the random effects was on the scale of the mean of the outcome conditional on the random effects not on the scale of the linear predictor (e.g., in the Gamma-Poisson example, on the linear predictor scale the assumed distribution would be a log-Gamma distribution).
There is nothing stoping you changing the distribution. For example, in the linear mixed model you could use a Studentβs t distribution for the random effects, or in categorical outcomes to use a normal distribution. But then you lose the computational advantage of having a closed-form posterior. There is considerable literature looking into the impact of changing the random-effects distribution. Many people have proposed flexible models for it; for example, using splines or mixtures to be able to capture random-effects distributions that are multi-modal. However, the general consensus has been that the normal distribution works pretty well. Namely, even if you simulate data from a bimodal or skewed distribution for the random effects, and you assume in your mixed model that it is normal, the results (i.e., parameter estimates and standard errors) are almost identical to when you fit a flexible model that captures this distribution more appropriately.
Hence, the choice of the normal distribution has dominated, even though other options do exist. With regard to your point on whether the choice of a normal distribution is defensible for categorical data, as Ben mentioned, note that the distribution of the random effects is placed not on the outcome but rather on the transformed mean of the outcome. For example, for Poisson data you assume a normal distribution for the random effects for $\log(\mu)$ where $\mu$ denotes the expected counts of the outcome variable $Y$ which is the observed counts. | Why are random effects assumed to follow a normal distribution in (G)LMMs?
Some points:
The choice of a normal distribution for the random effects in linear mixed models (i.e., normally distributed) outcome is typically done for mathematical convenience. That is, the normal |
20,172 | Is R-squared truly an invalid metric for non-linear models? | The sums-of-squares in linear regression are special cases of the more general deviance values in the generalised linear model. In the more general model there is a response distribution with mean linked to a linear function of the explanatory variables (with an intercept term). The three deviance statistics in a GLM are defined as:
$$\begin{matrix}
\text{Null Deviance} \quad \quad \text{ } \text{ } & & \text{ } D_{TOT} = 2(\hat{\ell}_{S} - \hat{\ell}_0), \\[6pt]
\text{Explained Deviance} & & D_{REG} = 2(\hat{\ell}_{p} - \hat{\ell}_0), \\[6pt]
\text{Residual Deviance}^\dagger \text{ } & & \text{ } D_{RES} = 2(\hat{\ell}_{S} - \hat{\ell}_{p}). \\[6pt]
\end{matrix}$$
In these expressions the value $\hat{\ell}_S$ is the maximised log-likelihood under a saturated model (one parameter per data point), $\hat{\ell}_0$ is the maximised log-likelihood under a null model (intercept only), and $\hat{\ell}_{p}$ is the maximised log-likelihood under the model (intercept term and $p$ coefficients).
These deviance statistics play a role analogous to scaled versions of the sums-of-squares in linear regression. It is easy to see that they satisfy the decomposition $D_{TOT} = D_{REG} + D_{RES}$, which is analogous to the decomposition of the sums-of-squares in linear regression. In fact, in the case where you have a normal response distribution with a linear link function you get a linear regression model, and the deviance statistics reduce to the following:
$$\begin{equation} \begin{aligned}
D_{TOT} = \frac{1}{\sigma^2} \sum_{i=1}^n (y_i - \bar{y})^2 = \frac{1}{\sigma^2} \cdot SS_{TOT}, \\[6pt]
D_{REG} = \frac{1}{\sigma^2} \sum_{i=1}^n (\hat{y}_i - \bar{y})^2 = \frac{1}{\sigma^2} \cdot SS_{REG}, \\[6pt]
D_{RES} = \frac{1}{\sigma^2} \sum_{i=1}^n (y_i - \hat{y}_i)^2 = \frac{1}{\sigma^2} \cdot SS_{RES}. \\[6pt]
\end{aligned} \end{equation}$$
Now, the coefficient of variation in a linear regression model is a goodness-of-fit statistic that measures the proportion of the total variation in the response that is attributable to the explanatory variables. A natural extension in the case of a GLM is to form the statistic:
$$R_{GLM}^2 = 1-\frac{D_{RES}}{D_{TOT}} = \frac{D_{REG}}{D_{TOT}}.$$
It is easily seen that this statistic reduces to the coefficient of variation in the special case of linear regression, since the scaling values cancel out. In the broader context of a GLM the statistic has a natural interpretation that is analogous to its interpretation in linear regression: it gives the proportion of the null deviance that is explained by the explanatory variables in the model.
Now that we have seen how the sums-of-squares in linear regression extend to the deviances in a GLM, we can see that the regular coefficient of variation is inappropriate in the non-linear model, since it is specific to the case of a linear model with a normally distributed error term. Nevertheless, we can see that although the standard coefficient of variation is inappropriate, it is possible to form an appropriate analogy using the deviance values, with an analogous interpretation.
$^\dagger$ The residual deviance is sometimes just called the deviance. | Is R-squared truly an invalid metric for non-linear models? | The sums-of-squares in linear regression are special cases of the more general deviance values in the generalised linear model. In the more general model there is a response distribution with mean li | Is R-squared truly an invalid metric for non-linear models?
The sums-of-squares in linear regression are special cases of the more general deviance values in the generalised linear model. In the more general model there is a response distribution with mean linked to a linear function of the explanatory variables (with an intercept term). The three deviance statistics in a GLM are defined as:
$$\begin{matrix}
\text{Null Deviance} \quad \quad \text{ } \text{ } & & \text{ } D_{TOT} = 2(\hat{\ell}_{S} - \hat{\ell}_0), \\[6pt]
\text{Explained Deviance} & & D_{REG} = 2(\hat{\ell}_{p} - \hat{\ell}_0), \\[6pt]
\text{Residual Deviance}^\dagger \text{ } & & \text{ } D_{RES} = 2(\hat{\ell}_{S} - \hat{\ell}_{p}). \\[6pt]
\end{matrix}$$
In these expressions the value $\hat{\ell}_S$ is the maximised log-likelihood under a saturated model (one parameter per data point), $\hat{\ell}_0$ is the maximised log-likelihood under a null model (intercept only), and $\hat{\ell}_{p}$ is the maximised log-likelihood under the model (intercept term and $p$ coefficients).
These deviance statistics play a role analogous to scaled versions of the sums-of-squares in linear regression. It is easy to see that they satisfy the decomposition $D_{TOT} = D_{REG} + D_{RES}$, which is analogous to the decomposition of the sums-of-squares in linear regression. In fact, in the case where you have a normal response distribution with a linear link function you get a linear regression model, and the deviance statistics reduce to the following:
$$\begin{equation} \begin{aligned}
D_{TOT} = \frac{1}{\sigma^2} \sum_{i=1}^n (y_i - \bar{y})^2 = \frac{1}{\sigma^2} \cdot SS_{TOT}, \\[6pt]
D_{REG} = \frac{1}{\sigma^2} \sum_{i=1}^n (\hat{y}_i - \bar{y})^2 = \frac{1}{\sigma^2} \cdot SS_{REG}, \\[6pt]
D_{RES} = \frac{1}{\sigma^2} \sum_{i=1}^n (y_i - \hat{y}_i)^2 = \frac{1}{\sigma^2} \cdot SS_{RES}. \\[6pt]
\end{aligned} \end{equation}$$
Now, the coefficient of variation in a linear regression model is a goodness-of-fit statistic that measures the proportion of the total variation in the response that is attributable to the explanatory variables. A natural extension in the case of a GLM is to form the statistic:
$$R_{GLM}^2 = 1-\frac{D_{RES}}{D_{TOT}} = \frac{D_{REG}}{D_{TOT}}.$$
It is easily seen that this statistic reduces to the coefficient of variation in the special case of linear regression, since the scaling values cancel out. In the broader context of a GLM the statistic has a natural interpretation that is analogous to its interpretation in linear regression: it gives the proportion of the null deviance that is explained by the explanatory variables in the model.
Now that we have seen how the sums-of-squares in linear regression extend to the deviances in a GLM, we can see that the regular coefficient of variation is inappropriate in the non-linear model, since it is specific to the case of a linear model with a normally distributed error term. Nevertheless, we can see that although the standard coefficient of variation is inappropriate, it is possible to form an appropriate analogy using the deviance values, with an analogous interpretation.
$^\dagger$ The residual deviance is sometimes just called the deviance. | Is R-squared truly an invalid metric for non-linear models?
The sums-of-squares in linear regression are special cases of the more general deviance values in the generalised linear model. In the more general model there is a response distribution with mean li |
20,173 | Is R-squared truly an invalid metric for non-linear models? | Why should SSE + SSR be equal to SST? It just happened to be the case for the linear model. There are many ways to show that it should hold for $y=X\beta+\varepsilon$ under Gauss-Markov conditions. However, it doesn't need to hold in general case. The burden is to prove that it holds, not that it doesn't | Is R-squared truly an invalid metric for non-linear models? | Why should SSE + SSR be equal to SST? It just happened to be the case for the linear model. There are many ways to show that it should hold for $y=X\beta+\varepsilon$ under Gauss-Markov conditions. Ho | Is R-squared truly an invalid metric for non-linear models?
Why should SSE + SSR be equal to SST? It just happened to be the case for the linear model. There are many ways to show that it should hold for $y=X\beta+\varepsilon$ under Gauss-Markov conditions. However, it doesn't need to hold in general case. The burden is to prove that it holds, not that it doesn't | Is R-squared truly an invalid metric for non-linear models?
Why should SSE + SSR be equal to SST? It just happened to be the case for the linear model. There are many ways to show that it should hold for $y=X\beta+\varepsilon$ under Gauss-Markov conditions. Ho |
20,174 | Is R-squared truly an invalid metric for non-linear models? | While R-squared may still be a flawed measurement in non-linear models for other reasons, I believe I have sufficiently shown that the SSR + SSE = SSTotal relationship still holds in a least-squares model for certain non-linear functions, especially those that allow for a constant term, such as polynomial models. I believe that this conclusion is compatible with what has been posted in this discussion, including what I read from the ncbi link provided, although I was unable to access the full report.
If one has a series of fitted values $\hat y_i$ with respect to a series of observations $y_i$, where $\hat y_i$ $ = A + f(X) = $ $\bar Y$ $ + (A-\bar Y)$ $+ f(X) $, with $A$ being a constant term and $f(X)$ a function of predictor variables, in which the vector of $(\hat{Y_i} - \bar{Y})$ is not orthogonal to $(Y_i - \hat{Y_i})$, one can create a new set of fitted values $Z_i$ such that $Z_i = c*(\hat{Y_i} - \bar{Y}) + \bar{Y}$, where c = $\sum{(\hat{Y_i}-\bar{Y})*(Y_i-\hat{Y_i})} / \sum{(\hat{Y_i} - \bar{Y})^2}$. With new fitted values $Z_i$, the vector $(Z_i - \bar{Y})$ will be orthogonal to the error vector and this new error vector $(Y_i - Z_i)$ will have a smaller sum of squares than the original $(Y_i-\hat{Y_i})$. The $Z_i$ were simply obtained by multiplying the original estimated model by a constant $"c"$ and adding a multiple of the observations' mean, which is compatible with the model having a constant term. Therefore a least-squares model should always have orthogonal regression and error vectors in these circumstances, which means that $SSE + SSR = SSTotal$.
I have created polynomial models on a handful of datasets at work and this relationship has held with all of them. I am just saying. | Is R-squared truly an invalid metric for non-linear models? | While R-squared may still be a flawed measurement in non-linear models for other reasons, I believe I have sufficiently shown that the SSR + SSE = SSTotal relationship still holds in a least-squares m | Is R-squared truly an invalid metric for non-linear models?
While R-squared may still be a flawed measurement in non-linear models for other reasons, I believe I have sufficiently shown that the SSR + SSE = SSTotal relationship still holds in a least-squares model for certain non-linear functions, especially those that allow for a constant term, such as polynomial models. I believe that this conclusion is compatible with what has been posted in this discussion, including what I read from the ncbi link provided, although I was unable to access the full report.
If one has a series of fitted values $\hat y_i$ with respect to a series of observations $y_i$, where $\hat y_i$ $ = A + f(X) = $ $\bar Y$ $ + (A-\bar Y)$ $+ f(X) $, with $A$ being a constant term and $f(X)$ a function of predictor variables, in which the vector of $(\hat{Y_i} - \bar{Y})$ is not orthogonal to $(Y_i - \hat{Y_i})$, one can create a new set of fitted values $Z_i$ such that $Z_i = c*(\hat{Y_i} - \bar{Y}) + \bar{Y}$, where c = $\sum{(\hat{Y_i}-\bar{Y})*(Y_i-\hat{Y_i})} / \sum{(\hat{Y_i} - \bar{Y})^2}$. With new fitted values $Z_i$, the vector $(Z_i - \bar{Y})$ will be orthogonal to the error vector and this new error vector $(Y_i - Z_i)$ will have a smaller sum of squares than the original $(Y_i-\hat{Y_i})$. The $Z_i$ were simply obtained by multiplying the original estimated model by a constant $"c"$ and adding a multiple of the observations' mean, which is compatible with the model having a constant term. Therefore a least-squares model should always have orthogonal regression and error vectors in these circumstances, which means that $SSE + SSR = SSTotal$.
I have created polynomial models on a handful of datasets at work and this relationship has held with all of them. I am just saying. | Is R-squared truly an invalid metric for non-linear models?
While R-squared may still be a flawed measurement in non-linear models for other reasons, I believe I have sufficiently shown that the SSR + SSE = SSTotal relationship still holds in a least-squares m |
20,175 | Is R-squared truly an invalid metric for non-linear models? | $R^2$ is of limited use in nonlinear regression. We make it available in GraphPad Prism, but suggest it be used in only one way:
Look at $R^2$ when you run a series of experiments, and you want to make sure that today's experiment is consistent with other runs of the experiment. For example, if you always get $R^2$ between 0.90 and 0.95 but today you got $R^2$=0.75, then you should be suspicious and look carefully to see if something went wrong with the methods or reagents used in that particular experiment. And if a new employee brings you results showing $R^2$ of 0.99 using that same system, you should look carefully at how many "outliers" were removed, and whether some data were made up.
More. | Is R-squared truly an invalid metric for non-linear models? | $R^2$ is of limited use in nonlinear regression. We make it available in GraphPad Prism, but suggest it be used in only one way:
Look at $R^2$ when you run a series of experiments, and you want to mak | Is R-squared truly an invalid metric for non-linear models?
$R^2$ is of limited use in nonlinear regression. We make it available in GraphPad Prism, but suggest it be used in only one way:
Look at $R^2$ when you run a series of experiments, and you want to make sure that today's experiment is consistent with other runs of the experiment. For example, if you always get $R^2$ between 0.90 and 0.95 but today you got $R^2$=0.75, then you should be suspicious and look carefully to see if something went wrong with the methods or reagents used in that particular experiment. And if a new employee brings you results showing $R^2$ of 0.99 using that same system, you should look carefully at how many "outliers" were removed, and whether some data were made up.
More. | Is R-squared truly an invalid metric for non-linear models?
$R^2$ is of limited use in nonlinear regression. We make it available in GraphPad Prism, but suggest it be used in only one way:
Look at $R^2$ when you run a series of experiments, and you want to mak |
20,176 | Convolution with a non-square kernel | Actually the ideal shape would probably be a circle, but that's computationally inconvenient. The point being that you typically have no a priori assumptions of the shapes of the features that your convolutional net should learn. For instance, the lowest layers of a convolutional net trained on images often learn to detect edges. These edges can have any orientation, e.g. vertical, diagonal, horizontal, or something in between. If you examined the weights for a vertical edge detector, you might find that you could actually fit them inside a tall rectangle and crop out some irrelevant (near-zero) weights from the sides of the kernel. Similarly, the horizontal edge detector might fit inside a wide rectangle, not needing the top and bottom bits of the square. But you don't know beforehand which feature will be learnt by which map, so you can't specify these shapes in advance, nor would it probably confer much of an advantage to do so. A circular kernel fits any feature of a given size (e.g. any edge detector with a maximum dimension of 5 pixels can fit inside a circle with a diameter of 5), and the square is the closest approximation to that that is easy to work with computationally.
If you knew in advance that all your features would tend to (for example) be wider than they are tall, then perhaps it might be worth using a (non-square) rectangular kernel. | Convolution with a non-square kernel | Actually the ideal shape would probably be a circle, but that's computationally inconvenient. The point being that you typically have no a priori assumptions of the shapes of the features that your co | Convolution with a non-square kernel
Actually the ideal shape would probably be a circle, but that's computationally inconvenient. The point being that you typically have no a priori assumptions of the shapes of the features that your convolutional net should learn. For instance, the lowest layers of a convolutional net trained on images often learn to detect edges. These edges can have any orientation, e.g. vertical, diagonal, horizontal, or something in between. If you examined the weights for a vertical edge detector, you might find that you could actually fit them inside a tall rectangle and crop out some irrelevant (near-zero) weights from the sides of the kernel. Similarly, the horizontal edge detector might fit inside a wide rectangle, not needing the top and bottom bits of the square. But you don't know beforehand which feature will be learnt by which map, so you can't specify these shapes in advance, nor would it probably confer much of an advantage to do so. A circular kernel fits any feature of a given size (e.g. any edge detector with a maximum dimension of 5 pixels can fit inside a circle with a diameter of 5), and the square is the closest approximation to that that is easy to work with computationally.
If you knew in advance that all your features would tend to (for example) be wider than they are tall, then perhaps it might be worth using a (non-square) rectangular kernel. | Convolution with a non-square kernel
Actually the ideal shape would probably be a circle, but that's computationally inconvenient. The point being that you typically have no a priori assumptions of the shapes of the features that your co |
20,177 | Convolution with a non-square kernel | It makes sense to use a non rectangular kernel if the input device has non rectangular geometry:
https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8853238
Non rectangular kernel could also reduce the amount of computation:
https://arxiv.org/pdf/1904.08755.pdf
Another example is convolution on point clouds. In the following paper, the kernel shape is no longer rigid, and defined inside a sphere.
https://arxiv.org/abs/1904.08889 | Convolution with a non-square kernel | It makes sense to use a non rectangular kernel if the input device has non rectangular geometry:
https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8853238
Non rectangular kernel could also reduce t | Convolution with a non-square kernel
It makes sense to use a non rectangular kernel if the input device has non rectangular geometry:
https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8853238
Non rectangular kernel could also reduce the amount of computation:
https://arxiv.org/pdf/1904.08755.pdf
Another example is convolution on point clouds. In the following paper, the kernel shape is no longer rigid, and defined inside a sphere.
https://arxiv.org/abs/1904.08889 | Convolution with a non-square kernel
It makes sense to use a non rectangular kernel if the input device has non rectangular geometry:
https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8853238
Non rectangular kernel could also reduce t |
20,178 | Convolution with a non-square kernel | An example application of non-square kernel would be something that operates on data that has different size in different dimensions.
For concrete example see this network. It is applies $4 \times 1$ kernels to short-time Fourier transform of sound (it runs on $513 \times 128$ input). | Convolution with a non-square kernel | An example application of non-square kernel would be something that operates on data that has different size in different dimensions.
For concrete example see this network. It is applies $4 \times 1$ | Convolution with a non-square kernel
An example application of non-square kernel would be something that operates on data that has different size in different dimensions.
For concrete example see this network. It is applies $4 \times 1$ kernels to short-time Fourier transform of sound (it runs on $513 \times 128$ input). | Convolution with a non-square kernel
An example application of non-square kernel would be something that operates on data that has different size in different dimensions.
For concrete example see this network. It is applies $4 \times 1$ |
20,179 | Convolution with a non-square kernel | In principle, the kernels may have arbitrary shapes. However, in practice it has been found that the kernel size does not affect the network performance too much; I suppose that is one of the reasons why you don't see irregular-shaped kernels around too much.
Convolution aggregates information from a region of shape corresponding to the shape of the kernel. In computer vision the horizontal and vertical dimension usually make no difference and thus you use square shaped kernel.
If it makes sense for a particular task to aggregate information in different sized neighborhood in each dimension, then just go for it. For example, we used kernels of shape [3x3x2] to work with 3D data in this article. | Convolution with a non-square kernel | In principle, the kernels may have arbitrary shapes. However, in practice it has been found that the kernel size does not affect the network performance too much; I suppose that is one of the reasons | Convolution with a non-square kernel
In principle, the kernels may have arbitrary shapes. However, in practice it has been found that the kernel size does not affect the network performance too much; I suppose that is one of the reasons why you don't see irregular-shaped kernels around too much.
Convolution aggregates information from a region of shape corresponding to the shape of the kernel. In computer vision the horizontal and vertical dimension usually make no difference and thus you use square shaped kernel.
If it makes sense for a particular task to aggregate information in different sized neighborhood in each dimension, then just go for it. For example, we used kernels of shape [3x3x2] to work with 3D data in this article. | Convolution with a non-square kernel
In principle, the kernels may have arbitrary shapes. However, in practice it has been found that the kernel size does not affect the network performance too much; I suppose that is one of the reasons |
20,180 | Forecasting several periods with machine learning | (Part of this is taken from a previous post of mine)
First of all you need to distinguish the two different ways to perform multistep times series forecasting: Recursive forecasting and direct forecasting:
In recursive forecasting (also called iterated forecasting) you train your model for one step ahead forecasts only. After the training is done you apply your final model recursively to forecast 1 step ahead, 2 steps ahead, etc...until you reach the desired $n$ steps forecast horizon. To do so, you feed the forecast from each successive step back into the model to generate the next step. This approach is used by traditional forecasting algorithms like ARIMA and Exponential Smoothing algorithms, and can be also used for Machine Learning based forecasting (see this post for an example, and this post for some discussion).
Direct forecasting is when you train a separate model for each step (so you are trying to "directly" forecast the $n^{th}$ step ahead instead of reaching $n$ steps recursively. See Ben Taied et al. for a discussion of direct forecasting and more complex combined approaches.
Now to answer your main question:
Can machine learning methods produce an h-steps-ahead forecasts?
Yes ML methods can, and they can produce h-steps ahead forecast using both recursive and direct multistep forecasts. Not only that, but for direct multi-step forecasting they are actually more suited to the task than traditional models like ARIMA or Exponential Smoothing. Note however that for direct multi-step forecasting, you need to specify before hand the h-steps ahead for which you want to forecast and train your model accordingly, whereas for recursive forecasting you can use your model for any number of future steps you want.
Moreover Chevillon & Hendry argue that in some cases direct multi-step forecasting is more accurate than recursive forecasting - implying that ML would be more accurate than traditional methods.
For your other questions:
What are the reasons that I don't see anyone using machine learning to make h-step-ahead forecasts?
Many people are using ML for multi-step forecasting, especially using neural netwroks: Hyndman's nnetar method available in the R Forecast package, Kourentzes' nnfor R package, Amazon's DeepAR model, and many others.
XGBoost has been used successfully in a few Kaggle time series competitions as well.
See Bontempi et al. for a general discussion.
If there is a method using machine learning, is it more or less precise than ARIMA?
That is an open question, and obviously depends on the data and the application that one is forecasting for. | Forecasting several periods with machine learning | (Part of this is taken from a previous post of mine)
First of all you need to distinguish the two different ways to perform multistep times series forecasting: Recursive forecasting and direct forecas | Forecasting several periods with machine learning
(Part of this is taken from a previous post of mine)
First of all you need to distinguish the two different ways to perform multistep times series forecasting: Recursive forecasting and direct forecasting:
In recursive forecasting (also called iterated forecasting) you train your model for one step ahead forecasts only. After the training is done you apply your final model recursively to forecast 1 step ahead, 2 steps ahead, etc...until you reach the desired $n$ steps forecast horizon. To do so, you feed the forecast from each successive step back into the model to generate the next step. This approach is used by traditional forecasting algorithms like ARIMA and Exponential Smoothing algorithms, and can be also used for Machine Learning based forecasting (see this post for an example, and this post for some discussion).
Direct forecasting is when you train a separate model for each step (so you are trying to "directly" forecast the $n^{th}$ step ahead instead of reaching $n$ steps recursively. See Ben Taied et al. for a discussion of direct forecasting and more complex combined approaches.
Now to answer your main question:
Can machine learning methods produce an h-steps-ahead forecasts?
Yes ML methods can, and they can produce h-steps ahead forecast using both recursive and direct multistep forecasts. Not only that, but for direct multi-step forecasting they are actually more suited to the task than traditional models like ARIMA or Exponential Smoothing. Note however that for direct multi-step forecasting, you need to specify before hand the h-steps ahead for which you want to forecast and train your model accordingly, whereas for recursive forecasting you can use your model for any number of future steps you want.
Moreover Chevillon & Hendry argue that in some cases direct multi-step forecasting is more accurate than recursive forecasting - implying that ML would be more accurate than traditional methods.
For your other questions:
What are the reasons that I don't see anyone using machine learning to make h-step-ahead forecasts?
Many people are using ML for multi-step forecasting, especially using neural netwroks: Hyndman's nnetar method available in the R Forecast package, Kourentzes' nnfor R package, Amazon's DeepAR model, and many others.
XGBoost has been used successfully in a few Kaggle time series competitions as well.
See Bontempi et al. for a general discussion.
If there is a method using machine learning, is it more or less precise than ARIMA?
That is an open question, and obviously depends on the data and the application that one is forecasting for. | Forecasting several periods with machine learning
(Part of this is taken from a previous post of mine)
First of all you need to distinguish the two different ways to perform multistep times series forecasting: Recursive forecasting and direct forecas |
20,181 | Forecasting several periods with machine learning | I have been playing with time series for anomaly detection in the last few months and I can share with you my experience.
The time series I've been working with was characterized by two seasonalities (daily and weekly), no trend and many peaks during daylights.
I did several experiments and then I chose a model based on LSTM neural nets because in my case it outperformed arima, but of course as everything in statistics, there's not an general solution.
To predict more than one time step in the future with a neural net is pretty simple, you will need to output N values instead of one and that N output will be compared to the real N observations.
From my experience I can tell you that by using a low N (say 1), the model will strictly use few time step in the past to predict the new one, without really "learning" the seasonality.
On the other side, by increasing N too mutch, the seasonalities are learned but the overall accuracy decreases.
For the purpose of my analysis I found N = 4 (2 hours in the future) to be a good compromise. | Forecasting several periods with machine learning | I have been playing with time series for anomaly detection in the last few months and I can share with you my experience.
The time series I've been working with was characterized by two seasonalities | Forecasting several periods with machine learning
I have been playing with time series for anomaly detection in the last few months and I can share with you my experience.
The time series I've been working with was characterized by two seasonalities (daily and weekly), no trend and many peaks during daylights.
I did several experiments and then I chose a model based on LSTM neural nets because in my case it outperformed arima, but of course as everything in statistics, there's not an general solution.
To predict more than one time step in the future with a neural net is pretty simple, you will need to output N values instead of one and that N output will be compared to the real N observations.
From my experience I can tell you that by using a low N (say 1), the model will strictly use few time step in the past to predict the new one, without really "learning" the seasonality.
On the other side, by increasing N too mutch, the seasonalities are learned but the overall accuracy decreases.
For the purpose of my analysis I found N = 4 (2 hours in the future) to be a good compromise. | Forecasting several periods with machine learning
I have been playing with time series for anomaly detection in the last few months and I can share with you my experience.
The time series I've been working with was characterized by two seasonalities |
20,182 | Forecasting several periods with machine learning | To answer your question in a more general term, it is possible to use machine learning and predict h-steps-ahead forecasts. The tricky part is that you have to reshape your data into a matrix in which you have, for each observation the actual value of the observation and past values of the time series for a defined range. You will need to define manually what is the range of data that appear relevant to predict your time series, in fact, as you would parameter an ARIMA model. The width/horizon of the matrix is critical to predict correctly the next value taken by your matrix. If your horizon is restricted, you might miss seasonality effects.
Once you have done that, to predict h-steps-ahead, you will need to predict the first next value based on your last observation. You will then have to store the prediction as an "actual value", which will be used to predict the second next value through a time shifting, just like an ARIMA model. You will have to iterate the process h times to get your h-steps-ahead. Each iteration will rely on the previous prediction.
An example using R code would be the following one.
library(forecast)
library(randomForest)
# create a daily pattern with random variations
myts <- ts(rep(c(5,6,7,8,11,13,14,15,16,15,14,17,13,12,15,13,12,12,11,10,9,8,7,6), 10)*runif(120,0.8,1.2), freq = 24)
myts_forecast <- forecast(myts, h = 24) # predict the time-series using ets + stl techniques
pred1 <- c(myts, myts_forecast1$mean) # store the prediction
# transform these observations into a matrix with the last 24 past values
idx <- c(1:24)
designmat <- data.frame(lapply(idx, function(x) myts[x:(215+x)])) # create a design matrix
colnames(designmat) <- c(paste0("x_",as.character(c(1:23))),"y")
# create a random forest model and predict iteratively each value
rfModel <- randomForest(y ~., designmat)
for (i in 1:24){
designvec <- data.frame(c(designmat[nrow(designmat), 2:24], 0))
colnames(designvec) <- colnames(designmat)
designvec$y <- predict(rfModel, designvec)
designmat <- rbind(designmat, designvec)
}
pred2 <- designmat$y
#plot to compare predictions
plot(pred1, type = "l")
lines(y = pred2[216:240], x = c(240:264), col = 2)
Now obviously, there are no general rules as to determine whether a time-series model or a machine learning model are more efficient. Computational time may be higher for machine learning models, but on the other hand, you may include any type of additional features to predict your time-series using them (e.g. not just numerical or logical features). General advice would be to test both, and pick the most efficient model. | Forecasting several periods with machine learning | To answer your question in a more general term, it is possible to use machine learning and predict h-steps-ahead forecasts. The tricky part is that you have to reshape your data into a matrix in which | Forecasting several periods with machine learning
To answer your question in a more general term, it is possible to use machine learning and predict h-steps-ahead forecasts. The tricky part is that you have to reshape your data into a matrix in which you have, for each observation the actual value of the observation and past values of the time series for a defined range. You will need to define manually what is the range of data that appear relevant to predict your time series, in fact, as you would parameter an ARIMA model. The width/horizon of the matrix is critical to predict correctly the next value taken by your matrix. If your horizon is restricted, you might miss seasonality effects.
Once you have done that, to predict h-steps-ahead, you will need to predict the first next value based on your last observation. You will then have to store the prediction as an "actual value", which will be used to predict the second next value through a time shifting, just like an ARIMA model. You will have to iterate the process h times to get your h-steps-ahead. Each iteration will rely on the previous prediction.
An example using R code would be the following one.
library(forecast)
library(randomForest)
# create a daily pattern with random variations
myts <- ts(rep(c(5,6,7,8,11,13,14,15,16,15,14,17,13,12,15,13,12,12,11,10,9,8,7,6), 10)*runif(120,0.8,1.2), freq = 24)
myts_forecast <- forecast(myts, h = 24) # predict the time-series using ets + stl techniques
pred1 <- c(myts, myts_forecast1$mean) # store the prediction
# transform these observations into a matrix with the last 24 past values
idx <- c(1:24)
designmat <- data.frame(lapply(idx, function(x) myts[x:(215+x)])) # create a design matrix
colnames(designmat) <- c(paste0("x_",as.character(c(1:23))),"y")
# create a random forest model and predict iteratively each value
rfModel <- randomForest(y ~., designmat)
for (i in 1:24){
designvec <- data.frame(c(designmat[nrow(designmat), 2:24], 0))
colnames(designvec) <- colnames(designmat)
designvec$y <- predict(rfModel, designvec)
designmat <- rbind(designmat, designvec)
}
pred2 <- designmat$y
#plot to compare predictions
plot(pred1, type = "l")
lines(y = pred2[216:240], x = c(240:264), col = 2)
Now obviously, there are no general rules as to determine whether a time-series model or a machine learning model are more efficient. Computational time may be higher for machine learning models, but on the other hand, you may include any type of additional features to predict your time-series using them (e.g. not just numerical or logical features). General advice would be to test both, and pick the most efficient model. | Forecasting several periods with machine learning
To answer your question in a more general term, it is possible to use machine learning and predict h-steps-ahead forecasts. The tricky part is that you have to reshape your data into a matrix in which |
20,183 | Measure of volatility for time series data? | In finance the volatility measure is the standard deviation of the series. The means are often near zero, e.g. price returns, so it's not the coefficient of variation usually.
There are many ways to calculate the standard deviation though. For instance, even when the series are stationary they often have autocorrelations. In this case GARCH is a popular approach, which will give you the conditional variance. So, you can look at both long running and conditional variances. Sometimes the series exhibit stochastic variance behavior, in this case the models like Heston could be used.
Even with the simplest Gaussian, independent assumption there are multiple ways of estimating the variance. Take a look at this paper on how it's done in Bloomberg terminal. | Measure of volatility for time series data? | In finance the volatility measure is the standard deviation of the series. The means are often near zero, e.g. price returns, so it's not the coefficient of variation usually.
There are many ways to | Measure of volatility for time series data?
In finance the volatility measure is the standard deviation of the series. The means are often near zero, e.g. price returns, so it's not the coefficient of variation usually.
There are many ways to calculate the standard deviation though. For instance, even when the series are stationary they often have autocorrelations. In this case GARCH is a popular approach, which will give you the conditional variance. So, you can look at both long running and conditional variances. Sometimes the series exhibit stochastic variance behavior, in this case the models like Heston could be used.
Even with the simplest Gaussian, independent assumption there are multiple ways of estimating the variance. Take a look at this paper on how it's done in Bloomberg terminal. | Measure of volatility for time series data?
In finance the volatility measure is the standard deviation of the series. The means are often near zero, e.g. price returns, so it's not the coefficient of variation usually.
There are many ways to |
20,184 | Measure of volatility for time series data? | As noted, typical statistical approaches based on L2 norms include the std dev as well as the coefficient of variation (which, for nonnegative metrics, produces a scale invariant measure) as well as the dispersion index (ratio of the variance to the mean). If the data is financial then it is also possible to calculate "upside" and/or "downside" measures of risk, aka above- or below-target semi-deviation, as described in these wiki articles (https://en.wikipedia.org/wiki/Downside_risk or https://en.wikipedia.org/wiki/Upside_risk).
L1 norm-based measures are possible, for instance, the MAD or mean absolute deviation and the MADM, the median absolute deviation from the median. Other nonparametric estimates include the interquartile range, the interdecile range, as well as metrics discussed by Rousseeuw and Croux in their paper, Alternatives to the Median Absolute Deviation (ungated copy here ... http://web.ipac.caltech.edu/staff/fmasci/home/astro_refs/BetterThanMAD.pdf).
Information-theoretic approaches include measures of entropy (https://en.wikipedia.org/wiki/Entropy_(information_theory)), such as Theil's U or the many variants of indexes of information diversity (e.g., https://en.wikipedia.org/wiki/Generalized_entropy_index).
Hyndman's contention is that his MASE metric is optimal for time series data. MASE is a normalized loss function. After creating train and test data, the test data residuals are normalized or divided by the average error in the training data. If MASE<1 then the proposed model is an improvement, on average, over a one-step ahead, random walk forecast.
See his paper, Hyndman and Koehler, Another look at measures of forecast accuracy, International Journal of Forecasting, 22(4):679-688, 2006, https://robjhyndman.com/papers/mase.pdf, p. 3 | Measure of volatility for time series data? | As noted, typical statistical approaches based on L2 norms include the std dev as well as the coefficient of variation (which, for nonnegative metrics, produces a scale invariant measure) as well as t | Measure of volatility for time series data?
As noted, typical statistical approaches based on L2 norms include the std dev as well as the coefficient of variation (which, for nonnegative metrics, produces a scale invariant measure) as well as the dispersion index (ratio of the variance to the mean). If the data is financial then it is also possible to calculate "upside" and/or "downside" measures of risk, aka above- or below-target semi-deviation, as described in these wiki articles (https://en.wikipedia.org/wiki/Downside_risk or https://en.wikipedia.org/wiki/Upside_risk).
L1 norm-based measures are possible, for instance, the MAD or mean absolute deviation and the MADM, the median absolute deviation from the median. Other nonparametric estimates include the interquartile range, the interdecile range, as well as metrics discussed by Rousseeuw and Croux in their paper, Alternatives to the Median Absolute Deviation (ungated copy here ... http://web.ipac.caltech.edu/staff/fmasci/home/astro_refs/BetterThanMAD.pdf).
Information-theoretic approaches include measures of entropy (https://en.wikipedia.org/wiki/Entropy_(information_theory)), such as Theil's U or the many variants of indexes of information diversity (e.g., https://en.wikipedia.org/wiki/Generalized_entropy_index).
Hyndman's contention is that his MASE metric is optimal for time series data. MASE is a normalized loss function. After creating train and test data, the test data residuals are normalized or divided by the average error in the training data. If MASE<1 then the proposed model is an improvement, on average, over a one-step ahead, random walk forecast.
See his paper, Hyndman and Koehler, Another look at measures of forecast accuracy, International Journal of Forecasting, 22(4):679-688, 2006, https://robjhyndman.com/papers/mase.pdf, p. 3 | Measure of volatility for time series data?
As noted, typical statistical approaches based on L2 norms include the std dev as well as the coefficient of variation (which, for nonnegative metrics, produces a scale invariant measure) as well as t |
20,185 | How can I derive effect sizes in lme4 and describe the magnitude of fixed effects? | Brysbaert and Stevens recently published a paper on how to compute effect sizes with the lme4 package.
Code:
library (lme4)
fit <- lmer(RT ~ prime + (prime|item) + (prime|participant), data = data)
summary(fit)
There is one fixed effect (the effect of prime) and four random effects:
The intercept per participant (capturing the fact that some participants are faster than others).
The intercept per item (capturing the fact that some items are easier than others).
The slope per participant (capturing the possibility that the priming effect is not the same for all participants).
The slope per item (capturing the possibility that the priming effect is not the same for all items).
I have not been able to use this solution as I used the nmle package because it lets me define the autocorrelation structure (Pinheiro & Bates, 2008) more easily, but I thought I will share it anyway. | How can I derive effect sizes in lme4 and describe the magnitude of fixed effects? | Brysbaert and Stevens recently published a paper on how to compute effect sizes with the lme4 package.
Code:
library (lme4)
fit <- lmer(RT ~ prime + (prime|item) + (prime|participant), data = data)
| How can I derive effect sizes in lme4 and describe the magnitude of fixed effects?
Brysbaert and Stevens recently published a paper on how to compute effect sizes with the lme4 package.
Code:
library (lme4)
fit <- lmer(RT ~ prime + (prime|item) + (prime|participant), data = data)
summary(fit)
There is one fixed effect (the effect of prime) and four random effects:
The intercept per participant (capturing the fact that some participants are faster than others).
The intercept per item (capturing the fact that some items are easier than others).
The slope per participant (capturing the possibility that the priming effect is not the same for all participants).
The slope per item (capturing the possibility that the priming effect is not the same for all items).
I have not been able to use this solution as I used the nmle package because it lets me define the autocorrelation structure (Pinheiro & Bates, 2008) more easily, but I thought I will share it anyway. | How can I derive effect sizes in lme4 and describe the magnitude of fixed effects?
Brysbaert and Stevens recently published a paper on how to compute effect sizes with the lme4 package.
Code:
library (lme4)
fit <- lmer(RT ~ prime + (prime|item) + (prime|participant), data = data)
|
20,186 | How can I derive effect sizes in lme4 and describe the magnitude of fixed effects? | The paper suggested by @simone, Brysbaert and Stevens as the title indicates, is focused on 'Power Analysis and Effect Size in Mixed Effects Models', but it includes a calculation of effect size, which is not present in @simone's answer, with a reference to Westfall et al. (2014), for the effect size calculation:
'*First, Westfall et al. (2014) showed how you can calculate the effect size (measured as d) for a design with random participants and random items. The equation is as follows:
d = difference between the means / ( sqrt( var.intercept_part + var.intercept_item + var.slope_part + var.slope_item + var_residual ) )*'
(Sorry about the equation notation)
Basicly meaning:
d = estimate for fixed effect / (sqrt of sum of variances of random effects)
From Westfall et al.: 'We follow there the general procedure specified by Cohen (1988) for simpler designs. This procedure involves first calculating an estimated effect size, analogous to Cohenβs d: the expected mean difference divided by the
expected variation of an individual observation, which in our case
accrues from all the variance components specified above'
Finally, this equation seems to be the same as in Hedges (2007), proposed by @d_williams.
Hope this helps. | How can I derive effect sizes in lme4 and describe the magnitude of fixed effects? | The paper suggested by @simone, Brysbaert and Stevens as the title indicates, is focused on 'Power Analysis and Effect Size in Mixed Effects Models', but it includes a calculation of effect size, whic | How can I derive effect sizes in lme4 and describe the magnitude of fixed effects?
The paper suggested by @simone, Brysbaert and Stevens as the title indicates, is focused on 'Power Analysis and Effect Size in Mixed Effects Models', but it includes a calculation of effect size, which is not present in @simone's answer, with a reference to Westfall et al. (2014), for the effect size calculation:
'*First, Westfall et al. (2014) showed how you can calculate the effect size (measured as d) for a design with random participants and random items. The equation is as follows:
d = difference between the means / ( sqrt( var.intercept_part + var.intercept_item + var.slope_part + var.slope_item + var_residual ) )*'
(Sorry about the equation notation)
Basicly meaning:
d = estimate for fixed effect / (sqrt of sum of variances of random effects)
From Westfall et al.: 'We follow there the general procedure specified by Cohen (1988) for simpler designs. This procedure involves first calculating an estimated effect size, analogous to Cohenβs d: the expected mean difference divided by the
expected variation of an individual observation, which in our case
accrues from all the variance components specified above'
Finally, this equation seems to be the same as in Hedges (2007), proposed by @d_williams.
Hope this helps. | How can I derive effect sizes in lme4 and describe the magnitude of fixed effects?
The paper suggested by @simone, Brysbaert and Stevens as the title indicates, is focused on 'Power Analysis and Effect Size in Mixed Effects Models', but it includes a calculation of effect size, whic |
20,187 | How can I derive effect sizes in lme4 and describe the magnitude of fixed effects? | You can indeed compute an effect size in multilevel models. The one provided is called delta total, where total is the total of the variance components. I generally use it when the co-variate in the model is categorical. It should be close to cohen's d, but I would not call it that. Rather, I would refer to it as an effect size parameter. Computing the interval will be challenging in a frequentist framework, but is easily done using Bayesian methods. Since Bayesian methods provide entire posterior distributions, calculation of delta total is done on the posterior distributions, which readily allows for computing credible intervals via the quantile function in r or some package for obtaining high density intervals.
This is a simple case, however, and I would recommend reading the paper cited for other ways to compute effect sizes in multilevel models.
$$
\delta_t = \frac{beta_{treat}} {sqrt(sigma_{visitor}^2 + sigma_{date:id}^2 +sigma_{display}^2 + sigma_{resid}^2 )}
$$
Hedges, L. V. (2007). Effect Sizes in Cluster-Randomized Designs. Journal of Educational and Behavioral Statistics, 32(4), 341β370. | How can I derive effect sizes in lme4 and describe the magnitude of fixed effects? | You can indeed compute an effect size in multilevel models. The one provided is called delta total, where total is the total of the variance components. I generally use it when the co-variate in the m | How can I derive effect sizes in lme4 and describe the magnitude of fixed effects?
You can indeed compute an effect size in multilevel models. The one provided is called delta total, where total is the total of the variance components. I generally use it when the co-variate in the model is categorical. It should be close to cohen's d, but I would not call it that. Rather, I would refer to it as an effect size parameter. Computing the interval will be challenging in a frequentist framework, but is easily done using Bayesian methods. Since Bayesian methods provide entire posterior distributions, calculation of delta total is done on the posterior distributions, which readily allows for computing credible intervals via the quantile function in r or some package for obtaining high density intervals.
This is a simple case, however, and I would recommend reading the paper cited for other ways to compute effect sizes in multilevel models.
$$
\delta_t = \frac{beta_{treat}} {sqrt(sigma_{visitor}^2 + sigma_{date:id}^2 +sigma_{display}^2 + sigma_{resid}^2 )}
$$
Hedges, L. V. (2007). Effect Sizes in Cluster-Randomized Designs. Journal of Educational and Behavioral Statistics, 32(4), 341β370. | How can I derive effect sizes in lme4 and describe the magnitude of fixed effects?
You can indeed compute an effect size in multilevel models. The one provided is called delta total, where total is the total of the variance components. I generally use it when the co-variate in the m |
20,188 | Best way to seed N independent random number generators from 1 value | It's not great practice, certainly. For example, consider what happens when you do two runs with root seeds of 12345 and 12346. Each run will have N-1 streams in common.
Mersenne Twister implementations (including numpy.random and random) typically use a different PRNG to expand the integer seed into the large state vector (624 32-bit integers) that MT uses; this is the array from RandomState.get_state(). A good way to do what you want is to run that PRNG, seeded with your input integer once, and get N*624 32-bit integers from it. Split that stream up into N state vectors and use RandomState.set_state() to explicitly initialize each RandomState instance. You may have to consult the C sources of numpy.random or _random from the standard library to get that PRNG (they are the same). I'm not sure if anyone has implemented a standalone version of that PRNG for Python. | Best way to seed N independent random number generators from 1 value | It's not great practice, certainly. For example, consider what happens when you do two runs with root seeds of 12345 and 12346. Each run will have N-1 streams in common.
Mersenne Twister implementatio | Best way to seed N independent random number generators from 1 value
It's not great practice, certainly. For example, consider what happens when you do two runs with root seeds of 12345 and 12346. Each run will have N-1 streams in common.
Mersenne Twister implementations (including numpy.random and random) typically use a different PRNG to expand the integer seed into the large state vector (624 32-bit integers) that MT uses; this is the array from RandomState.get_state(). A good way to do what you want is to run that PRNG, seeded with your input integer once, and get N*624 32-bit integers from it. Split that stream up into N state vectors and use RandomState.set_state() to explicitly initialize each RandomState instance. You may have to consult the C sources of numpy.random or _random from the standard library to get that PRNG (they are the same). I'm not sure if anyone has implemented a standalone version of that PRNG for Python. | Best way to seed N independent random number generators from 1 value
It's not great practice, certainly. For example, consider what happens when you do two runs with root seeds of 12345 and 12346. Each run will have N-1 streams in common.
Mersenne Twister implementatio |
20,189 | Best way to seed N independent random number generators from 1 value | A solution that is used in parallel processing is to use your random generator $\Phi(u)$, where $u$ is your seed, by $N$-batches:
generate $\Phi(u),\Phi^N(u),\Phi^{2*N}(u),...$
generate $\Phi^2(u),\Phi^{1+N}(u),\Phi^{1+2*N}(u),...$
...
generate $\Phi^{N-1}(u),\Phi^{N-1+N}(u),\Phi^{N-1+2*N}(u),...$
where $\Phi^n(u)=\Phi(\Phi^{n-1}(u))$. This way you use a single seed and your sequences are all uniform and independent. | Best way to seed N independent random number generators from 1 value | A solution that is used in parallel processing is to use your random generator $\Phi(u)$, where $u$ is your seed, by $N$-batches:
generate $\Phi(u),\Phi^N(u),\Phi^{2*N}(u),...$
generate $\Phi^2(u),\P | Best way to seed N independent random number generators from 1 value
A solution that is used in parallel processing is to use your random generator $\Phi(u)$, where $u$ is your seed, by $N$-batches:
generate $\Phi(u),\Phi^N(u),\Phi^{2*N}(u),...$
generate $\Phi^2(u),\Phi^{1+N}(u),\Phi^{1+2*N}(u),...$
...
generate $\Phi^{N-1}(u),\Phi^{N-1+N}(u),\Phi^{N-1+2*N}(u),...$
where $\Phi^n(u)=\Phi(\Phi^{n-1}(u))$. This way you use a single seed and your sequences are all uniform and independent. | Best way to seed N independent random number generators from 1 value
A solution that is used in parallel processing is to use your random generator $\Phi(u)$, where $u$ is your seed, by $N$-batches:
generate $\Phi(u),\Phi^N(u),\Phi^{2*N}(u),...$
generate $\Phi^2(u),\P |
20,190 | Best way to seed N independent random number generators from 1 value | There is now a Python package called RandomGen that has methods to achieve this.
It supports independent streams created from a single seed, as well as a jumping protocol for older random number generators such as MT19937. | Best way to seed N independent random number generators from 1 value | There is now a Python package called RandomGen that has methods to achieve this.
It supports independent streams created from a single seed, as well as a jumping protocol for older random number gener | Best way to seed N independent random number generators from 1 value
There is now a Python package called RandomGen that has methods to achieve this.
It supports independent streams created from a single seed, as well as a jumping protocol for older random number generators such as MT19937. | Best way to seed N independent random number generators from 1 value
There is now a Python package called RandomGen that has methods to achieve this.
It supports independent streams created from a single seed, as well as a jumping protocol for older random number gener |
20,191 | Best way to seed N independent random number generators from 1 value | Some people claim that there are correlations in the random numbers generated by sequential seeds. https://stackoverflow.com/questions/10900852/near-seeds-in-random-number-generation-may-give-similar-random-numbers I'm not sure how true that is.
If you are worried about it, why not use a single random number generator to choose the seeds for all of the other generators? | Best way to seed N independent random number generators from 1 value | Some people claim that there are correlations in the random numbers generated by sequential seeds. https://stackoverflow.com/questions/10900852/near-seeds-in-random-number-generation-may-give-similar- | Best way to seed N independent random number generators from 1 value
Some people claim that there are correlations in the random numbers generated by sequential seeds. https://stackoverflow.com/questions/10900852/near-seeds-in-random-number-generation-may-give-similar-random-numbers I'm not sure how true that is.
If you are worried about it, why not use a single random number generator to choose the seeds for all of the other generators? | Best way to seed N independent random number generators from 1 value
Some people claim that there are correlations in the random numbers generated by sequential seeds. https://stackoverflow.com/questions/10900852/near-seeds-in-random-number-generation-may-give-similar- |
20,192 | Two methods of adding random effects to a GAM give very different results. Why is this and which one should be used? | I suspect the difference is in terms of what fitted values you are getting. If you look at what I would call the model fit, the coefficient estimates, variance terms, the models are identical. Compare summary(m2$lme) with summary(m1) and gam.vcomp(m1).
> summary(m1)
Family: gaussian
Link function: identity
Formula:
y ~ x + s(ID, bs = "re")
Parametric coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.05234 0.07932 0.66 0.51
x 1.01375 0.03535 28.68 <2e-16 ***
---
Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1
Approximate significance of smooth terms:
edf Ref.df F p-value
s(ID) 167.1 199 5.243 <2e-16 ***
---
Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1
R-sq.(adj) = 0.674 Deviance explained = 72.9%
GCV = 1.2133 Scale est. = 1.0082 n = 1000
> summary(m2$lme)
Linear mixed-effects model fit by maximum likelihood
Data: strip.offset(mf)
AIC BIC logLik
3218.329 3237.96 -1605.165
Random effects:
Formula: ~1 | ID
(Intercept) Residual
StdDev: 1.025306 1.003452
Fixed effects: y.0 ~ X - 1
Value Std.Error DF t-value p-value
X(Intercept) 0.0523358 0.07922717 799 0.660578 0.5091
Xx 1.0137531 0.03535887 799 28.670404 0.0000
Correlation:
X(Int)
Xx 0.014
Standardized Within-Group Residuals:
Min Q1 Med Q3 Max
-2.80375873 -0.67702485 0.04245145 0.64026891 2.59257295
Number of Observations: 1000
Number of Groups: 200
We see that the estimates for $\hat{\beta}_x$ are 1.01375 and $\hat{\beta}_0$ ~0.05 in both models. Note also the estimate for the between subject/group variance (as a standard deviation), $\hat{\sigma}_{\mathrm{ID}}$ is given as 1.025 in the output from summary(m2$lme). The same information can be computed from the gam model using gam.vcomp(), which gives for m1
> gam.vcomp(m1)
s(ID)
1.027795
which is near enough a match for us to not worry about it.
Hence the fitted methods must be returning different fitted values; if we generate fitted values from m2$lme, then we get the same values as that produced by fitted(m1):
> mean((fitted(m1)-fitted(m2$lme))^2)
[1] 2.966927e-07
which is for all intents and purposes 0.
fitted.lme is documented to return contributions from the the population level (averaging over ID) and for the subject-specific components. This is what fitted.gam will be doing for m1 because it represents the random effect as a spline "fixed" effect. In the case of the gamm model, fitted.gam is returning fitted values for the "fixed" effect part of the model, which would explain the difference. (I'm writing "fixed" because with splines the terms "fixed" and "random" effects get a little blurred.)
In his book, Simon Wood mentions this issue in the example fit to the Sole data using gamm(). He talks about using resid() and fitted() on the $lme component of the gamm model as excluding and including the random effects, respectively. He says this is appropriate for model diagnostics in the specific example here is using.
Which you need will depend on the context of your specific usage/research question.
If all you need are simple random effects like this and you are familiar with GAMs and mgcv then it might be simpler all round to just use the random effect spline basis with gam() rather than having to deal with the weird output of the hybrid that is a GAMM model fitted via gamm(). As I've shown above, the two models are effectively equivalent and the difference you report is just down to whether the fitted values include or exclude the subject (or ID) specific effects. | Two methods of adding random effects to a GAM give very different results. Why is this and which one | I suspect the difference is in terms of what fitted values you are getting. If you look at what I would call the model fit, the coefficient estimates, variance terms, the models are identical. Compare | Two methods of adding random effects to a GAM give very different results. Why is this and which one should be used?
I suspect the difference is in terms of what fitted values you are getting. If you look at what I would call the model fit, the coefficient estimates, variance terms, the models are identical. Compare summary(m2$lme) with summary(m1) and gam.vcomp(m1).
> summary(m1)
Family: gaussian
Link function: identity
Formula:
y ~ x + s(ID, bs = "re")
Parametric coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.05234 0.07932 0.66 0.51
x 1.01375 0.03535 28.68 <2e-16 ***
---
Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1
Approximate significance of smooth terms:
edf Ref.df F p-value
s(ID) 167.1 199 5.243 <2e-16 ***
---
Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1
R-sq.(adj) = 0.674 Deviance explained = 72.9%
GCV = 1.2133 Scale est. = 1.0082 n = 1000
> summary(m2$lme)
Linear mixed-effects model fit by maximum likelihood
Data: strip.offset(mf)
AIC BIC logLik
3218.329 3237.96 -1605.165
Random effects:
Formula: ~1 | ID
(Intercept) Residual
StdDev: 1.025306 1.003452
Fixed effects: y.0 ~ X - 1
Value Std.Error DF t-value p-value
X(Intercept) 0.0523358 0.07922717 799 0.660578 0.5091
Xx 1.0137531 0.03535887 799 28.670404 0.0000
Correlation:
X(Int)
Xx 0.014
Standardized Within-Group Residuals:
Min Q1 Med Q3 Max
-2.80375873 -0.67702485 0.04245145 0.64026891 2.59257295
Number of Observations: 1000
Number of Groups: 200
We see that the estimates for $\hat{\beta}_x$ are 1.01375 and $\hat{\beta}_0$ ~0.05 in both models. Note also the estimate for the between subject/group variance (as a standard deviation), $\hat{\sigma}_{\mathrm{ID}}$ is given as 1.025 in the output from summary(m2$lme). The same information can be computed from the gam model using gam.vcomp(), which gives for m1
> gam.vcomp(m1)
s(ID)
1.027795
which is near enough a match for us to not worry about it.
Hence the fitted methods must be returning different fitted values; if we generate fitted values from m2$lme, then we get the same values as that produced by fitted(m1):
> mean((fitted(m1)-fitted(m2$lme))^2)
[1] 2.966927e-07
which is for all intents and purposes 0.
fitted.lme is documented to return contributions from the the population level (averaging over ID) and for the subject-specific components. This is what fitted.gam will be doing for m1 because it represents the random effect as a spline "fixed" effect. In the case of the gamm model, fitted.gam is returning fitted values for the "fixed" effect part of the model, which would explain the difference. (I'm writing "fixed" because with splines the terms "fixed" and "random" effects get a little blurred.)
In his book, Simon Wood mentions this issue in the example fit to the Sole data using gamm(). He talks about using resid() and fitted() on the $lme component of the gamm model as excluding and including the random effects, respectively. He says this is appropriate for model diagnostics in the specific example here is using.
Which you need will depend on the context of your specific usage/research question.
If all you need are simple random effects like this and you are familiar with GAMs and mgcv then it might be simpler all round to just use the random effect spline basis with gam() rather than having to deal with the weird output of the hybrid that is a GAMM model fitted via gamm(). As I've shown above, the two models are effectively equivalent and the difference you report is just down to whether the fitted values include or exclude the subject (or ID) specific effects. | Two methods of adding random effects to a GAM give very different results. Why is this and which one
I suspect the difference is in terms of what fitted values you are getting. If you look at what I would call the model fit, the coefficient estimates, variance terms, the models are identical. Compare |
20,193 | How to choose $\alpha$ in cost-complexity pruning? | Yes, such a mapping does exist, but it is less useful than expected.
The overall goal is to minimize the cost-complexity function
$$
C_\alpha (T) = R(T)+ \alpha|T|
$$
where $|T|$ is the number of leaves in tree $T$ and $R(T)$ a loss function calculated across these leaves.
First step is to calculate a sequence of subtrees $T^0\supseteq T^{1}...\supseteq T^{n-1}\supseteq T^{n}$ where $T_n$ is the tree consisting only of the root node and $T_0$ the whole tree.
This is done by successively replacing a subtree $T_t$ with root node $t$ with a leaf (i.e. collapsing this subtree). In each step the subtree $T_t$ is selected, which minimizes the decrease in the cost-complexity function and hence is the weakest link of the tree.
As formula: Minimize
$$
C_\alpha(T-T_t) - C_\alpha(T)\\
=R(T-T_t)+ \alpha|T-T_t| - (R(T)+ \alpha|T|)\\
=R(T-T_t)-R(T)+\alpha(|T-T_t|-|T|)\\
=^1 R(T)-R(T_t)+R(t)-R(T) + \alpha(|T|-|T_t|+1-|T|)\\
=R(t)-R(T_t) + \alpha(1-|T_t|)\\
$$
This is 0 exactly when
$$
\alpha=\frac{R(t)-R(T_t)}{|T_t|-1}
$$
So minimizing $C_\alpha(T-T_t) - C_\alpha(T)$ means minimizing $\alpha=\frac{R(t)-R(T_t)}{|T_t|-1}$
So starting with the whole tree $T^0$ (and $\alpha^0=0$) in each step s the algorithm
selects the node t which minimizes $\frac{R(t)-R(T^{s-1}_t)}{|T^{s-1}_t|-1}$
set $T^s=T^{s-1}-T_t$, $\alpha^s=\frac{R(t)-R(T^{s-1}_t)}{|T^{s-1}_t|-1}$
until the tree consists only of the root node.
Hence as output we get a sequence of subtrees
$T^0\supseteq T^{1}...\supseteq T^{n-1}\supseteq T^{n}$
alongside with the corresponding $\alpha$-values
$0=\alpha^0\leq\alpha^1\leq...\alpha^{n-1}\leq\alpha^{n}$
Using these values one can define a mapping from $\alpha$ to a list of subtrees.
BUT
The cost-complexity function and so the loss / error function have been calculated on the training data, hence the danger of self-validation and overfitting is present. Because of this the final $\alpha$ is determined by crossvalidation.$^2$
Calculating the sequence of subtrees of the tree trained on all the training-data (before optimization via inner crossvalidation) at least gives us an interval of possible $\alpha$-values to select from.
Sources:
cost-complexity pruning explained by Alexey Grigorev
Cost-complexity pruning of random forests by Kiran Bangalore Ravi, Jean Serra
The Elements of Statistical Learning by Friedman et. al
The original source all the sources above are referring to is Breiman, L., Friedman, J., Olshen, R. and Stone, C. (1984). Classification
and Regression Trees, Wadsworth, New York. Unfortunately I was not able to get my hands on it.
Appendix
(1) Why is this true ?
$$
=R(T-T_t)-R(T)+\alpha(|T-T_t|-|T|)\\
=R(T)-R(T_t)+R(t)-R(T) + \alpha(|T|-|T_t|+1-|T|)\\
$$
It is easier to understand with an image
Let's look at $R(T-T_t)=R(T)-R(T_t)+R(t)$
The error / loss function $R$ is calculated across all leaves of the input tree. The transformation $T-T_t$ collapses the subtree $T_t$ into into one leaf $t$. So $R(T-T_t)$ is
$R(T)$ (across all leaves)
- $R(T_t)$ (across the leaves of the "removed" subtree $T_t$)
+ $R(t)$ (across the freshly added leaf $t$ the subtree $T_t$ has been collapsed to)
Same logic applies to part calculating the number of leaves.
(2) How to determine $\alpha$ by crossvalidation ?
I am not sure if this is canon, but this how I would do it.
Input: Training data provided by the outer surrounding crossvalidation
Train tree on entire training data
Calculate sequence of subtrees $S$ and $\alpha$s $A$ to test.
Apply inner crossvalidation. For every run:
Train tree on training data provided by inner crossvalidation
Calculate sequence of subtrees
For each $\alpha$ in $A$, keep subtree which minimizes $C_\alpha(T)$
Evaluate these test-trees on test-set
Select $\alpha$ with best performance based on inner crossvalidation
Find subtree in the sequence $S$ built based on entire training data for that $\alpha$
Return that subtree
A similar approach is described in a lecture in Stanford University(starting at slide 10). | How to choose $\alpha$ in cost-complexity pruning? | Yes, such a mapping does exist, but it is less useful than expected.
The overall goal is to minimize the cost-complexity function
$$
C_\alpha (T) = R(T)+ \alpha|T|
$$
where $|T|$ is the number of leav | How to choose $\alpha$ in cost-complexity pruning?
Yes, such a mapping does exist, but it is less useful than expected.
The overall goal is to minimize the cost-complexity function
$$
C_\alpha (T) = R(T)+ \alpha|T|
$$
where $|T|$ is the number of leaves in tree $T$ and $R(T)$ a loss function calculated across these leaves.
First step is to calculate a sequence of subtrees $T^0\supseteq T^{1}...\supseteq T^{n-1}\supseteq T^{n}$ where $T_n$ is the tree consisting only of the root node and $T_0$ the whole tree.
This is done by successively replacing a subtree $T_t$ with root node $t$ with a leaf (i.e. collapsing this subtree). In each step the subtree $T_t$ is selected, which minimizes the decrease in the cost-complexity function and hence is the weakest link of the tree.
As formula: Minimize
$$
C_\alpha(T-T_t) - C_\alpha(T)\\
=R(T-T_t)+ \alpha|T-T_t| - (R(T)+ \alpha|T|)\\
=R(T-T_t)-R(T)+\alpha(|T-T_t|-|T|)\\
=^1 R(T)-R(T_t)+R(t)-R(T) + \alpha(|T|-|T_t|+1-|T|)\\
=R(t)-R(T_t) + \alpha(1-|T_t|)\\
$$
This is 0 exactly when
$$
\alpha=\frac{R(t)-R(T_t)}{|T_t|-1}
$$
So minimizing $C_\alpha(T-T_t) - C_\alpha(T)$ means minimizing $\alpha=\frac{R(t)-R(T_t)}{|T_t|-1}$
So starting with the whole tree $T^0$ (and $\alpha^0=0$) in each step s the algorithm
selects the node t which minimizes $\frac{R(t)-R(T^{s-1}_t)}{|T^{s-1}_t|-1}$
set $T^s=T^{s-1}-T_t$, $\alpha^s=\frac{R(t)-R(T^{s-1}_t)}{|T^{s-1}_t|-1}$
until the tree consists only of the root node.
Hence as output we get a sequence of subtrees
$T^0\supseteq T^{1}...\supseteq T^{n-1}\supseteq T^{n}$
alongside with the corresponding $\alpha$-values
$0=\alpha^0\leq\alpha^1\leq...\alpha^{n-1}\leq\alpha^{n}$
Using these values one can define a mapping from $\alpha$ to a list of subtrees.
BUT
The cost-complexity function and so the loss / error function have been calculated on the training data, hence the danger of self-validation and overfitting is present. Because of this the final $\alpha$ is determined by crossvalidation.$^2$
Calculating the sequence of subtrees of the tree trained on all the training-data (before optimization via inner crossvalidation) at least gives us an interval of possible $\alpha$-values to select from.
Sources:
cost-complexity pruning explained by Alexey Grigorev
Cost-complexity pruning of random forests by Kiran Bangalore Ravi, Jean Serra
The Elements of Statistical Learning by Friedman et. al
The original source all the sources above are referring to is Breiman, L., Friedman, J., Olshen, R. and Stone, C. (1984). Classification
and Regression Trees, Wadsworth, New York. Unfortunately I was not able to get my hands on it.
Appendix
(1) Why is this true ?
$$
=R(T-T_t)-R(T)+\alpha(|T-T_t|-|T|)\\
=R(T)-R(T_t)+R(t)-R(T) + \alpha(|T|-|T_t|+1-|T|)\\
$$
It is easier to understand with an image
Let's look at $R(T-T_t)=R(T)-R(T_t)+R(t)$
The error / loss function $R$ is calculated across all leaves of the input tree. The transformation $T-T_t$ collapses the subtree $T_t$ into into one leaf $t$. So $R(T-T_t)$ is
$R(T)$ (across all leaves)
- $R(T_t)$ (across the leaves of the "removed" subtree $T_t$)
+ $R(t)$ (across the freshly added leaf $t$ the subtree $T_t$ has been collapsed to)
Same logic applies to part calculating the number of leaves.
(2) How to determine $\alpha$ by crossvalidation ?
I am not sure if this is canon, but this how I would do it.
Input: Training data provided by the outer surrounding crossvalidation
Train tree on entire training data
Calculate sequence of subtrees $S$ and $\alpha$s $A$ to test.
Apply inner crossvalidation. For every run:
Train tree on training data provided by inner crossvalidation
Calculate sequence of subtrees
For each $\alpha$ in $A$, keep subtree which minimizes $C_\alpha(T)$
Evaluate these test-trees on test-set
Select $\alpha$ with best performance based on inner crossvalidation
Find subtree in the sequence $S$ built based on entire training data for that $\alpha$
Return that subtree
A similar approach is described in a lecture in Stanford University(starting at slide 10). | How to choose $\alpha$ in cost-complexity pruning?
Yes, such a mapping does exist, but it is less useful than expected.
The overall goal is to minimize the cost-complexity function
$$
C_\alpha (T) = R(T)+ \alpha|T|
$$
where $|T|$ is the number of leav |
20,194 | How to choose $\alpha$ in cost-complexity pruning? | The tuning parameter alpha controls the tradeoff between the complexity of the tree and its accuracy/fit. 'alpha' being the penalty and 'T' the number of terminal nodes of the tree, as you increase alpha, branches get pruned in a predictable fashion ground up i.e there exists a different subtree that minimizes the cost complexity criterion for each value of the penalty.
As you mentioned, you can select an optimal value of alpha by using K-fold cross validation - build as large a tree as you can on each fold while aiming to minimize the cost complexity criterion for a different value of alpha. Averaging the results of all the trees and predicting on the kth fold would give you error rates for each alpha. Pick the penalty that minimizes the cross validation error.
Equation 9.16 in the 4th printing of ESL is simply a different representation of the same (cost complexity) criterion. | How to choose $\alpha$ in cost-complexity pruning? | The tuning parameter alpha controls the tradeoff between the complexity of the tree and its accuracy/fit. 'alpha' being the penalty and 'T' the number of terminal nodes of the tree, as you increase al | How to choose $\alpha$ in cost-complexity pruning?
The tuning parameter alpha controls the tradeoff between the complexity of the tree and its accuracy/fit. 'alpha' being the penalty and 'T' the number of terminal nodes of the tree, as you increase alpha, branches get pruned in a predictable fashion ground up i.e there exists a different subtree that minimizes the cost complexity criterion for each value of the penalty.
As you mentioned, you can select an optimal value of alpha by using K-fold cross validation - build as large a tree as you can on each fold while aiming to minimize the cost complexity criterion for a different value of alpha. Averaging the results of all the trees and predicting on the kth fold would give you error rates for each alpha. Pick the penalty that minimizes the cross validation error.
Equation 9.16 in the 4th printing of ESL is simply a different representation of the same (cost complexity) criterion. | How to choose $\alpha$ in cost-complexity pruning?
The tuning parameter alpha controls the tradeoff between the complexity of the tree and its accuracy/fit. 'alpha' being the penalty and 'T' the number of terminal nodes of the tree, as you increase al |
20,195 | Why is the 95% CI for the median supposed to be $Β±1.57*IQR/\sqrt{N}$? | That's easy. If we check the original paper where notched box-and-whisker plots were introduced (Robert McGill, John W. Tukey and Wayne A. Larsen. Variations of Box Plots, The American Statistician, Vol. 32, No. 1 (Feb., 1978), pp. 12-16; fortunately, it's on JSTOR), we found section 7 where this formula is justified in the following way:
Should one desire a notch indicating a 95 percent confidence interval about
each median, C=1.96 would be used. [Here C is different constant which is
related to ours, but the exact relation is of no importance as will be clear
later β I.S.] However, since a form of "gap gauge" which
would indicate significant differences
at the 95 percent level was desired, this was not done. It can be shown that C = 1.96 would only be appropriate if the standard deviations of the two groups
were vastly different. If they were nearly equal, C = 1.386 would be the
appropriate value, with 1.96 resulting in far too stringent a test (far beyond 99 percent).
A value between these limits, C = 1.7, was empirically selected as preferable.
Thus the notches used were computed as $M \pm 1.7(1.25R/1.35 \sqrt{N})$.
Emphasis is mine. Note that $1.7\times 1.25/1.35=1.57$, which is your magic number.
So, the short answer is: it is not a general formula for median CI but a particular tool for visualization and the constant was empirically selected to achieve a particular goal.
There's no magic.
Sorry. | Why is the 95% CI for the median supposed to be $Β±1.57*IQR/\sqrt{N}$? | That's easy. If we check the original paper where notched box-and-whisker plots were introduced (Robert McGill, John W. Tukey and Wayne A. Larsen. Variations of Box Plots, The American Statistician, V | Why is the 95% CI for the median supposed to be $Β±1.57*IQR/\sqrt{N}$?
That's easy. If we check the original paper where notched box-and-whisker plots were introduced (Robert McGill, John W. Tukey and Wayne A. Larsen. Variations of Box Plots, The American Statistician, Vol. 32, No. 1 (Feb., 1978), pp. 12-16; fortunately, it's on JSTOR), we found section 7 where this formula is justified in the following way:
Should one desire a notch indicating a 95 percent confidence interval about
each median, C=1.96 would be used. [Here C is different constant which is
related to ours, but the exact relation is of no importance as will be clear
later β I.S.] However, since a form of "gap gauge" which
would indicate significant differences
at the 95 percent level was desired, this was not done. It can be shown that C = 1.96 would only be appropriate if the standard deviations of the two groups
were vastly different. If they were nearly equal, C = 1.386 would be the
appropriate value, with 1.96 resulting in far too stringent a test (far beyond 99 percent).
A value between these limits, C = 1.7, was empirically selected as preferable.
Thus the notches used were computed as $M \pm 1.7(1.25R/1.35 \sqrt{N})$.
Emphasis is mine. Note that $1.7\times 1.25/1.35=1.57$, which is your magic number.
So, the short answer is: it is not a general formula for median CI but a particular tool for visualization and the constant was empirically selected to achieve a particular goal.
There's no magic.
Sorry. | Why is the 95% CI for the median supposed to be $Β±1.57*IQR/\sqrt{N}$?
That's easy. If we check the original paper where notched box-and-whisker plots were introduced (Robert McGill, John W. Tukey and Wayne A. Larsen. Variations of Box Plots, The American Statistician, V |
20,196 | What is the difference between 'hypothesis testing' and 'model selection'? | To me the distinction is that with hypothesis testing one is considering contrasts of model parameters and is not entertaining the thought of changing the model. For example, in ANOVA, people are smart enough not to convert a 4 degree of freedom $F$-test to a 3 d.f. $F$-test when comparing 5 groups and finding that two of the groups have similar means. People who formulating models often make the basic mistake of selecting which parameters should be in the model on the basis of statistical tests/comparisons, not realizing that this biases things (especially $\sigma^2$). The the example to which I just alluded, the unbiased estimate of $\sigma^2$ comes from the model having 5 regression parameters (overall intercept + 4 indicator variables).
Model selection often involves (dangerously) choosing
among a set of competing model families or distributions
which $X$s should be in the model
how each $X$ should be modeled (e.g., consideration of nonlinear terms) | What is the difference between 'hypothesis testing' and 'model selection'? | To me the distinction is that with hypothesis testing one is considering contrasts of model parameters and is not entertaining the thought of changing the model. For example, in ANOVA, people are sma | What is the difference between 'hypothesis testing' and 'model selection'?
To me the distinction is that with hypothesis testing one is considering contrasts of model parameters and is not entertaining the thought of changing the model. For example, in ANOVA, people are smart enough not to convert a 4 degree of freedom $F$-test to a 3 d.f. $F$-test when comparing 5 groups and finding that two of the groups have similar means. People who formulating models often make the basic mistake of selecting which parameters should be in the model on the basis of statistical tests/comparisons, not realizing that this biases things (especially $\sigma^2$). The the example to which I just alluded, the unbiased estimate of $\sigma^2$ comes from the model having 5 regression parameters (overall intercept + 4 indicator variables).
Model selection often involves (dangerously) choosing
among a set of competing model families or distributions
which $X$s should be in the model
how each $X$ should be modeled (e.g., consideration of nonlinear terms) | What is the difference between 'hypothesis testing' and 'model selection'?
To me the distinction is that with hypothesis testing one is considering contrasts of model parameters and is not entertaining the thought of changing the model. For example, in ANOVA, people are sma |
20,197 | Why does SAS PROC GLIMMIX give me VERY different random slopes than glmer (lme4) for a binomial glmm | It appears that I shouldn't have expected the random slopes to be similar between packages, according to Zhang et al 2011. In their paper On Fitting Generalized Linear Mixed-effects Models for Binary Responses using Different Statistical Packages, they describe:
Abstract:
The generalized linear mixed-effects model (GLMM) is a popular paradigm to extend models for cross-sectional data to a longitudinal setting. When applied to modeling binary responses, different software packages and even different procedures within a package may give quite different results. In this report, we describe the statistical approaches that underlie these different procedures and discuss their strengths and weaknesses when applied to fit correlated binary responses. We then illustrate these considerations by applying these procedures implemented in some popular software packages to simulated and real study data. Our simulation results indicate a lack of reliability for most of the procedures considered, which carries significant implications for applying such popular software packages in practice.
I hope @BenBolker and team will consider my question as a vote for R to incorporate empirical standard errors and Gauss-Hermite Quadrature capability for models with several random slope terms to glmer, as I prefer the R interface and would love to be able to apply some further analyses in that program. Happily, even while R and SAS do not have comparable values for random slopes, the overall trends are the same. Thanks all for your input, I really appreciate the time and consideration that you put into this! | Why does SAS PROC GLIMMIX give me VERY different random slopes than glmer (lme4) for a binomial glmm | It appears that I shouldn't have expected the random slopes to be similar between packages, according to Zhang et al 2011. In their paper On Fitting Generalized Linear Mixed-effects Models for Binary | Why does SAS PROC GLIMMIX give me VERY different random slopes than glmer (lme4) for a binomial glmm
It appears that I shouldn't have expected the random slopes to be similar between packages, according to Zhang et al 2011. In their paper On Fitting Generalized Linear Mixed-effects Models for Binary Responses using Different Statistical Packages, they describe:
Abstract:
The generalized linear mixed-effects model (GLMM) is a popular paradigm to extend models for cross-sectional data to a longitudinal setting. When applied to modeling binary responses, different software packages and even different procedures within a package may give quite different results. In this report, we describe the statistical approaches that underlie these different procedures and discuss their strengths and weaknesses when applied to fit correlated binary responses. We then illustrate these considerations by applying these procedures implemented in some popular software packages to simulated and real study data. Our simulation results indicate a lack of reliability for most of the procedures considered, which carries significant implications for applying such popular software packages in practice.
I hope @BenBolker and team will consider my question as a vote for R to incorporate empirical standard errors and Gauss-Hermite Quadrature capability for models with several random slope terms to glmer, as I prefer the R interface and would love to be able to apply some further analyses in that program. Happily, even while R and SAS do not have comparable values for random slopes, the overall trends are the same. Thanks all for your input, I really appreciate the time and consideration that you put into this! | Why does SAS PROC GLIMMIX give me VERY different random slopes than glmer (lme4) for a binomial glmm
It appears that I shouldn't have expected the random slopes to be similar between packages, according to Zhang et al 2011. In their paper On Fitting Generalized Linear Mixed-effects Models for Binary |
20,198 | Why does SAS PROC GLIMMIX give me VERY different random slopes than glmer (lme4) for a binomial glmm | A mixture of an answer and commentary/more questions:
I fitted the 'toy' data set with three different optimizer choices. (*Note 1: it would probably be more useful for comparative purposes to make a small data set by subsampling from within every year and id, rather than by subsampling the grouping variables. As it is, we know that the GLMM won't perform particularly well with such a small number of grouping variable levels. You can do this via something like:
library(plyr)
subdata <- ddply(fulldata,c("year","id"),
function(x) x[sample(nrow(x),size=round(nrow(x)*0.1)),])
Batch fitting code:
Ntoy <- readRDS("Newton_toy.RDS")
library(lme4)
fitfun <- function(opt) {
tt <- system.time(fit1 <- glmer(use ~ ps + th + rs + hw +
(1 + ps + th + rs + hw |id/year),
family = binomial, data = Ntoy,
control=glmerControl(optimizer=opt),
verbose=100))
return(list(time=tt,fit=fit1))
}
opts <- c("nloptwrap","nlminbwrap","bobyqa")
## use for() instead of lapply so we can checkpoint more easily
res <- setNames(vector("list",length(opts)),opts)
for (i in opts) {
res[[i]] <- fitfun(i)
save("res",file="Newton_batch.RData")
}
Then I read in the results in a new session:
load("Newton_batch.RData")
library(lme4)
Elapsed time and deviance:
cbind(time=unname(sapply(res,function(x) x$time["elapsed"])),
dev=sapply(res,function(x) deviance(x$fit)))
## time dev
## nloptwrap 1001.824 6067.706
## nlminbwrap 3495.671 6068.730
## bobyqa 4945.332 6068.731
These deviances are considerably below the deviance reported by the OP from R (6101.7), and slightly below the ones reported by the OP from SAS (6078.9), although comparing deviances across packages is not always sensible.
I was indeed surprised that SAS converged in only about 100 function evaluations!
Times range from 17 minutes (nloptwrap) to 80 minutes (bobyqa) on a Macbook Pro, consistent with the OP's experience. Deviance is a bit better for nloptwrap.
round(cbind(sapply(res,function(x) fixef(x$fit))),3)
## nloptwrap nlminbwrap bobyqa
## (Intercept) -5.815 -5.322 -5.322
## ps -0.989 0.171 0.171
## th -0.033 -1.342 -1.341
## rs 1.361 -0.140 -0.139
## hw -2.100 -2.082 -2.082
Answers appear quite different with nloptwrap -- although the standard errors are quite large ...
round(coef(summary(res[[1]]$fit)),3)
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -5.815 0.750 -7.750 0.000
## ps -0.989 1.275 -0.776 0.438
## th -0.033 2.482 -0.013 0.989
## rs 1.361 2.799 0.486 0.627
## hw -2.100 0.490 -4.283 0.000
(code here gives some warnings about year:id that I should track down)
To be continued ... ? | Why does SAS PROC GLIMMIX give me VERY different random slopes than glmer (lme4) for a binomial glmm | A mixture of an answer and commentary/more questions:
I fitted the 'toy' data set with three different optimizer choices. (*Note 1: it would probably be more useful for comparative purposes to make a | Why does SAS PROC GLIMMIX give me VERY different random slopes than glmer (lme4) for a binomial glmm
A mixture of an answer and commentary/more questions:
I fitted the 'toy' data set with three different optimizer choices. (*Note 1: it would probably be more useful for comparative purposes to make a small data set by subsampling from within every year and id, rather than by subsampling the grouping variables. As it is, we know that the GLMM won't perform particularly well with such a small number of grouping variable levels. You can do this via something like:
library(plyr)
subdata <- ddply(fulldata,c("year","id"),
function(x) x[sample(nrow(x),size=round(nrow(x)*0.1)),])
Batch fitting code:
Ntoy <- readRDS("Newton_toy.RDS")
library(lme4)
fitfun <- function(opt) {
tt <- system.time(fit1 <- glmer(use ~ ps + th + rs + hw +
(1 + ps + th + rs + hw |id/year),
family = binomial, data = Ntoy,
control=glmerControl(optimizer=opt),
verbose=100))
return(list(time=tt,fit=fit1))
}
opts <- c("nloptwrap","nlminbwrap","bobyqa")
## use for() instead of lapply so we can checkpoint more easily
res <- setNames(vector("list",length(opts)),opts)
for (i in opts) {
res[[i]] <- fitfun(i)
save("res",file="Newton_batch.RData")
}
Then I read in the results in a new session:
load("Newton_batch.RData")
library(lme4)
Elapsed time and deviance:
cbind(time=unname(sapply(res,function(x) x$time["elapsed"])),
dev=sapply(res,function(x) deviance(x$fit)))
## time dev
## nloptwrap 1001.824 6067.706
## nlminbwrap 3495.671 6068.730
## bobyqa 4945.332 6068.731
These deviances are considerably below the deviance reported by the OP from R (6101.7), and slightly below the ones reported by the OP from SAS (6078.9), although comparing deviances across packages is not always sensible.
I was indeed surprised that SAS converged in only about 100 function evaluations!
Times range from 17 minutes (nloptwrap) to 80 minutes (bobyqa) on a Macbook Pro, consistent with the OP's experience. Deviance is a bit better for nloptwrap.
round(cbind(sapply(res,function(x) fixef(x$fit))),3)
## nloptwrap nlminbwrap bobyqa
## (Intercept) -5.815 -5.322 -5.322
## ps -0.989 0.171 0.171
## th -0.033 -1.342 -1.341
## rs 1.361 -0.140 -0.139
## hw -2.100 -2.082 -2.082
Answers appear quite different with nloptwrap -- although the standard errors are quite large ...
round(coef(summary(res[[1]]$fit)),3)
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -5.815 0.750 -7.750 0.000
## ps -0.989 1.275 -0.776 0.438
## th -0.033 2.482 -0.013 0.989
## rs 1.361 2.799 0.486 0.627
## hw -2.100 0.490 -4.283 0.000
(code here gives some warnings about year:id that I should track down)
To be continued ... ? | Why does SAS PROC GLIMMIX give me VERY different random slopes than glmer (lme4) for a binomial glmm
A mixture of an answer and commentary/more questions:
I fitted the 'toy' data set with three different optimizer choices. (*Note 1: it would probably be more useful for comparative purposes to make a |
20,199 | What is the maximum likelihood estimate of the covariance of bivariate normal data when mean and variance are known? | The estimator for the correlation coefficient (which in the case of a bivariate standard normal equals the covariance)
$$\tilde r = \frac 1n\sum_{i=1}^nx_iy_i$$
is the Method-of-Moments estimator, the sample covariance. Let's see if it coincides with the maximum likelihood estimator, $\hat \rho$.
The joint density of a bivariate standard normal with correlation coefficient $\rho$ is
$$f(x,y) = \frac{1}{2 \pi \sqrt{1-\rho^2}}
\exp\left\{-\frac{x^2 +y^2 -2\rho xy}{2(1-\rho^2)}\right\} $$
and so the log-likelihood of an i.i.d. sample of size $n$ is
$$\ln L = -n\ln(2\pi) -\frac n2\ln(1-\rho^2) - \frac 1{2(1-\rho^2)}\sum_{i=1}^n(x_i^2 +y_i^2 -2\rho x_iy_i)$$
(here the i.i.d assumption is with respect to each draw from the two-dimensional population of course)
Taking the derivative with respect to $\rho$ and setting it equal to zero gives a 3d-degree polynomial in $\rho$:
$$\hat \rho: n\hat \rho^3 -\left(\sum_{i=1}^nx_iy_i\right)\hat\rho^2 -\left(1- \frac 1n\sum_{i=1}^n(x_i^2 +y_i^2) \right)n\hat \rho - \sum_{i=1}^nx_iy_i =0 $$
That the calculations are correct can be verified if one takes the expected value of the derivative evaluated at the true coefficient $\rho$ -it will equal zero.
For compactness, write $(1/n)\sum_{i=1}^n(x_i^2 +y_i^2) = (1/n)S_2$, which is the sum of the sample variances of $X$ and $Y$. If we divide the 1st-derivative expression by $n$ the MoM estimator will appear, specificaly
$$\hat \rho: \hat \rho^3 -\tilde r \hat \rho^2 + \big[(1/n)S_2-1\big]\hat \rho -\tilde r=0$$
$$\Rightarrow \hat \rho\Big(\hat \rho^2 -\tilde r \hat \rho + \big[(1/n)S_2-1\big] \Big) = \tilde r$$
Doing the algebra, it is not difficult to conclude that we will obtain $\hat \rho = \tilde r$ if,and only if, $(1/n)S_2 =2$, i.e. only if it so happens that the sum of sample variances equals the sum of true variances.
So in general
$$\hat \rho \neq \tilde r$$
So what happens here? Somebody wiser will explain it, for the moment, let's try
a simulation: I generated an i.i.d. sample of two standard normals with correlation coefficient $\rho=0.6$. The sample size was $n=1.000$. The sample values were
$$\sum_{i=1}^nx_iy_i = 522.05,\;\;S_2 = 1913.28$$
The Method-of-Moments estimator gives us
$$\tilde r = \frac {522.05}{1000} = 0.522$$
What happens with the log-likelihood? Visually, we have
Numerically, we have
\begin{array}{| r | r | r |}
\hline
\hline
Ο&\text{1st deriv}&\text{lnL}\\
\hline
0.5&-70.92&-783.65\\
0.51&-59.41&-782.47\\
0.52&-47.7&-781.48\\
0.53&-35.78&-780.68\\
0.54&-23.64&-780.1\\
0.55&-11.29&-779.75\\
0.56&1.29&-779.64\\
0.57&14.1&-779.81\\
0.58&27.15&-780.27\\
0.59&40.44&-781.05\\
0.6&53.98&-782.18\\
\hline
\end{array}
and we see that the log-likelihood has a maximum a tad before $\rho=0.56$ where also the 1st derivative becomes zero $(\hat \rho = 0.558985)$. No surprises for the values of $\rho$ not shown. Also, the 1st derivative has no other root.
So this simulation accords with the result that the maximum likelihood estimator does not equal the method of moments estimator (which is the sample covariance between the two r.v.'s).
But it appears that "everybody" is saying that it should... so somebody should come up with an explanation.
UPDATE
A reference that proves that the MLE is the Method-of-Moments estimator: Anderson, T. W., & Olkin, I. (1985). Maximum-likelihood estimation of the parameters of a multivariate normal distribution. Linear algebra and its applications, 70, 147-171.
Does it matter that here all means and variances are free to vary and not fixed?
... Probably yes, because @guy's comment in another (now deleted) answer says that, with given mean and variance parameters, the bivariate normal becomes a member of the curved exponential family (and so some results and properties change)... which appears to be the only way that can reconcile the two results. | What is the maximum likelihood estimate of the covariance of bivariate normal data when mean and var | The estimator for the correlation coefficient (which in the case of a bivariate standard normal equals the covariance)
$$\tilde r = \frac 1n\sum_{i=1}^nx_iy_i$$
is the Method-of-Moments estimator, th | What is the maximum likelihood estimate of the covariance of bivariate normal data when mean and variance are known?
The estimator for the correlation coefficient (which in the case of a bivariate standard normal equals the covariance)
$$\tilde r = \frac 1n\sum_{i=1}^nx_iy_i$$
is the Method-of-Moments estimator, the sample covariance. Let's see if it coincides with the maximum likelihood estimator, $\hat \rho$.
The joint density of a bivariate standard normal with correlation coefficient $\rho$ is
$$f(x,y) = \frac{1}{2 \pi \sqrt{1-\rho^2}}
\exp\left\{-\frac{x^2 +y^2 -2\rho xy}{2(1-\rho^2)}\right\} $$
and so the log-likelihood of an i.i.d. sample of size $n$ is
$$\ln L = -n\ln(2\pi) -\frac n2\ln(1-\rho^2) - \frac 1{2(1-\rho^2)}\sum_{i=1}^n(x_i^2 +y_i^2 -2\rho x_iy_i)$$
(here the i.i.d assumption is with respect to each draw from the two-dimensional population of course)
Taking the derivative with respect to $\rho$ and setting it equal to zero gives a 3d-degree polynomial in $\rho$:
$$\hat \rho: n\hat \rho^3 -\left(\sum_{i=1}^nx_iy_i\right)\hat\rho^2 -\left(1- \frac 1n\sum_{i=1}^n(x_i^2 +y_i^2) \right)n\hat \rho - \sum_{i=1}^nx_iy_i =0 $$
That the calculations are correct can be verified if one takes the expected value of the derivative evaluated at the true coefficient $\rho$ -it will equal zero.
For compactness, write $(1/n)\sum_{i=1}^n(x_i^2 +y_i^2) = (1/n)S_2$, which is the sum of the sample variances of $X$ and $Y$. If we divide the 1st-derivative expression by $n$ the MoM estimator will appear, specificaly
$$\hat \rho: \hat \rho^3 -\tilde r \hat \rho^2 + \big[(1/n)S_2-1\big]\hat \rho -\tilde r=0$$
$$\Rightarrow \hat \rho\Big(\hat \rho^2 -\tilde r \hat \rho + \big[(1/n)S_2-1\big] \Big) = \tilde r$$
Doing the algebra, it is not difficult to conclude that we will obtain $\hat \rho = \tilde r$ if,and only if, $(1/n)S_2 =2$, i.e. only if it so happens that the sum of sample variances equals the sum of true variances.
So in general
$$\hat \rho \neq \tilde r$$
So what happens here? Somebody wiser will explain it, for the moment, let's try
a simulation: I generated an i.i.d. sample of two standard normals with correlation coefficient $\rho=0.6$. The sample size was $n=1.000$. The sample values were
$$\sum_{i=1}^nx_iy_i = 522.05,\;\;S_2 = 1913.28$$
The Method-of-Moments estimator gives us
$$\tilde r = \frac {522.05}{1000} = 0.522$$
What happens with the log-likelihood? Visually, we have
Numerically, we have
\begin{array}{| r | r | r |}
\hline
\hline
Ο&\text{1st deriv}&\text{lnL}\\
\hline
0.5&-70.92&-783.65\\
0.51&-59.41&-782.47\\
0.52&-47.7&-781.48\\
0.53&-35.78&-780.68\\
0.54&-23.64&-780.1\\
0.55&-11.29&-779.75\\
0.56&1.29&-779.64\\
0.57&14.1&-779.81\\
0.58&27.15&-780.27\\
0.59&40.44&-781.05\\
0.6&53.98&-782.18\\
\hline
\end{array}
and we see that the log-likelihood has a maximum a tad before $\rho=0.56$ where also the 1st derivative becomes zero $(\hat \rho = 0.558985)$. No surprises for the values of $\rho$ not shown. Also, the 1st derivative has no other root.
So this simulation accords with the result that the maximum likelihood estimator does not equal the method of moments estimator (which is the sample covariance between the two r.v.'s).
But it appears that "everybody" is saying that it should... so somebody should come up with an explanation.
UPDATE
A reference that proves that the MLE is the Method-of-Moments estimator: Anderson, T. W., & Olkin, I. (1985). Maximum-likelihood estimation of the parameters of a multivariate normal distribution. Linear algebra and its applications, 70, 147-171.
Does it matter that here all means and variances are free to vary and not fixed?
... Probably yes, because @guy's comment in another (now deleted) answer says that, with given mean and variance parameters, the bivariate normal becomes a member of the curved exponential family (and so some results and properties change)... which appears to be the only way that can reconcile the two results. | What is the maximum likelihood estimate of the covariance of bivariate normal data when mean and var
The estimator for the correlation coefficient (which in the case of a bivariate standard normal equals the covariance)
$$\tilde r = \frac 1n\sum_{i=1}^nx_iy_i$$
is the Method-of-Moments estimator, th |
20,200 | What is the maximum likelihood estimate of the covariance of bivariate normal data when mean and variance are known? | Under the stated conditions ($\mu_X = \mu_Y = 0$ and $\sigma_X = \sigma_Y = 1$), the likelihood function for a random sample of size $n$ is $$L(\rho\; |\; X, Y) = \frac{1}{(2\pi[1-\rho^2])^{n/2}}\exp \left[-\frac{1}{2(1-\rho^2)}(X'X - 2\rho X'Y + Y'Y)\right].$$
Now find the log-likelihood and take the derivative with respect to $\rho$. Next, set it equal to 0, solving for $\hat{\rho}$. You should of course do some appropriate test to show what you've found is in fact a global maximum. | What is the maximum likelihood estimate of the covariance of bivariate normal data when mean and var | Under the stated conditions ($\mu_X = \mu_Y = 0$ and $\sigma_X = \sigma_Y = 1$), the likelihood function for a random sample of size $n$ is $$L(\rho\; |\; X, Y) = \frac{1}{(2\pi[1-\rho^2])^{n/2}}\exp | What is the maximum likelihood estimate of the covariance of bivariate normal data when mean and variance are known?
Under the stated conditions ($\mu_X = \mu_Y = 0$ and $\sigma_X = \sigma_Y = 1$), the likelihood function for a random sample of size $n$ is $$L(\rho\; |\; X, Y) = \frac{1}{(2\pi[1-\rho^2])^{n/2}}\exp \left[-\frac{1}{2(1-\rho^2)}(X'X - 2\rho X'Y + Y'Y)\right].$$
Now find the log-likelihood and take the derivative with respect to $\rho$. Next, set it equal to 0, solving for $\hat{\rho}$. You should of course do some appropriate test to show what you've found is in fact a global maximum. | What is the maximum likelihood estimate of the covariance of bivariate normal data when mean and var
Under the stated conditions ($\mu_X = \mu_Y = 0$ and $\sigma_X = \sigma_Y = 1$), the likelihood function for a random sample of size $n$ is $$L(\rho\; |\; X, Y) = \frac{1}{(2\pi[1-\rho^2])^{n/2}}\exp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.