idx int64 1 56k | question stringlengths 15 155 | answer stringlengths 2 29.2k ⌀ | question_cut stringlengths 15 100 | answer_cut stringlengths 2 200 ⌀ | conversation stringlengths 47 29.3k | conversation_cut stringlengths 47 301 |
|---|---|---|---|---|---|---|
34,001 | Is feature importance in Random Forest useless? | Standard Feature Importances simply tell you which ones of your features were more useful when building the model. They are not to be interpreted as a direct dependence between predictor and target.
As a consequence:
They are completely useless if your model is weak. If your model does not generalize to validation data - like in the case you mentioned of completely random predictors - then feature importances have no meaning. That is because all the splits are simply overfitting the training data and not capturing any real trend, so all the gini impurity you sum is useless
They are strongly influenced by correlated features. As you mentioned, it is a fact. Just know it and perform some good old feature engineering before hand to avoid having features that are too correlated
They are biased towards numerical and high cardinality features. This is definitely a problem. There are some alternative approaches to help relieve this
Therefore you MUST not interpret them as "correlations" or "strength coefficients", as they do not represent a dependency with the target. Yet, this does not mean at all that they are useless!
Some alternative approaches to limit the drawbacks are:
Permutation Importances: these are computed on VALIDATION data, and therefore solve that first overfitting issue. If a feature splits are overfitting on the training data, its importance will be low on test data. Moreover, as they are computed on a metric of your choice, they are easier to interpret and can in some sense be seen as a "strength coefficient", since they answer the question: "How much does the performance of my model degrade if I shuffle this predictor?". Boruta - which was mentioned in the comments - uses an algorithm that is based on this.
Unbiased Feature Importances: There are multiple works on this and the one linked is one of the newer ones. They are not yet implemented in major packages, but allow for a better measurement of importances that does not suffer from the above problems of overfitting
Oblivious Trees: This approach for building trees, which is used for example in catboost, forces all the splits on the same level of a tree to be done on the same feature. This forces splits on features that generalize better, and often gives importances that resent much less from overfitting the training.
Finally - feature importances are very useful and help discern important features form unimportant ones when using very powerful algorithms such as GBMs and RFs - however, they need to be used with care and interpreted the right way. At the same time, there are some alternatives and packages that solve some of the major flaws of classic feature importances, making them even more easy to use and interpret. | Is feature importance in Random Forest useless? | Standard Feature Importances simply tell you which ones of your features were more useful when building the model. They are not to be interpreted as a direct dependence between predictor and target.
| Is feature importance in Random Forest useless?
Standard Feature Importances simply tell you which ones of your features were more useful when building the model. They are not to be interpreted as a direct dependence between predictor and target.
As a consequence:
They are completely useless if your model is weak. If your model does not generalize to validation data - like in the case you mentioned of completely random predictors - then feature importances have no meaning. That is because all the splits are simply overfitting the training data and not capturing any real trend, so all the gini impurity you sum is useless
They are strongly influenced by correlated features. As you mentioned, it is a fact. Just know it and perform some good old feature engineering before hand to avoid having features that are too correlated
They are biased towards numerical and high cardinality features. This is definitely a problem. There are some alternative approaches to help relieve this
Therefore you MUST not interpret them as "correlations" or "strength coefficients", as they do not represent a dependency with the target. Yet, this does not mean at all that they are useless!
Some alternative approaches to limit the drawbacks are:
Permutation Importances: these are computed on VALIDATION data, and therefore solve that first overfitting issue. If a feature splits are overfitting on the training data, its importance will be low on test data. Moreover, as they are computed on a metric of your choice, they are easier to interpret and can in some sense be seen as a "strength coefficient", since they answer the question: "How much does the performance of my model degrade if I shuffle this predictor?". Boruta - which was mentioned in the comments - uses an algorithm that is based on this.
Unbiased Feature Importances: There are multiple works on this and the one linked is one of the newer ones. They are not yet implemented in major packages, but allow for a better measurement of importances that does not suffer from the above problems of overfitting
Oblivious Trees: This approach for building trees, which is used for example in catboost, forces all the splits on the same level of a tree to be done on the same feature. This forces splits on features that generalize better, and often gives importances that resent much less from overfitting the training.
Finally - feature importances are very useful and help discern important features form unimportant ones when using very powerful algorithms such as GBMs and RFs - however, they need to be used with care and interpreted the right way. At the same time, there are some alternatives and packages that solve some of the major flaws of classic feature importances, making them even more easy to use and interpret. | Is feature importance in Random Forest useless?
Standard Feature Importances simply tell you which ones of your features were more useful when building the model. They are not to be interpreted as a direct dependence between predictor and target.
|
34,002 | Is feature importance in Random Forest useless? | Let me copy and paste a warning message from sklearn permutation importance page
Warning: Features that are deemed of low importance for a bad model (low cross-validation score) could be very important for a good model. Therefore it is always important to evaluate the predictive power of a model using a held-out set (or better with cross-validation) prior to computing importances. Permutation importance does not reflect to the intrinsic predictive value of a feature by itself but how important this feature is for a particular model.
Bold faces are mine. This bold faced sentence is actually true for many other feature importance measures: they measure the importance relative to a particular model. They do not measure the importance of the feature independent of a particular model. IMO, The term "Feature Importance" is a bad naming in this regard because it is ambigous whether this is the importance of the feature within a particular model or the importance of the feature in a more general sense. According to this second sense "Feature Importance" can be defined as the degree of dependency between the feature and the target class. If the feature and the target class are independent of each other then we can say that the feature is not important for the target.
But this situation does not make feature importance (for a particular model) useless. You might want to know the importance of a feature inside a model in order to interpret the predictions of the model or understand how the features effect the predictions. | Is feature importance in Random Forest useless? | Let me copy and paste a warning message from sklearn permutation importance page
Warning: Features that are deemed of low importance for a bad model (low cross-validation score) could be very importa | Is feature importance in Random Forest useless?
Let me copy and paste a warning message from sklearn permutation importance page
Warning: Features that are deemed of low importance for a bad model (low cross-validation score) could be very important for a good model. Therefore it is always important to evaluate the predictive power of a model using a held-out set (or better with cross-validation) prior to computing importances. Permutation importance does not reflect to the intrinsic predictive value of a feature by itself but how important this feature is for a particular model.
Bold faces are mine. This bold faced sentence is actually true for many other feature importance measures: they measure the importance relative to a particular model. They do not measure the importance of the feature independent of a particular model. IMO, The term "Feature Importance" is a bad naming in this regard because it is ambigous whether this is the importance of the feature within a particular model or the importance of the feature in a more general sense. According to this second sense "Feature Importance" can be defined as the degree of dependency between the feature and the target class. If the feature and the target class are independent of each other then we can say that the feature is not important for the target.
But this situation does not make feature importance (for a particular model) useless. You might want to know the importance of a feature inside a model in order to interpret the predictions of the model or understand how the features effect the predictions. | Is feature importance in Random Forest useless?
Let me copy and paste a warning message from sklearn permutation importance page
Warning: Features that are deemed of low importance for a bad model (low cross-validation score) could be very importa |
34,003 | Limit of $t$-distribution as $n$ goes to infinity | Stirling's approximation gives $$\Gamma(z) = \sqrt{\frac{2\pi}{z}}\,{\left(\frac{z}{e}\right)}^z \left(1 + O\left(\tfrac{1}{z}\right)\right)$$ so
$$\frac{\Gamma(\frac{n+1}{2})}{\Gamma(\frac{n}{2})} = \dfrac{\sqrt{\frac{2\pi}{\frac{n+1}{2}}}\,{\left(\frac{\frac{n+1}{2}}{e}\right)}^{\frac{n+1}{2}}}{\sqrt{\frac{2\pi}{\frac{n}{2}}}\,{\left(\frac{\frac{n}{2}}{e}\right)}^{\frac{n}{2}}}\left(1 + O\left(\tfrac{1}{n}\right)\right)\\= {\sqrt{\frac{\frac{n+1}{2}}{e}}}\left(1+\frac1n\right)^{\frac{n}{2}}\left(1 + O\left(\tfrac{1}{n}\right)\right) \\= \sqrt{\frac{n}{2}} \left(1 + O\left(\tfrac{1}{n}\right)\right)\\ \to \sqrt{\frac{n}{2}}$$ and you may have a slight typo in your question
In fact when considering limits as $n\to \infty$, you should not have $n$ in the solution; instead you can say the ratio tends to $1$ and it turns out here that the difference tends to $0$. Another point is that $\sqrt{\frac{n}{2}-\frac14}$ is a better approximation, in that not only does the difference tend to $0$, but so too does the difference of the squares. | Limit of $t$-distribution as $n$ goes to infinity | Stirling's approximation gives $$\Gamma(z) = \sqrt{\frac{2\pi}{z}}\,{\left(\frac{z}{e}\right)}^z \left(1 + O\left(\tfrac{1}{z}\right)\right)$$ so
$$\frac{\Gamma(\frac{n+1}{2})}{\Gamma(\frac{n}{2})} | Limit of $t$-distribution as $n$ goes to infinity
Stirling's approximation gives $$\Gamma(z) = \sqrt{\frac{2\pi}{z}}\,{\left(\frac{z}{e}\right)}^z \left(1 + O\left(\tfrac{1}{z}\right)\right)$$ so
$$\frac{\Gamma(\frac{n+1}{2})}{\Gamma(\frac{n}{2})} = \dfrac{\sqrt{\frac{2\pi}{\frac{n+1}{2}}}\,{\left(\frac{\frac{n+1}{2}}{e}\right)}^{\frac{n+1}{2}}}{\sqrt{\frac{2\pi}{\frac{n}{2}}}\,{\left(\frac{\frac{n}{2}}{e}\right)}^{\frac{n}{2}}}\left(1 + O\left(\tfrac{1}{n}\right)\right)\\= {\sqrt{\frac{\frac{n+1}{2}}{e}}}\left(1+\frac1n\right)^{\frac{n}{2}}\left(1 + O\left(\tfrac{1}{n}\right)\right) \\= \sqrt{\frac{n}{2}} \left(1 + O\left(\tfrac{1}{n}\right)\right)\\ \to \sqrt{\frac{n}{2}}$$ and you may have a slight typo in your question
In fact when considering limits as $n\to \infty$, you should not have $n$ in the solution; instead you can say the ratio tends to $1$ and it turns out here that the difference tends to $0$. Another point is that $\sqrt{\frac{n}{2}-\frac14}$ is a better approximation, in that not only does the difference tend to $0$, but so too does the difference of the squares. | Limit of $t$-distribution as $n$ goes to infinity
Stirling's approximation gives $$\Gamma(z) = \sqrt{\frac{2\pi}{z}}\,{\left(\frac{z}{e}\right)}^z \left(1 + O\left(\tfrac{1}{z}\right)\right)$$ so
$$\frac{\Gamma(\frac{n+1}{2})}{\Gamma(\frac{n}{2})} |
34,004 | Limit of $t$-distribution as $n$ goes to infinity | A generalization uncovers a fundamental idea. One nice thing about it is how it circumvents calculation altogether: the Gamma functions don't play any role and, in fact, neither do the specific expressions for the Normal and Chi-squared pdfs.
Recall that the Student $t$ distribution with $\nu$ degrees of freedom originates (both historically, pedagogically, and from a basic statistical standpoint) as the ratio
$$t_\nu = \frac{Z}{\sqrt{S_\nu^2/\nu}}$$
where $Z$ has a standard Normal distribution and $S^2$ is a random variable independent of $Z$ with a $\chi^2(\nu)$ distribution. (This characterization suffices to derive the probability density function proportional to
$$f_\nu(t) \propto \left(1 + \frac{t^2}{\nu}\right)^{-(\nu+1)/2}$$
for $\nu \in \{1,2,3,\ldots\};$ this is then generalized by allowing $\nu$ to be any positive real number. However, we will not need this detail; I present it only to make an explicit connection with how the question is framed.)
Generalization Part 1
Let $Z$ instead be a random variable with any distribution. Later I will want to work with its logarithm, so for this purpose use the indicator function $\mathcal I$ to split $Z$ into its negative, zero, and positive parts:
$$Z = -\mathcal{I}(Z\lt 0)(-Z) + \mathcal{I}(Z=0)Z + \mathcal{I}(Z\gt 0)Z = -Z_{-} + Z_0 + Z_{+}.$$
The fraction $t_\nu$ analogously splits into three parts by dividing each term by $\sqrt{S_\nu^2/\nu}.$ The part with numerator $Z_0$ is identically $0$ and the other parts are expressed as ratios with strictly positive random variables $Z_{-}$ and $Z_{+}$ in their numerators. These are the ratios we need to analyze.
Generalization Part 2
Let us suppose $S_\nu^2$ is a sequence of positive random variables that, for sufficiently large $\nu,$ have finite variances $v^2_\nu$ and (therefore) have finite means $m_\nu$ such that
$$\lim_{\nu\to\infty} \frac{m_\nu}{\nu}=1$$
and
$$\lim_{\nu\to\infty} \frac{v^2_\nu}{\nu^2} = 0.$$
(Both are well-known, easily-established properties of Chi-squared distributions.) This is just a specific way of stipulating that $S_\nu^2$ tends to get more and more concentrated (relative to its location) around the value $\nu$ as $\nu$ increases, but equivalently it shows that $S_\nu^2/\nu$ tends to $1$ while its variance tends to $0.$ Chebyshev's Inequality then implies an arbitrarily large amount of the probability of $S_\nu^2/\nu$ eventually becomes concentrated in arbitrarily small neighborhoods of $1.$ That in turn implies an arbitrarily large amount of the probability of $\varphi_\nu=\log\left(S_\nu^2/\nu\right)$ becomes concentrated in arbitrarily small neighborhoods of $0.$
In mathematical analysis, a sequence like $(\varphi_\nu)$ is sometimes called a "mollifier" (provided $\varphi_\nu$ is smooth and compactly supported). The key idea is that adding a mollifier to another random variable has less and less of an effect, converging (almost surely) to that other variable in the limit. That result does not depend on the smoothness of the mollifying functions and it only really requires that their supports constrict down to zero. However, since our $\varphi_\nu$ do not have compact support, the usual conclusion that convergence occurs almost everywhere (with respect to Lebesgue measure) has to be weakened to convergence in probability.
Analysis
Let $W$ represent either $Z_{+}$ or $Z_{-}$ and let $T_\nu = S_\nu^2/\nu.$ Because $W$ and $T_\nu$ are both positive, we may take logarithms:
$$\log\left(\frac{W}{\sqrt{T_\nu}}\right) = \log(W) + \left(- \frac{1}{2}\log(T_\nu)\right).$$
The factor of $-1/2$ does not affect the mollifying properties of the sequence of $\varphi_\nu = \log(T_\nu).$ Thus, the sequence $\log(W/\sqrt{T_\nu})$ converges in probability to $\log(W).$ Since the $\log$ is continuous, we see that $W/\sqrt{T_\nu}$ converges to $W.$
Obviously when $W$ is an atom at $0,$ the sequence $W/\sqrt{T_\nu}$ is constantly $0.$
Finally, now that we have seen that all three components of $Z/\sqrt{T_\nu}$ converge to the corresponding components of $Z,$ we conclude
In the generalized setting, $t_\nu=\frac{Z}{\sqrt{S_\nu^2/\nu}}$ converges in probability to $Z.$
If, in addition, $Z$ and $S_\nu^2$ (for each $\nu,$ at least eventually for large $\nu$) have continuous distributions with bounded densities (as in the case of Normal and Chi-squared distributions in the Student $t$ setting), it is now straightforward to show the sequence of distribution functions of $t_\nu$ converges uniformly to the distribution function of $Z.$ (The boundedness allows us to conclude that the convergence is uniform.) | Limit of $t$-distribution as $n$ goes to infinity | A generalization uncovers a fundamental idea. One nice thing about it is how it circumvents calculation altogether: the Gamma functions don't play any role and, in fact, neither do the specific expre | Limit of $t$-distribution as $n$ goes to infinity
A generalization uncovers a fundamental idea. One nice thing about it is how it circumvents calculation altogether: the Gamma functions don't play any role and, in fact, neither do the specific expressions for the Normal and Chi-squared pdfs.
Recall that the Student $t$ distribution with $\nu$ degrees of freedom originates (both historically, pedagogically, and from a basic statistical standpoint) as the ratio
$$t_\nu = \frac{Z}{\sqrt{S_\nu^2/\nu}}$$
where $Z$ has a standard Normal distribution and $S^2$ is a random variable independent of $Z$ with a $\chi^2(\nu)$ distribution. (This characterization suffices to derive the probability density function proportional to
$$f_\nu(t) \propto \left(1 + \frac{t^2}{\nu}\right)^{-(\nu+1)/2}$$
for $\nu \in \{1,2,3,\ldots\};$ this is then generalized by allowing $\nu$ to be any positive real number. However, we will not need this detail; I present it only to make an explicit connection with how the question is framed.)
Generalization Part 1
Let $Z$ instead be a random variable with any distribution. Later I will want to work with its logarithm, so for this purpose use the indicator function $\mathcal I$ to split $Z$ into its negative, zero, and positive parts:
$$Z = -\mathcal{I}(Z\lt 0)(-Z) + \mathcal{I}(Z=0)Z + \mathcal{I}(Z\gt 0)Z = -Z_{-} + Z_0 + Z_{+}.$$
The fraction $t_\nu$ analogously splits into three parts by dividing each term by $\sqrt{S_\nu^2/\nu}.$ The part with numerator $Z_0$ is identically $0$ and the other parts are expressed as ratios with strictly positive random variables $Z_{-}$ and $Z_{+}$ in their numerators. These are the ratios we need to analyze.
Generalization Part 2
Let us suppose $S_\nu^2$ is a sequence of positive random variables that, for sufficiently large $\nu,$ have finite variances $v^2_\nu$ and (therefore) have finite means $m_\nu$ such that
$$\lim_{\nu\to\infty} \frac{m_\nu}{\nu}=1$$
and
$$\lim_{\nu\to\infty} \frac{v^2_\nu}{\nu^2} = 0.$$
(Both are well-known, easily-established properties of Chi-squared distributions.) This is just a specific way of stipulating that $S_\nu^2$ tends to get more and more concentrated (relative to its location) around the value $\nu$ as $\nu$ increases, but equivalently it shows that $S_\nu^2/\nu$ tends to $1$ while its variance tends to $0.$ Chebyshev's Inequality then implies an arbitrarily large amount of the probability of $S_\nu^2/\nu$ eventually becomes concentrated in arbitrarily small neighborhoods of $1.$ That in turn implies an arbitrarily large amount of the probability of $\varphi_\nu=\log\left(S_\nu^2/\nu\right)$ becomes concentrated in arbitrarily small neighborhoods of $0.$
In mathematical analysis, a sequence like $(\varphi_\nu)$ is sometimes called a "mollifier" (provided $\varphi_\nu$ is smooth and compactly supported). The key idea is that adding a mollifier to another random variable has less and less of an effect, converging (almost surely) to that other variable in the limit. That result does not depend on the smoothness of the mollifying functions and it only really requires that their supports constrict down to zero. However, since our $\varphi_\nu$ do not have compact support, the usual conclusion that convergence occurs almost everywhere (with respect to Lebesgue measure) has to be weakened to convergence in probability.
Analysis
Let $W$ represent either $Z_{+}$ or $Z_{-}$ and let $T_\nu = S_\nu^2/\nu.$ Because $W$ and $T_\nu$ are both positive, we may take logarithms:
$$\log\left(\frac{W}{\sqrt{T_\nu}}\right) = \log(W) + \left(- \frac{1}{2}\log(T_\nu)\right).$$
The factor of $-1/2$ does not affect the mollifying properties of the sequence of $\varphi_\nu = \log(T_\nu).$ Thus, the sequence $\log(W/\sqrt{T_\nu})$ converges in probability to $\log(W).$ Since the $\log$ is continuous, we see that $W/\sqrt{T_\nu}$ converges to $W.$
Obviously when $W$ is an atom at $0,$ the sequence $W/\sqrt{T_\nu}$ is constantly $0.$
Finally, now that we have seen that all three components of $Z/\sqrt{T_\nu}$ converge to the corresponding components of $Z,$ we conclude
In the generalized setting, $t_\nu=\frac{Z}{\sqrt{S_\nu^2/\nu}}$ converges in probability to $Z.$
If, in addition, $Z$ and $S_\nu^2$ (for each $\nu,$ at least eventually for large $\nu$) have continuous distributions with bounded densities (as in the case of Normal and Chi-squared distributions in the Student $t$ setting), it is now straightforward to show the sequence of distribution functions of $t_\nu$ converges uniformly to the distribution function of $Z.$ (The boundedness allows us to conclude that the convergence is uniform.) | Limit of $t$-distribution as $n$ goes to infinity
A generalization uncovers a fundamental idea. One nice thing about it is how it circumvents calculation altogether: the Gamma functions don't play any role and, in fact, neither do the specific expre |
34,005 | Limit of $t$-distribution as $n$ goes to infinity | While this is not as elementary as Stirling's approximation, the pointwise convergence of the density can be shown using dominated convergence theorem.
The density of a t-distribution with $n$ degrees of freedom is of the form $$f_n(x)=c_n\cdot\left(1+\frac{x^2}{n}\right)^{-(n+1)/2}\quad,\,x\in\mathbb R$$
Let $g_n(x)=\left(1+\frac{x^2}{n}\right)^{-(n+1)/2}$, so that $g_n(x)\to e^{-x^2/2}$ as $n\to \infty$.
So just remains to show that $c_n\to \frac1{\sqrt{2\pi}}$ as $n\to\infty$.
Now, $$\left(1+\frac{x^2}{n}\right)^{(n+1)/2}\ge \left(1+(n+1)\frac{x^2}{n}+\frac{n+1}{2n}x^4\right)^{1/2}\ge \left(1+\frac{x^4}{2}\right)^{1/2}$$
This implies $$|g_n(x)|\le \left(1+\frac{x^4}{2}\right)^{-1/2}\,,$$
where $$\int_{-\infty}^\infty \left(1+\frac{x^4}{2}\right)^{-1/2}\,dx<\infty$$
So by dominated convergence theorem,
$$\lim_{n\to\infty}\int_{-\infty}^\infty g_n(x)\,dx=\int_{-\infty}^\infty \lim_{n\to\infty}g_n(x)\,dx=\int_{-\infty}^\infty e^{-x^2/2}\,dx=\sqrt{2\pi}$$
Finally, as $\int_{-\infty}^\infty f_n(x)\,dx=c_n\int_{-\infty}^\infty g_n(x)\,dx=1$, taking limit on both sides yields
$$\lim_{n\to\infty}c_n\cdot\sqrt{2\pi}=1$$
The nice thing about this approach is that we don't need to know what $c_n$ is to determine its limit.
Yet another way to derive this result is by using Slutsky's theorem, as shown here. | Limit of $t$-distribution as $n$ goes to infinity | While this is not as elementary as Stirling's approximation, the pointwise convergence of the density can be shown using dominated convergence theorem.
The density of a t-distribution with $n$ degrees | Limit of $t$-distribution as $n$ goes to infinity
While this is not as elementary as Stirling's approximation, the pointwise convergence of the density can be shown using dominated convergence theorem.
The density of a t-distribution with $n$ degrees of freedom is of the form $$f_n(x)=c_n\cdot\left(1+\frac{x^2}{n}\right)^{-(n+1)/2}\quad,\,x\in\mathbb R$$
Let $g_n(x)=\left(1+\frac{x^2}{n}\right)^{-(n+1)/2}$, so that $g_n(x)\to e^{-x^2/2}$ as $n\to \infty$.
So just remains to show that $c_n\to \frac1{\sqrt{2\pi}}$ as $n\to\infty$.
Now, $$\left(1+\frac{x^2}{n}\right)^{(n+1)/2}\ge \left(1+(n+1)\frac{x^2}{n}+\frac{n+1}{2n}x^4\right)^{1/2}\ge \left(1+\frac{x^4}{2}\right)^{1/2}$$
This implies $$|g_n(x)|\le \left(1+\frac{x^4}{2}\right)^{-1/2}\,,$$
where $$\int_{-\infty}^\infty \left(1+\frac{x^4}{2}\right)^{-1/2}\,dx<\infty$$
So by dominated convergence theorem,
$$\lim_{n\to\infty}\int_{-\infty}^\infty g_n(x)\,dx=\int_{-\infty}^\infty \lim_{n\to\infty}g_n(x)\,dx=\int_{-\infty}^\infty e^{-x^2/2}\,dx=\sqrt{2\pi}$$
Finally, as $\int_{-\infty}^\infty f_n(x)\,dx=c_n\int_{-\infty}^\infty g_n(x)\,dx=1$, taking limit on both sides yields
$$\lim_{n\to\infty}c_n\cdot\sqrt{2\pi}=1$$
The nice thing about this approach is that we don't need to know what $c_n$ is to determine its limit.
Yet another way to derive this result is by using Slutsky's theorem, as shown here. | Limit of $t$-distribution as $n$ goes to infinity
While this is not as elementary as Stirling's approximation, the pointwise convergence of the density can be shown using dominated convergence theorem.
The density of a t-distribution with $n$ degrees |
34,006 | Limit of $t$-distribution as $n$ goes to infinity | There are many ways you can establish that the T-distribution approaches the normal distribution in the limit. For the direct method you are using, you can find asymptotic expansions for the ratio of gamma functions are analysed in detail in Tricomi and Erdélyi (1951). The simplest expansion comes through application of Stirling's inequality, to obtain the general result (p. 133):
$$\frac{\Gamma(z+\alpha)}{\Gamma(z+\beta)}
= z^{\alpha-\beta} \Big[ 1 + \frac{(\alpha - \beta) (\alpha + \beta - 1)}{2z} + \mathcal{O}(|z|^{-2}) \Big].$$
Taking $\beta = 0$ gives the simplified asymptotic form:
$$\frac{\Gamma(z+\alpha)}{\Gamma(z)}
= z^{\alpha} \Big[ 1 + \frac{\alpha (\alpha - 1)}{2z} + \mathcal{O}(|z|^{-2}) \Big].$$
To obtain a form for the function of interest we can take $z = \tfrac{n}{2}$ and $\alpha = \tfrac{1}{2}$ to obtain:
$$H(n) \equiv \frac{\Gamma(\tfrac{n+1}{2})}{\Gamma(\tfrac{n}{2})}
= \sqrt{\frac{n}{2}} \Big[ 1 - \frac{1}{4n} + \mathcal{O}(n^{-2}) \Big].$$
We therefore have the desire limit:
$$\lim_{n \rightarrow \infty} \frac{\Gamma(\tfrac{n+1}{2})}{\sqrt{n \pi} \ \Gamma(\tfrac{n}{2})} = \lim_{n \rightarrow \infty} \frac{1}{\sqrt{2 \pi}} \Big[ 1 - \frac{1}{4n} + \mathcal{O}(n^{-2}) \Big] = \frac{1}{\sqrt{2 \pi}}.$$ | Limit of $t$-distribution as $n$ goes to infinity | There are many ways you can establish that the T-distribution approaches the normal distribution in the limit. For the direct method you are using, you can find asymptotic expansions for the ratio of | Limit of $t$-distribution as $n$ goes to infinity
There are many ways you can establish that the T-distribution approaches the normal distribution in the limit. For the direct method you are using, you can find asymptotic expansions for the ratio of gamma functions are analysed in detail in Tricomi and Erdélyi (1951). The simplest expansion comes through application of Stirling's inequality, to obtain the general result (p. 133):
$$\frac{\Gamma(z+\alpha)}{\Gamma(z+\beta)}
= z^{\alpha-\beta} \Big[ 1 + \frac{(\alpha - \beta) (\alpha + \beta - 1)}{2z} + \mathcal{O}(|z|^{-2}) \Big].$$
Taking $\beta = 0$ gives the simplified asymptotic form:
$$\frac{\Gamma(z+\alpha)}{\Gamma(z)}
= z^{\alpha} \Big[ 1 + \frac{\alpha (\alpha - 1)}{2z} + \mathcal{O}(|z|^{-2}) \Big].$$
To obtain a form for the function of interest we can take $z = \tfrac{n}{2}$ and $\alpha = \tfrac{1}{2}$ to obtain:
$$H(n) \equiv \frac{\Gamma(\tfrac{n+1}{2})}{\Gamma(\tfrac{n}{2})}
= \sqrt{\frac{n}{2}} \Big[ 1 - \frac{1}{4n} + \mathcal{O}(n^{-2}) \Big].$$
We therefore have the desire limit:
$$\lim_{n \rightarrow \infty} \frac{\Gamma(\tfrac{n+1}{2})}{\sqrt{n \pi} \ \Gamma(\tfrac{n}{2})} = \lim_{n \rightarrow \infty} \frac{1}{\sqrt{2 \pi}} \Big[ 1 - \frac{1}{4n} + \mathcal{O}(n^{-2}) \Big] = \frac{1}{\sqrt{2 \pi}}.$$ | Limit of $t$-distribution as $n$ goes to infinity
There are many ways you can establish that the T-distribution approaches the normal distribution in the limit. For the direct method you are using, you can find asymptotic expansions for the ratio of |
34,007 | Limit of $t$-distribution as $n$ goes to infinity | An easy, intuitive way is to recognize that the noncentral scaled t-distribution with n degrees of freedom is the posterior predictive of the normal model based on n data points. (I think this is essentially its origin, and gives a common sense interpretation of the t-test.) As n goes to infinity, the model becomes "perfect", and must converge to a normal distribution. | Limit of $t$-distribution as $n$ goes to infinity | An easy, intuitive way is to recognize that the noncentral scaled t-distribution with n degrees of freedom is the posterior predictive of the normal model based on n data points. (I think this is ess | Limit of $t$-distribution as $n$ goes to infinity
An easy, intuitive way is to recognize that the noncentral scaled t-distribution with n degrees of freedom is the posterior predictive of the normal model based on n data points. (I think this is essentially its origin, and gives a common sense interpretation of the t-test.) As n goes to infinity, the model becomes "perfect", and must converge to a normal distribution. | Limit of $t$-distribution as $n$ goes to infinity
An easy, intuitive way is to recognize that the noncentral scaled t-distribution with n degrees of freedom is the posterior predictive of the normal model based on n data points. (I think this is ess |
34,008 | Linearity assumption of linear regression | You still need to have a function or functions of the original variable(s) that the response is linear in.
You're correct that linear regression is linear in the coefficients, but then it's equally linear in the things the coefficients are multiplied by. (Where here we're talking in the sense of a linear map, rather than "has a straight-line relationship", though the two are related concepts when you have a constant term included in the predictors.)
For multiple regression we write $E(Y|\mathbf{x})= X\beta$, where $X$ is the matrix of variables as actually supplied to the regression (and the constant). This is linear in $\beta$ but it's equally linear in the columns of $X$.
In the case of simple regression, if for example you can write an equation $Y = \beta_0+\beta_1 t(x) + \epsilon$, or $E(Y|x)=\beta_0+\beta_1 t(x)$ that's linear in the supplied variables $(1,x^*)$, where $x^*=t(x)$.
If you know a $t(x)$ to supply to the regression, that means you don't need to have a straight-line relationship between $y$ and $x$, but there's still a linear relationship.
There's a variety of approaches that will model nonlinear relationships with linear equations, including polynomials, various kinds of regression splines, trigonometric functions, and so forth, that can have this property of still being (multiple) linear regression models. | Linearity assumption of linear regression | You still need to have a function or functions of the original variable(s) that the response is linear in.
You're correct that linear regression is linear in the coefficients, but then it's equally li | Linearity assumption of linear regression
You still need to have a function or functions of the original variable(s) that the response is linear in.
You're correct that linear regression is linear in the coefficients, but then it's equally linear in the things the coefficients are multiplied by. (Where here we're talking in the sense of a linear map, rather than "has a straight-line relationship", though the two are related concepts when you have a constant term included in the predictors.)
For multiple regression we write $E(Y|\mathbf{x})= X\beta$, where $X$ is the matrix of variables as actually supplied to the regression (and the constant). This is linear in $\beta$ but it's equally linear in the columns of $X$.
In the case of simple regression, if for example you can write an equation $Y = \beta_0+\beta_1 t(x) + \epsilon$, or $E(Y|x)=\beta_0+\beta_1 t(x)$ that's linear in the supplied variables $(1,x^*)$, where $x^*=t(x)$.
If you know a $t(x)$ to supply to the regression, that means you don't need to have a straight-line relationship between $y$ and $x$, but there's still a linear relationship.
There's a variety of approaches that will model nonlinear relationships with linear equations, including polynomials, various kinds of regression splines, trigonometric functions, and so forth, that can have this property of still being (multiple) linear regression models. | Linearity assumption of linear regression
You still need to have a function or functions of the original variable(s) that the response is linear in.
You're correct that linear regression is linear in the coefficients, but then it's equally li |
34,009 | Linearity assumption of linear regression | The confusion here is mainly semantic: between 1) linear regression and 2) linear dependence/relation between the variables. The relation between the predictor and the response in the plot shown is clearly a nonlinear one. On the other hand, you still can fit it by a linear model of the type: $y = a_0 + a_1 x + a_3 x^2 $ or any other linear combination of possibly nonlinear functions. | Linearity assumption of linear regression | The confusion here is mainly semantic: between 1) linear regression and 2) linear dependence/relation between the variables. The relation between the predictor and the response in the plot shown is cl | Linearity assumption of linear regression
The confusion here is mainly semantic: between 1) linear regression and 2) linear dependence/relation between the variables. The relation between the predictor and the response in the plot shown is clearly a nonlinear one. On the other hand, you still can fit it by a linear model of the type: $y = a_0 + a_1 x + a_3 x^2 $ or any other linear combination of possibly nonlinear functions. | Linearity assumption of linear regression
The confusion here is mainly semantic: between 1) linear regression and 2) linear dependence/relation between the variables. The relation between the predictor and the response in the plot shown is cl |
34,010 | Do Bayesian credible intervals treat the estimated parameter as a random variable? | Consider the situation in which you have $n = 20$ observations of a binary (2-coutcome) process. Often the two possible outcomes on each trial are called Success and Failure.
Frequentist confidence interval. Suppose you observe $x = 15$ successes in the $n = 20$ trials. View the number $X$ of Successes as a random variable $X \sim \mathsf{Binom}(n=20; p),$ where the success probability $p$ is an unknown constant. The Wald 95% frequentist confidence interval
is based on $\hat p = 15/20 = 0.75,$ an estimate of $p.$
Using a normal approximation, this CI is of the form $\hat p \pm 1.96\sqrt{\hat p(1-\hat p)/n}$ or
$(0.560, 0.940).$ [The somewhat improved Agresti-Coull
style of 95% CI is $(0.526, 0.890).]$
A common interpretation is that the procedure that
produces such an interval will produce lower and upper confidence limits that include the true value of $p$ in 95% of instances over the long run. [The advantage of the Agresti-Coull interval is that the long run proportion of such inclusions is nearer to 95% than for the Wald interval.]
Bayesian credible interval. The Bayesian approach
begins by treating $p$ as a random variable. Prior to seeing data, if we have no experience with the kind binomial experiment being conducted or no personal
opinion as to the distribution of $p,$ we may choose
the 'flat' or 'noninformative' uniform distribution,
saying $p \sim \mathsf{Unif}(0, 1) \equiv
\mathsf{Beta}(1,1).$
Then, given 15 successes in 20 binomial trials, we find the posterior distribution of $p$ as
the product of the prior distribution and the binomial likelihood function.
$$f(p|x) \propto p^{1-1}(1-p)^{1-1} \times
p^{15}(1-p)^{5} \propto
p^{16-1}(1-p)^{6-1},$$
where the symbol $\propto$ (read 'proportional to')
indicates that we are omitting 'norming' constant
factors of the distributions, which do not contain $p.$
Without the norming factor, a density function or PMF
is called the 'kernel' of the distribution.
Here we recognize that the kernel of the posterior distribution is that of the distribution $\mathsf{Beta}(16, 6).$ Then a 95% Bayesian posterior interval
or credible interval is found by cutting 2.5% from each tail of the posterior distribution. Here is the result from R:
$(0.528,0.887).$ [For information about beta distributions, see Wikipedia.]
qbeta(c(.025,.975), 16, 6)
[1] 0.5283402 0.8871906
If we believed the prior to be reasonable and believe that
the 20-trial binomial experiment was fairly conducted,
then logically we must expect the Bayesian
interval estimate to give useful information about
the experiment at hand---with no reference to a hypothetical long-run future.
Notice that this Bayesian credible interval
is numerically similar to the Agresti-Coull confidence interval. However, as you point out,
the interpretations of the two types of interval estimates (frequentist and Bayesian) are not the same.
Informative prior. Before we saw the data, if we had reason to believe
that $p \approx 2/3,$ then we might have chosen the
distribution $\mathsf{Beta}(8,4)$ as the prior distribution. [This distribution has mean 2/3, standard deviation about 0.35, and puts about 95% of its
probability in the interval $(0.39, 0.89).$]
qbeta(c(.025,.975), 8,4)
[1] 0.3902574 0.8907366
In that case, multiplying the prior by the likelihood gives the posterior kernel of $\mathsf{Beta}(23,7),$
so that the 95% Bayesian credible interval is
$(0.603, 0.897).$ The posterior distribution is a melding of the information in the prior and the likelihood, which are in rough agreement, so the resulting Bayesian interval
estimate is shorter than than the interval from
the flat prior.
qbeta(c(.025,.975), 23,7)
[1] 0.6027531 0.8970164
Notes: (1) The beta prior and binomial likelihood function
are 'conjugate`, that is, mathematically compatible in a way that allows us to find the posterior distribution without computation. Sometimes, there does not seem to
be a prior distribution that is conjugate with the likelihood. Then it may be necessary to use numerical integration to find the posterior distribution.
(2) A Bayesian credible interval from an noninformative prior essentially depends on the likelihood function. Also, much of frequentist inference depends of the likelihood function. Thus is is not
a surprise that a Bayesian credible interval from a flat prior may be numerically similar to a frequentist confidence interval based on the same likelihood. | Do Bayesian credible intervals treat the estimated parameter as a random variable? | Consider the situation in which you have $n = 20$ observations of a binary (2-coutcome) process. Often the two possible outcomes on each trial are called Success and Failure.
Frequentist confidence in | Do Bayesian credible intervals treat the estimated parameter as a random variable?
Consider the situation in which you have $n = 20$ observations of a binary (2-coutcome) process. Often the two possible outcomes on each trial are called Success and Failure.
Frequentist confidence interval. Suppose you observe $x = 15$ successes in the $n = 20$ trials. View the number $X$ of Successes as a random variable $X \sim \mathsf{Binom}(n=20; p),$ where the success probability $p$ is an unknown constant. The Wald 95% frequentist confidence interval
is based on $\hat p = 15/20 = 0.75,$ an estimate of $p.$
Using a normal approximation, this CI is of the form $\hat p \pm 1.96\sqrt{\hat p(1-\hat p)/n}$ or
$(0.560, 0.940).$ [The somewhat improved Agresti-Coull
style of 95% CI is $(0.526, 0.890).]$
A common interpretation is that the procedure that
produces such an interval will produce lower and upper confidence limits that include the true value of $p$ in 95% of instances over the long run. [The advantage of the Agresti-Coull interval is that the long run proportion of such inclusions is nearer to 95% than for the Wald interval.]
Bayesian credible interval. The Bayesian approach
begins by treating $p$ as a random variable. Prior to seeing data, if we have no experience with the kind binomial experiment being conducted or no personal
opinion as to the distribution of $p,$ we may choose
the 'flat' or 'noninformative' uniform distribution,
saying $p \sim \mathsf{Unif}(0, 1) \equiv
\mathsf{Beta}(1,1).$
Then, given 15 successes in 20 binomial trials, we find the posterior distribution of $p$ as
the product of the prior distribution and the binomial likelihood function.
$$f(p|x) \propto p^{1-1}(1-p)^{1-1} \times
p^{15}(1-p)^{5} \propto
p^{16-1}(1-p)^{6-1},$$
where the symbol $\propto$ (read 'proportional to')
indicates that we are omitting 'norming' constant
factors of the distributions, which do not contain $p.$
Without the norming factor, a density function or PMF
is called the 'kernel' of the distribution.
Here we recognize that the kernel of the posterior distribution is that of the distribution $\mathsf{Beta}(16, 6).$ Then a 95% Bayesian posterior interval
or credible interval is found by cutting 2.5% from each tail of the posterior distribution. Here is the result from R:
$(0.528,0.887).$ [For information about beta distributions, see Wikipedia.]
qbeta(c(.025,.975), 16, 6)
[1] 0.5283402 0.8871906
If we believed the prior to be reasonable and believe that
the 20-trial binomial experiment was fairly conducted,
then logically we must expect the Bayesian
interval estimate to give useful information about
the experiment at hand---with no reference to a hypothetical long-run future.
Notice that this Bayesian credible interval
is numerically similar to the Agresti-Coull confidence interval. However, as you point out,
the interpretations of the two types of interval estimates (frequentist and Bayesian) are not the same.
Informative prior. Before we saw the data, if we had reason to believe
that $p \approx 2/3,$ then we might have chosen the
distribution $\mathsf{Beta}(8,4)$ as the prior distribution. [This distribution has mean 2/3, standard deviation about 0.35, and puts about 95% of its
probability in the interval $(0.39, 0.89).$]
qbeta(c(.025,.975), 8,4)
[1] 0.3902574 0.8907366
In that case, multiplying the prior by the likelihood gives the posterior kernel of $\mathsf{Beta}(23,7),$
so that the 95% Bayesian credible interval is
$(0.603, 0.897).$ The posterior distribution is a melding of the information in the prior and the likelihood, which are in rough agreement, so the resulting Bayesian interval
estimate is shorter than than the interval from
the flat prior.
qbeta(c(.025,.975), 23,7)
[1] 0.6027531 0.8970164
Notes: (1) The beta prior and binomial likelihood function
are 'conjugate`, that is, mathematically compatible in a way that allows us to find the posterior distribution without computation. Sometimes, there does not seem to
be a prior distribution that is conjugate with the likelihood. Then it may be necessary to use numerical integration to find the posterior distribution.
(2) A Bayesian credible interval from an noninformative prior essentially depends on the likelihood function. Also, much of frequentist inference depends of the likelihood function. Thus is is not
a surprise that a Bayesian credible interval from a flat prior may be numerically similar to a frequentist confidence interval based on the same likelihood. | Do Bayesian credible intervals treat the estimated parameter as a random variable?
Consider the situation in which you have $n = 20$ observations of a binary (2-coutcome) process. Often the two possible outcomes on each trial are called Success and Failure.
Frequentist confidence in |
34,011 | Do Bayesian credible intervals treat the estimated parameter as a random variable? | Your interpretation is correct. In my opinion that particular passage in the Wikipedia article obfuscates a simple concept with opaque technical language. The initial passage is much clearer: "is an interval within which an unobserved parameter value falls with a particular subjective probability".
The technical term "random variable" is misleading, especially from a Bayesian point of view. It's still used just out of tradition; take a look at Shafer's intriguing historical study When to call a variable random about its origins. From a Bayesian point of view, "random" simply means "unknown" or "uncertain" (for whatever reason), and "variable" is a misnomer for "quantity" or "value". For example, when we try to assess our uncertainty about the speed of light $c$ from a measurement or experiment, we speak of $c$ as a "random variable"; but it's obviously not "random" (and what does "random" mean?), nor is it "variable" – in fact, it's a constant. It's just a physical constant whose exact value we're uncertain about. See § 16.4 (and other places) in Jaynes's book for an illuminating discussion of this topic.
The question "what does a Bayesian interval for a 'parameter' mean?" comes from the even more important question "what does this parameter mean?". There are two main points of view – not mutually exclusive – about the meaning of "parameters" in Bayesian theory. Both use de Finetti's theorem. Chapter 4 of Bernardo & Smith's Bayesian Theory has a beautifully deep discussion of the theorem; see also Dawid's summary Exchangeability and its ramifications.
The first point of view is that the parameter and its distribution are just mathematical objects that completely summarize an infinite set of joint belief distributions about the actually observable quantities $x_1, x_2, \dotsc$ (say, the outcomes of the tosses of a coin, or the presences of a genetic allele in individuals having a particular disease). So, in the binomial case, when we say "we have a 95% belief that the parameter value $p$ is within interval $I$", we mean "we have a belief between $b_1$% and $b_1'$% that $x_1=1$", "we have a belief between $b_2$% and $b_2'$% that $x_1=1$ and $x_2=1$", and all possible similar statements. The exact numerical relation between the $b_i$s and the interval $I$ is given by de Finetti's integral formula.
The second point of view is that such "parameters" are long-run observable quantities, so it does make sense to speak about our belief in their values. For example, the binomial parameter $p$ is the long-run frequency of observations of "successes" (tails for a coin, minor allele for the genetic case, and so on). So when we say "we have a 95% belief that the parameter value $p$ is within interval $I$" we mean "we have a 95% belief that the long-run relative frequency of successes is within interval $I$". The context here is that, if an oracle or jinn told us that the long-run relative frequency were, say, 0.643, then our belief that the next observation is a success would be, from symmetry reasons, 64.3%; for the next two observations, 41.3449%, and so on. ("From symmetry reasons" because we believe equally in all possible time sequences of successes and failures – this is the context of the theorem.) These long-run observations need not be infinite, but just large enough: in this case de Finetti's infinite-exchangeability formula can be considered as an approximation of a finite-exchangeability one (for example, the binomial distribution is an approximation for a hypergeometric one: "drawing without replacement"); see Diaconis & Freedman about such approximation. Often such parameters are related to long-run statistics (see again the cited chapter in Bernardo & Smith). In short, the "parameter" is a long-run frequency or other observable, empirical statistics.
I personally like the second point of view – which tries to find the empirical meaning of the parameter as a physical quantity – also because it helps me to assess my pre-data belief distribution about that specific physical quantity, in its specific context. See for example Diaconis & al's paper Dynamical bias in the coin toss for a beautiful study of the relation between long-run parameters and physical principles. Today, unfortunately, many "models" and parameters come just as black boxes: people use them just because other people use them. In Diaconis's words:
de Finetti's alarm at statisticians introducing reams of unobservable
parameters has been repeatedly justified in the modern curve fitting
exercises of today's big models. These seem to lose all contact with
scientific reality focusing attention on details of large programs and
fitting instead of observation and understanding of basic mechanism.
In frequentist theory the term "random variable" may have a different meaning though. I'm not an expert in this theory, so I won't try to define it there. I think there's some literature around that shows that frequentist confidence intervals and Bayesian intervals can be quite different; see for example Confidence intervals vs Bayesian intervals or https://www.ncbi.nlm.nih.gov/pubmed/6830080. | Do Bayesian credible intervals treat the estimated parameter as a random variable? | Your interpretation is correct. In my opinion that particular passage in the Wikipedia article obfuscates a simple concept with opaque technical language. The initial passage is much clearer: "is an i | Do Bayesian credible intervals treat the estimated parameter as a random variable?
Your interpretation is correct. In my opinion that particular passage in the Wikipedia article obfuscates a simple concept with opaque technical language. The initial passage is much clearer: "is an interval within which an unobserved parameter value falls with a particular subjective probability".
The technical term "random variable" is misleading, especially from a Bayesian point of view. It's still used just out of tradition; take a look at Shafer's intriguing historical study When to call a variable random about its origins. From a Bayesian point of view, "random" simply means "unknown" or "uncertain" (for whatever reason), and "variable" is a misnomer for "quantity" or "value". For example, when we try to assess our uncertainty about the speed of light $c$ from a measurement or experiment, we speak of $c$ as a "random variable"; but it's obviously not "random" (and what does "random" mean?), nor is it "variable" – in fact, it's a constant. It's just a physical constant whose exact value we're uncertain about. See § 16.4 (and other places) in Jaynes's book for an illuminating discussion of this topic.
The question "what does a Bayesian interval for a 'parameter' mean?" comes from the even more important question "what does this parameter mean?". There are two main points of view – not mutually exclusive – about the meaning of "parameters" in Bayesian theory. Both use de Finetti's theorem. Chapter 4 of Bernardo & Smith's Bayesian Theory has a beautifully deep discussion of the theorem; see also Dawid's summary Exchangeability and its ramifications.
The first point of view is that the parameter and its distribution are just mathematical objects that completely summarize an infinite set of joint belief distributions about the actually observable quantities $x_1, x_2, \dotsc$ (say, the outcomes of the tosses of a coin, or the presences of a genetic allele in individuals having a particular disease). So, in the binomial case, when we say "we have a 95% belief that the parameter value $p$ is within interval $I$", we mean "we have a belief between $b_1$% and $b_1'$% that $x_1=1$", "we have a belief between $b_2$% and $b_2'$% that $x_1=1$ and $x_2=1$", and all possible similar statements. The exact numerical relation between the $b_i$s and the interval $I$ is given by de Finetti's integral formula.
The second point of view is that such "parameters" are long-run observable quantities, so it does make sense to speak about our belief in their values. For example, the binomial parameter $p$ is the long-run frequency of observations of "successes" (tails for a coin, minor allele for the genetic case, and so on). So when we say "we have a 95% belief that the parameter value $p$ is within interval $I$" we mean "we have a 95% belief that the long-run relative frequency of successes is within interval $I$". The context here is that, if an oracle or jinn told us that the long-run relative frequency were, say, 0.643, then our belief that the next observation is a success would be, from symmetry reasons, 64.3%; for the next two observations, 41.3449%, and so on. ("From symmetry reasons" because we believe equally in all possible time sequences of successes and failures – this is the context of the theorem.) These long-run observations need not be infinite, but just large enough: in this case de Finetti's infinite-exchangeability formula can be considered as an approximation of a finite-exchangeability one (for example, the binomial distribution is an approximation for a hypergeometric one: "drawing without replacement"); see Diaconis & Freedman about such approximation. Often such parameters are related to long-run statistics (see again the cited chapter in Bernardo & Smith). In short, the "parameter" is a long-run frequency or other observable, empirical statistics.
I personally like the second point of view – which tries to find the empirical meaning of the parameter as a physical quantity – also because it helps me to assess my pre-data belief distribution about that specific physical quantity, in its specific context. See for example Diaconis & al's paper Dynamical bias in the coin toss for a beautiful study of the relation between long-run parameters and physical principles. Today, unfortunately, many "models" and parameters come just as black boxes: people use them just because other people use them. In Diaconis's words:
de Finetti's alarm at statisticians introducing reams of unobservable
parameters has been repeatedly justified in the modern curve fitting
exercises of today's big models. These seem to lose all contact with
scientific reality focusing attention on details of large programs and
fitting instead of observation and understanding of basic mechanism.
In frequentist theory the term "random variable" may have a different meaning though. I'm not an expert in this theory, so I won't try to define it there. I think there's some literature around that shows that frequentist confidence intervals and Bayesian intervals can be quite different; see for example Confidence intervals vs Bayesian intervals or https://www.ncbi.nlm.nih.gov/pubmed/6830080. | Do Bayesian credible intervals treat the estimated parameter as a random variable?
Your interpretation is correct. In my opinion that particular passage in the Wikipedia article obfuscates a simple concept with opaque technical language. The initial passage is much clearer: "is an i |
34,012 | Do Bayesian credible intervals treat the estimated parameter as a random variable? | My interpretation of the credible interval was that it encapsulated our own uncertainty about the true value of the estimated parameter but that the estimated parameter itself did have some kind of 'true' value. This is slightly different to saying that the estimated parameter is a 'random variable'. Am I wrong?
Although you say that you interpret the credible interval as encapsulating our own uncertainty, the logic of your conclusion proceeds from the premise that a quantity with a true value is not a random variable. This is taking an aleatory view of probability (and subsequent "randomness") which conceives of randomness as a property that inheres in nature. Mathematically, a random variable is merely a quantity that corresponds to possible outcomes in a sample space, with a probability measure attached. Thus, your approach would only make sense if you take that probability measure as an inherent property of nature, giving the propensity for a metaphysically "random" event to occur. You then conclude that a parameter that has a true value must not be metaphysically "random" and therefore cannot be described by a (non-degenerate) probability measure.
That approach is at odds with the epistemic interpretation of probability that is generally used in Bayesian theory. Under the latter approach (which is the standard interpretation), the probability measure is interpreted only as a measure of degree-of-belief (under certain coherence requirements) of the analyst (or some other subject). Under the epistemic interpretation, "random variable" is synonymous with "unknown quantity", and thus, there is no problem with saying that a parameter has a true value, but is still a random variable with a (non-degenerate) probability measure. The quote you are looking at is using this epistemic approach to probability, but your conclusion appears to be using a premise that is at odds with this interpretation. | Do Bayesian credible intervals treat the estimated parameter as a random variable? | My interpretation of the credible interval was that it encapsulated our own uncertainty about the true value of the estimated parameter but that the estimated parameter itself did have some kind of 't | Do Bayesian credible intervals treat the estimated parameter as a random variable?
My interpretation of the credible interval was that it encapsulated our own uncertainty about the true value of the estimated parameter but that the estimated parameter itself did have some kind of 'true' value. This is slightly different to saying that the estimated parameter is a 'random variable'. Am I wrong?
Although you say that you interpret the credible interval as encapsulating our own uncertainty, the logic of your conclusion proceeds from the premise that a quantity with a true value is not a random variable. This is taking an aleatory view of probability (and subsequent "randomness") which conceives of randomness as a property that inheres in nature. Mathematically, a random variable is merely a quantity that corresponds to possible outcomes in a sample space, with a probability measure attached. Thus, your approach would only make sense if you take that probability measure as an inherent property of nature, giving the propensity for a metaphysically "random" event to occur. You then conclude that a parameter that has a true value must not be metaphysically "random" and therefore cannot be described by a (non-degenerate) probability measure.
That approach is at odds with the epistemic interpretation of probability that is generally used in Bayesian theory. Under the latter approach (which is the standard interpretation), the probability measure is interpreted only as a measure of degree-of-belief (under certain coherence requirements) of the analyst (or some other subject). Under the epistemic interpretation, "random variable" is synonymous with "unknown quantity", and thus, there is no problem with saying that a parameter has a true value, but is still a random variable with a (non-degenerate) probability measure. The quote you are looking at is using this epistemic approach to probability, but your conclusion appears to be using a premise that is at odds with this interpretation. | Do Bayesian credible intervals treat the estimated parameter as a random variable?
My interpretation of the credible interval was that it encapsulated our own uncertainty about the true value of the estimated parameter but that the estimated parameter itself did have some kind of 't |
34,013 | Is it possible that AIC = BIC? | As a reminder:
$$AIC = - 2 \log \mathcal{L}(\hat{\theta}|X)+2k $$
$$BIC = - 2 \log \mathcal{L}(\hat{\theta}|X)+k \ln(n)$$
So for what values of $n$ is $2 = \ln(n)$? | Is it possible that AIC = BIC? | As a reminder:
$$AIC = - 2 \log \mathcal{L}(\hat{\theta}|X)+2k $$
$$BIC = - 2 \log \mathcal{L}(\hat{\theta}|X)+k \ln(n)$$
So for what values of $n$ is $2 = \ln(n)$? | Is it possible that AIC = BIC?
As a reminder:
$$AIC = - 2 \log \mathcal{L}(\hat{\theta}|X)+2k $$
$$BIC = - 2 \log \mathcal{L}(\hat{\theta}|X)+k \ln(n)$$
So for what values of $n$ is $2 = \ln(n)$? | Is it possible that AIC = BIC?
As a reminder:
$$AIC = - 2 \log \mathcal{L}(\hat{\theta}|X)+2k $$
$$BIC = - 2 \log \mathcal{L}(\hat{\theta}|X)+k \ln(n)$$
So for what values of $n$ is $2 = \ln(n)$? |
34,014 | Variance of average of $n$ correlated random variables | By definition, we have
$$\operatorname{var}\left(\sum_{i=1}^n{X_i}\right)=\operatorname{cov}\left(\sum_{i=1}^n{X_i},\sum_{i=1}^n{X_i}\right)=\sum_{i=1}^n{\operatorname{var}(X_i)}+\sum_{i\neq j}\operatorname{cov}(X_i,X_j)$$
which is $n \operatorname{var}(X_i)+n(n-1)\operatorname{cov}(X_i,X_j)=n\sigma^2+n(n-1)\rho\sigma^2$, where $i\neq j$. Substituting this into the original equation yields the following:
$$\operatorname{var}\left(\frac{1}{n}\sum_{i=1}^nX_i\right)=\frac{1}{n^2}(n\sigma^2+n(n-1)\rho\sigma^2)=\rho\sigma^2+\frac{1-\rho}{n}\sigma^2$$
Each $X_i$ can be thought of as a single decision mechanism, call it DM, (e.g. regressor). The variance of your decision was $\sigma^2$. By using bootstrap samples and aggregating your DMs' outputs, you end up with a decision variance as above, which is strictly smaller than $\sigma^2$ when $\rho \neq 1$ and $n\neq 1$. DMs will have some degree of correlation of course, because they are trained over bootstrap samples obtained from the same base dataset; however, the correlation between them most probably won't be equal to $1$. Overfitted mechanisms in general have large variance, so by aiming to decrease the variance of your DM, you actually address the problem of overfitting implicitly. | Variance of average of $n$ correlated random variables | By definition, we have
$$\operatorname{var}\left(\sum_{i=1}^n{X_i}\right)=\operatorname{cov}\left(\sum_{i=1}^n{X_i},\sum_{i=1}^n{X_i}\right)=\sum_{i=1}^n{\operatorname{var}(X_i)}+\sum_{i\neq j}\opera | Variance of average of $n$ correlated random variables
By definition, we have
$$\operatorname{var}\left(\sum_{i=1}^n{X_i}\right)=\operatorname{cov}\left(\sum_{i=1}^n{X_i},\sum_{i=1}^n{X_i}\right)=\sum_{i=1}^n{\operatorname{var}(X_i)}+\sum_{i\neq j}\operatorname{cov}(X_i,X_j)$$
which is $n \operatorname{var}(X_i)+n(n-1)\operatorname{cov}(X_i,X_j)=n\sigma^2+n(n-1)\rho\sigma^2$, where $i\neq j$. Substituting this into the original equation yields the following:
$$\operatorname{var}\left(\frac{1}{n}\sum_{i=1}^nX_i\right)=\frac{1}{n^2}(n\sigma^2+n(n-1)\rho\sigma^2)=\rho\sigma^2+\frac{1-\rho}{n}\sigma^2$$
Each $X_i$ can be thought of as a single decision mechanism, call it DM, (e.g. regressor). The variance of your decision was $\sigma^2$. By using bootstrap samples and aggregating your DMs' outputs, you end up with a decision variance as above, which is strictly smaller than $\sigma^2$ when $\rho \neq 1$ and $n\neq 1$. DMs will have some degree of correlation of course, because they are trained over bootstrap samples obtained from the same base dataset; however, the correlation between them most probably won't be equal to $1$. Overfitted mechanisms in general have large variance, so by aiming to decrease the variance of your DM, you actually address the problem of overfitting implicitly. | Variance of average of $n$ correlated random variables
By definition, we have
$$\operatorname{var}\left(\sum_{i=1}^n{X_i}\right)=\operatorname{cov}\left(\sum_{i=1}^n{X_i},\sum_{i=1}^n{X_i}\right)=\sum_{i=1}^n{\operatorname{var}(X_i)}+\sum_{i\neq j}\opera |
34,015 | Standard Error of simple linear regression coefficients | Let a simple linear regression model
$$
y_i = \beta_1 + \beta_2x_i + \epsilon_i
$$
from $n$ observations, where $\epsilon_i$ are iid and of same variance $\sigma^2$.
OLS estimators of $\beta_1$ and $\beta_2$ are given by
$$
\hat{\beta}_2 = \frac{\sum(x_i-\bar{x})y_i}{\sum(x_i - \bar{x}^2}
$$
and
$$
\hat{\beta}_1 = \bar{y} - \hat{\beta}_2 \bar{x}
$$
where $\bar{x}$ denotes sample mean. From each parameter we only have one value (since we have one sample).
We do not need to estimate $\sigma^2$ to compute both $\hat{\beta_1}$ and $\hat{\beta}_2$.
However, it can be estimated with
\begin{align*}
\hat{\sigma}^2 &= \frac{1}{n-2} \sum( y_i - \hat{y}_i )^2 \\
&= \frac{1}{n-2} \sum( y_i - \hat{\beta}_1 - \hat{\beta}_2 x_i )^2
\end{align*}
But even if we only have one value for each estimator, we have the following results : for OLS estimates $\hat{\beta}_1$ and $\hat{\beta}_2$.
$$
\text{Var}(\hat{\beta}_1) =\frac{1}{n} \frac{\sigma^2 \sum x_i^2}{\sum(x_i - \bar{x})^2}
$$
and
$$
\text{Var}(\hat{\beta}_2) = \frac{\sigma^2}{\sum(x_i - \bar{x})^2}
$$
Moreover,
$$
\text{Cov}(\hat{\beta}_1,\hat{\beta}_2) = - \frac{\sigma^2 \bar{x}}{\sum(x_i - \bar{x})^2}
$$
Proof of these results can be found in any textbook on linear regression.
Since we can estimate $\sigma^2$ from the original sample, we can estimate variances of estimators, even if we only have one value of them.
These variances estimates can also be computed from bootstrapping the sample, i.e by taking samples of the original sample and by computing estimators for each sub sample. For example for $\beta_1$, if you take $K$ sub sample then you get a sample $\hat{\beta}_1^{(1)},\dots,\hat{\beta}_1^{(K)}$ from which you can empirically estimate the variance of $\hat{\beta}_1$.
Here is a simple code (in R) showing how the two methods can be used
data<-data.frame(do.call(rbind,lapply(1:500,function(i){
id=i
x<-rexp(1,1)
y<- 1 + 3*x + rnorm(1,0,1)
return(c(id,y,x))
})))
names(data)<-c("id", "y","x")
summary(lm(y~x,data)) ## OLS std estimates from full sample
## by bootstrapping
Nboot<-500
list<-lapply(1:Nboot,function(i){
Ids <- sort(sample(data$id,replace=TRUE))
data.s = data[Ids,]
mod.s<-lm(y~x,data.s)
return(mod.s$coefficients)
})
## Bootstrap variances estimates
var(sapply(list,function(x) x[[1]]))**0.5 # beta1
var(sapply(list,function(x) x[[2]]))**0.5 # beta2
in the command
summary(lm(y~x,data)) ## OLS std estimates
the values in the "Std. Error" column should be close to the values computed in the last two lines | Standard Error of simple linear regression coefficients | Let a simple linear regression model
$$
y_i = \beta_1 + \beta_2x_i + \epsilon_i
$$
from $n$ observations, where $\epsilon_i$ are iid and of same variance $\sigma^2$.
OLS estimators of $\beta_1$ and $\ | Standard Error of simple linear regression coefficients
Let a simple linear regression model
$$
y_i = \beta_1 + \beta_2x_i + \epsilon_i
$$
from $n$ observations, where $\epsilon_i$ are iid and of same variance $\sigma^2$.
OLS estimators of $\beta_1$ and $\beta_2$ are given by
$$
\hat{\beta}_2 = \frac{\sum(x_i-\bar{x})y_i}{\sum(x_i - \bar{x}^2}
$$
and
$$
\hat{\beta}_1 = \bar{y} - \hat{\beta}_2 \bar{x}
$$
where $\bar{x}$ denotes sample mean. From each parameter we only have one value (since we have one sample).
We do not need to estimate $\sigma^2$ to compute both $\hat{\beta_1}$ and $\hat{\beta}_2$.
However, it can be estimated with
\begin{align*}
\hat{\sigma}^2 &= \frac{1}{n-2} \sum( y_i - \hat{y}_i )^2 \\
&= \frac{1}{n-2} \sum( y_i - \hat{\beta}_1 - \hat{\beta}_2 x_i )^2
\end{align*}
But even if we only have one value for each estimator, we have the following results : for OLS estimates $\hat{\beta}_1$ and $\hat{\beta}_2$.
$$
\text{Var}(\hat{\beta}_1) =\frac{1}{n} \frac{\sigma^2 \sum x_i^2}{\sum(x_i - \bar{x})^2}
$$
and
$$
\text{Var}(\hat{\beta}_2) = \frac{\sigma^2}{\sum(x_i - \bar{x})^2}
$$
Moreover,
$$
\text{Cov}(\hat{\beta}_1,\hat{\beta}_2) = - \frac{\sigma^2 \bar{x}}{\sum(x_i - \bar{x})^2}
$$
Proof of these results can be found in any textbook on linear regression.
Since we can estimate $\sigma^2$ from the original sample, we can estimate variances of estimators, even if we only have one value of them.
These variances estimates can also be computed from bootstrapping the sample, i.e by taking samples of the original sample and by computing estimators for each sub sample. For example for $\beta_1$, if you take $K$ sub sample then you get a sample $\hat{\beta}_1^{(1)},\dots,\hat{\beta}_1^{(K)}$ from which you can empirically estimate the variance of $\hat{\beta}_1$.
Here is a simple code (in R) showing how the two methods can be used
data<-data.frame(do.call(rbind,lapply(1:500,function(i){
id=i
x<-rexp(1,1)
y<- 1 + 3*x + rnorm(1,0,1)
return(c(id,y,x))
})))
names(data)<-c("id", "y","x")
summary(lm(y~x,data)) ## OLS std estimates from full sample
## by bootstrapping
Nboot<-500
list<-lapply(1:Nboot,function(i){
Ids <- sort(sample(data$id,replace=TRUE))
data.s = data[Ids,]
mod.s<-lm(y~x,data.s)
return(mod.s$coefficients)
})
## Bootstrap variances estimates
var(sapply(list,function(x) x[[1]]))**0.5 # beta1
var(sapply(list,function(x) x[[2]]))**0.5 # beta2
in the command
summary(lm(y~x,data)) ## OLS std estimates
the values in the "Std. Error" column should be close to the values computed in the last two lines | Standard Error of simple linear regression coefficients
Let a simple linear regression model
$$
y_i = \beta_1 + \beta_2x_i + \epsilon_i
$$
from $n$ observations, where $\epsilon_i$ are iid and of same variance $\sigma^2$.
OLS estimators of $\beta_1$ and $\ |
34,016 | Standard Error of simple linear regression coefficients | I think OP may be more concerned with an intuitive understanding of a standard error than of its calculation.
Consider a population. In the population, there is a population slope $\beta_1$ and a population intercept $\beta_0$ that govern the relationship between $X$ and $Y$. If you draw a sample from that population, using the formulas described in @winperikle's answer, you can compute the sample slope and sample intercept, $\hat{\beta}_1$ and $\hat{\beta}_0$. They won't be exactly equal to $\beta_1$ and $\beta_0$ due to sampling error (i.e., random chance), but they will probably be close (especially with a large sample).
Imagine we could do the previous activity again: draw a sample from the population and compute the sample slope and sample intercept, $\hat{\beta}_1$ and $\hat{\beta}_0$ (but we'll just focus on the sample slope for now). Imagine repeating this activity an infinite amount of times. You now have a collection of $\hat{\beta}_1$s, one from each sample. These will not all be equal to each other across samples because each sample is different. We can say that the many values of $\hat{\beta}_1$ have a distribution which has some variability and a center.
The variability of the collection of $\hat{\beta}_1$s can be quantified as the standard error, which is simply the standard deviation of the $\hat{\beta}_1$s. It is a fixed value that depends only on the qualities of the population and the size of each of the samples. If we knew this value, we could easily compute how far a single sample slope $\hat{\beta}_1$ is from the value of $\beta_1$ under the null hypothesis, which would allow us to determine whether we want to reject or fail to reject the null hypothesis.
In practice, we don't have access to the true standard error. We get to draw one sample and try to extract as much information as possible from it. The formula for the standard error of $\hat{\beta}_1$ in @winperikle's answer is a good estimate of the true standard error, even though we're only calculating it from one sample. So, from our one sample, we can compute an estimate of $\beta_1$ and an estimate of the standard error. This is where the standard error in regression output comes from. | Standard Error of simple linear regression coefficients | I think OP may be more concerned with an intuitive understanding of a standard error than of its calculation.
Consider a population. In the population, there is a population slope $\beta_1$ and a popu | Standard Error of simple linear regression coefficients
I think OP may be more concerned with an intuitive understanding of a standard error than of its calculation.
Consider a population. In the population, there is a population slope $\beta_1$ and a population intercept $\beta_0$ that govern the relationship between $X$ and $Y$. If you draw a sample from that population, using the formulas described in @winperikle's answer, you can compute the sample slope and sample intercept, $\hat{\beta}_1$ and $\hat{\beta}_0$. They won't be exactly equal to $\beta_1$ and $\beta_0$ due to sampling error (i.e., random chance), but they will probably be close (especially with a large sample).
Imagine we could do the previous activity again: draw a sample from the population and compute the sample slope and sample intercept, $\hat{\beta}_1$ and $\hat{\beta}_0$ (but we'll just focus on the sample slope for now). Imagine repeating this activity an infinite amount of times. You now have a collection of $\hat{\beta}_1$s, one from each sample. These will not all be equal to each other across samples because each sample is different. We can say that the many values of $\hat{\beta}_1$ have a distribution which has some variability and a center.
The variability of the collection of $\hat{\beta}_1$s can be quantified as the standard error, which is simply the standard deviation of the $\hat{\beta}_1$s. It is a fixed value that depends only on the qualities of the population and the size of each of the samples. If we knew this value, we could easily compute how far a single sample slope $\hat{\beta}_1$ is from the value of $\beta_1$ under the null hypothesis, which would allow us to determine whether we want to reject or fail to reject the null hypothesis.
In practice, we don't have access to the true standard error. We get to draw one sample and try to extract as much information as possible from it. The formula for the standard error of $\hat{\beta}_1$ in @winperikle's answer is a good estimate of the true standard error, even though we're only calculating it from one sample. So, from our one sample, we can compute an estimate of $\beta_1$ and an estimate of the standard error. This is where the standard error in regression output comes from. | Standard Error of simple linear regression coefficients
I think OP may be more concerned with an intuitive understanding of a standard error than of its calculation.
Consider a population. In the population, there is a population slope $\beta_1$ and a popu |
34,017 | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution? | It means that two things are true.
First:
$$ P(X_1 < t) = P(X_2 < t) $$
for all real numbers $t$ (i.e., $X_1$ and $X_2$ have the same distribution, often the shorthand equidistributed is used to describe this condition).
Second:
$$ P(X_1 < t) = \frac{1}{\sigma \sqrt{2 \pi}}\int_{-\infty}^t e^{\frac{(x - \mu)^2}{2 \sigma^2}} \,\text{d}x$$
for some fixed numbers $\mu$ and $\sigma$ (i.e. the distribution of $X_1$ (*) is a normal distribution).
This doesn't imply that $(X_1, X_2)$ is joint normal without further assumptions. If that was intended, it's not what the author actually wrote.
(*) Given the first condition, this implies that the distribution of $X_2$ is also a normal distribution. | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution? | It means that two things are true.
First:
$$ P(X_1 < t) = P(X_2 < t) $$
for all real numbers $t$ (i.e., $X_1$ and $X_2$ have the same distribution, often the shorthand equidistributed is used to descr | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution?
It means that two things are true.
First:
$$ P(X_1 < t) = P(X_2 < t) $$
for all real numbers $t$ (i.e., $X_1$ and $X_2$ have the same distribution, often the shorthand equidistributed is used to describe this condition).
Second:
$$ P(X_1 < t) = \frac{1}{\sigma \sqrt{2 \pi}}\int_{-\infty}^t e^{\frac{(x - \mu)^2}{2 \sigma^2}} \,\text{d}x$$
for some fixed numbers $\mu$ and $\sigma$ (i.e. the distribution of $X_1$ (*) is a normal distribution).
This doesn't imply that $(X_1, X_2)$ is joint normal without further assumptions. If that was intended, it's not what the author actually wrote.
(*) Given the first condition, this implies that the distribution of $X_2$ is also a normal distribution. | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution?
It means that two things are true.
First:
$$ P(X_1 < t) = P(X_2 < t) $$
for all real numbers $t$ (i.e., $X_1$ and $X_2$ have the same distribution, often the shorthand equidistributed is used to descr |
34,018 | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution? | I think "common" here just means that the marginal distribution $\text{N}(0,1)$ is common to both random variables (i.e., they have the same marginal distribution). Although technically this is insufficient to give a bivariate normal distribution, I think the writer probably intended that form:
$$\begin{bmatrix} X \\ Y \end{bmatrix} \sim \text{N} \Big( \begin{bmatrix} 0 \\ 0 \end{bmatrix}, \begin{bmatrix} 1 & \rho \\ \rho & 1 \end{bmatrix} \Big).$$
That specification would yield common marginal distributions $X \sim \text{N}(0,1)$ and $Y \sim \text{N}(0,1)$. If I were you, I would suggest noting this technicality, and then proceed on the basis that the random variables are bivariate normal. You might want to note the issue again as a caveat once you give your answer. | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution? | I think "common" here just means that the marginal distribution $\text{N}(0,1)$ is common to both random variables (i.e., they have the same marginal distribution). Although technically this is insuf | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution?
I think "common" here just means that the marginal distribution $\text{N}(0,1)$ is common to both random variables (i.e., they have the same marginal distribution). Although technically this is insufficient to give a bivariate normal distribution, I think the writer probably intended that form:
$$\begin{bmatrix} X \\ Y \end{bmatrix} \sim \text{N} \Big( \begin{bmatrix} 0 \\ 0 \end{bmatrix}, \begin{bmatrix} 1 & \rho \\ \rho & 1 \end{bmatrix} \Big).$$
That specification would yield common marginal distributions $X \sim \text{N}(0,1)$ and $Y \sim \text{N}(0,1)$. If I were you, I would suggest noting this technicality, and then proceed on the basis that the random variables are bivariate normal. You might want to note the issue again as a caveat once you give your answer. | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution?
I think "common" here just means that the marginal distribution $\text{N}(0,1)$ is common to both random variables (i.e., they have the same marginal distribution). Although technically this is insuf |
34,019 | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution? | The exercise is badly phrased. I suspect what is meant is that the two random variables are jointly normal and have a common distribution. If they're separately normal but not jointly normal, then you don't have enough information to answer the question. If my suspicion is right, then the exercise should have said they are jointly normal.
To have a "common" distribution simply means they both have the same distribution. Thus:
\begin{align}
\require{cancel}
& \left[ \begin{array}{l} X_1 \\ X_2 \end{array} \right] \sim \xcancel{\operatorname N\left( \left[ \begin{array}{l} \mu_1 \\ \mu_2 \end{array} \right], \left[ \begin{array}{cc} \sigma_1^2 & \rho \sigma_1\sigma_2 \\ \rho\sigma_1\sigma_2 & \sigma_2^2 \end{array} \right] \right)} & & \longleftarrow \text{ not common} \\[10pt]
& \left[ \begin{array}{l} X_1 \\ X_2 \end{array} \right] \sim \operatorname N\left( \left[ \begin{array}{l} \mu \\ \mu \end{array} \right], \left[ \begin{array}{cc} \sigma^2 & \rho \sigma^2 \\ \rho\sigma^2 & \sigma^2 \end{array} \right] \right) & & \longleftarrow\text{ common}
\end{align}
In the second case we have $X_i\sim\operatorname N(\mu,\sigma^2)$ for $i=1,2,$ thus each is normally distributed and they have that normal distribution in common. | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution? | The exercise is badly phrased. I suspect what is meant is that the two random variables are jointly normal and have a common distribution. If they're separately normal but not jointly normal, then you | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution?
The exercise is badly phrased. I suspect what is meant is that the two random variables are jointly normal and have a common distribution. If they're separately normal but not jointly normal, then you don't have enough information to answer the question. If my suspicion is right, then the exercise should have said they are jointly normal.
To have a "common" distribution simply means they both have the same distribution. Thus:
\begin{align}
\require{cancel}
& \left[ \begin{array}{l} X_1 \\ X_2 \end{array} \right] \sim \xcancel{\operatorname N\left( \left[ \begin{array}{l} \mu_1 \\ \mu_2 \end{array} \right], \left[ \begin{array}{cc} \sigma_1^2 & \rho \sigma_1\sigma_2 \\ \rho\sigma_1\sigma_2 & \sigma_2^2 \end{array} \right] \right)} & & \longleftarrow \text{ not common} \\[10pt]
& \left[ \begin{array}{l} X_1 \\ X_2 \end{array} \right] \sim \operatorname N\left( \left[ \begin{array}{l} \mu \\ \mu \end{array} \right], \left[ \begin{array}{cc} \sigma^2 & \rho \sigma^2 \\ \rho\sigma^2 & \sigma^2 \end{array} \right] \right) & & \longleftarrow\text{ common}
\end{align}
In the second case we have $X_i\sim\operatorname N(\mu,\sigma^2)$ for $i=1,2,$ thus each is normally distributed and they have that normal distribution in common. | What does it mean to say that $X_1, X_2$ have a "common" Normal distribution?
The exercise is badly phrased. I suspect what is meant is that the two random variables are jointly normal and have a common distribution. If they're separately normal but not jointly normal, then you |
34,020 | Overfitting on purpose | In General it does not make sense to overfit your data on purpose. The problem is that it is difficult to make sure that the patterns also appear in the part which is not included in your data. You have to affirm that there are pattern in the data. One possibility of doing so is the concept of stationarity.
What you describe reminds me of stationarity and ergodicity. From a contextual side/ business side you assume that your time series follows certain patterns. These patterns are called stationarity or ergodicity.
Definition stationarity:
A stationary process is a stochastic process whose unconditional joint probability distribution does not change when shifted in time. Therefore parameters such as mean and variance also do not change over time.
Definition ergodicity:
An ergodic process is a process relating to or denoting systems or processes with the property that, given sufficient time, they include or impinge on all points in a given space and can be represented statistically by a reasonably large selection of points.
Now you want to make sure that it really follows these certain patterns. You can do this, e.g. with Unit root test (like Dickey-Fuller) or Stationarity test (like KPSS).
Definition Unit root test:
$H_0:$ There is a unit root.
$H_1:$ There is no unit root. This implies in most cases stationarity.
Definition Stationarity test:
$H_0:$ There is stationarity.
$H_1:$ There is no stationarity.
Further reading:
What is the difference between a stationary test and a unit root test?
It the time-series really follows these patterns forecasting and predicting will be "easier from a statistical point of view", for example you can apply econometric models for forecasting like ARIMA or TBATS. My answer relates to univariate and also multivariate time series if you have cross-sectional data stationarity and unit roots are not common concepts. | Overfitting on purpose | In General it does not make sense to overfit your data on purpose. The problem is that it is difficult to make sure that the patterns also appear in the part which is not included in your data. You ha | Overfitting on purpose
In General it does not make sense to overfit your data on purpose. The problem is that it is difficult to make sure that the patterns also appear in the part which is not included in your data. You have to affirm that there are pattern in the data. One possibility of doing so is the concept of stationarity.
What you describe reminds me of stationarity and ergodicity. From a contextual side/ business side you assume that your time series follows certain patterns. These patterns are called stationarity or ergodicity.
Definition stationarity:
A stationary process is a stochastic process whose unconditional joint probability distribution does not change when shifted in time. Therefore parameters such as mean and variance also do not change over time.
Definition ergodicity:
An ergodic process is a process relating to or denoting systems or processes with the property that, given sufficient time, they include or impinge on all points in a given space and can be represented statistically by a reasonably large selection of points.
Now you want to make sure that it really follows these certain patterns. You can do this, e.g. with Unit root test (like Dickey-Fuller) or Stationarity test (like KPSS).
Definition Unit root test:
$H_0:$ There is a unit root.
$H_1:$ There is no unit root. This implies in most cases stationarity.
Definition Stationarity test:
$H_0:$ There is stationarity.
$H_1:$ There is no stationarity.
Further reading:
What is the difference between a stationary test and a unit root test?
It the time-series really follows these patterns forecasting and predicting will be "easier from a statistical point of view", for example you can apply econometric models for forecasting like ARIMA or TBATS. My answer relates to univariate and also multivariate time series if you have cross-sectional data stationarity and unit roots are not common concepts. | Overfitting on purpose
In General it does not make sense to overfit your data on purpose. The problem is that it is difficult to make sure that the patterns also appear in the part which is not included in your data. You ha |
34,021 | Overfitting on purpose | No, it does not make sense to overfit your data.
The term overfitting actually refers to a comparison between models: If model_a performance better on the given training data but worse out-of-sample than model_b, model_a is overfitting. Or in other words: "there exists a better alternative".
If the traffic status "will not vary at all with respect to the training data", then you will achieve the best possible results by simply memorizing the training data (again, that's not "overfitting").
But "data will not vary much with respect to the training data" simply equates to having a reasonable representation of the underlying pattern. This is where machine learning works best (stationary environment as Ferdi explained). | Overfitting on purpose | No, it does not make sense to overfit your data.
The term overfitting actually refers to a comparison between models: If model_a performance better on the given training data but worse out-of-sample | Overfitting on purpose
No, it does not make sense to overfit your data.
The term overfitting actually refers to a comparison between models: If model_a performance better on the given training data but worse out-of-sample than model_b, model_a is overfitting. Or in other words: "there exists a better alternative".
If the traffic status "will not vary at all with respect to the training data", then you will achieve the best possible results by simply memorizing the training data (again, that's not "overfitting").
But "data will not vary much with respect to the training data" simply equates to having a reasonable representation of the underlying pattern. This is where machine learning works best (stationary environment as Ferdi explained). | Overfitting on purpose
No, it does not make sense to overfit your data.
The term overfitting actually refers to a comparison between models: If model_a performance better on the given training data but worse out-of-sample |
34,022 | Overfitting on purpose | I would say, that there is a sense to overfit your data, but only for research purposes. (Don't use overfitted model in production!)
In cases when data can be complex and task non-trivial, trying to overfit a model can be an important step!
If you can overfit a model - it means that the data is possible to be described by the model.
If you cannot even overfit - it can give you a clue for investigation:
you data is not ready to be modelled, so you would need do more data preparation / feature engineering
your model is too simple and cannot capture all data dependencies | Overfitting on purpose | I would say, that there is a sense to overfit your data, but only for research purposes. (Don't use overfitted model in production!)
In cases when data can be complex and task non-trivial, trying to o | Overfitting on purpose
I would say, that there is a sense to overfit your data, but only for research purposes. (Don't use overfitted model in production!)
In cases when data can be complex and task non-trivial, trying to overfit a model can be an important step!
If you can overfit a model - it means that the data is possible to be described by the model.
If you cannot even overfit - it can give you a clue for investigation:
you data is not ready to be modelled, so you would need do more data preparation / feature engineering
your model is too simple and cannot capture all data dependencies | Overfitting on purpose
I would say, that there is a sense to overfit your data, but only for research purposes. (Don't use overfitted model in production!)
In cases when data can be complex and task non-trivial, trying to o |
34,023 | Dealing with LSTM overfitting | Your NN is not necessarily overfitting. Usually, when it overfits, validation loss goes up as the NN memorizes the train set, your graph is definitely not doing that. The mere difference between train and validation loss could just mean that the validation set is harder or has a different distribution (unseen data). Also, I don't know what the error means, but maybe 0.15 is not a big difference, and it is just a matter of scaling.
As a suggestion, you could try a few things that worked for me:
Add a small dropout to your NN (start with 0.1, for example);
You can add dropout to your RNN, but it is trickier, you have to use the same mask for every step, instead of a random mask for each step;
You could experiment with NN size, maybe the answer is not making it smaller, but actually bigger, so your NN can learn more complex functions. To know if it is underfitting or overfitting, try to plot predict vs real;
You could do feature selection/engineering -- try to add more features or remove the ones that you might think that are just adding noise;
If your NN is simply input -> rnn layers -> output, try adding a few fully connected layers before/after the rNN, and use MISH as an activation function, instead of ReLU;
For the optimizer, instead of Adam, try using Ranger.
The problem could be the loss function. Maybe your labels are very sparse (a lot of zeros), and the model learns to predict all zeros (sudden drop in the beginning) and cant progress further after that. To solve situations like that you can try different metric, like pos_weight on BCE, dice loss, focal loss, etc.
Good luck! | Dealing with LSTM overfitting | Your NN is not necessarily overfitting. Usually, when it overfits, validation loss goes up as the NN memorizes the train set, your graph is definitely not doing that. The mere difference between train | Dealing with LSTM overfitting
Your NN is not necessarily overfitting. Usually, when it overfits, validation loss goes up as the NN memorizes the train set, your graph is definitely not doing that. The mere difference between train and validation loss could just mean that the validation set is harder or has a different distribution (unseen data). Also, I don't know what the error means, but maybe 0.15 is not a big difference, and it is just a matter of scaling.
As a suggestion, you could try a few things that worked for me:
Add a small dropout to your NN (start with 0.1, for example);
You can add dropout to your RNN, but it is trickier, you have to use the same mask for every step, instead of a random mask for each step;
You could experiment with NN size, maybe the answer is not making it smaller, but actually bigger, so your NN can learn more complex functions. To know if it is underfitting or overfitting, try to plot predict vs real;
You could do feature selection/engineering -- try to add more features or remove the ones that you might think that are just adding noise;
If your NN is simply input -> rnn layers -> output, try adding a few fully connected layers before/after the rNN, and use MISH as an activation function, instead of ReLU;
For the optimizer, instead of Adam, try using Ranger.
The problem could be the loss function. Maybe your labels are very sparse (a lot of zeros), and the model learns to predict all zeros (sudden drop in the beginning) and cant progress further after that. To solve situations like that you can try different metric, like pos_weight on BCE, dice loss, focal loss, etc.
Good luck! | Dealing with LSTM overfitting
Your NN is not necessarily overfitting. Usually, when it overfits, validation loss goes up as the NN memorizes the train set, your graph is definitely not doing that. The mere difference between train |
34,024 | Dealing with LSTM overfitting | Yeah, that’s overfitting because the test error is much larger than the training error.
Three stacked LSTMs is hard to train. Try a simpler network and work up to a more complex one. Keep in mind that the tendency of adding LSTM layers is to grow the magnitude of the memory cells. Linked memory-forget cells enforce memory convexity and make it easier to train deeper LSTM networks.
Learning rate tweaking or even scheduling might also help.
In general, fitting a neural network involves a lot of experimentation and refinement. Finding the best network involves tuning a lot of dials together. | Dealing with LSTM overfitting | Yeah, that’s overfitting because the test error is much larger than the training error.
Three stacked LSTMs is hard to train. Try a simpler network and work up to a more complex one. Keep in mind tha | Dealing with LSTM overfitting
Yeah, that’s overfitting because the test error is much larger than the training error.
Three stacked LSTMs is hard to train. Try a simpler network and work up to a more complex one. Keep in mind that the tendency of adding LSTM layers is to grow the magnitude of the memory cells. Linked memory-forget cells enforce memory convexity and make it easier to train deeper LSTM networks.
Learning rate tweaking or even scheduling might also help.
In general, fitting a neural network involves a lot of experimentation and refinement. Finding the best network involves tuning a lot of dials together. | Dealing with LSTM overfitting
Yeah, that’s overfitting because the test error is much larger than the training error.
Three stacked LSTMs is hard to train. Try a simpler network and work up to a more complex one. Keep in mind tha |
34,025 | Are all 20 subjects the same height if the standard deviation of the sample is reported as 0.0? | According to this biology SE thread, the standard deviation of male adult height is about $0.07$ metres, and of females is about $0.06$ metres.
Rounding these to one decimal place would give $0.1$ metres. The fact that the standard deviation is reported as $0.0$ metres indicates a standard deviation below $0.05$ metres ... but a standard deviation of, say, $0.048$ metres would still be consistent with the reported figure as it would round to $0.0$, yet would indicate a variation in heights in the sample only slightly less than the variability we observe everyday in the general population.
Is the figure well-reported? Well, it would be far more useful if the standard deviation had been reported to two decimal places, as the mean was. It may also be a simple numerical or rounding error; for example $0.07$ could have been truncated to $0.0$ rather than rounded. But could it be possible the figure refers to the standard error instead? I often see figures written in a way that makes it ambiguous whether a standard deviation or standard error is being quoted — for example, "the sample mean is $1.62 (\pm 0.06)$".
Just how plausible is it for the correct standard deviation to round to $0.0$ to one decimal place? The following R code simulates one million samples of size twenty taken from a population of standard deviation $0.06$ (as has been reported elsewhere for female height), finds the standard deviation for each sample, plots a histogram of the results, and calculates the proportion of samples in which the observed standard deviation was below $0.05$:
set.seed(123) #so uses same random numbers each time code is run
x <- replicate(1e6, sd(rnorm(20, sd=0.06)))
hist(x)
sum(x < 0.05)/1e6
[1] 0.170691
Hence a standard deviation that rounds to $0.0$ is not implausible, occurring about seventeen percent of the time if heights are normally distributed with true standard deviation $0.06$.
Subject to these assumptions we can also calculate, rather than simulate, that probability as approximately seventeen percent, as follows:
$$P(S^2 < 0.05^2) = P\left(\frac{19 S^2}{0.06^2} < \frac{19 \times 0.05^2}{0.06^2}\right) = P\left(\frac{19 S^2}{0.06^2} < 13.194\right) = 0.1715$$
where we have used the fact that ${(n-1) S^2}/{\sigma^2} = {19 S^2}/{0.06^2}$ follows the chi-squared distribution with $n-1 = 19$ degrees of freedom. You can calculate the probability in R using pchisq(q = 19*0.05^2/0.06^2, df = 19); if you replace $0.06$ by $0.07$ in line with published figures for male standard deviations, the probability is reduced to about four percent. As @whuber points out in the comments below, this kind of small "rounds to zero" SD is more likely to occur if the group sampled from was more homogeneous than the general population. If the population standard deviation is about $0.06$ metres, then the probability of obtaining such a small sample standard deviation would also have declined if the sample size had been larger.
curve(pchisq(q = 19*0.05^2/x^2, df = 19), from=0.005, to=0.1,
xlab="Population SD", ylab="Probability sample SD < 0.05 if n = 20")
curve(pchisq(q = (x-1)*0.05^2/0.06^2, df = x-1), from=2, to=50, ylim=c(0,0.6),
xlab="Sample size", ylab="Probability sample SD < 0.05 if population SD = 0.06") | Are all 20 subjects the same height if the standard deviation of the sample is reported as 0.0? | According to this biology SE thread, the standard deviation of male adult height is about $0.07$ metres, and of females is about $0.06$ metres.
Rounding these to one decimal place would give $0.1$ met | Are all 20 subjects the same height if the standard deviation of the sample is reported as 0.0?
According to this biology SE thread, the standard deviation of male adult height is about $0.07$ metres, and of females is about $0.06$ metres.
Rounding these to one decimal place would give $0.1$ metres. The fact that the standard deviation is reported as $0.0$ metres indicates a standard deviation below $0.05$ metres ... but a standard deviation of, say, $0.048$ metres would still be consistent with the reported figure as it would round to $0.0$, yet would indicate a variation in heights in the sample only slightly less than the variability we observe everyday in the general population.
Is the figure well-reported? Well, it would be far more useful if the standard deviation had been reported to two decimal places, as the mean was. It may also be a simple numerical or rounding error; for example $0.07$ could have been truncated to $0.0$ rather than rounded. But could it be possible the figure refers to the standard error instead? I often see figures written in a way that makes it ambiguous whether a standard deviation or standard error is being quoted — for example, "the sample mean is $1.62 (\pm 0.06)$".
Just how plausible is it for the correct standard deviation to round to $0.0$ to one decimal place? The following R code simulates one million samples of size twenty taken from a population of standard deviation $0.06$ (as has been reported elsewhere for female height), finds the standard deviation for each sample, plots a histogram of the results, and calculates the proportion of samples in which the observed standard deviation was below $0.05$:
set.seed(123) #so uses same random numbers each time code is run
x <- replicate(1e6, sd(rnorm(20, sd=0.06)))
hist(x)
sum(x < 0.05)/1e6
[1] 0.170691
Hence a standard deviation that rounds to $0.0$ is not implausible, occurring about seventeen percent of the time if heights are normally distributed with true standard deviation $0.06$.
Subject to these assumptions we can also calculate, rather than simulate, that probability as approximately seventeen percent, as follows:
$$P(S^2 < 0.05^2) = P\left(\frac{19 S^2}{0.06^2} < \frac{19 \times 0.05^2}{0.06^2}\right) = P\left(\frac{19 S^2}{0.06^2} < 13.194\right) = 0.1715$$
where we have used the fact that ${(n-1) S^2}/{\sigma^2} = {19 S^2}/{0.06^2}$ follows the chi-squared distribution with $n-1 = 19$ degrees of freedom. You can calculate the probability in R using pchisq(q = 19*0.05^2/0.06^2, df = 19); if you replace $0.06$ by $0.07$ in line with published figures for male standard deviations, the probability is reduced to about four percent. As @whuber points out in the comments below, this kind of small "rounds to zero" SD is more likely to occur if the group sampled from was more homogeneous than the general population. If the population standard deviation is about $0.06$ metres, then the probability of obtaining such a small sample standard deviation would also have declined if the sample size had been larger.
curve(pchisq(q = 19*0.05^2/x^2, df = 19), from=0.005, to=0.1,
xlab="Population SD", ylab="Probability sample SD < 0.05 if n = 20")
curve(pchisq(q = (x-1)*0.05^2/0.06^2, df = x-1), from=2, to=50, ylim=c(0,0.6),
xlab="Sample size", ylab="Probability sample SD < 0.05 if population SD = 0.06") | Are all 20 subjects the same height if the standard deviation of the sample is reported as 0.0?
According to this biology SE thread, the standard deviation of male adult height is about $0.07$ metres, and of females is about $0.06$ metres.
Rounding these to one decimal place would give $0.1$ met |
34,026 | Are all 20 subjects the same height if the standard deviation of the sample is reported as 0.0? | It is almost certainly a reporting error, unless the people were selected for being that height. | Are all 20 subjects the same height if the standard deviation of the sample is reported as 0.0? | It is almost certainly a reporting error, unless the people were selected for being that height. | Are all 20 subjects the same height if the standard deviation of the sample is reported as 0.0?
It is almost certainly a reporting error, unless the people were selected for being that height. | Are all 20 subjects the same height if the standard deviation of the sample is reported as 0.0?
It is almost certainly a reporting error, unless the people were selected for being that height. |
34,027 | Minimum CDF of random variables | Let $x$ by any number. Consider the event $\min(X,Y)\le x$. It can be expressed as the union of two events
$$\min(X,Y)\le x = (X\le x) \cup (Y \le x),$$
shown by the overlapping yellow and green regions in this figure, respectively:
The intersection of these events (shown in the bottom left corner where they overlap) obviously is $\{X\le x,\,Y\le x\}=\max(X,Y)\le x$. Therefore (by the PIE),
$$\Pr\left(\min(X,Y)\le x\right) = \Pr(X\le x) + \Pr (Y\le x) - \Pr\left(\max(X,Y)\le x\right).$$
All three probabilities are given directly by $F$ (answering the main question):
$$\eqalign{\Pr\left(\min(X,Y)\le x\right) &= F_{X,Y}(x,\infty) + F_{X,Y}(\infty, x) - F_{X,Y}(x,x)\\&= F_X(x) + F_Y(x) - F_{X,Y}(x,x).\tag{1}}$$
The use of "$\infty$" as an argument refers to the limit; thus, e.g., $F_X(x)=F_{X,Y}(x,\infty)=\lim_{y\to\infty} F_{X,Y}(x,y).$
The result can be expressed in terms of the marginal distributions (only) when $X$ and $Y$ are independent, for then $(1)$ becomes
$$\eqalign{\Pr\left(\min(X,Y)\le x\right) &= F_X(x) + F_Y(x) - F_X(x)F_Y(x) \\&= 1 - (1-F_X(x))(1-F_Y(x)).\tag{2}}$$
The latter expression is recognizable as computing the chance that independent variables $X$ and $Y$ are both not less than or equal to $x$, given by $(1-F_X(x))(1-F_Y(x))$: the subtraction from $1$ then gives the complementary chance that at least one of those variables is less than or equal to $x$, which is precisely what $\min(X,Y)\le x$ means. Thus $(1)$ is the natural generalization of $(2)$ to all bivariate distributions.
As a final comment, please note that care is needed in the use of "$\le$" and "$\lt$". They can be interchanged in all the preceding calculations when $F$ is continuous, but otherwise they make a difference. | Minimum CDF of random variables | Let $x$ by any number. Consider the event $\min(X,Y)\le x$. It can be expressed as the union of two events
$$\min(X,Y)\le x = (X\le x) \cup (Y \le x),$$
shown by the overlapping yellow and green reg | Minimum CDF of random variables
Let $x$ by any number. Consider the event $\min(X,Y)\le x$. It can be expressed as the union of two events
$$\min(X,Y)\le x = (X\le x) \cup (Y \le x),$$
shown by the overlapping yellow and green regions in this figure, respectively:
The intersection of these events (shown in the bottom left corner where they overlap) obviously is $\{X\le x,\,Y\le x\}=\max(X,Y)\le x$. Therefore (by the PIE),
$$\Pr\left(\min(X,Y)\le x\right) = \Pr(X\le x) + \Pr (Y\le x) - \Pr\left(\max(X,Y)\le x\right).$$
All three probabilities are given directly by $F$ (answering the main question):
$$\eqalign{\Pr\left(\min(X,Y)\le x\right) &= F_{X,Y}(x,\infty) + F_{X,Y}(\infty, x) - F_{X,Y}(x,x)\\&= F_X(x) + F_Y(x) - F_{X,Y}(x,x).\tag{1}}$$
The use of "$\infty$" as an argument refers to the limit; thus, e.g., $F_X(x)=F_{X,Y}(x,\infty)=\lim_{y\to\infty} F_{X,Y}(x,y).$
The result can be expressed in terms of the marginal distributions (only) when $X$ and $Y$ are independent, for then $(1)$ becomes
$$\eqalign{\Pr\left(\min(X,Y)\le x\right) &= F_X(x) + F_Y(x) - F_X(x)F_Y(x) \\&= 1 - (1-F_X(x))(1-F_Y(x)).\tag{2}}$$
The latter expression is recognizable as computing the chance that independent variables $X$ and $Y$ are both not less than or equal to $x$, given by $(1-F_X(x))(1-F_Y(x))$: the subtraction from $1$ then gives the complementary chance that at least one of those variables is less than or equal to $x$, which is precisely what $\min(X,Y)\le x$ means. Thus $(1)$ is the natural generalization of $(2)$ to all bivariate distributions.
As a final comment, please note that care is needed in the use of "$\le$" and "$\lt$". They can be interchanged in all the preceding calculations when $F$ is continuous, but otherwise they make a difference. | Minimum CDF of random variables
Let $x$ by any number. Consider the event $\min(X,Y)\le x$. It can be expressed as the union of two events
$$\min(X,Y)\le x = (X\le x) \cup (Y \le x),$$
shown by the overlapping yellow and green reg |
34,028 | Minimum CDF of random variables | Since it says so in the title (though not repeated in the body of the question), I'm going to assume that $X$ and $Y$ are independent; otherwise, we can't say much. One of the key properties of independence is that $\Pr(X \le x, Y \le y) = \Pr(X \le x) \Pr(Y \le y)$. We can use that to find the values of your two expressions, which are actually not the same thing:
\begin{align}
F_{X,Y}(x, x)
&= \Pr(X \le x, Y \le x)
= \Pr(\max(X, Y) \le x)
\\&= \Pr(X \le x) \Pr(Y \le x)
\\&= F_X(x) F_Y(x)
.\end{align}
On the other hand, $\min(X, Y) \le x$ exactly when we have at least one of $X \le x$ or $Y \le x$, and so we have
\begin{align}
\Pr(\min(X, Y) \le x)
&= \Pr(X \le x \;\text{or}\; Y \le x)
\\&= \Pr(X \le x) + \Pr(Y \le x) - \Pr(X \le x, Y \le x)
\\&= F_X(x) + F_Y(x) - F_X(x) F_Y(x)
.\end{align} | Minimum CDF of random variables | Since it says so in the title (though not repeated in the body of the question), I'm going to assume that $X$ and $Y$ are independent; otherwise, we can't say much. One of the key properties of indepe | Minimum CDF of random variables
Since it says so in the title (though not repeated in the body of the question), I'm going to assume that $X$ and $Y$ are independent; otherwise, we can't say much. One of the key properties of independence is that $\Pr(X \le x, Y \le y) = \Pr(X \le x) \Pr(Y \le y)$. We can use that to find the values of your two expressions, which are actually not the same thing:
\begin{align}
F_{X,Y}(x, x)
&= \Pr(X \le x, Y \le x)
= \Pr(\max(X, Y) \le x)
\\&= \Pr(X \le x) \Pr(Y \le x)
\\&= F_X(x) F_Y(x)
.\end{align}
On the other hand, $\min(X, Y) \le x$ exactly when we have at least one of $X \le x$ or $Y \le x$, and so we have
\begin{align}
\Pr(\min(X, Y) \le x)
&= \Pr(X \le x \;\text{or}\; Y \le x)
\\&= \Pr(X \le x) + \Pr(Y \le x) - \Pr(X \le x, Y \le x)
\\&= F_X(x) + F_Y(x) - F_X(x) F_Y(x)
.\end{align} | Minimum CDF of random variables
Since it says so in the title (though not repeated in the body of the question), I'm going to assume that $X$ and $Y$ are independent; otherwise, we can't say much. One of the key properties of indepe |
34,029 | Minimum CDF of random variables | $$W=min(X,Y)$$
$F_W(w)=P[W<=w]=P[min(X,Y)<=w]=1-P[min(X,Y)>w]$
$$=1-\int_{w}^{\infty} \int_{w}^{\infty}f_{X,Y}(x,y) \,dx\,dy$$ | Minimum CDF of random variables | $$W=min(X,Y)$$
$F_W(w)=P[W<=w]=P[min(X,Y)<=w]=1-P[min(X,Y)>w]$
$$=1-\int_{w}^{\infty} \int_{w}^{\infty}f_{X,Y}(x,y) \,dx\,dy$$ | Minimum CDF of random variables
$$W=min(X,Y)$$
$F_W(w)=P[W<=w]=P[min(X,Y)<=w]=1-P[min(X,Y)>w]$
$$=1-\int_{w}^{\infty} \int_{w}^{\infty}f_{X,Y}(x,y) \,dx\,dy$$ | Minimum CDF of random variables
$$W=min(X,Y)$$
$F_W(w)=P[W<=w]=P[min(X,Y)<=w]=1-P[min(X,Y)>w]$
$$=1-\int_{w}^{\infty} \int_{w}^{\infty}f_{X,Y}(x,y) \,dx\,dy$$ |
34,030 | Logistic Regression: Different Formulas between Courses? | $h_{\theta}(x)=\dfrac{1}{1+e^{-X\beta}}=\dfrac{1}{1+\frac{1}{e^{X\beta}}}=\dfrac{1}{\dfrac{e^{X\beta}}{e^{X\beta}}+\dfrac{1}{e^{X\beta}}}=\dfrac{1}{\dfrac{e^{X\beta}+1}{e^{X\beta}}}=\dfrac{e^{X\beta}}{1+e^{X\beta}}=p(X)$ | Logistic Regression: Different Formulas between Courses? | $h_{\theta}(x)=\dfrac{1}{1+e^{-X\beta}}=\dfrac{1}{1+\frac{1}{e^{X\beta}}}=\dfrac{1}{\dfrac{e^{X\beta}}{e^{X\beta}}+\dfrac{1}{e^{X\beta}}}=\dfrac{1}{\dfrac{e^{X\beta}+1}{e^{X\beta}}}=\dfrac{e^{X\beta}} | Logistic Regression: Different Formulas between Courses?
$h_{\theta}(x)=\dfrac{1}{1+e^{-X\beta}}=\dfrac{1}{1+\frac{1}{e^{X\beta}}}=\dfrac{1}{\dfrac{e^{X\beta}}{e^{X\beta}}+\dfrac{1}{e^{X\beta}}}=\dfrac{1}{\dfrac{e^{X\beta}+1}{e^{X\beta}}}=\dfrac{e^{X\beta}}{1+e^{X\beta}}=p(X)$ | Logistic Regression: Different Formulas between Courses?
$h_{\theta}(x)=\dfrac{1}{1+e^{-X\beta}}=\dfrac{1}{1+\frac{1}{e^{X\beta}}}=\dfrac{1}{\dfrac{e^{X\beta}}{e^{X\beta}}+\dfrac{1}{e^{X\beta}}}=\dfrac{1}{\dfrac{e^{X\beta}+1}{e^{X\beta}}}=\dfrac{e^{X\beta}} |
34,031 | Log-Log Regression - Dummy Variable and Index | When you include dummy variables for categories, you generally leave one dummy out so that the design matrix $X$ is not rank deficient. (This is an extremely important, somewhat abstract concept.)
Let's say you have dummies for Jan, Feb, ..., Nov, that is, you leave out the dummy for December.
The coefficient on Jan is then the effect of being in Jan relative to December.
Eg. if $b_2$ were .02, it would imply that sales are about 2% higher in January than December.
Changes in logs is conceptually similar to percent changes in levels.
Side note:
For $y_2$ near $y_1$, you have:
$$\log y_2 - \log y_1 \approx \frac{y_2 - y_1} {y_1}$$
That is, the log difference is close to the percent change (you can prove this using first order Taylor expand to linearize the log near 1). Eg. $\log(2.02) - \log(2) = .01$. As $y_2$ and $y_1$ get farther apart though, that approximation breaks down. Eg. $\log(1.4) - \log(1) = .3365$. 1.4 is 40% higher than 1, but the log difference is only .3365. | Log-Log Regression - Dummy Variable and Index | When you include dummy variables for categories, you generally leave one dummy out so that the design matrix $X$ is not rank deficient. (This is an extremely important, somewhat abstract concept.)
Le | Log-Log Regression - Dummy Variable and Index
When you include dummy variables for categories, you generally leave one dummy out so that the design matrix $X$ is not rank deficient. (This is an extremely important, somewhat abstract concept.)
Let's say you have dummies for Jan, Feb, ..., Nov, that is, you leave out the dummy for December.
The coefficient on Jan is then the effect of being in Jan relative to December.
Eg. if $b_2$ were .02, it would imply that sales are about 2% higher in January than December.
Changes in logs is conceptually similar to percent changes in levels.
Side note:
For $y_2$ near $y_1$, you have:
$$\log y_2 - \log y_1 \approx \frac{y_2 - y_1} {y_1}$$
That is, the log difference is close to the percent change (you can prove this using first order Taylor expand to linearize the log near 1). Eg. $\log(2.02) - \log(2) = .01$. As $y_2$ and $y_1$ get farther apart though, that approximation breaks down. Eg. $\log(1.4) - \log(1) = .3365$. 1.4 is 40% higher than 1, but the log difference is only .3365. | Log-Log Regression - Dummy Variable and Index
When you include dummy variables for categories, you generally leave one dummy out so that the design matrix $X$ is not rank deficient. (This is an extremely important, somewhat abstract concept.)
Le |
34,032 | Log-Log Regression - Dummy Variable and Index | The interpretation of a dummy variable in a model with a logged dependent variable is in a sense asymmetric: it depends on whether you're turning January "on" (from 0 to 1) or turning January "off."
Let $Y$ be your sales index and $X$ your January dummy. I think it's fair to describe your model as the following (I'm going to follow convention and play it loose with subscripts). I'm omitting the advertising spend component because you've mentioned that you understand how to interpret that. We've got:
$$ \log{Y} = \alpha + \beta X + \epsilon $$
If we exponentiate both sides, this is
$$ Y = e^{\alpha + \epsilon} $$ when January is "off", and
$$ Y = e^{\alpha + \beta + \epsilon} $$ when January is "on"
Now if we want to compare the difference between two numbers, A and B, relative to B, we calculate (A-B)/B, right? I say 15 is 50% larger than 10 because (15-10)/10 = 0.5; let's use this framework on the expressions above.
Difference going from January "off" to January "on" =
$$ \frac{e^{\alpha + \beta + \epsilon} - e^{\alpha + \epsilon}}{e^{\alpha + \epsilon}} = e^\beta - 1 $$
Difference going from January "on" to January "off" =
$$ \frac{e^{\alpha + \epsilon} - e^{\alpha + \beta + \epsilon}}{e^{\alpha + \beta + \epsilon}} = e^{-\beta} - 1 $$
Perhaps you see where this is going. Let's choose a value for $\beta$, say $0.3.$ Then going from off to on increases $Y$ by $e^{0.3} - 1= 0.35$, an increase of 35 percent. But going the other way decreases $Y$ by $-(e^{-0.3} - 1) = 0.26$, a decrease of 26 percent. Notably, neither of these matches your coefficient of 0.3!
And of course, this has all ignored the the error in estimating your regression parameters. That's fine if you're really interested in estimating changes not in $Y$, but in $\log{Y}$. It seems however that you care about $Y$ itself, and that invokes another problem: retransformation bias in log-linear models. That will bias your predictions of $Y$ downwards, and is independent of whether your independent variables are continuous or not, so I won't discuss that topic here. | Log-Log Regression - Dummy Variable and Index | The interpretation of a dummy variable in a model with a logged dependent variable is in a sense asymmetric: it depends on whether you're turning January "on" (from 0 to 1) or turning January "off."
L | Log-Log Regression - Dummy Variable and Index
The interpretation of a dummy variable in a model with a logged dependent variable is in a sense asymmetric: it depends on whether you're turning January "on" (from 0 to 1) or turning January "off."
Let $Y$ be your sales index and $X$ your January dummy. I think it's fair to describe your model as the following (I'm going to follow convention and play it loose with subscripts). I'm omitting the advertising spend component because you've mentioned that you understand how to interpret that. We've got:
$$ \log{Y} = \alpha + \beta X + \epsilon $$
If we exponentiate both sides, this is
$$ Y = e^{\alpha + \epsilon} $$ when January is "off", and
$$ Y = e^{\alpha + \beta + \epsilon} $$ when January is "on"
Now if we want to compare the difference between two numbers, A and B, relative to B, we calculate (A-B)/B, right? I say 15 is 50% larger than 10 because (15-10)/10 = 0.5; let's use this framework on the expressions above.
Difference going from January "off" to January "on" =
$$ \frac{e^{\alpha + \beta + \epsilon} - e^{\alpha + \epsilon}}{e^{\alpha + \epsilon}} = e^\beta - 1 $$
Difference going from January "on" to January "off" =
$$ \frac{e^{\alpha + \epsilon} - e^{\alpha + \beta + \epsilon}}{e^{\alpha + \beta + \epsilon}} = e^{-\beta} - 1 $$
Perhaps you see where this is going. Let's choose a value for $\beta$, say $0.3.$ Then going from off to on increases $Y$ by $e^{0.3} - 1= 0.35$, an increase of 35 percent. But going the other way decreases $Y$ by $-(e^{-0.3} - 1) = 0.26$, a decrease of 26 percent. Notably, neither of these matches your coefficient of 0.3!
And of course, this has all ignored the the error in estimating your regression parameters. That's fine if you're really interested in estimating changes not in $Y$, but in $\log{Y}$. It seems however that you care about $Y$ itself, and that invokes another problem: retransformation bias in log-linear models. That will bias your predictions of $Y$ downwards, and is independent of whether your independent variables are continuous or not, so I won't discuss that topic here. | Log-Log Regression - Dummy Variable and Index
The interpretation of a dummy variable in a model with a logged dependent variable is in a sense asymmetric: it depends on whether you're turning January "on" (from 0 to 1) or turning January "off."
L |
34,033 | Log-Log Regression - Dummy Variable and Index | On way to interpret the coefficient with the dummy variable is as a variable intercept. Something similar is explained here: Confusion of "slope" and "intercept" in linear regression
If you back transform to a linear scale then the intercept plays a role as a multiplicative constant.
$$\ln(\text{Sales Index}) = B_0 + B_1 * \ln(\text{advertising spend}) + B_2 (January) + \dots + \epsilon$$
which is equivalent to
$$\text{Sales Index} = \text{advertising spend}^{B_1} * \ln(B_0 + B_2 (\text {January}) + \dots) + \epsilon^\prime$$
This term $\ln(B_0 + B_2 (\text {January}) + \dots)$ will be having different values for different months
$$ln(B_0 + B_2 (\text {January}) + \dots) = \begin{cases} \ln(B_0 + B_2) & \quad \text{if it is January} \\
\ln(B_0 + B_3) & \quad \text{if it is Febuary} \\
\ln(B_0 + B_4) & \quad \text{if it is March} \\
\ln(B_0 + B_5) & \quad \text{if it is April} \\
\dots\\
\ln(B_0 + B_{13}) & \quad \text{if it is December} \\
\end{cases}$$ | Log-Log Regression - Dummy Variable and Index | On way to interpret the coefficient with the dummy variable is as a variable intercept. Something similar is explained here: Confusion of "slope" and "intercept" in linear regression
If you back trans | Log-Log Regression - Dummy Variable and Index
On way to interpret the coefficient with the dummy variable is as a variable intercept. Something similar is explained here: Confusion of "slope" and "intercept" in linear regression
If you back transform to a linear scale then the intercept plays a role as a multiplicative constant.
$$\ln(\text{Sales Index}) = B_0 + B_1 * \ln(\text{advertising spend}) + B_2 (January) + \dots + \epsilon$$
which is equivalent to
$$\text{Sales Index} = \text{advertising spend}^{B_1} * \ln(B_0 + B_2 (\text {January}) + \dots) + \epsilon^\prime$$
This term $\ln(B_0 + B_2 (\text {January}) + \dots)$ will be having different values for different months
$$ln(B_0 + B_2 (\text {January}) + \dots) = \begin{cases} \ln(B_0 + B_2) & \quad \text{if it is January} \\
\ln(B_0 + B_3) & \quad \text{if it is Febuary} \\
\ln(B_0 + B_4) & \quad \text{if it is March} \\
\ln(B_0 + B_5) & \quad \text{if it is April} \\
\dots\\
\ln(B_0 + B_{13}) & \quad \text{if it is December} \\
\end{cases}$$ | Log-Log Regression - Dummy Variable and Index
On way to interpret the coefficient with the dummy variable is as a variable intercept. Something similar is explained here: Confusion of "slope" and "intercept" in linear regression
If you back trans |
34,034 | Log-Log Regression - Dummy Variable and Index | Also worth having a look at "Halvorsen, R., & Palmquist, R. (1980). The interpretation of dummy variables in semilogarithmic equations. American economic review, 70(3), 474-475." | Log-Log Regression - Dummy Variable and Index | Also worth having a look at "Halvorsen, R., & Palmquist, R. (1980). The interpretation of dummy variables in semilogarithmic equations. American economic review, 70(3), 474-475." | Log-Log Regression - Dummy Variable and Index
Also worth having a look at "Halvorsen, R., & Palmquist, R. (1980). The interpretation of dummy variables in semilogarithmic equations. American economic review, 70(3), 474-475." | Log-Log Regression - Dummy Variable and Index
Also worth having a look at "Halvorsen, R., & Palmquist, R. (1980). The interpretation of dummy variables in semilogarithmic equations. American economic review, 70(3), 474-475." |
34,035 | You randomly select two distinct integers between 1 and 100. What is the probability that the larger number is exactly twice the smaller number? | Your first mistake is that there are 50 outcomes, there's actually 100 (Edit: See comment below for clarification). This is because getting (1,2) and (2,1) are the results of two seperate outcomes, but in each case the larger number is exactly twice the smaller number.
So the total possible ways of getting this is actually given by the set:
{ (1,2), (2,1), (2,4), (4,2), ..., (50,100), (100,50) }
Which is a list of 100 possible outcomes.
The total number of possible outcomes is $100 \times 99$
Since there are 100 possible numbers to choose the first time, and then 99 for the second since they must be distinct.
Hence the answer is given by:
$P = \frac{100}{100 \times 99} = \frac{1}{99}$
Using the same argument, it is straightforward to prove that the probability for the more general case of choosing numbers from $1, 2, ..., n$ where $n$ is some positive even number is given by:
$P = \frac{1}{n-1}$ | You randomly select two distinct integers between 1 and 100. What is the probability that the larger | Your first mistake is that there are 50 outcomes, there's actually 100 (Edit: See comment below for clarification). This is because getting (1,2) and (2,1) are the results of two seperate outcomes, b | You randomly select two distinct integers between 1 and 100. What is the probability that the larger number is exactly twice the smaller number?
Your first mistake is that there are 50 outcomes, there's actually 100 (Edit: See comment below for clarification). This is because getting (1,2) and (2,1) are the results of two seperate outcomes, but in each case the larger number is exactly twice the smaller number.
So the total possible ways of getting this is actually given by the set:
{ (1,2), (2,1), (2,4), (4,2), ..., (50,100), (100,50) }
Which is a list of 100 possible outcomes.
The total number of possible outcomes is $100 \times 99$
Since there are 100 possible numbers to choose the first time, and then 99 for the second since they must be distinct.
Hence the answer is given by:
$P = \frac{100}{100 \times 99} = \frac{1}{99}$
Using the same argument, it is straightforward to prove that the probability for the more general case of choosing numbers from $1, 2, ..., n$ where $n$ is some positive even number is given by:
$P = \frac{1}{n-1}$ | You randomly select two distinct integers between 1 and 100. What is the probability that the larger
Your first mistake is that there are 50 outcomes, there's actually 100 (Edit: See comment below for clarification). This is because getting (1,2) and (2,1) are the results of two seperate outcomes, b |
34,036 | You randomly select two distinct integers between 1 and 100. What is the probability that the larger number is exactly twice the smaller number? | The "Hacker" in the name of the test suggests we try to find a computing-oriented solution.
Let's therefore start with a program for brute-force enumeration of (a) the "favorable" cases where one integer is twice the other and (b) all possible cases. The answer would then be their ratio. I have coded a general solution. Its input is a positive integer n and its output is the probability.
n=100
all=favorable=0
for i=1 to n
for j=1 to n
if (i != j) all=all+1 {1}
if (j == 2*i) favorable = favorable+1 {2}
if (i == 2*j) favorable = favorable+1 {3}
return(favorable / all)
(The proof of correctness relies on the fact that $i \ne 2i$ for any positive number $i$.)
This program requires $3$ tests and up to $3$ increments for each iteration of the inner loop. Therefore it needs between $3n$ and $6n$ calculations each time the inner loop is performed, or $3n^2$ to $6n^2$ overall. That's $O(n^2)$ performance: OK for small $n$ like $n=100$, but terrible once $n$ exceeds $10000$ or so.
As a hacker, one of the first things you will want to do is eliminate the quadratic performance by simplifying the inner loop (if possible). To this end, systematically go through the lines in the inner loop (as numbered) and note the following:
Line 1 is executed all but once for each value of i and therefore all is incremented $n-1$ times. Consequently, for the computation of all, the loop over j can be replaced by incrementing all by n-1.
Line 2 is executed exactly once when $2i \le n$ and otherwise not at all. Therefore it can be replaced by incrementing all by $1$ whenever $2i \le n$.
Line 3 is executed once provided i is even.
Here is the transformed program.
n=100
all=favorable=0
for i=1 to n
all = all + (n-1) {1'}
if (2*i <= n) favorable = favorable+1 {2'}
if (even(i)) favorable = favorable+1 {3'}
return(favorable / all)
Can we go further and eliminate its loop?
Line 1' is executed $n$ times. Therefore all is incremented by n*(n-1).
Line 2' is executed only when $2i \le n$. One way to count this is $\lfloor n/2\rfloor$ (the greatest integer less than or equal to $n/2$).
Line 3' is executed only for even values of $i$. Again, that happens $\lfloor n/2 \rfloor$ times.
The second transformation of the program is:
n=100
all=favorable=0 {0}
all = all + n * (n-1) {1''}
favorable = favorable + floor(n/2) {2''}
favorable = favorable + floor(n/2) {3''}
return(favorable / all)
This is already a tremendous accomplishment: a $O(n^2)$ algorithm has been reduced to a $O(1)$ algorithm (which can be considered a "closed formula" for the answer).
Finally, there are some simple algebraic transformations we can make by rolling the initialization (line 0) into the first use of each variable and combining lines 2'' and 3'':
n=100
all = n * (n-1)
favorable = 2 * floor(n/2)
return(favorable / all)
At this point a human could execute the program. Let's do it with $n=100$:
all = 100 * (100-1) = 100*99
favorable = 2 * floor(100/2) = 2*50 = 100
favorable/all = 100 / (100*99) = 1/99
The output therefore is $1/99$.
To summarize, a brute-force algorithm can be transformed systematically using simple program rewriting rules into a sleek, elegant, $O(1)$ program. | You randomly select two distinct integers between 1 and 100. What is the probability that the larger | The "Hacker" in the name of the test suggests we try to find a computing-oriented solution.
Let's therefore start with a program for brute-force enumeration of (a) the "favorable" cases where one inte | You randomly select two distinct integers between 1 and 100. What is the probability that the larger number is exactly twice the smaller number?
The "Hacker" in the name of the test suggests we try to find a computing-oriented solution.
Let's therefore start with a program for brute-force enumeration of (a) the "favorable" cases where one integer is twice the other and (b) all possible cases. The answer would then be their ratio. I have coded a general solution. Its input is a positive integer n and its output is the probability.
n=100
all=favorable=0
for i=1 to n
for j=1 to n
if (i != j) all=all+1 {1}
if (j == 2*i) favorable = favorable+1 {2}
if (i == 2*j) favorable = favorable+1 {3}
return(favorable / all)
(The proof of correctness relies on the fact that $i \ne 2i$ for any positive number $i$.)
This program requires $3$ tests and up to $3$ increments for each iteration of the inner loop. Therefore it needs between $3n$ and $6n$ calculations each time the inner loop is performed, or $3n^2$ to $6n^2$ overall. That's $O(n^2)$ performance: OK for small $n$ like $n=100$, but terrible once $n$ exceeds $10000$ or so.
As a hacker, one of the first things you will want to do is eliminate the quadratic performance by simplifying the inner loop (if possible). To this end, systematically go through the lines in the inner loop (as numbered) and note the following:
Line 1 is executed all but once for each value of i and therefore all is incremented $n-1$ times. Consequently, for the computation of all, the loop over j can be replaced by incrementing all by n-1.
Line 2 is executed exactly once when $2i \le n$ and otherwise not at all. Therefore it can be replaced by incrementing all by $1$ whenever $2i \le n$.
Line 3 is executed once provided i is even.
Here is the transformed program.
n=100
all=favorable=0
for i=1 to n
all = all + (n-1) {1'}
if (2*i <= n) favorable = favorable+1 {2'}
if (even(i)) favorable = favorable+1 {3'}
return(favorable / all)
Can we go further and eliminate its loop?
Line 1' is executed $n$ times. Therefore all is incremented by n*(n-1).
Line 2' is executed only when $2i \le n$. One way to count this is $\lfloor n/2\rfloor$ (the greatest integer less than or equal to $n/2$).
Line 3' is executed only for even values of $i$. Again, that happens $\lfloor n/2 \rfloor$ times.
The second transformation of the program is:
n=100
all=favorable=0 {0}
all = all + n * (n-1) {1''}
favorable = favorable + floor(n/2) {2''}
favorable = favorable + floor(n/2) {3''}
return(favorable / all)
This is already a tremendous accomplishment: a $O(n^2)$ algorithm has been reduced to a $O(1)$ algorithm (which can be considered a "closed formula" for the answer).
Finally, there are some simple algebraic transformations we can make by rolling the initialization (line 0) into the first use of each variable and combining lines 2'' and 3'':
n=100
all = n * (n-1)
favorable = 2 * floor(n/2)
return(favorable / all)
At this point a human could execute the program. Let's do it with $n=100$:
all = 100 * (100-1) = 100*99
favorable = 2 * floor(100/2) = 2*50 = 100
favorable/all = 100 / (100*99) = 1/99
The output therefore is $1/99$.
To summarize, a brute-force algorithm can be transformed systematically using simple program rewriting rules into a sleek, elegant, $O(1)$ program. | You randomly select two distinct integers between 1 and 100. What is the probability that the larger
The "Hacker" in the name of the test suggests we try to find a computing-oriented solution.
Let's therefore start with a program for brute-force enumeration of (a) the "favorable" cases where one inte |
34,037 | You randomly select two distinct integers between 1 and 100. What is the probability that the larger number is exactly twice the smaller number? | First of all, you are sampling without replacement. Thus, there are 100*99 different outcomes, e.g. (1,1) is not a valid outcome.
Secondly, order does not matter. The larger must be exactly twice, not the second. Thus, remove symmetric pairs.
Thus, 50 out of (100)*99/2are positive, or 1/99 | You randomly select two distinct integers between 1 and 100. What is the probability that the larger | First of all, you are sampling without replacement. Thus, there are 100*99 different outcomes, e.g. (1,1) is not a valid outcome.
Secondly, order does not matter. The larger must be exactly twice, not | You randomly select two distinct integers between 1 and 100. What is the probability that the larger number is exactly twice the smaller number?
First of all, you are sampling without replacement. Thus, there are 100*99 different outcomes, e.g. (1,1) is not a valid outcome.
Secondly, order does not matter. The larger must be exactly twice, not the second. Thus, remove symmetric pairs.
Thus, 50 out of (100)*99/2are positive, or 1/99 | You randomly select two distinct integers between 1 and 100. What is the probability that the larger
First of all, you are sampling without replacement. Thus, there are 100*99 different outcomes, e.g. (1,1) is not a valid outcome.
Secondly, order does not matter. The larger must be exactly twice, not |
34,038 | What does this plot tell me about my linear model? | This sort of "problem" occurs quite naturally and can look this way without actually indicating a problem. (There might be some problem, but a pattern similar to this doesn't necessarily indicate one.)
It's a consequence of regression to the mean and arises directly out of fitting the conditional mean (i.e. it's exactly what you expect to see with regression).
One thing that might throw off some answerers is that you have your plot "backward" to what most of us are used to -- with the random variable on the x axis rather than the y-axis.
Here I have generated some data according to a regression model (with a normally distributed predictor and conditionally normal response) and fitted a model of the same form as the one that generated the data. Here's the corresponding plot to yours drawn the other way around:
Looking at the slice between the blue lines, the red line (which is just the line with slope 1 and intercept 0) passes very near the mean of the $y$ in that slice. That is, $\hat{y}\approx E(Y|x)$.
You are asking if you should "tweak" your line to lay closer to the major axis of the roughly elliptical point cloud ... but that is not going to be the "best fit" line, and will tend to overpredict the mean for large $y$ values and underpredict it for small y values.
If the regression assumptions are reasonable, and assuming you actually want to predict $E(Y|x)$, then there's nothing wrong here -- you see exactly what you should.
A case where you might see something like this, and where it might be an issue:
However, if your line at the edge of the cloud doesn't pass near the middle of small slices (vertical ones in my case) that might indicate that you have some underprediction (such as might occur if you're shrinking coefficients).
That may or may not be a problem: shrinking coefficients toward zero is often quite useful; that will lead to bias but bias isn't the whole story of fitting.
A small amount of bias toward zero (shrinkage) in the coefficients will produce a slightly "shallower" fit than the least squares line (on my plot; steeper on yours). That's not necessarily a problem at all.
It's only if the bias is larger than you want it to be that there would be any need to act at all. Otherwise it could still be doing exactly what it should.
So I don't see a problem here -- it looks to me like your model is doing what it should.
For reference, here's the plot from the question flipped around:
There's some hint that it's slightly biased toward 0 (which as mentioned, may not be a problem), and also perhaps a slight suggestion of a nonlinear relationship (which might potentially be a problem). | What does this plot tell me about my linear model? | This sort of "problem" occurs quite naturally and can look this way without actually indicating a problem. (There might be some problem, but a pattern similar to this doesn't necessarily indicate one. | What does this plot tell me about my linear model?
This sort of "problem" occurs quite naturally and can look this way without actually indicating a problem. (There might be some problem, but a pattern similar to this doesn't necessarily indicate one.)
It's a consequence of regression to the mean and arises directly out of fitting the conditional mean (i.e. it's exactly what you expect to see with regression).
One thing that might throw off some answerers is that you have your plot "backward" to what most of us are used to -- with the random variable on the x axis rather than the y-axis.
Here I have generated some data according to a regression model (with a normally distributed predictor and conditionally normal response) and fitted a model of the same form as the one that generated the data. Here's the corresponding plot to yours drawn the other way around:
Looking at the slice between the blue lines, the red line (which is just the line with slope 1 and intercept 0) passes very near the mean of the $y$ in that slice. That is, $\hat{y}\approx E(Y|x)$.
You are asking if you should "tweak" your line to lay closer to the major axis of the roughly elliptical point cloud ... but that is not going to be the "best fit" line, and will tend to overpredict the mean for large $y$ values and underpredict it for small y values.
If the regression assumptions are reasonable, and assuming you actually want to predict $E(Y|x)$, then there's nothing wrong here -- you see exactly what you should.
A case where you might see something like this, and where it might be an issue:
However, if your line at the edge of the cloud doesn't pass near the middle of small slices (vertical ones in my case) that might indicate that you have some underprediction (such as might occur if you're shrinking coefficients).
That may or may not be a problem: shrinking coefficients toward zero is often quite useful; that will lead to bias but bias isn't the whole story of fitting.
A small amount of bias toward zero (shrinkage) in the coefficients will produce a slightly "shallower" fit than the least squares line (on my plot; steeper on yours). That's not necessarily a problem at all.
It's only if the bias is larger than you want it to be that there would be any need to act at all. Otherwise it could still be doing exactly what it should.
So I don't see a problem here -- it looks to me like your model is doing what it should.
For reference, here's the plot from the question flipped around:
There's some hint that it's slightly biased toward 0 (which as mentioned, may not be a problem), and also perhaps a slight suggestion of a nonlinear relationship (which might potentially be a problem). | What does this plot tell me about my linear model?
This sort of "problem" occurs quite naturally and can look this way without actually indicating a problem. (There might be some problem, but a pattern similar to this doesn't necessarily indicate one. |
34,039 | What does this plot tell me about my linear model? | What these results tell you is something that is almost inevitable in this type of modeling: a model based on a training set will not fit a test set as well. The type of problem you face, with a difference in the slope of the relation between your linear predictor and the outcome variable between the training and test sets, seems to be one of calibration, as noted here in the context of logistic regression.
Your suggestion to "pivot" the slope of the line is similar to the general idea of "shrinking" regression coefficients to improve predictive ability on new data, but you would be better off using established methods like those provided by the rms package in R. Note that these efforts necessarily entail making a bias-variance tradeoff in predictive modeling. If you are unfamilar with that tradeoff, you should read An Introduction to Statistical Learning or a similar general reference.
Also, separate training and test sets might not be the most efficient way to use your data; developing the model on the entire data set and checking and adjusting calibration by bootstrap resampling may be better. Consider consulting Frank Harrell's course notes or his book for more detail.
Please check that your axes are labeled correctly. Typically one expects predicted values to be over-optimistic, with a wider range of predicted values than of observed. Also, the range of your results suggests that you might be using proportions as your outcome variable. If so, then there might be an issue if you used standard linear regression to develop your model. | What does this plot tell me about my linear model? | What these results tell you is something that is almost inevitable in this type of modeling: a model based on a training set will not fit a test set as well. The type of problem you face, with a diffe | What does this plot tell me about my linear model?
What these results tell you is something that is almost inevitable in this type of modeling: a model based on a training set will not fit a test set as well. The type of problem you face, with a difference in the slope of the relation between your linear predictor and the outcome variable between the training and test sets, seems to be one of calibration, as noted here in the context of logistic regression.
Your suggestion to "pivot" the slope of the line is similar to the general idea of "shrinking" regression coefficients to improve predictive ability on new data, but you would be better off using established methods like those provided by the rms package in R. Note that these efforts necessarily entail making a bias-variance tradeoff in predictive modeling. If you are unfamilar with that tradeoff, you should read An Introduction to Statistical Learning or a similar general reference.
Also, separate training and test sets might not be the most efficient way to use your data; developing the model on the entire data set and checking and adjusting calibration by bootstrap resampling may be better. Consider consulting Frank Harrell's course notes or his book for more detail.
Please check that your axes are labeled correctly. Typically one expects predicted values to be over-optimistic, with a wider range of predicted values than of observed. Also, the range of your results suggests that you might be using proportions as your outcome variable. If so, then there might be an issue if you used standard linear regression to develop your model. | What does this plot tell me about my linear model?
What these results tell you is something that is almost inevitable in this type of modeling: a model based on a training set will not fit a test set as well. The type of problem you face, with a diffe |
34,040 | What does this plot tell me about my linear model? | I think most of the relevant information here has been provided by @EdM. Let me add a few thoughts:
Regarding your plot, I would put the predicted values on the x-axis and the observed values on the y-axis. That is the way scatterplots are more typically constructed and may help with interpretation. In addition, I would make the plot square and force the plotting area to range over the same possible values (say, $.1$ to $.9$) on both dimensions. Lastly, I would plot a LOWESS fit as well as the one to one line. These should make what is going on easier to see.
My guess is that your fitted model has too shallow a slope relative to the test data, but that the mean prediction is not biased (much). That shouldn't happen often. If your data were randomly split into train and test, they should be very similar, so the slopes wouldn't differ by much. This is also true given that you seem to have a lot of data. That should make estimates fairly stable. For me, these facts raise some questions:
Was the split random, or was it by some pre-existing group structure (e.g., males vs. females)?
Did you do a lot of fitting to get your model (such that it was overfitted)? More specifically, what was your modeling process?
Do you have a lot of variables or complex functions of variables in the original model (and/or relative to the amount of data)?
More information is needed here.
It is also possible that you are missing some curvature in the data. | What does this plot tell me about my linear model? | I think most of the relevant information here has been provided by @EdM. Let me add a few thoughts:
Regarding your plot, I would put the predicted values on the x-axis and the observed values on th | What does this plot tell me about my linear model?
I think most of the relevant information here has been provided by @EdM. Let me add a few thoughts:
Regarding your plot, I would put the predicted values on the x-axis and the observed values on the y-axis. That is the way scatterplots are more typically constructed and may help with interpretation. In addition, I would make the plot square and force the plotting area to range over the same possible values (say, $.1$ to $.9$) on both dimensions. Lastly, I would plot a LOWESS fit as well as the one to one line. These should make what is going on easier to see.
My guess is that your fitted model has too shallow a slope relative to the test data, but that the mean prediction is not biased (much). That shouldn't happen often. If your data were randomly split into train and test, they should be very similar, so the slopes wouldn't differ by much. This is also true given that you seem to have a lot of data. That should make estimates fairly stable. For me, these facts raise some questions:
Was the split random, or was it by some pre-existing group structure (e.g., males vs. females)?
Did you do a lot of fitting to get your model (such that it was overfitted)? More specifically, what was your modeling process?
Do you have a lot of variables or complex functions of variables in the original model (and/or relative to the amount of data)?
More information is needed here.
It is also possible that you are missing some curvature in the data. | What does this plot tell me about my linear model?
I think most of the relevant information here has been provided by @EdM. Let me add a few thoughts:
Regarding your plot, I would put the predicted values on the x-axis and the observed values on th |
34,041 | Interaction term in a linear mixed effect model in R | Here's what I would do:
First, I would have a look here on how to specify the random term in your model1. I am not quite sure what you are trying to fit. There is also a lot of info on linear mixed effects models here on CV. Click on the lme4-nlme tag, which you also provided. It would also help if you could provide an example dataset, or at least the structure of your data.
Then, you most likely only need one model, which is presumably in the form of:
my_model <- lmer(carbon ~ species + landuse + species : landuse + (1|site), data = mydata)
I specified the random effect to be + (1|site), because you said:
Study sites are included as the random effect in the model.
To get the ANOVA table you can either do:
library(car)
Anova(my_model)
or:
library(afex)
mixed(carbon ~ species + landuse + species : landuse + (1|site), data = mydata)
or instead of running lmer() through the lme4 package, load the lmerTest package and run:
my_model <- lmer(carbon ~ species + landuse + species : landuse + (1|site), data = mydata)
anova(my_model)
This will give you the ANOVA table you probably need eventually. Make sure to have a look at those functions and their arguments (?Anova, ?mixed, ?lmerTest::anova).
I don't quite understand why would want to exclude species if the interaction is significant and run separate models for all species?!
However, if your main effects are not significant you could consider tossing them out and re-running the model with the interaction only. However, if one or both main effects are significant, I would keep them both in the model and report this together with a potential significant interaction.
In any case, if you have a significant interaction you should focus on interpreting the interaction and not the main effects since their interpretation could now be misleading. The interpretation of the interaction should start by visualizing it. You could do this for example using the emmip() function in the emmeans package:
library(emmeans)
emmip(my_model, landuse ~ species)
Regarding the adjustment of p-values, you only need to do that if you are following up with post-hoc tests.
This could be done with the emmeans() function (also from the emmeans package):
emmeans(my_model, pairwise ~ species : landuse) | Interaction term in a linear mixed effect model in R | Here's what I would do:
First, I would have a look here on how to specify the random term in your model1. I am not quite sure what you are trying to fit. There is also a lot of info on linear mixed ef | Interaction term in a linear mixed effect model in R
Here's what I would do:
First, I would have a look here on how to specify the random term in your model1. I am not quite sure what you are trying to fit. There is also a lot of info on linear mixed effects models here on CV. Click on the lme4-nlme tag, which you also provided. It would also help if you could provide an example dataset, or at least the structure of your data.
Then, you most likely only need one model, which is presumably in the form of:
my_model <- lmer(carbon ~ species + landuse + species : landuse + (1|site), data = mydata)
I specified the random effect to be + (1|site), because you said:
Study sites are included as the random effect in the model.
To get the ANOVA table you can either do:
library(car)
Anova(my_model)
or:
library(afex)
mixed(carbon ~ species + landuse + species : landuse + (1|site), data = mydata)
or instead of running lmer() through the lme4 package, load the lmerTest package and run:
my_model <- lmer(carbon ~ species + landuse + species : landuse + (1|site), data = mydata)
anova(my_model)
This will give you the ANOVA table you probably need eventually. Make sure to have a look at those functions and their arguments (?Anova, ?mixed, ?lmerTest::anova).
I don't quite understand why would want to exclude species if the interaction is significant and run separate models for all species?!
However, if your main effects are not significant you could consider tossing them out and re-running the model with the interaction only. However, if one or both main effects are significant, I would keep them both in the model and report this together with a potential significant interaction.
In any case, if you have a significant interaction you should focus on interpreting the interaction and not the main effects since their interpretation could now be misleading. The interpretation of the interaction should start by visualizing it. You could do this for example using the emmip() function in the emmeans package:
library(emmeans)
emmip(my_model, landuse ~ species)
Regarding the adjustment of p-values, you only need to do that if you are following up with post-hoc tests.
This could be done with the emmeans() function (also from the emmeans package):
emmeans(my_model, pairwise ~ species : landuse) | Interaction term in a linear mixed effect model in R
Here's what I would do:
First, I would have a look here on how to specify the random term in your model1. I am not quite sure what you are trying to fit. There is also a lot of info on linear mixed ef |
34,042 | Invalid survival times for this distribution | The survreg function in R does not allow time = 0. This is because for several of the distributions, including the lognormal distribution, having events occur at time = 0 will result in an undefined estimator.
You can think that having time = 0 for a lognormal would be similar to having y = -Inf for a normal distribution. | Invalid survival times for this distribution | The survreg function in R does not allow time = 0. This is because for several of the distributions, including the lognormal distribution, having events occur at time = 0 will result in an undefined e | Invalid survival times for this distribution
The survreg function in R does not allow time = 0. This is because for several of the distributions, including the lognormal distribution, having events occur at time = 0 will result in an undefined estimator.
You can think that having time = 0 for a lognormal would be similar to having y = -Inf for a normal distribution. | Invalid survival times for this distribution
The survreg function in R does not allow time = 0. This is because for several of the distributions, including the lognormal distribution, having events occur at time = 0 will result in an undefined e |
34,043 | Likelihood of 10000:1 probability happening exactly once in 10,000 tries | a 1 in 10000 probability, what is the likelihood probability that in 10000 trials it will occur exactly 1 time
$1/e\approx 0.3679$, as near as makes no odds. (The probability that it happens exactly 0 times is almost exactly the same.)
Edit: As Mark L Stone quite rightly points out, I've taken your question as implying the trials are independent without establishing that it's the case. This is a critical assumption (and may not be reasonable in many situations). Nevertheless I'll continue answering on that basis, because I continue to think that it was your intent.
The same is true for $n$ trials and a probability of $1/n$, for any sufficiently large $n$.
The probabilities (for any large $n$) look much like this (showing the case for $n$=10000):
If an event has a probability of 1:10,000, therefore in 100,000 trials it would then be likely to occur 10 times; in 1,000,000 trials, it would be likely to occur 100 times, but would it not be also just as likely that it occur in any given set of 1,000,000 trials any number of times, for example: 98 times, 99 times, 101 times, 96 times, 102 times, etc.
Not quite: 99 and 100 have the same chance, but everything else has a lower chance:
(the probability continues to go down as you move further out).
Specifically, you're dealing with a binomial distribution with $n=1000000$ and $p=1/10000$.
Since $n$ is large and $p$ is small, it's well approximated by a Poisson distribution with mean $\lambda=np=100$.
how many trials must be averaged and accounted for to approach a statistical certainty that a particular result is actually 1:10000, and not 1:9999 or 1:10001
You can't be certain it's actually 1/10000, since you can be arbitrarily close to it but different from it.
In $n$ trials, the expected number of successes is $np$ with sd $\sqrt{np(1-p)}\approx \sqrt{np}$.
If $p=1/10000$, and $n=10^{12}$, then the expected number of successes is $10^{8}$ with sd $10^{4}$; if $p=1/9999$ the expected number of successes would be $100,010,000$ ... about one standard deviation away -- not enough to tell them apart "reliably". But with $n=4\times 10^{12}$, you're about $2$sd's away, and you can tell them apart more easily; that's probably about as low as most people would want to go. At $n=10^{13}$ you could tell them apart quite well (the chances of 1/10000 looking like 1/9999 or 1/10001 or anything further away by chance are pretty small by that point).
Say you were happy with $10^{13}$ trials for distinguishing $p=1/10000$ from $1/9999$. If you wanted to rule out 1/9999.5 at the same confidence as you had for ruling out 1/9999, you'd need 4 times as many trials.
You can see that pinning down proportions to many figures of accuracy (when $p$ is very small) requires a lot of trials; you need a sample size several times more than $(1/p)^3$ to get the estimate accurate enough that you can rule out $p=1/(k\pm 1)$ when it's really $1/k$.
let's say after 10,000,000,000 trials the result occured 999,982 times, would you then state the probability for the next trial to be 1:9999.82 or 1:10000 or some calculated result involving the deviation? ..(Or I guess the same could be asked after only 1 set of 10,000 trials with much less accuracy!)
Yes, it could be asked at 10000 trials or 1000 or 100.
Let's simplify things and take 10000 trials and 98 successes. One could of course take as a point estimate of the probability of a success 98/10000 = 0.0098 but this won't actually be the underlying proportion, only an estimate of it. It might well be 0.944... or 0.997... or any number of other values.
So one thing people do is construct an interval of values that would be (in some sense) reasonably consistent with the observed proportion. There are two main philosophies of statistics (Bayesian and frequentist statistics) that in large samples would usually tend to generate similar intervals but which have rather different interpretations.
The most common would be a (frequentist) confidence interval; an interval for the parameter ($p$) that would (over many repetitions of the same experiment) be expected include the parameter a given proportion of the time.
A typical Bayesian interval would start with a prior distribution on the parameter representing your uncertainty about its value, and use the data to update that knowledge of it to a posterior distribution and from it obtain a credible interval.
Confidence intervals are very widely used (though a credible interval may come closer to your expectations about what an interval should do). In the case of binomial proportion confidence interval, as here, there are a variety of approaches, though in large samples they all give you pretty much the same interval.
with dice even 6 x 10^9 trials may not result in exactly 1 x 10^9 for each of six results
Correct; you would expect (with fair dice) to get between 999.94 million and 1000.06 million success almost (but not quite) every time you tried it.
If actual probability is 1:10000, then increasing trials within the expected deviation would tend to confirm that
It will nearly always continue to be consistent with it (and with a range of other nearby values). What happens is not that you can tell it's 1/10000, but that the interval of probability values consistent with your results will get narrower as the sample size grows. | Likelihood of 10000:1 probability happening exactly once in 10,000 tries | a 1 in 10000 probability, what is the likelihood probability that in 10000 trials it will occur exactly 1 time
$1/e\approx 0.3679$, as near as makes no odds. (The probability that it happens exactly | Likelihood of 10000:1 probability happening exactly once in 10,000 tries
a 1 in 10000 probability, what is the likelihood probability that in 10000 trials it will occur exactly 1 time
$1/e\approx 0.3679$, as near as makes no odds. (The probability that it happens exactly 0 times is almost exactly the same.)
Edit: As Mark L Stone quite rightly points out, I've taken your question as implying the trials are independent without establishing that it's the case. This is a critical assumption (and may not be reasonable in many situations). Nevertheless I'll continue answering on that basis, because I continue to think that it was your intent.
The same is true for $n$ trials and a probability of $1/n$, for any sufficiently large $n$.
The probabilities (for any large $n$) look much like this (showing the case for $n$=10000):
If an event has a probability of 1:10,000, therefore in 100,000 trials it would then be likely to occur 10 times; in 1,000,000 trials, it would be likely to occur 100 times, but would it not be also just as likely that it occur in any given set of 1,000,000 trials any number of times, for example: 98 times, 99 times, 101 times, 96 times, 102 times, etc.
Not quite: 99 and 100 have the same chance, but everything else has a lower chance:
(the probability continues to go down as you move further out).
Specifically, you're dealing with a binomial distribution with $n=1000000$ and $p=1/10000$.
Since $n$ is large and $p$ is small, it's well approximated by a Poisson distribution with mean $\lambda=np=100$.
how many trials must be averaged and accounted for to approach a statistical certainty that a particular result is actually 1:10000, and not 1:9999 or 1:10001
You can't be certain it's actually 1/10000, since you can be arbitrarily close to it but different from it.
In $n$ trials, the expected number of successes is $np$ with sd $\sqrt{np(1-p)}\approx \sqrt{np}$.
If $p=1/10000$, and $n=10^{12}$, then the expected number of successes is $10^{8}$ with sd $10^{4}$; if $p=1/9999$ the expected number of successes would be $100,010,000$ ... about one standard deviation away -- not enough to tell them apart "reliably". But with $n=4\times 10^{12}$, you're about $2$sd's away, and you can tell them apart more easily; that's probably about as low as most people would want to go. At $n=10^{13}$ you could tell them apart quite well (the chances of 1/10000 looking like 1/9999 or 1/10001 or anything further away by chance are pretty small by that point).
Say you were happy with $10^{13}$ trials for distinguishing $p=1/10000$ from $1/9999$. If you wanted to rule out 1/9999.5 at the same confidence as you had for ruling out 1/9999, you'd need 4 times as many trials.
You can see that pinning down proportions to many figures of accuracy (when $p$ is very small) requires a lot of trials; you need a sample size several times more than $(1/p)^3$ to get the estimate accurate enough that you can rule out $p=1/(k\pm 1)$ when it's really $1/k$.
let's say after 10,000,000,000 trials the result occured 999,982 times, would you then state the probability for the next trial to be 1:9999.82 or 1:10000 or some calculated result involving the deviation? ..(Or I guess the same could be asked after only 1 set of 10,000 trials with much less accuracy!)
Yes, it could be asked at 10000 trials or 1000 or 100.
Let's simplify things and take 10000 trials and 98 successes. One could of course take as a point estimate of the probability of a success 98/10000 = 0.0098 but this won't actually be the underlying proportion, only an estimate of it. It might well be 0.944... or 0.997... or any number of other values.
So one thing people do is construct an interval of values that would be (in some sense) reasonably consistent with the observed proportion. There are two main philosophies of statistics (Bayesian and frequentist statistics) that in large samples would usually tend to generate similar intervals but which have rather different interpretations.
The most common would be a (frequentist) confidence interval; an interval for the parameter ($p$) that would (over many repetitions of the same experiment) be expected include the parameter a given proportion of the time.
A typical Bayesian interval would start with a prior distribution on the parameter representing your uncertainty about its value, and use the data to update that knowledge of it to a posterior distribution and from it obtain a credible interval.
Confidence intervals are very widely used (though a credible interval may come closer to your expectations about what an interval should do). In the case of binomial proportion confidence interval, as here, there are a variety of approaches, though in large samples they all give you pretty much the same interval.
with dice even 6 x 10^9 trials may not result in exactly 1 x 10^9 for each of six results
Correct; you would expect (with fair dice) to get between 999.94 million and 1000.06 million success almost (but not quite) every time you tried it.
If actual probability is 1:10000, then increasing trials within the expected deviation would tend to confirm that
It will nearly always continue to be consistent with it (and with a range of other nearby values). What happens is not that you can tell it's 1/10000, but that the interval of probability values consistent with your results will get narrower as the sample size grows. | Likelihood of 10000:1 probability happening exactly once in 10,000 tries
a 1 in 10000 probability, what is the likelihood probability that in 10000 trials it will occur exactly 1 time
$1/e\approx 0.3679$, as near as makes no odds. (The probability that it happens exactly |
34,044 | Likelihood of 10000:1 probability happening exactly once in 10,000 tries | I came up to this question based on its title, while hoping to find the probability of an event with $p = \frac{1}{n}$ happening at least once in $n$ iterations. I know your question was about exactly once but I guess it's somehow related.
It looks like for $n$ sufficiently large, this likelihood tends to $1 / e ≃ 0.632$ and is (quite surprisingly) almost independent of $n$.
Explanation:
Suppose I roll a dice 6 times. The probability of getting 1 at least once out of those 6 tries is:
Probability of not getting '1' for each try:
$p = \frac{5}{6}$
Probability of not getting any '1' in 6 tries:
$p = \frac{5}{6}^{6}$
Probability of getting '1' at least once in 6 tries:
$p = 1 - \frac{5}{6}^{6} \approx 0.665$
Similarly, suppose an event has a probability of 1/10000. The probability of this event happening at least once out of 10000 tries is:
$p = 1 - \frac{9999}{10000}^{10000} \approx 0.634$
We can extrapolate this for any n and get:
Probability of event with $p = \frac{1}{n}$ occurring at least once out of $n$ tries:
$p = 1 - (\frac{n-1}{n})^{n}$
And since:
$\lim\limits_{n \rightarrow +\infty} \frac{n-1}{n}^{n} = \lim\limits_{n \rightarrow +\infty} (1 - \frac{1}{n})^{n} = \frac{1}{e} \approx 0.368$
We can say that:
$\lim\limits_{n \rightarrow +\infty} 1 - \frac{n-1}{n}^{n} \approx 0.632$
Plotting this equation in Grapher, we get something like this:
Conclusion: although it makes perfect sense, I was actually quite surprised by the fact that the probability of an event having $p = \frac{1}{n}$ happening at least once out of $n$ tries is almost independent of $n$, for $n$ as little as $3$ already. | Likelihood of 10000:1 probability happening exactly once in 10,000 tries | I came up to this question based on its title, while hoping to find the probability of an event with $p = \frac{1}{n}$ happening at least once in $n$ iterations. I know your question was about exactly | Likelihood of 10000:1 probability happening exactly once in 10,000 tries
I came up to this question based on its title, while hoping to find the probability of an event with $p = \frac{1}{n}$ happening at least once in $n$ iterations. I know your question was about exactly once but I guess it's somehow related.
It looks like for $n$ sufficiently large, this likelihood tends to $1 / e ≃ 0.632$ and is (quite surprisingly) almost independent of $n$.
Explanation:
Suppose I roll a dice 6 times. The probability of getting 1 at least once out of those 6 tries is:
Probability of not getting '1' for each try:
$p = \frac{5}{6}$
Probability of not getting any '1' in 6 tries:
$p = \frac{5}{6}^{6}$
Probability of getting '1' at least once in 6 tries:
$p = 1 - \frac{5}{6}^{6} \approx 0.665$
Similarly, suppose an event has a probability of 1/10000. The probability of this event happening at least once out of 10000 tries is:
$p = 1 - \frac{9999}{10000}^{10000} \approx 0.634$
We can extrapolate this for any n and get:
Probability of event with $p = \frac{1}{n}$ occurring at least once out of $n$ tries:
$p = 1 - (\frac{n-1}{n})^{n}$
And since:
$\lim\limits_{n \rightarrow +\infty} \frac{n-1}{n}^{n} = \lim\limits_{n \rightarrow +\infty} (1 - \frac{1}{n})^{n} = \frac{1}{e} \approx 0.368$
We can say that:
$\lim\limits_{n \rightarrow +\infty} 1 - \frac{n-1}{n}^{n} \approx 0.632$
Plotting this equation in Grapher, we get something like this:
Conclusion: although it makes perfect sense, I was actually quite surprised by the fact that the probability of an event having $p = \frac{1}{n}$ happening at least once out of $n$ tries is almost independent of $n$, for $n$ as little as $3$ already. | Likelihood of 10000:1 probability happening exactly once in 10,000 tries
I came up to this question based on its title, while hoping to find the probability of an event with $p = \frac{1}{n}$ happening at least once in $n$ iterations. I know your question was about exactly |
34,045 | Likelihood of 10000:1 probability happening exactly once in 10,000 tries | Let establish on simpler problem on dice. Lets calculate the likelihood probability that on 6 throws of dice, score will be 1 exactly once.
How many ways can this happen [and their respective probabilities]:
1 is scored in first throw but not in any other throws[1/6*5/6*5/6*...] [=3125/46656]
1 is scored in second throw but not in any other throw [5/6*1/6*5/6*...] [=3125/46656]
...
...
so total probability that 1 is scored only once in 6 throws is (3125/46656)*6 = 3125/7776
You can extend same development for events with probability 1/n. Probability of event occurring only once in n trials would be
((n-1)/n)^(n-1)
This might look a bit familiar when I rearrange it:
(1-1/n)^(n-1)
Other part of your question: reducing deviation as number of samples increases, is already well explained in another answer. | Likelihood of 10000:1 probability happening exactly once in 10,000 tries | Let establish on simpler problem on dice. Lets calculate the likelihood probability that on 6 throws of dice, score will be 1 exactly once.
How many ways can this happen [and their respective probabil | Likelihood of 10000:1 probability happening exactly once in 10,000 tries
Let establish on simpler problem on dice. Lets calculate the likelihood probability that on 6 throws of dice, score will be 1 exactly once.
How many ways can this happen [and their respective probabilities]:
1 is scored in first throw but not in any other throws[1/6*5/6*5/6*...] [=3125/46656]
1 is scored in second throw but not in any other throw [5/6*1/6*5/6*...] [=3125/46656]
...
...
so total probability that 1 is scored only once in 6 throws is (3125/46656)*6 = 3125/7776
You can extend same development for events with probability 1/n. Probability of event occurring only once in n trials would be
((n-1)/n)^(n-1)
This might look a bit familiar when I rearrange it:
(1-1/n)^(n-1)
Other part of your question: reducing deviation as number of samples increases, is already well explained in another answer. | Likelihood of 10000:1 probability happening exactly once in 10,000 tries
Let establish on simpler problem on dice. Lets calculate the likelihood probability that on 6 throws of dice, score will be 1 exactly once.
How many ways can this happen [and their respective probabil |
34,046 | Visualization and Overplotting: Alternative to scatters | A couple techniques are demonstrated in this plot I made a few months ago.
Only label the "interesting" points, and rely on a hover label for identifying other points on demand. This requires human intervention to do well, though software can come close with heuristics such as only showing labels when they can be shown without overlap.
Transform the scale, such as with logs or quantiles. The caution here is that the scale is no longer directly aligned with our perception. The viewer has to keep the transformation in mind.
Other options:
Use trellising or small multiples. That is, show a series of graphs, each with a subset of the points, such as one graph for each region for your country data.
Use linked single-variable charts, such as bars or dot plots, so that the label is in the axis. It helps if you can sort by either variable interactively. | Visualization and Overplotting: Alternative to scatters | A couple techniques are demonstrated in this plot I made a few months ago.
Only label the "interesting" points, and rely on a hover label for identifying other points on demand. This requires human i | Visualization and Overplotting: Alternative to scatters
A couple techniques are demonstrated in this plot I made a few months ago.
Only label the "interesting" points, and rely on a hover label for identifying other points on demand. This requires human intervention to do well, though software can come close with heuristics such as only showing labels when they can be shown without overlap.
Transform the scale, such as with logs or quantiles. The caution here is that the scale is no longer directly aligned with our perception. The viewer has to keep the transformation in mind.
Other options:
Use trellising or small multiples. That is, show a series of graphs, each with a subset of the points, such as one graph for each region for your country data.
Use linked single-variable charts, such as bars or dot plots, so that the label is in the axis. It helps if you can sort by either variable interactively. | Visualization and Overplotting: Alternative to scatters
A couple techniques are demonstrated in this plot I made a few months ago.
Only label the "interesting" points, and rely on a hover label for identifying other points on demand. This requires human i |
34,047 | Visualization and Overplotting: Alternative to scatters | If you want an alternative to a scatter plot, then a parallel coordinates plot may work, particularly if you are trying to show the relationship between many variables. You "have a lot of graphs", and a parallel coordinates plot might be able to reduce that down to one! Here's an example on the famous Iris data set, taken from Wikipedia (image credit):
The plot shows variation between species very clearly. You might choose to colour by geographic region or level of development instead. We can see how hard it is to distinguish the three species based on sepal width, but there is more separation in their petal lengths. After a bit of mental adjustment (our eyes can be too trained to look for an "upward slope"), there is obviously a positive correlation between petal width and petal length because higher petal widths are associated with higher petal lengths. Flowers at the top of the scale for one, tend to be at the top of the scale for the other - this is manifested in roughly parallel lines running between the axes. On the other hand there is a negative correlation between sepal width and sepal length, because plants with a high sepal width tend to move down to having a low sepal length and vice versa (we see diagonal lines crossing over).
The image manages to capture much of the information available in a whole matrix of scatter plots (image credit):
On the positive side, the parallel axis plot gives us the ability to follow an individual across all measured variables: if we see two interesting points on two separate scatterplots, particularly outliers, it may not be evident whether they represent the same individual, but on a parallel axis plot we can just "follow the thread". On the downside, ditching all those scatter plots throws away information about multivariate relationships. Most obviously, we can't see some details of the clustering so clearly (though note Nick Cox recommends parallel coordinate plots for the purpose of investigating how "deep" clustering goes through the variables) and possibilities for linear discrimination are completely obscured. Also, it can get hard to see correlations between axes which are far apart on the parallel coordinates plot, which would be more evident in a scatter matrix.
If you have the option of interactivity, rather than a static visualization, then parallel coordinate plots offer you some options to get around this. For example, a user can switch the order of the axes, putting variables next to each other to see the relationship of interest more clearly. Because positive and negative correlation behave so differently on a parallel coordinates plot, it's helpful to be able to flip an axis (if you reverse the direction of an axis which has negative correlation with an adjacent axis, then the lines between them get "untangled"). Even on a static plot, it's most effective to reverse axes to produce as many positive correlations as possible, and order axes so as to make consecutive correlations as strong as possible, since it's hard to follow a strand through a tangle (see Nick Cox on this point).
Perhaps the most important interactive feature is brushing and linking: the user can select e.g. the upper quartile of individuals based on one variable, and their lines are automatically highlighted all the way through the plot. If on another axis, points mostly around the top are highlighted, then this suggests positive correlation (but we ought to check to see the lower quartile is associated with points around the bottom of the second variable); if points mostly around the bottom are highlighted, it suggests negative correlation; if a selection of points randomly scattered all the way up the axis are highlighted, it suggests little correlation.
With the number of countries you're including, it seems difficult to label them all on any plot unless you have unusually generous space constraints. You may have to settle for highlighting only the most important individual countries. On an interactive visualization, hover labels can avoid clutter (as @xan points out) and perhaps you could allow users to highlight all countries in a given region (or some other grouping) which might automatically display their labels.
If you only use a limited number of labels, one place you might consider putting them is on the axes themselves. If you look at Edward Tufte's The Visual Display of Quantitative Information, Chapter 7: Multifunctioning Graphical Elements, you'll see this closely resembles Tufte's suggestion for what he called a "table-graphic" for government tax receipts (it may be more familiar to you as a "slopegraph"). Each axis becomes a sort of ranking table, which is a nice feature. (There are some differences between the approaches, particularly since Tufte's example table-graphic used the same units and scale on each axis, rather than normalizing the data to fit on, and since his "axes" represented an earlier and later time period, the slopes had an additional interpretation as a rate of growth. Those interpretations will not generally hold for a parallel coordinates plot, but the idea of a ranking table on each axis does.)
Links and references
Cox, N.J. "Speaking Stata: Graphing agreement and disagreement", The Stata Journal (2004) 4, Number 3, pp. 329–349 - this covers parallel coordinates plots but also some others that may be of interest to you.
Edward Tufte's blog post on slopegraphs, including his "table-graphic".
Robert Kosara's blog post on parallel coordinates, including some advantages and limitations (due to the impossibility of representing categorical data on a traditional parallel coordinates plot, Kosara developed a parallel sets visualization - see also his paper).
Some interactive examples: a nice one using Protovis, and another one using its smoother replacement, D3.js (drag the axis names to move them around; see more examples here). | Visualization and Overplotting: Alternative to scatters | If you want an alternative to a scatter plot, then a parallel coordinates plot may work, particularly if you are trying to show the relationship between many variables. You "have a lot of graphs", and | Visualization and Overplotting: Alternative to scatters
If you want an alternative to a scatter plot, then a parallel coordinates plot may work, particularly if you are trying to show the relationship between many variables. You "have a lot of graphs", and a parallel coordinates plot might be able to reduce that down to one! Here's an example on the famous Iris data set, taken from Wikipedia (image credit):
The plot shows variation between species very clearly. You might choose to colour by geographic region or level of development instead. We can see how hard it is to distinguish the three species based on sepal width, but there is more separation in their petal lengths. After a bit of mental adjustment (our eyes can be too trained to look for an "upward slope"), there is obviously a positive correlation between petal width and petal length because higher petal widths are associated with higher petal lengths. Flowers at the top of the scale for one, tend to be at the top of the scale for the other - this is manifested in roughly parallel lines running between the axes. On the other hand there is a negative correlation between sepal width and sepal length, because plants with a high sepal width tend to move down to having a low sepal length and vice versa (we see diagonal lines crossing over).
The image manages to capture much of the information available in a whole matrix of scatter plots (image credit):
On the positive side, the parallel axis plot gives us the ability to follow an individual across all measured variables: if we see two interesting points on two separate scatterplots, particularly outliers, it may not be evident whether they represent the same individual, but on a parallel axis plot we can just "follow the thread". On the downside, ditching all those scatter plots throws away information about multivariate relationships. Most obviously, we can't see some details of the clustering so clearly (though note Nick Cox recommends parallel coordinate plots for the purpose of investigating how "deep" clustering goes through the variables) and possibilities for linear discrimination are completely obscured. Also, it can get hard to see correlations between axes which are far apart on the parallel coordinates plot, which would be more evident in a scatter matrix.
If you have the option of interactivity, rather than a static visualization, then parallel coordinate plots offer you some options to get around this. For example, a user can switch the order of the axes, putting variables next to each other to see the relationship of interest more clearly. Because positive and negative correlation behave so differently on a parallel coordinates plot, it's helpful to be able to flip an axis (if you reverse the direction of an axis which has negative correlation with an adjacent axis, then the lines between them get "untangled"). Even on a static plot, it's most effective to reverse axes to produce as many positive correlations as possible, and order axes so as to make consecutive correlations as strong as possible, since it's hard to follow a strand through a tangle (see Nick Cox on this point).
Perhaps the most important interactive feature is brushing and linking: the user can select e.g. the upper quartile of individuals based on one variable, and their lines are automatically highlighted all the way through the plot. If on another axis, points mostly around the top are highlighted, then this suggests positive correlation (but we ought to check to see the lower quartile is associated with points around the bottom of the second variable); if points mostly around the bottom are highlighted, it suggests negative correlation; if a selection of points randomly scattered all the way up the axis are highlighted, it suggests little correlation.
With the number of countries you're including, it seems difficult to label them all on any plot unless you have unusually generous space constraints. You may have to settle for highlighting only the most important individual countries. On an interactive visualization, hover labels can avoid clutter (as @xan points out) and perhaps you could allow users to highlight all countries in a given region (or some other grouping) which might automatically display their labels.
If you only use a limited number of labels, one place you might consider putting them is on the axes themselves. If you look at Edward Tufte's The Visual Display of Quantitative Information, Chapter 7: Multifunctioning Graphical Elements, you'll see this closely resembles Tufte's suggestion for what he called a "table-graphic" for government tax receipts (it may be more familiar to you as a "slopegraph"). Each axis becomes a sort of ranking table, which is a nice feature. (There are some differences between the approaches, particularly since Tufte's example table-graphic used the same units and scale on each axis, rather than normalizing the data to fit on, and since his "axes" represented an earlier and later time period, the slopes had an additional interpretation as a rate of growth. Those interpretations will not generally hold for a parallel coordinates plot, but the idea of a ranking table on each axis does.)
Links and references
Cox, N.J. "Speaking Stata: Graphing agreement and disagreement", The Stata Journal (2004) 4, Number 3, pp. 329–349 - this covers parallel coordinates plots but also some others that may be of interest to you.
Edward Tufte's blog post on slopegraphs, including his "table-graphic".
Robert Kosara's blog post on parallel coordinates, including some advantages and limitations (due to the impossibility of representing categorical data on a traditional parallel coordinates plot, Kosara developed a parallel sets visualization - see also his paper).
Some interactive examples: a nice one using Protovis, and another one using its smoother replacement, D3.js (drag the axis names to move them around; see more examples here). | Visualization and Overplotting: Alternative to scatters
If you want an alternative to a scatter plot, then a parallel coordinates plot may work, particularly if you are trying to show the relationship between many variables. You "have a lot of graphs", and |
34,048 | Two-way ANOVA with count data | Can we report a Two-way ANOVA with count data?
Of course you can, the bigger question is whether you should.
In general, you should not - but instead you should do a similar analysis suitable for the particular kind of count data you might have.
If No, Why?
Because they don't satisfy the assumptions of anova. You have heteroskedasticity (variance is related to mean), skewness (counts can't be negative, and in small average counts the skewness will be substantial), and discreteness (again, with small average counts the impact can be substantial).
our responses are number of patients
"number of patients" doing what? Is this number of patients having some characteristic out of some total (like number out of the total exposed who responded to treatment or showing some symptom, say) or something else?
You may need some binomial or Poisson GLM (or perhaps negative binomial or some other model would be more suitable), or it may be you can set it up as a chi-square test.
That said, sometimes an ANOVA can work fairly well. If the counts are large enough that the above issues with skewness/closeness to 0 don't impact much, and you're mostly just interested in whether you can reject the null, the test should have close to the desired significance level under the null (heteroskedasiticity should only crop up under the alternative). | Two-way ANOVA with count data | Can we report a Two-way ANOVA with count data?
Of course you can, the bigger question is whether you should.
In general, you should not - but instead you should do a similar analysis suitable for th | Two-way ANOVA with count data
Can we report a Two-way ANOVA with count data?
Of course you can, the bigger question is whether you should.
In general, you should not - but instead you should do a similar analysis suitable for the particular kind of count data you might have.
If No, Why?
Because they don't satisfy the assumptions of anova. You have heteroskedasticity (variance is related to mean), skewness (counts can't be negative, and in small average counts the skewness will be substantial), and discreteness (again, with small average counts the impact can be substantial).
our responses are number of patients
"number of patients" doing what? Is this number of patients having some characteristic out of some total (like number out of the total exposed who responded to treatment or showing some symptom, say) or something else?
You may need some binomial or Poisson GLM (or perhaps negative binomial or some other model would be more suitable), or it may be you can set it up as a chi-square test.
That said, sometimes an ANOVA can work fairly well. If the counts are large enough that the above issues with skewness/closeness to 0 don't impact much, and you're mostly just interested in whether you can reject the null, the test should have close to the desired significance level under the null (heteroskedasiticity should only crop up under the alternative). | Two-way ANOVA with count data
Can we report a Two-way ANOVA with count data?
Of course you can, the bigger question is whether you should.
In general, you should not - but instead you should do a similar analysis suitable for th |
34,049 | Two-way ANOVA with count data | IF your count variable can be modelled as a Poisson distribution, you can use a GLM---Poisson regression, or some variants thereof. If the distribution only is "similar to" a Poisson, you can use quasi-Poisson regression or negative binomial regression.
OR, in some cases (especially if your only covariable is group membership) you can use ANOVA, after using a variance-stabilizing transformation. For the Poisson, that is the square root. In most cases today, it will be better to use a generalized linear model (Poisson or negbin) than transforming. For some strong opinion see here. | Two-way ANOVA with count data | IF your count variable can be modelled as a Poisson distribution, you can use a GLM---Poisson regression, or some variants thereof. If the distribution only is "similar to" a Poisson, you can use quas | Two-way ANOVA with count data
IF your count variable can be modelled as a Poisson distribution, you can use a GLM---Poisson regression, or some variants thereof. If the distribution only is "similar to" a Poisson, you can use quasi-Poisson regression or negative binomial regression.
OR, in some cases (especially if your only covariable is group membership) you can use ANOVA, after using a variance-stabilizing transformation. For the Poisson, that is the square root. In most cases today, it will be better to use a generalized linear model (Poisson or negbin) than transforming. For some strong opinion see here. | Two-way ANOVA with count data
IF your count variable can be modelled as a Poisson distribution, you can use a GLM---Poisson regression, or some variants thereof. If the distribution only is "similar to" a Poisson, you can use quas |
34,050 | Two-way ANOVA with count data | A little bit different answer from Glen_b's (though I agree with his).
Count data is usually best modeled with distributions like a binomial (where there is a maximum count), Poisson, or negative binomial (or others). In these distributions there is a relationship between the mean and the variance. ANOVA models assume normal distributions and equal variance, both of which are violated if the "truth" is one of these other distributions. That being said, the binomial, Poisson, and negative binomial can all be approximated by a normal distribution under certain conditions (large sample sizes and means far from the boundaries), so if your counts are high enough (and the resulting variances are not too different) then an ANOVA model may be a reasonable approximation (but the other models will still be better). | Two-way ANOVA with count data | A little bit different answer from Glen_b's (though I agree with his).
Count data is usually best modeled with distributions like a binomial (where there is a maximum count), Poisson, or negative bino | Two-way ANOVA with count data
A little bit different answer from Glen_b's (though I agree with his).
Count data is usually best modeled with distributions like a binomial (where there is a maximum count), Poisson, or negative binomial (or others). In these distributions there is a relationship between the mean and the variance. ANOVA models assume normal distributions and equal variance, both of which are violated if the "truth" is one of these other distributions. That being said, the binomial, Poisson, and negative binomial can all be approximated by a normal distribution under certain conditions (large sample sizes and means far from the boundaries), so if your counts are high enough (and the resulting variances are not too different) then an ANOVA model may be a reasonable approximation (but the other models will still be better). | Two-way ANOVA with count data
A little bit different answer from Glen_b's (though I agree with his).
Count data is usually best modeled with distributions like a binomial (where there is a maximum count), Poisson, or negative bino |
34,051 | How to get both MSE and R2 from a sklearn GridSearchCV? | You can for example create a scorer that computes MSE score and R2 score and choose which one you're gonna use in the GridSearch, however you will be able to see the two scores, if you insert a print in each score function.
Here is a starter code:
from sklearn.metrics import r2_score, mean_squared_error, make_scorer
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import Ridge
def MSE(y_true,y_pred):
mse = mean_squared_error(y_true, y_pred)
print 'MSE: %2.3f' % mse
return mse
def R2(y_true,y_pred):
r2 = r2_score(y_true, y_pred)
print 'R2: %2.3f' % r2
return r2
def two_score(y_true,y_pred):
MSE(y_true,y_pred) #set score here and not below if using MSE in GridCV
score = R2(y_true,y_pred)
return score
def two_scorer():
return make_scorer(two_score, greater_is_better=True) # change for false if using MSE
model = Ridge()
param_grid = {'alpha':[0.1,1,10]}
X_train = [[1,2],[1,5],[-3,2],[3,7],[-1,1],[0,-1]]
y_train = [1,0,1,0,3,5]
grid = GridSearchCV(model, param_grid, scoring=two_scorer())
grid.fit(X_train, y_train)
best_params = grid.best_params_
model = grid.best_estimator_
score = grid.best_score_
for item in grid.grid_scores_:
print "\t%s %s %s" % ('\tGRIDSCORES\t', "R" , item)
print '%s\tHP\t%s\t%f' % ("R" , str(best_params) ,abs(score))
And it's the output:
MSE: 2.376
R2: -8.506
MSE: 6.246
R2: -23.985
MSE: 7.304
R2: -6.304
MSE: 2.226
R2: -7.904
MSE: 5.058
R2: -19.230
MSE: 7.755
R2: -6.755
MSE: 1.786
R2: -6.144
MSE: 1.776
R2: -6.104
MSE: 9.660
R2: -8.660
GRIDSCORES R mean: -12.93166, std: 7.86753, params: {'alpha': 0.1}
GRIDSCORES R mean: -11.29644, std: 5.62964, params: {'alpha': 1}
GRIDSCORES R mean: -6.96916, std: 1.19536, params: {'alpha': 10}
R HP {'alpha': 10} 6.969163 | How to get both MSE and R2 from a sklearn GridSearchCV? | You can for example create a scorer that computes MSE score and R2 score and choose which one you're gonna use in the GridSearch, however you will be able to see the two scores, if you insert a print | How to get both MSE and R2 from a sklearn GridSearchCV?
You can for example create a scorer that computes MSE score and R2 score and choose which one you're gonna use in the GridSearch, however you will be able to see the two scores, if you insert a print in each score function.
Here is a starter code:
from sklearn.metrics import r2_score, mean_squared_error, make_scorer
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import Ridge
def MSE(y_true,y_pred):
mse = mean_squared_error(y_true, y_pred)
print 'MSE: %2.3f' % mse
return mse
def R2(y_true,y_pred):
r2 = r2_score(y_true, y_pred)
print 'R2: %2.3f' % r2
return r2
def two_score(y_true,y_pred):
MSE(y_true,y_pred) #set score here and not below if using MSE in GridCV
score = R2(y_true,y_pred)
return score
def two_scorer():
return make_scorer(two_score, greater_is_better=True) # change for false if using MSE
model = Ridge()
param_grid = {'alpha':[0.1,1,10]}
X_train = [[1,2],[1,5],[-3,2],[3,7],[-1,1],[0,-1]]
y_train = [1,0,1,0,3,5]
grid = GridSearchCV(model, param_grid, scoring=two_scorer())
grid.fit(X_train, y_train)
best_params = grid.best_params_
model = grid.best_estimator_
score = grid.best_score_
for item in grid.grid_scores_:
print "\t%s %s %s" % ('\tGRIDSCORES\t', "R" , item)
print '%s\tHP\t%s\t%f' % ("R" , str(best_params) ,abs(score))
And it's the output:
MSE: 2.376
R2: -8.506
MSE: 6.246
R2: -23.985
MSE: 7.304
R2: -6.304
MSE: 2.226
R2: -7.904
MSE: 5.058
R2: -19.230
MSE: 7.755
R2: -6.755
MSE: 1.786
R2: -6.144
MSE: 1.776
R2: -6.104
MSE: 9.660
R2: -8.660
GRIDSCORES R mean: -12.93166, std: 7.86753, params: {'alpha': 0.1}
GRIDSCORES R mean: -11.29644, std: 5.62964, params: {'alpha': 1}
GRIDSCORES R mean: -6.96916, std: 1.19536, params: {'alpha': 10}
R HP {'alpha': 10} 6.969163 | How to get both MSE and R2 from a sklearn GridSearchCV?
You can for example create a scorer that computes MSE score and R2 score and choose which one you're gonna use in the GridSearch, however you will be able to see the two scores, if you insert a print |
34,052 | Avoid negative results in Holt Winters forecasting | When your data must be positive, you shouldn't fit a model that can go negative, and if you do, you shouldn't be surprised that it may forecast there.
If your values are all strictly $> 0$, one common approach is to take logarithms and fit (and forecast) a model on that scale.
There are other ways to approach this sort of problem, but that's probably the simplest place to start.
You do need to take care when transforming forecasts though - a mean forecast on the log scale, if you simply exponentiate it, won't be a mean after you transform it back (it may be a good estimate of the median, however, and if you must have a mean there's an adjustment that can be made). | Avoid negative results in Holt Winters forecasting | When your data must be positive, you shouldn't fit a model that can go negative, and if you do, you shouldn't be surprised that it may forecast there.
If your values are all strictly $> 0$, one common | Avoid negative results in Holt Winters forecasting
When your data must be positive, you shouldn't fit a model that can go negative, and if you do, you shouldn't be surprised that it may forecast there.
If your values are all strictly $> 0$, one common approach is to take logarithms and fit (and forecast) a model on that scale.
There are other ways to approach this sort of problem, but that's probably the simplest place to start.
You do need to take care when transforming forecasts though - a mean forecast on the log scale, if you simply exponentiate it, won't be a mean after you transform it back (it may be a good estimate of the median, however, and if you must have a mean there's an adjustment that can be made). | Avoid negative results in Holt Winters forecasting
When your data must be positive, you shouldn't fit a model that can go negative, and if you do, you shouldn't be surprised that it may forecast there.
If your values are all strictly $> 0$, one common |
34,053 | Avoid negative results in Holt Winters forecasting | To address the part of your question related to R, the ets function from the forecast package includes a lambda argument -- when true, a Box-Cox transformation is used that will keep the forecasts strictly positive. You may be able to use the same general approach in Java. | Avoid negative results in Holt Winters forecasting | To address the part of your question related to R, the ets function from the forecast package includes a lambda argument -- when true, a Box-Cox transformation is used that will keep the forecasts str | Avoid negative results in Holt Winters forecasting
To address the part of your question related to R, the ets function from the forecast package includes a lambda argument -- when true, a Box-Cox transformation is used that will keep the forecasts strictly positive. You may be able to use the same general approach in Java. | Avoid negative results in Holt Winters forecasting
To address the part of your question related to R, the ets function from the forecast package includes a lambda argument -- when true, a Box-Cox transformation is used that will keep the forecasts str |
34,054 | Linear regression on a sample spanning many orders of magnitude | Let the physics (of the experiment and the measuring apparatus) guide you.
Ultimately, absorption is determined by measuring amounts of radiation passing through the medium and those measurements come down to counting photons. When the medium is macroscopic, thermodynamic fluctuations in concentration are negligible so the principal source of error lies in the counting. This error (or "shot noise") has a Poisson distribution. This implies the error is relatively large at high concentrations when little radiation is passing through.
With sufficient care in the laboratory, concentrations typically are measured extremely accurately, so I will not worry about errors in concentrations.
The absorbance itself is directly related to the logarithm of the measured radiation. Taking the logarithm evens out the amount of error across the entire possible range of concentrations. For this reason alone, it is best to analyze the absorbance in terms of its usual values rather than re-expressing them. In particular, we should avoid taking logs of absorbance, even though that would simplify the expression of the Beer-Lambert law.
We should also be alert to possible non-linearities. The derivation of the Beer-Lambert Law suggests the absorbance vs concentration curve will become nonlinear at high concentrations. Some way to detect or test this is needed.
These considerations suggest a simple procedure to analyze a series of $(C_i, A_i)$ pairs of concentrations and measured absorbances:
Estimate the coefficient $\kappa$ as the arithmetic mean of $A/C$, $\hat{\kappa} = \sum_i \frac{A_i}{C_i}$.
Predict the absorbance at each concentration in terms of the estimated coefficient: $\hat{A}(C) = \hat{\kappa}C.$
Check the additive residuals $A_i - \hat{A_i}$ for nonlinear trends in $C_i$.
Of course all this is theoretical and somewhat speculative--we haven't any actual data to analyze--but it is a reasonable place to start. If repeated laboratory experience suggests the data depart from the statistical behaviors described here, then some modifications of these procedures would be called for.
To illustrate these ideas, I have created a simulation that implements the key aspects of the measurement, including the Poisson noise and possibly nonlinear responses. By running it many times, we can observe the kind of variation that is likely to be encountered in the laboratory. Here are the results of one simulation run. (Other simulations can be carried out simply by changing the starting seed in the code below and modifying various parameters as desired.)
This simulated experiment measured absorbance at concentrations of $1$ down to $1/32$. The vertical spreads in values apparent in the scatterplot show the effects of (a) shot noise in the transmission measurements and (b) shot noise in the initial transmission measurement at zero concentration. (Notice how this actually creates some negative absorbance values.) Although the resulting errors are not going to have exactly the same distributions at each concentration, the roughly equal spreads are empirical evidence that the distributions are close enough to being the same that we needn't worry about that. In other words, there is no need to weight the absorbances according to the concentrations.
The red diagonal line has been estimated from all 50 simulations. It has a slope of $\hat{\kappa}=2.13$, which differs slightly from the physically correct slope of $2$ that was used in the simulations. This deviation is so large because I assumed there was very little radiation to measure; the maximum photon count was only $1000$. In practice, maximum counts could be many orders of magnitude greater than this, leading to highly precise slope estimates--but then we would not learn much from this figure!
The histogram of residuals does not look good: it is skewed to the right. This indicates some kind of trouble. That trouble does not come from asymmetry in the residuals at each concentration; rather, it comes from a lack of fit. That is evident in the boxplots at the right: although the first five of them line up almost horizontally, the last one--at the highest concentration--clearly differs in location (it is too high) and scale (it is too long). This results from a nonlinear response I built into the simulation. Although the nonlinearity is present throughout the full range of concentrations, it has an appreciable effect only at the very highest concentrations. This is more or less what would happen in the laboratory, too. However, with only one calibration run available we could not draw such boxplots. Consider analyzing multiple independent runs if nonlinearity might be a problem.
The simulation was performed in R. The calculations with actual data, though, are simple to conduct by hand or with a spreadsheet: just make sure to check the residuals for nonlinearity.
#
# Simulate instrument responses:
# `concentration` is an array of concentrations to use.
# `kappa` is the Beer-Lambert law coefficient.
# `n.0` is the largest expected photon count (at 0 concentration).
# `start` is a tiny positive value used to avoid logs of zero.
# `beta` is the amount of nonlinearity (it is a quadratic perturbation
# of the Beer-Lambert law).
# The return value is a parallel array of measured absorbances; it is subject
# to random fluctuations.
#
observe <- function(concentration, kappa=1, n.0=10^3, start=1/6, beta=0.2) {
transmission <- exp(-kappa * concentration - beta * concentration^2)
transmission.observed <- start + rpois(length(transmission), transmission * n.0)
absorbance <- -log(transmission.observed / rpois(1, n.0))
return(absorbance)
}
#
# Perform a set of simulations.
#
concentration <- 2^(-(0:5)) # Concentrations to use
n.iter <- 50 # Number of iterations
set.seed(17) # Make the results reproducible
absorbance <- replicate(n.iter, observe(concentration, kappa=2))
#
# Put the results into a data frame for further analysis.
#
a.df <- data.frame(absorbance = as.vector(absorbance))
a.df$concentration <- concentration # ($ interferes with TeX processing on this site)
#
# Create the figures.
#
par(mfrow=c(1,3))
#
# Set up a region for the scatterplot.
#
plot(c(min(concentration), max(concentration)),
c(min(absorbance), max(absorbance)), type="n",
xlab="Concentration", ylab="Absorbance",
main=paste("Scatterplot of", n.iter, "iterations"))
#
# Make the scatterplot.
#
invisible(apply(absorbance, 2,
function(a) points(concentration, a, col="#40404080")))
slope <- mean(a.df$absorbance / a.df$concentration)
abline(c(0, slope), col="Red")
#
# Show the residuals.
#
a.df$residuals <- a.df$absorbance - slope * a.df$concentration # $
hist(a.df$residuals, main="Histogram of residuals", xlab="Absorbance Difference") # $
#
# Study the residual distribution vs. concentration.
#
boxplot(a.df$residuals ~ a.df$concentration, main="Residual distributions",
xlab="Concentration") | Linear regression on a sample spanning many orders of magnitude | Let the physics (of the experiment and the measuring apparatus) guide you.
Ultimately, absorption is determined by measuring amounts of radiation passing through the medium and those measurements come | Linear regression on a sample spanning many orders of magnitude
Let the physics (of the experiment and the measuring apparatus) guide you.
Ultimately, absorption is determined by measuring amounts of radiation passing through the medium and those measurements come down to counting photons. When the medium is macroscopic, thermodynamic fluctuations in concentration are negligible so the principal source of error lies in the counting. This error (or "shot noise") has a Poisson distribution. This implies the error is relatively large at high concentrations when little radiation is passing through.
With sufficient care in the laboratory, concentrations typically are measured extremely accurately, so I will not worry about errors in concentrations.
The absorbance itself is directly related to the logarithm of the measured radiation. Taking the logarithm evens out the amount of error across the entire possible range of concentrations. For this reason alone, it is best to analyze the absorbance in terms of its usual values rather than re-expressing them. In particular, we should avoid taking logs of absorbance, even though that would simplify the expression of the Beer-Lambert law.
We should also be alert to possible non-linearities. The derivation of the Beer-Lambert Law suggests the absorbance vs concentration curve will become nonlinear at high concentrations. Some way to detect or test this is needed.
These considerations suggest a simple procedure to analyze a series of $(C_i, A_i)$ pairs of concentrations and measured absorbances:
Estimate the coefficient $\kappa$ as the arithmetic mean of $A/C$, $\hat{\kappa} = \sum_i \frac{A_i}{C_i}$.
Predict the absorbance at each concentration in terms of the estimated coefficient: $\hat{A}(C) = \hat{\kappa}C.$
Check the additive residuals $A_i - \hat{A_i}$ for nonlinear trends in $C_i$.
Of course all this is theoretical and somewhat speculative--we haven't any actual data to analyze--but it is a reasonable place to start. If repeated laboratory experience suggests the data depart from the statistical behaviors described here, then some modifications of these procedures would be called for.
To illustrate these ideas, I have created a simulation that implements the key aspects of the measurement, including the Poisson noise and possibly nonlinear responses. By running it many times, we can observe the kind of variation that is likely to be encountered in the laboratory. Here are the results of one simulation run. (Other simulations can be carried out simply by changing the starting seed in the code below and modifying various parameters as desired.)
This simulated experiment measured absorbance at concentrations of $1$ down to $1/32$. The vertical spreads in values apparent in the scatterplot show the effects of (a) shot noise in the transmission measurements and (b) shot noise in the initial transmission measurement at zero concentration. (Notice how this actually creates some negative absorbance values.) Although the resulting errors are not going to have exactly the same distributions at each concentration, the roughly equal spreads are empirical evidence that the distributions are close enough to being the same that we needn't worry about that. In other words, there is no need to weight the absorbances according to the concentrations.
The red diagonal line has been estimated from all 50 simulations. It has a slope of $\hat{\kappa}=2.13$, which differs slightly from the physically correct slope of $2$ that was used in the simulations. This deviation is so large because I assumed there was very little radiation to measure; the maximum photon count was only $1000$. In practice, maximum counts could be many orders of magnitude greater than this, leading to highly precise slope estimates--but then we would not learn much from this figure!
The histogram of residuals does not look good: it is skewed to the right. This indicates some kind of trouble. That trouble does not come from asymmetry in the residuals at each concentration; rather, it comes from a lack of fit. That is evident in the boxplots at the right: although the first five of them line up almost horizontally, the last one--at the highest concentration--clearly differs in location (it is too high) and scale (it is too long). This results from a nonlinear response I built into the simulation. Although the nonlinearity is present throughout the full range of concentrations, it has an appreciable effect only at the very highest concentrations. This is more or less what would happen in the laboratory, too. However, with only one calibration run available we could not draw such boxplots. Consider analyzing multiple independent runs if nonlinearity might be a problem.
The simulation was performed in R. The calculations with actual data, though, are simple to conduct by hand or with a spreadsheet: just make sure to check the residuals for nonlinearity.
#
# Simulate instrument responses:
# `concentration` is an array of concentrations to use.
# `kappa` is the Beer-Lambert law coefficient.
# `n.0` is the largest expected photon count (at 0 concentration).
# `start` is a tiny positive value used to avoid logs of zero.
# `beta` is the amount of nonlinearity (it is a quadratic perturbation
# of the Beer-Lambert law).
# The return value is a parallel array of measured absorbances; it is subject
# to random fluctuations.
#
observe <- function(concentration, kappa=1, n.0=10^3, start=1/6, beta=0.2) {
transmission <- exp(-kappa * concentration - beta * concentration^2)
transmission.observed <- start + rpois(length(transmission), transmission * n.0)
absorbance <- -log(transmission.observed / rpois(1, n.0))
return(absorbance)
}
#
# Perform a set of simulations.
#
concentration <- 2^(-(0:5)) # Concentrations to use
n.iter <- 50 # Number of iterations
set.seed(17) # Make the results reproducible
absorbance <- replicate(n.iter, observe(concentration, kappa=2))
#
# Put the results into a data frame for further analysis.
#
a.df <- data.frame(absorbance = as.vector(absorbance))
a.df$concentration <- concentration # ($ interferes with TeX processing on this site)
#
# Create the figures.
#
par(mfrow=c(1,3))
#
# Set up a region for the scatterplot.
#
plot(c(min(concentration), max(concentration)),
c(min(absorbance), max(absorbance)), type="n",
xlab="Concentration", ylab="Absorbance",
main=paste("Scatterplot of", n.iter, "iterations"))
#
# Make the scatterplot.
#
invisible(apply(absorbance, 2,
function(a) points(concentration, a, col="#40404080")))
slope <- mean(a.df$absorbance / a.df$concentration)
abline(c(0, slope), col="Red")
#
# Show the residuals.
#
a.df$residuals <- a.df$absorbance - slope * a.df$concentration # $
hist(a.df$residuals, main="Histogram of residuals", xlab="Absorbance Difference") # $
#
# Study the residual distribution vs. concentration.
#
boxplot(a.df$residuals ~ a.df$concentration, main="Residual distributions",
xlab="Concentration") | Linear regression on a sample spanning many orders of magnitude
Let the physics (of the experiment and the measuring apparatus) guide you.
Ultimately, absorption is determined by measuring amounts of radiation passing through the medium and those measurements come |
34,055 | Linear regression on a sample spanning many orders of magnitude | Neither of your fitted models can be correct for your original equation, and your original equation cannot be a correct model for the random variables you observe.
Let's address some issues one at a time.
1) Your original equation is $A=kC$, but of course data is not observed at population values (otherwise you'd only need one $x$ and $y$ value, since $k=y/x$. Clearly this is not the right model for the data or you wouldn't be trying to fit regressions. We'll see how to rewrite it shortly.
2) If both variables are observed with error, you need more specialized techniques than simple linear regression models.
3) If $C$ is observed with no error (or very low error relative to $A$), you presumably mean a model something like say $E(A|C) = kC$.
The question then is "how to model the variation about the mean" - we need a distribution for $A$ at each $C$, or at least some information relating to the distribution.
a) As you suggested, you could fit a linear model directly to the data on the original scale:
$$\text{E}(A|C)=kC$$
This might suitable if the variability is near constant on this scale ($\text{Var}(A|C)$ near-constant).
Note that this model, based on your population model, has no intercept term; it goes through the origin.
Alternatively, if you have some other model for the variation about the line, such as $\text{Var}(A|C)\propto C^p$, then you could fit a weighted regression.
b) As you mention, another possible model may be fitted on the log-scale:
$$\text{E}(\log_{10}A|\log_{10}C)=\log_{10}k+\log_{10}C$$
This might suitable if the variation is near constant on the log scale ($\text{Var}(\log_{10}A|\log_{10}C)$ near-constant) ... which you'd tend to see if the variance-power in (a) were 2 or close to 2.
Note that this model has an intercept, but has a slope coefficient of 1. A way to fit this model is to fit:
$$\text{E}(\log_{10}A|\log_{10}C)-\log_{10}C=\log_{10}k$$
(That said, you may want to check a more general model that your original one, such as considering a non-unit slope in (b) for example.
The fits in (a) and (b) weight the data differently (though with $p=2$ in (a) the results will be quite close), so they won't give identical answers. On your data they differ by about 26%, which illustrates that for such a sample the choice is quite important.
If you don't have any prior knowledge to guide the choice, residual analysis might be a way to arrive at a model (especially if you have another data set on which you can base that choice); alternatively, you could make $p$ a parameter of a larger model.
(As it happens, a little residual analysis suggests to me there may be potential problems with both (a) with constant variance and with the model in (b); neither model, nor even, perhaps, the more general models (a)-with0intercept and (b)-with-non-unit slope are necessarily suitable (there's a suggestion of curvature about the line). One of the concerns is leverage in (a), which stems from the 'many orders of magnitude')
4) Note that there are numerous other models that might be fitted.
For example, consider $E(A^q|C) = k^qC^q$ for some specified constant $q$ (the log-model corresponds to $q=0$). | Linear regression on a sample spanning many orders of magnitude | Neither of your fitted models can be correct for your original equation, and your original equation cannot be a correct model for the random variables you observe.
Let's address some issues one at a t | Linear regression on a sample spanning many orders of magnitude
Neither of your fitted models can be correct for your original equation, and your original equation cannot be a correct model for the random variables you observe.
Let's address some issues one at a time.
1) Your original equation is $A=kC$, but of course data is not observed at population values (otherwise you'd only need one $x$ and $y$ value, since $k=y/x$. Clearly this is not the right model for the data or you wouldn't be trying to fit regressions. We'll see how to rewrite it shortly.
2) If both variables are observed with error, you need more specialized techniques than simple linear regression models.
3) If $C$ is observed with no error (or very low error relative to $A$), you presumably mean a model something like say $E(A|C) = kC$.
The question then is "how to model the variation about the mean" - we need a distribution for $A$ at each $C$, or at least some information relating to the distribution.
a) As you suggested, you could fit a linear model directly to the data on the original scale:
$$\text{E}(A|C)=kC$$
This might suitable if the variability is near constant on this scale ($\text{Var}(A|C)$ near-constant).
Note that this model, based on your population model, has no intercept term; it goes through the origin.
Alternatively, if you have some other model for the variation about the line, such as $\text{Var}(A|C)\propto C^p$, then you could fit a weighted regression.
b) As you mention, another possible model may be fitted on the log-scale:
$$\text{E}(\log_{10}A|\log_{10}C)=\log_{10}k+\log_{10}C$$
This might suitable if the variation is near constant on the log scale ($\text{Var}(\log_{10}A|\log_{10}C)$ near-constant) ... which you'd tend to see if the variance-power in (a) were 2 or close to 2.
Note that this model has an intercept, but has a slope coefficient of 1. A way to fit this model is to fit:
$$\text{E}(\log_{10}A|\log_{10}C)-\log_{10}C=\log_{10}k$$
(That said, you may want to check a more general model that your original one, such as considering a non-unit slope in (b) for example.
The fits in (a) and (b) weight the data differently (though with $p=2$ in (a) the results will be quite close), so they won't give identical answers. On your data they differ by about 26%, which illustrates that for such a sample the choice is quite important.
If you don't have any prior knowledge to guide the choice, residual analysis might be a way to arrive at a model (especially if you have another data set on which you can base that choice); alternatively, you could make $p$ a parameter of a larger model.
(As it happens, a little residual analysis suggests to me there may be potential problems with both (a) with constant variance and with the model in (b); neither model, nor even, perhaps, the more general models (a)-with0intercept and (b)-with-non-unit slope are necessarily suitable (there's a suggestion of curvature about the line). One of the concerns is leverage in (a), which stems from the 'many orders of magnitude')
4) Note that there are numerous other models that might be fitted.
For example, consider $E(A^q|C) = k^qC^q$ for some specified constant $q$ (the log-model corresponds to $q=0$). | Linear regression on a sample spanning many orders of magnitude
Neither of your fitted models can be correct for your original equation, and your original equation cannot be a correct model for the random variables you observe.
Let's address some issues one at a t |
34,056 | Is there a simple method to calculate the minimum number of datalines needed for a machine learning algorithm with x variables? | in addition to Dikran Marsupial's excellent advise:
While there is no hard minimum requirement for the training data you need,
There is a rule of thumb that says that with 5* cases per variate in each class you can usually have a stable linear classifier. Now, stable doesn't guarantee good, but unstable will always be bad. Note however, that in many disciplines with very wide data, good models are trained with far less samples.
* I've also seen 3 and 6, but that's the same order of magnitude.
you can calculate minimum sample sizes required for testing: usually, building a good model is not sufficient. You also need to show that the model performs well. For relatively easy problems for which, however, only small sample sizes are available, this can actually be the harder part of the problem.
Not sure whether it applies to your scenario, though: you may be able to generate enough independent rows that this is not the concern.
Note also that classification performance measures that are proportions of test cases (overall accuracy, sensitivity, specificity, predictive values, precision, recall, etc.) are subject to very high variance and thus need large test sample sizes. This can also cause considerable difficulties with the learning curve (see the paper below for illustrations). Frank Harrell will tell you that better measures, e.g. Brier's score, should be used (see e.g. the discussion linked below). However, depending on your field, you may have to report the proportions.
Here's a paper we wrote about this: Beleites, C. and Neugebauer, U. and Bocklitz, T. and Krafft, C. and Popp, J.: Sample size planning for classification models. Anal Chim Acta, 2013, 760, 25-33.
DOI: 10.1016/j.aca.2012.11.007
accepted manuscript on arXiv: 1211.1323
See also: How large a training set is needed? | Is there a simple method to calculate the minimum number of datalines needed for a machine learning | in addition to Dikran Marsupial's excellent advise:
While there is no hard minimum requirement for the training data you need,
There is a rule of thumb that says that with 5* cases per variate in eac | Is there a simple method to calculate the minimum number of datalines needed for a machine learning algorithm with x variables?
in addition to Dikran Marsupial's excellent advise:
While there is no hard minimum requirement for the training data you need,
There is a rule of thumb that says that with 5* cases per variate in each class you can usually have a stable linear classifier. Now, stable doesn't guarantee good, but unstable will always be bad. Note however, that in many disciplines with very wide data, good models are trained with far less samples.
* I've also seen 3 and 6, but that's the same order of magnitude.
you can calculate minimum sample sizes required for testing: usually, building a good model is not sufficient. You also need to show that the model performs well. For relatively easy problems for which, however, only small sample sizes are available, this can actually be the harder part of the problem.
Not sure whether it applies to your scenario, though: you may be able to generate enough independent rows that this is not the concern.
Note also that classification performance measures that are proportions of test cases (overall accuracy, sensitivity, specificity, predictive values, precision, recall, etc.) are subject to very high variance and thus need large test sample sizes. This can also cause considerable difficulties with the learning curve (see the paper below for illustrations). Frank Harrell will tell you that better measures, e.g. Brier's score, should be used (see e.g. the discussion linked below). However, depending on your field, you may have to report the proportions.
Here's a paper we wrote about this: Beleites, C. and Neugebauer, U. and Bocklitz, T. and Krafft, C. and Popp, J.: Sample size planning for classification models. Anal Chim Acta, 2013, 760, 25-33.
DOI: 10.1016/j.aca.2012.11.007
accepted manuscript on arXiv: 1211.1323
See also: How large a training set is needed? | Is there a simple method to calculate the minimum number of datalines needed for a machine learning
in addition to Dikran Marsupial's excellent advise:
While there is no hard minimum requirement for the training data you need,
There is a rule of thumb that says that with 5* cases per variate in eac |
34,057 | Is there a simple method to calculate the minimum number of datalines needed for a machine learning algorithm with x variables? | When you choose the sample number for training, you may consider the trade-off between bias and variance.
One purpose (among many) of training is to estimate the out-of-sample error Eout given the obtained in-sample error Ein. There is such generalization in VC analysis: Eout <= Ein + Omega (also known as Hoeding inequality written in a probability format). So people tend to experimentally observe the changes of Eout and Ein. What they found is: as the sample number increases, the Eout would finally converged to Ein with a simple model; while Eout also converges from a huge value to a relatively constant value as well with a complex model, but still larger enough than Ein. Such VC analysis curve can be equivalently viewed as a bias-variance trade-off curve which indicates the variance decreases as the sample number increases. You can refer this slide for more details. On the other hand, the target complexity also influences on the generalization error. This slide shows a overfit measure as the number of data points changes. You can observe that if the target is complicated, increasing the sample number may not necessarily reduce the overfitting any more (the red region in the figures), yet it is still effective in reducing the overfitting if the target is not complicated.
As analyzed above, the training sample size is usually related to model complexity (number of variates) and target complexity, whereas test sample size can be estimated based on a required accuracy performance. Like @Dikran suggested, you need to try the effects by observing your own learning curve. | Is there a simple method to calculate the minimum number of datalines needed for a machine learning | When you choose the sample number for training, you may consider the trade-off between bias and variance.
One purpose (among many) of training is to estimate the out-of-sample error Eout given the obt | Is there a simple method to calculate the minimum number of datalines needed for a machine learning algorithm with x variables?
When you choose the sample number for training, you may consider the trade-off between bias and variance.
One purpose (among many) of training is to estimate the out-of-sample error Eout given the obtained in-sample error Ein. There is such generalization in VC analysis: Eout <= Ein + Omega (also known as Hoeding inequality written in a probability format). So people tend to experimentally observe the changes of Eout and Ein. What they found is: as the sample number increases, the Eout would finally converged to Ein with a simple model; while Eout also converges from a huge value to a relatively constant value as well with a complex model, but still larger enough than Ein. Such VC analysis curve can be equivalently viewed as a bias-variance trade-off curve which indicates the variance decreases as the sample number increases. You can refer this slide for more details. On the other hand, the target complexity also influences on the generalization error. This slide shows a overfit measure as the number of data points changes. You can observe that if the target is complicated, increasing the sample number may not necessarily reduce the overfitting any more (the red region in the figures), yet it is still effective in reducing the overfitting if the target is not complicated.
As analyzed above, the training sample size is usually related to model complexity (number of variates) and target complexity, whereas test sample size can be estimated based on a required accuracy performance. Like @Dikran suggested, you need to try the effects by observing your own learning curve. | Is there a simple method to calculate the minimum number of datalines needed for a machine learning
When you choose the sample number for training, you may consider the trade-off between bias and variance.
One purpose (among many) of training is to estimate the out-of-sample error Eout given the obt |
34,058 | Is there a simple method to calculate the minimum number of datalines needed for a machine learning algorithm with x variables? | There are no useful rules of thumb for this as the number of patterns required strongly depends on the nature of the problem, in particular the more complex the form of underlying relationship between the variables, the more data you will need to estimate it, the more noise corrupting the data, the more data you are likely to need to average out the effects of the noise. There is also a fairly strong dependence on the nature of the machine learning algorithm as well, if the technique is well suited to the problem you will need less data, if it is not well suited, you will need more data.
At the end of the day, there is no minimum amount of data that you need to perform inference, the more data you have the more confident you can be of your inference, but it is generally a smooth relationship.
I would advise generating a learning curve - a plot of the test set error as a function of the number of training patterns. This will give you a good indication of the amount of data you will need to train your model, and whether you have already reached the point of diminishing returns. | Is there a simple method to calculate the minimum number of datalines needed for a machine learning | There are no useful rules of thumb for this as the number of patterns required strongly depends on the nature of the problem, in particular the more complex the form of underlying relationship between | Is there a simple method to calculate the minimum number of datalines needed for a machine learning algorithm with x variables?
There are no useful rules of thumb for this as the number of patterns required strongly depends on the nature of the problem, in particular the more complex the form of underlying relationship between the variables, the more data you will need to estimate it, the more noise corrupting the data, the more data you are likely to need to average out the effects of the noise. There is also a fairly strong dependence on the nature of the machine learning algorithm as well, if the technique is well suited to the problem you will need less data, if it is not well suited, you will need more data.
At the end of the day, there is no minimum amount of data that you need to perform inference, the more data you have the more confident you can be of your inference, but it is generally a smooth relationship.
I would advise generating a learning curve - a plot of the test set error as a function of the number of training patterns. This will give you a good indication of the amount of data you will need to train your model, and whether you have already reached the point of diminishing returns. | Is there a simple method to calculate the minimum number of datalines needed for a machine learning
There are no useful rules of thumb for this as the number of patterns required strongly depends on the nature of the problem, in particular the more complex the form of underlying relationship between |
34,059 | Covariance matrix of least squares estimator $\hat{\beta}$ [duplicate] | A good reference is Greene, Econometric Analysis. You should be able to pick up an older version (sixth edition or before) online for relatively cheap. Seventh is not noticeably better than sixth. I am changing your notation $Cov(\hat{\beta})$ to
$V(\hat{\beta}_{\textrm{OLS}})$, but I mean the same thing by it.
Here is the proof:
If
$Y=Z\beta+\epsilon$
$E\left\{\epsilon|Z \right\}=0$
$V\left(\epsilon|Z \right)=\sigma^2I$
The OLS estimator exists and is unique (i.e. $Z'Z$ invertible)
then the OLS estimator is unbiased for $\beta$ and
$V\left(\hat{\beta}_{\textrm{OLS}}|Z \right)=\sigma^2(Z'Z)^{-1}$.
Proof:
Using the definition of the OLS estimator and then substituting in using 1:
\begin{align}
\hat{\beta}_{\textrm{OLS}} &= \left( Z'Z\right)^{-1}Z'Y\\
&= \left( Z'Z\right)^{-1}Z'\left( Z\beta+\epsilon \right)\\
&= \left( Z'Z\right)^{-1}Z'Z\beta
+ \left( Z'Z\right)^{-1}Z'\epsilon\\
&= \beta + \left( Z'Z\right)^{-1}Z'\epsilon
\end{align}
Taking expectations of both sides conditional on $Z$ gives you that the OLS estimator is unbiased. Taking variances on both sides conditional on $Z$ gives you:
\begin{align}
V\left( \hat{\beta}_{\textrm{OLS}} | Z \right)
&= V\left( \beta + \left( Z'Z\right)^{-1}Z'\epsilon | Z \right)\\
&= V\left(\left( Z'Z\right)^{-1}Z'\epsilon | Z \right) \\
&= \left( Z'Z\right)^{-1}Z'V\left(\epsilon | Z \right) Z \left( Z'Z\right)^{-1} \\
&= \left( Z'Z\right)^{-1}Z'\sigma^2I Z \left( Z'Z\right)^{-1} \\
&= \sigma^2\left( Z'Z\right)^{-1}Z'Z \left( Z'Z\right)^{-1} \\
&= \sigma^2\left( Z'Z\right)^{-1}
\end{align}
QED
This does not quite give you what you asked for, since the variance is conditional on $Z$ rather than unconditional. If you want the variance to be unconditional, you have to additionally assume that $Z$ is fixed, so that the conditional variance becomes just an unconditional variance. On the other hand, this is the right variance conditional on the dataset you used to estimate $\beta$ with OLS, and inference based on this variance gives (asymptotically, if you don't assume $\epsilon$ normal) you correctly-sized hypothesis tests and confidence intervals. | Covariance matrix of least squares estimator $\hat{\beta}$ [duplicate] | A good reference is Greene, Econometric Analysis. You should be able to pick up an older version (sixth edition or before) online for relatively cheap. Seventh is not noticeably better than sixth. | Covariance matrix of least squares estimator $\hat{\beta}$ [duplicate]
A good reference is Greene, Econometric Analysis. You should be able to pick up an older version (sixth edition or before) online for relatively cheap. Seventh is not noticeably better than sixth. I am changing your notation $Cov(\hat{\beta})$ to
$V(\hat{\beta}_{\textrm{OLS}})$, but I mean the same thing by it.
Here is the proof:
If
$Y=Z\beta+\epsilon$
$E\left\{\epsilon|Z \right\}=0$
$V\left(\epsilon|Z \right)=\sigma^2I$
The OLS estimator exists and is unique (i.e. $Z'Z$ invertible)
then the OLS estimator is unbiased for $\beta$ and
$V\left(\hat{\beta}_{\textrm{OLS}}|Z \right)=\sigma^2(Z'Z)^{-1}$.
Proof:
Using the definition of the OLS estimator and then substituting in using 1:
\begin{align}
\hat{\beta}_{\textrm{OLS}} &= \left( Z'Z\right)^{-1}Z'Y\\
&= \left( Z'Z\right)^{-1}Z'\left( Z\beta+\epsilon \right)\\
&= \left( Z'Z\right)^{-1}Z'Z\beta
+ \left( Z'Z\right)^{-1}Z'\epsilon\\
&= \beta + \left( Z'Z\right)^{-1}Z'\epsilon
\end{align}
Taking expectations of both sides conditional on $Z$ gives you that the OLS estimator is unbiased. Taking variances on both sides conditional on $Z$ gives you:
\begin{align}
V\left( \hat{\beta}_{\textrm{OLS}} | Z \right)
&= V\left( \beta + \left( Z'Z\right)^{-1}Z'\epsilon | Z \right)\\
&= V\left(\left( Z'Z\right)^{-1}Z'\epsilon | Z \right) \\
&= \left( Z'Z\right)^{-1}Z'V\left(\epsilon | Z \right) Z \left( Z'Z\right)^{-1} \\
&= \left( Z'Z\right)^{-1}Z'\sigma^2I Z \left( Z'Z\right)^{-1} \\
&= \sigma^2\left( Z'Z\right)^{-1}Z'Z \left( Z'Z\right)^{-1} \\
&= \sigma^2\left( Z'Z\right)^{-1}
\end{align}
QED
This does not quite give you what you asked for, since the variance is conditional on $Z$ rather than unconditional. If you want the variance to be unconditional, you have to additionally assume that $Z$ is fixed, so that the conditional variance becomes just an unconditional variance. On the other hand, this is the right variance conditional on the dataset you used to estimate $\beta$ with OLS, and inference based on this variance gives (asymptotically, if you don't assume $\epsilon$ normal) you correctly-sized hypothesis tests and confidence intervals. | Covariance matrix of least squares estimator $\hat{\beta}$ [duplicate]
A good reference is Greene, Econometric Analysis. You should be able to pick up an older version (sixth edition or before) online for relatively cheap. Seventh is not noticeably better than sixth. |
34,060 | Covariance matrix of least squares estimator $\hat{\beta}$ [duplicate] | This is the expression for the conditional variance-covariance matrix of the estimator. For the model $$Y=Z\beta + U, \; E(U\mid Z) =0,\; E(UU'\mid Z) = \sigma^2I$$
we have
$$\operatorname {Cov}(\hat\beta \mid Z)=\operatorname {Cov} \left[(Z'Z)^{-1}Z'y\mid Z\right]$$
$$=\operatorname {Cov} \left[(Z'Z)^{-1}Z'(Z\beta +U)\mid Z\right] = \operatorname {Cov} \left[\beta +(Z'Z)^{-1}Z'U)\mid Z\right] = \operatorname {Cov} \left[(Z'Z)^{-1}Z'U)\mid Z\right] $$
Since $\beta$ is treated as a constant in the frequentist approach. Now
$$\operatorname {Cov} \left[(Z'Z)^{-1}Z'U)\mid Z\right] = E\Big\{\left[(Z'Z)^{-1}Z'U\right]\left[(Z'Z)^{-1}Z'U)\right]'\mid Z\Big\} - E\left[(Z'Z)^{-1}Z'U)\mid Z\right]E\left[(Z'Z)^{-1}Z'U)\mid Z\right]'$$
Since
$$E\left[(Z'Z)^{-1}Z'U)\mid Z\right]' = (Z'Z)^{-1}Z'E\left[U\mid Z\right]' = 0$$
we are left with
$$\operatorname {Cov} \left[(Z'Z)^{-1}Z'U)\mid Z\right] = E\Big\{\left[(Z'Z)^{-1}Z'U\right]\left[(Z'Z)^{-1}Z'U)\right]'\mid Z\Big\} $$
$$= (Z'Z)^{-1}Z'E(UU'\mid Z)Z(Z'Z)^{-1}= (Z'Z)^{-1}Z'\sigma^2IZ(Z'Z)^{-1} $$
$$=\sigma^2(Z'Z)^{-1} $$ | Covariance matrix of least squares estimator $\hat{\beta}$ [duplicate] | This is the expression for the conditional variance-covariance matrix of the estimator. For the model $$Y=Z\beta + U, \; E(U\mid Z) =0,\; E(UU'\mid Z) = \sigma^2I$$
we have
$$\operatorname {Cov}(\ha | Covariance matrix of least squares estimator $\hat{\beta}$ [duplicate]
This is the expression for the conditional variance-covariance matrix of the estimator. For the model $$Y=Z\beta + U, \; E(U\mid Z) =0,\; E(UU'\mid Z) = \sigma^2I$$
we have
$$\operatorname {Cov}(\hat\beta \mid Z)=\operatorname {Cov} \left[(Z'Z)^{-1}Z'y\mid Z\right]$$
$$=\operatorname {Cov} \left[(Z'Z)^{-1}Z'(Z\beta +U)\mid Z\right] = \operatorname {Cov} \left[\beta +(Z'Z)^{-1}Z'U)\mid Z\right] = \operatorname {Cov} \left[(Z'Z)^{-1}Z'U)\mid Z\right] $$
Since $\beta$ is treated as a constant in the frequentist approach. Now
$$\operatorname {Cov} \left[(Z'Z)^{-1}Z'U)\mid Z\right] = E\Big\{\left[(Z'Z)^{-1}Z'U\right]\left[(Z'Z)^{-1}Z'U)\right]'\mid Z\Big\} - E\left[(Z'Z)^{-1}Z'U)\mid Z\right]E\left[(Z'Z)^{-1}Z'U)\mid Z\right]'$$
Since
$$E\left[(Z'Z)^{-1}Z'U)\mid Z\right]' = (Z'Z)^{-1}Z'E\left[U\mid Z\right]' = 0$$
we are left with
$$\operatorname {Cov} \left[(Z'Z)^{-1}Z'U)\mid Z\right] = E\Big\{\left[(Z'Z)^{-1}Z'U\right]\left[(Z'Z)^{-1}Z'U)\right]'\mid Z\Big\} $$
$$= (Z'Z)^{-1}Z'E(UU'\mid Z)Z(Z'Z)^{-1}= (Z'Z)^{-1}Z'\sigma^2IZ(Z'Z)^{-1} $$
$$=\sigma^2(Z'Z)^{-1} $$ | Covariance matrix of least squares estimator $\hat{\beta}$ [duplicate]
This is the expression for the conditional variance-covariance matrix of the estimator. For the model $$Y=Z\beta + U, \; E(U\mid Z) =0,\; E(UU'\mid Z) = \sigma^2I$$
we have
$$\operatorname {Cov}(\ha |
34,061 | How to perform unsupervised Random Forest classification using Breiman's code? | Given that your model exhibits good accuracy you can just use it to predict the class labels of records in the unlabeled dataset. However, you cannot evaluate the performances on unlabeled data.
Be careful that you should assess the quality of your model on the labeled data by cross-validation. It is not enough to check the training error rate.
If your model is not accurate enough you might think about semi-supervised learning. The unlabeled data is used in order to improve the quality of your model via inductive learning. The accuracy should always be computed by cross-validation on your labeled data.
Have a look at [ Crimisini et al. Decision Forests: A Unified Framework
for Classification, Regression, Density Estimation, Manifold Learning and
Semi-Supervised Learning ] Chapter 7 about semi-supervised learning and 7.4 about induction with semi-supervised learning. | How to perform unsupervised Random Forest classification using Breiman's code? | Given that your model exhibits good accuracy you can just use it to predict the class labels of records in the unlabeled dataset. However, you cannot evaluate the performances on unlabeled data.
Be c | How to perform unsupervised Random Forest classification using Breiman's code?
Given that your model exhibits good accuracy you can just use it to predict the class labels of records in the unlabeled dataset. However, you cannot evaluate the performances on unlabeled data.
Be careful that you should assess the quality of your model on the labeled data by cross-validation. It is not enough to check the training error rate.
If your model is not accurate enough you might think about semi-supervised learning. The unlabeled data is used in order to improve the quality of your model via inductive learning. The accuracy should always be computed by cross-validation on your labeled data.
Have a look at [ Crimisini et al. Decision Forests: A Unified Framework
for Classification, Regression, Density Estimation, Manifold Learning and
Semi-Supervised Learning ] Chapter 7 about semi-supervised learning and 7.4 about induction with semi-supervised learning. | How to perform unsupervised Random Forest classification using Breiman's code?
Given that your model exhibits good accuracy you can just use it to predict the class labels of records in the unlabeled dataset. However, you cannot evaluate the performances on unlabeled data.
Be c |
34,062 | How to perform unsupervised Random Forest classification using Breiman's code? | I doubt that unsupervised will work better but it could be a cool exercise to try out. Unsupervised learning with random forest is done by constructing a joint distribution based on your independent variables that roughly describes your data. Then simulate a certain number of observations using this distribution. For example if you have 1000 observations you could simulate 1000 more. Then you label them, e.g. 1:= real observation, 0:=simulated observation. After this, you run a usual random forest classifier trying to distinguish the real observations from the simulated ones. Note that you must have the calculate the proximity option turned on. The real useful output is exactly this, a description of proximity between your observations based on what Random Forest does when trying to assign these labels. You now have a description of how "close" or "similar" your observations are from each other and you could even cluster them based on many techniques. A straightforward one would be to select thresholds for these "distances". I mean stick together observations that are closer than a certain threshold. Another easy option is to do hierarchical clustering but using this particular distance matrix. If you can work with R, most hierarchical clustering packages allow you to feed the functions custom distance matrices. You then select a cutoff point, you may visualize it as a dendrogram and so on and so forth.
This used to be a very good tutorial on Random Forest clustering and they shared some useful R functions which they wrote for this purpose but the link seems to be dead now. Maybe it will come back up later. They also wrote a very neat random glm R package (which is analogous to random forest but based on duh...glms) if you want to check that out. You could always write to the authors and ask for the material for Random Forest classification which used to be available on the dead link. I have the R code but it's too large to paste here, I can send it to you if you send me a private message. | How to perform unsupervised Random Forest classification using Breiman's code? | I doubt that unsupervised will work better but it could be a cool exercise to try out. Unsupervised learning with random forest is done by constructing a joint distribution based on your independent v | How to perform unsupervised Random Forest classification using Breiman's code?
I doubt that unsupervised will work better but it could be a cool exercise to try out. Unsupervised learning with random forest is done by constructing a joint distribution based on your independent variables that roughly describes your data. Then simulate a certain number of observations using this distribution. For example if you have 1000 observations you could simulate 1000 more. Then you label them, e.g. 1:= real observation, 0:=simulated observation. After this, you run a usual random forest classifier trying to distinguish the real observations from the simulated ones. Note that you must have the calculate the proximity option turned on. The real useful output is exactly this, a description of proximity between your observations based on what Random Forest does when trying to assign these labels. You now have a description of how "close" or "similar" your observations are from each other and you could even cluster them based on many techniques. A straightforward one would be to select thresholds for these "distances". I mean stick together observations that are closer than a certain threshold. Another easy option is to do hierarchical clustering but using this particular distance matrix. If you can work with R, most hierarchical clustering packages allow you to feed the functions custom distance matrices. You then select a cutoff point, you may visualize it as a dendrogram and so on and so forth.
This used to be a very good tutorial on Random Forest clustering and they shared some useful R functions which they wrote for this purpose but the link seems to be dead now. Maybe it will come back up later. They also wrote a very neat random glm R package (which is analogous to random forest but based on duh...glms) if you want to check that out. You could always write to the authors and ask for the material for Random Forest classification which used to be available on the dead link. I have the R code but it's too large to paste here, I can send it to you if you send me a private message. | How to perform unsupervised Random Forest classification using Breiman's code?
I doubt that unsupervised will work better but it could be a cool exercise to try out. Unsupervised learning with random forest is done by constructing a joint distribution based on your independent v |
34,063 | How to perform unsupervised Random Forest classification using Breiman's code? | If you want to use random forest in an unsupervised setting, you'll be focusing on the distance metric obtained in what Breiman calls the "proximities". This should be an NxN matrix representing the times that the samples co-occur in terminal nodes. In R's randomForest, this is obtained via (I've never used Breiman's but I'm sure it's available):
rf = randomForest( ... )
1 - rf$proximities
Now, in an unsupervised setting, random forest has no idea how many classes there should be, so that will be your job. This can be done in a variety of ways, e.g., KNN, PAM, etc., where you choose k = 2.
As you can imagine, this is quite a bit different supervised random forest, so comparing the classification accuracy between the two procedures might not be illuminating. | How to perform unsupervised Random Forest classification using Breiman's code? | If you want to use random forest in an unsupervised setting, you'll be focusing on the distance metric obtained in what Breiman calls the "proximities". This should be an NxN matrix representing the t | How to perform unsupervised Random Forest classification using Breiman's code?
If you want to use random forest in an unsupervised setting, you'll be focusing on the distance metric obtained in what Breiman calls the "proximities". This should be an NxN matrix representing the times that the samples co-occur in terminal nodes. In R's randomForest, this is obtained via (I've never used Breiman's but I'm sure it's available):
rf = randomForest( ... )
1 - rf$proximities
Now, in an unsupervised setting, random forest has no idea how many classes there should be, so that will be your job. This can be done in a variety of ways, e.g., KNN, PAM, etc., where you choose k = 2.
As you can imagine, this is quite a bit different supervised random forest, so comparing the classification accuracy between the two procedures might not be illuminating. | How to perform unsupervised Random Forest classification using Breiman's code?
If you want to use random forest in an unsupervised setting, you'll be focusing on the distance metric obtained in what Breiman calls the "proximities". This should be an NxN matrix representing the t |
34,064 | What's the advantages of bayesian version of linear regression, logistic regression etc | Doing Bayesian regression is not an algorithm but a different approach to statistical inference. The major advantage is that, by this Bayesian processing, you recover the whole range of inferential solutions, rather than a point estimate and a confidence interval as in classical regression. (I can only recommend you to read a statistics manual to understand the difference between an algorithm and statistical inference.) | What's the advantages of bayesian version of linear regression, logistic regression etc | Doing Bayesian regression is not an algorithm but a different approach to statistical inference. The major advantage is that, by this Bayesian processing, you recover the whole range of inferential so | What's the advantages of bayesian version of linear regression, logistic regression etc
Doing Bayesian regression is not an algorithm but a different approach to statistical inference. The major advantage is that, by this Bayesian processing, you recover the whole range of inferential solutions, rather than a point estimate and a confidence interval as in classical regression. (I can only recommend you to read a statistics manual to understand the difference between an algorithm and statistical inference.) | What's the advantages of bayesian version of linear regression, logistic regression etc
Doing Bayesian regression is not an algorithm but a different approach to statistical inference. The major advantage is that, by this Bayesian processing, you recover the whole range of inferential so |
34,065 | What's the advantages of bayesian version of linear regression, logistic regression etc | The Difference
Let's do a small thought experiment with regards to regression. Let's make this simple regression:
$y = \beta_0 + \beta_1 x$
We can apply solve for the best possible weights and linear algebra states that the best weights can be found via:
$\beta^* = [\beta_0, \beta_1]^T = (X'X)^{-1} X'y$
Now imagine that we run the regression with a small dataset and with a large dataset. I think it should be safe to argue that we are much more certain that our estimate $\beta^*$ is sensible when we have 1000 points of data opposed to if we only have 10 points of data. Because $\beta^*$ is a single datapoint and not a distribution, we cannot quantify our certainty with it.
This is where and why bayesians interpret $\beta$ differently. Bayesians look at $\beta$ and think that depending on the dataset, we can be more or less certain about it. If this feels very confusing, you may appreciate this blogpost where the difference is mentioned in more detail. [Disclaimer, this blogposts are written by myself]
The Benefit
Now we will assume that we've learned our $\beta^*$ and this is a distribution instead of a mere number. You'll notice that our prediction now becomes stochastic.
$\beta_0 + \beta_1 x_i \to \hat{y_i} $
Our prediction $y_i$ is now a distribution too. This means that we have confidence bounds on our prediction. If you care about the uncertainty of your prediction, this is a very very nice thing. | What's the advantages of bayesian version of linear regression, logistic regression etc | The Difference
Let's do a small thought experiment with regards to regression. Let's make this simple regression:
$y = \beta_0 + \beta_1 x$
We can apply solve for the best possible weights and linear | What's the advantages of bayesian version of linear regression, logistic regression etc
The Difference
Let's do a small thought experiment with regards to regression. Let's make this simple regression:
$y = \beta_0 + \beta_1 x$
We can apply solve for the best possible weights and linear algebra states that the best weights can be found via:
$\beta^* = [\beta_0, \beta_1]^T = (X'X)^{-1} X'y$
Now imagine that we run the regression with a small dataset and with a large dataset. I think it should be safe to argue that we are much more certain that our estimate $\beta^*$ is sensible when we have 1000 points of data opposed to if we only have 10 points of data. Because $\beta^*$ is a single datapoint and not a distribution, we cannot quantify our certainty with it.
This is where and why bayesians interpret $\beta$ differently. Bayesians look at $\beta$ and think that depending on the dataset, we can be more or less certain about it. If this feels very confusing, you may appreciate this blogpost where the difference is mentioned in more detail. [Disclaimer, this blogposts are written by myself]
The Benefit
Now we will assume that we've learned our $\beta^*$ and this is a distribution instead of a mere number. You'll notice that our prediction now becomes stochastic.
$\beta_0 + \beta_1 x_i \to \hat{y_i} $
Our prediction $y_i$ is now a distribution too. This means that we have confidence bounds on our prediction. If you care about the uncertainty of your prediction, this is a very very nice thing. | What's the advantages of bayesian version of linear regression, logistic regression etc
The Difference
Let's do a small thought experiment with regards to regression. Let's make this simple regression:
$y = \beta_0 + \beta_1 x$
We can apply solve for the best possible weights and linear |
34,066 | What's the advantages of bayesian version of linear regression, logistic regression etc | In general, the advantage of Bayesian estimation is that you can incorporate the use of a prior, or assumed knowledge about the current state of "beliefs", and how the evidence might update those beliefs. | What's the advantages of bayesian version of linear regression, logistic regression etc | In general, the advantage of Bayesian estimation is that you can incorporate the use of a prior, or assumed knowledge about the current state of "beliefs", and how the evidence might update those beli | What's the advantages of bayesian version of linear regression, logistic regression etc
In general, the advantage of Bayesian estimation is that you can incorporate the use of a prior, or assumed knowledge about the current state of "beliefs", and how the evidence might update those beliefs. | What's the advantages of bayesian version of linear regression, logistic regression etc
In general, the advantage of Bayesian estimation is that you can incorporate the use of a prior, or assumed knowledge about the current state of "beliefs", and how the evidence might update those beli |
34,067 | What's the advantages of bayesian version of linear regression, logistic regression etc | Maximum Likelihood Estimation(MLE) of the parameters of a Non Bayesian Regression model or simply a linear regression model overfits the data, meaning the unknown value for a certain value of independent variable becomes too precise when calculated. Bayesian Linear Regression relaxes this fact, saying that there is uncertainty involved by incorporating "Predictive Distribution". | What's the advantages of bayesian version of linear regression, logistic regression etc | Maximum Likelihood Estimation(MLE) of the parameters of a Non Bayesian Regression model or simply a linear regression model overfits the data, meaning the unknown value for a certain value of independ | What's the advantages of bayesian version of linear regression, logistic regression etc
Maximum Likelihood Estimation(MLE) of the parameters of a Non Bayesian Regression model or simply a linear regression model overfits the data, meaning the unknown value for a certain value of independent variable becomes too precise when calculated. Bayesian Linear Regression relaxes this fact, saying that there is uncertainty involved by incorporating "Predictive Distribution". | What's the advantages of bayesian version of linear regression, logistic regression etc
Maximum Likelihood Estimation(MLE) of the parameters of a Non Bayesian Regression model or simply a linear regression model overfits the data, meaning the unknown value for a certain value of independ |
34,068 | Covariance of a variable and a linear combination of other variables | Is there any way of doing this without expanding out $E[(X-E[X])(aA+......)]$?
Yes. There is a property of covariance called bilinearity which is that the covariance of a linear combination
$$ {\rm cov}(aX + bY, cW + dZ) $$
(where $a,b,c,d$ are constants and $X,Y,W,Z$ are random variables) can be decomposed as
$$
ac\cdot {\rm cov}(X,W) +
ad\cdot {\rm cov}(X,Z) +
bc\cdot {\rm cov}(Y,W) +
bd\cdot {\rm cov}(Y,Z) $$
In the example you've given, you can use this property to write $\textrm{cov}(X,aA + bB + cC + dD)$ as
$$ a\ {\rm cov}(X, A) +b\ {\rm cov}(X, B) +c\ {\rm cov}(X, C) +d\ {\rm cov}(X, D) $$ | Covariance of a variable and a linear combination of other variables | Is there any way of doing this without expanding out $E[(X-E[X])(aA+......)]$?
Yes. There is a property of covariance called bilinearity which is that the covariance of a linear combination
$$ {\rm c | Covariance of a variable and a linear combination of other variables
Is there any way of doing this without expanding out $E[(X-E[X])(aA+......)]$?
Yes. There is a property of covariance called bilinearity which is that the covariance of a linear combination
$$ {\rm cov}(aX + bY, cW + dZ) $$
(where $a,b,c,d$ are constants and $X,Y,W,Z$ are random variables) can be decomposed as
$$
ac\cdot {\rm cov}(X,W) +
ad\cdot {\rm cov}(X,Z) +
bc\cdot {\rm cov}(Y,W) +
bd\cdot {\rm cov}(Y,Z) $$
In the example you've given, you can use this property to write $\textrm{cov}(X,aA + bB + cC + dD)$ as
$$ a\ {\rm cov}(X, A) +b\ {\rm cov}(X, B) +c\ {\rm cov}(X, C) +d\ {\rm cov}(X, D) $$ | Covariance of a variable and a linear combination of other variables
Is there any way of doing this without expanding out $E[(X-E[X])(aA+......)]$?
Yes. There is a property of covariance called bilinearity which is that the covariance of a linear combination
$$ {\rm c |
34,069 | How to interpret a post hoc Tukey's test? | Your discomfort is related to the theory of vagueness in philosophy. Statisticians generally believe that cases like yours are resolvable, and thus, this situation is a case of ambiguity rather than true vagueness (although this is ultimately a philosophical belief rather than something that can be proven). So, from a statistical perspective, we say that you simply have insufficient power, as standard logic (crisp sets) demands that A is either drawn from the same population as B, as C, or is drawn from it's own population. Thus, you must have at least 1 type II error. That is, if A is drawn from the same population as B, then $\text H:A=C$ should have been rejected, likewise if it's the same as C, then $\text H:A=B$ should have been rejected, and if drawn from a distinct population, then both nulls should have been rejected. In the interim, you can say that there is a difference between B and C. (Sorry to get all metaphysical.) | How to interpret a post hoc Tukey's test? | Your discomfort is related to the theory of vagueness in philosophy. Statisticians generally believe that cases like yours are resolvable, and thus, this situation is a case of ambiguity rather than | How to interpret a post hoc Tukey's test?
Your discomfort is related to the theory of vagueness in philosophy. Statisticians generally believe that cases like yours are resolvable, and thus, this situation is a case of ambiguity rather than true vagueness (although this is ultimately a philosophical belief rather than something that can be proven). So, from a statistical perspective, we say that you simply have insufficient power, as standard logic (crisp sets) demands that A is either drawn from the same population as B, as C, or is drawn from it's own population. Thus, you must have at least 1 type II error. That is, if A is drawn from the same population as B, then $\text H:A=C$ should have been rejected, likewise if it's the same as C, then $\text H:A=B$ should have been rejected, and if drawn from a distinct population, then both nulls should have been rejected. In the interim, you can say that there is a difference between B and C. (Sorry to get all metaphysical.) | How to interpret a post hoc Tukey's test?
Your discomfort is related to the theory of vagueness in philosophy. Statisticians generally believe that cases like yours are resolvable, and thus, this situation is a case of ambiguity rather than |
34,070 | How to interpret a post hoc Tukey's test? | Most statisticians would conclude that there is a significant difference between B and C in that case.
It is generally agreed that rejecting a null hypothesis is more informative than accepting it. As a student, I even had to write "the null hypothesis is not rejected" instead of "the null hypothesis is accepted". This is so because you know that the probability of being wrong while rejecting is small (typically lower than 0.05) but you have no idea of the probability of being wrong while accepting (which can be close to 1).
For the rest, I fully agree with the answer of @gung. | How to interpret a post hoc Tukey's test? | Most statisticians would conclude that there is a significant difference between B and C in that case.
It is generally agreed that rejecting a null hypothesis is more informative than accepting it. As | How to interpret a post hoc Tukey's test?
Most statisticians would conclude that there is a significant difference between B and C in that case.
It is generally agreed that rejecting a null hypothesis is more informative than accepting it. As a student, I even had to write "the null hypothesis is not rejected" instead of "the null hypothesis is accepted". This is so because you know that the probability of being wrong while rejecting is small (typically lower than 0.05) but you have no idea of the probability of being wrong while accepting (which can be close to 1).
For the rest, I fully agree with the answer of @gung. | How to interpret a post hoc Tukey's test?
Most statisticians would conclude that there is a significant difference between B and C in that case.
It is generally agreed that rejecting a null hypothesis is more informative than accepting it. As |
34,071 | How to sample from $\{1, 2, ..., K\}$ for $n$ random variables, each with different mass functions, in R? | We can do this in a couple of simple ways. The first is easy to code, easy to understand and reasonably fast. The second is a little trickier, but much more efficient for this size of problem than the first method or other approaches mentioned here.
Method 1: Quick and dirty.
To get a single observation from the probability distribution of each row, we can simply do the following.
# Q is the cumulative distribution of each row.
Q <- t(apply(P,1,cumsum))
# Get a sample with one observation from the distribution of each row.
X <- rowSums(runif(N) > Q) + 1
This produces the cumulative distribution of each row of $P$ and then samples one observation from each distribution. Notice that if we can reuse $P$ then we can calculate $Q$ once and store it for later use. However, the question needs something that works for a different $P$ at each iteration.
If you need multiple ($n$) observations from each row, then replace the last line with the following one.
# Returns an N x n matrix
X <- replicate(n, rowSums(runif(N) > Q)+1)
This is really not an extremely efficient way in general to do this, but it does take good advantage of R vectorization capabilities, which is usually the primary determinant of execution speed. It is also straightforward to understand.
Method 2: Concatenating the cdfs.
Suppose we had a function that took two vectors, the second of which was sorted in monotonically nondecreasing order and found the index in the second vector of the greatest lower bound of each element in the first. Then, we could use this function and a slick trick: Just create the cumulative sum of the cdfs of all the rows. This gives a monotonically increasing vector with elements in the range $[0,N]$.
Here is the code.
i <- 0:(N-1)
# Cumulative function of the cdfs of each row of P.
Q <- cumsum(t(P))
# Find the interval and then back adjust
findInterval(runif(N)+i, Q)-i*K+1
Notice what the last line does, it creates random variables distributed in $(0,1), (1,2), \dots, (N-1,N)$ and then calls findInterval to find the index of the greatest lower bound of each entry. So, this tells us that the first element of runif(N)+i will be found between index 1 and index $K$, the second will be found between index $K+1$ and $2K$, etc, each according to the distribution of the corresponding row of $P$. Then we need to back transform to get each of the indices back in the range $\{1,\ldots,K\}$.
Because findInterval is fast both algorithmically and implementation-wise, this method turns out to be extremely efficient.
A benchmark
On my old laptop (MacBook Pro, 2.66 GHz, 8GB RAM), I tried this with $N = 10000$ and $K = 100$ and generating 5000 samples of size $N$, exactly as suggested in the updated question, for a total of 50 million random variates.
The code for Method 1 took almost exactly 15 minutes to execute, or about 55K random variates per second. The code for Method 2 took about four and a half minutes to execute, or about 183K random variates per second.
Here is the code for the sake of reproducibility. (Note that, as indicated in a comment, $Q$ is recalculated for each of the 5000 iterations to simulate the OP's situation.)
# Benchmark code
N <- 10000
K <- 100
set.seed(17)
P <- matrix(runif(N*K),N,K)
P <- P / rowSums(P)
method.one <- function(P)
{
Q <- t(apply(P,1,cumsum))
X <- rowSums(runif(nrow(P)) > Q) + 1
}
method.two <- function(P)
{
n <- nrow(P)
i <- 0:(n-1)
Q <- cumsum(t(P))
findInterval(runif(n)+i, Q)-i*ncol(P)+1
}
Here is the output.
# Method 1: Timing
> system.time(replicate(5e3, method.one(P)))
user system elapsed
691.693 195.812 899.246
# Method 2: Timing
> system.time(replicate(5e3, method.two(P)))
user system elapsed
182.325 82.430 273.021
Postscript: By looking at the code for findInterval, we can see that it does some checks on the input to see if there are NA entries or if the second argument is not sorted. Hence, if we wanted to squeeze more performance out of this, we could create our own modified version of findInterval which strips out these checks which are unnecessary in our case. | How to sample from $\{1, 2, ..., K\}$ for $n$ random variables, each with different mass functions, | We can do this in a couple of simple ways. The first is easy to code, easy to understand and reasonably fast. The second is a little trickier, but much more efficient for this size of problem than the | How to sample from $\{1, 2, ..., K\}$ for $n$ random variables, each with different mass functions, in R?
We can do this in a couple of simple ways. The first is easy to code, easy to understand and reasonably fast. The second is a little trickier, but much more efficient for this size of problem than the first method or other approaches mentioned here.
Method 1: Quick and dirty.
To get a single observation from the probability distribution of each row, we can simply do the following.
# Q is the cumulative distribution of each row.
Q <- t(apply(P,1,cumsum))
# Get a sample with one observation from the distribution of each row.
X <- rowSums(runif(N) > Q) + 1
This produces the cumulative distribution of each row of $P$ and then samples one observation from each distribution. Notice that if we can reuse $P$ then we can calculate $Q$ once and store it for later use. However, the question needs something that works for a different $P$ at each iteration.
If you need multiple ($n$) observations from each row, then replace the last line with the following one.
# Returns an N x n matrix
X <- replicate(n, rowSums(runif(N) > Q)+1)
This is really not an extremely efficient way in general to do this, but it does take good advantage of R vectorization capabilities, which is usually the primary determinant of execution speed. It is also straightforward to understand.
Method 2: Concatenating the cdfs.
Suppose we had a function that took two vectors, the second of which was sorted in monotonically nondecreasing order and found the index in the second vector of the greatest lower bound of each element in the first. Then, we could use this function and a slick trick: Just create the cumulative sum of the cdfs of all the rows. This gives a monotonically increasing vector with elements in the range $[0,N]$.
Here is the code.
i <- 0:(N-1)
# Cumulative function of the cdfs of each row of P.
Q <- cumsum(t(P))
# Find the interval and then back adjust
findInterval(runif(N)+i, Q)-i*K+1
Notice what the last line does, it creates random variables distributed in $(0,1), (1,2), \dots, (N-1,N)$ and then calls findInterval to find the index of the greatest lower bound of each entry. So, this tells us that the first element of runif(N)+i will be found between index 1 and index $K$, the second will be found between index $K+1$ and $2K$, etc, each according to the distribution of the corresponding row of $P$. Then we need to back transform to get each of the indices back in the range $\{1,\ldots,K\}$.
Because findInterval is fast both algorithmically and implementation-wise, this method turns out to be extremely efficient.
A benchmark
On my old laptop (MacBook Pro, 2.66 GHz, 8GB RAM), I tried this with $N = 10000$ and $K = 100$ and generating 5000 samples of size $N$, exactly as suggested in the updated question, for a total of 50 million random variates.
The code for Method 1 took almost exactly 15 minutes to execute, or about 55K random variates per second. The code for Method 2 took about four and a half minutes to execute, or about 183K random variates per second.
Here is the code for the sake of reproducibility. (Note that, as indicated in a comment, $Q$ is recalculated for each of the 5000 iterations to simulate the OP's situation.)
# Benchmark code
N <- 10000
K <- 100
set.seed(17)
P <- matrix(runif(N*K),N,K)
P <- P / rowSums(P)
method.one <- function(P)
{
Q <- t(apply(P,1,cumsum))
X <- rowSums(runif(nrow(P)) > Q) + 1
}
method.two <- function(P)
{
n <- nrow(P)
i <- 0:(n-1)
Q <- cumsum(t(P))
findInterval(runif(n)+i, Q)-i*ncol(P)+1
}
Here is the output.
# Method 1: Timing
> system.time(replicate(5e3, method.one(P)))
user system elapsed
691.693 195.812 899.246
# Method 2: Timing
> system.time(replicate(5e3, method.two(P)))
user system elapsed
182.325 82.430 273.021
Postscript: By looking at the code for findInterval, we can see that it does some checks on the input to see if there are NA entries or if the second argument is not sorted. Hence, if we wanted to squeeze more performance out of this, we could create our own modified version of findInterval which strips out these checks which are unnecessary in our case. | How to sample from $\{1, 2, ..., K\}$ for $n$ random variables, each with different mass functions,
We can do this in a couple of simple ways. The first is easy to code, easy to understand and reasonably fast. The second is a little trickier, but much more efficient for this size of problem than the |
34,072 | How to sample from $\{1, 2, ..., K\}$ for $n$ random variables, each with different mass functions, in R? | A for loop may be terribly slow in R. How about this simple vectorization with sapply?
n <- 10000
k <- 200
S <- 1:k
p <- matrix(rep(1 / k, n * k), nrow = n, ncol = k)
x <- numeric(n)
x <- sapply(1:n, function(i) sample(S, 1, prob = p[i,]))
Of course, this uniform p is just for testing. | How to sample from $\{1, 2, ..., K\}$ for $n$ random variables, each with different mass functions, | A for loop may be terribly slow in R. How about this simple vectorization with sapply?
n <- 10000
k <- 200
S <- 1:k
p <- matrix(rep(1 / k, n * k), nrow = n, ncol = k)
x <- numeric(n)
x <- sapply(1:n | How to sample from $\{1, 2, ..., K\}$ for $n$ random variables, each with different mass functions, in R?
A for loop may be terribly slow in R. How about this simple vectorization with sapply?
n <- 10000
k <- 200
S <- 1:k
p <- matrix(rep(1 / k, n * k), nrow = n, ncol = k)
x <- numeric(n)
x <- sapply(1:n, function(i) sample(S, 1, prob = p[i,]))
Of course, this uniform p is just for testing. | How to sample from $\{1, 2, ..., K\}$ for $n$ random variables, each with different mass functions,
A for loop may be terribly slow in R. How about this simple vectorization with sapply?
n <- 10000
k <- 200
S <- 1:k
p <- matrix(rep(1 / k, n * k), nrow = n, ncol = k)
x <- numeric(n)
x <- sapply(1:n |
34,073 | What is the difference between simple linear model and loess model? | A VERY non-technical answer
A simple linear model fits a straight line through a set of points. The line is the best possible straight line (at least, for one sensible definition of best)
A loess model fits a complicated curve through a set of points. In some ways, it can be thought of as a complicated moving average. It is the best possible curve (at least, for one sensible definition of best) | What is the difference between simple linear model and loess model? | A VERY non-technical answer
A simple linear model fits a straight line through a set of points. The line is the best possible straight line (at least, for one sensible definition of best)
A loess mode | What is the difference between simple linear model and loess model?
A VERY non-technical answer
A simple linear model fits a straight line through a set of points. The line is the best possible straight line (at least, for one sensible definition of best)
A loess model fits a complicated curve through a set of points. In some ways, it can be thought of as a complicated moving average. It is the best possible curve (at least, for one sensible definition of best) | What is the difference between simple linear model and loess model?
A VERY non-technical answer
A simple linear model fits a straight line through a set of points. The line is the best possible straight line (at least, for one sensible definition of best)
A loess mode |
34,074 | What is the difference between simple linear model and loess model? | The loess.demo function in the TeachingDemos package for R will interactively demonstrate the ideas behind a loess fit. It will plot a set of data and the loess fit, then when you click on a point it will show the window used to fit at that point, the relative weights of the points within the window, and the "linear model" fit to that weighted data. Clicking on additional points will then update the display to show the general concept of the loess fit.
This may help explain what loess does and may help in an explanation of the difference. | What is the difference between simple linear model and loess model? | The loess.demo function in the TeachingDemos package for R will interactively demonstrate the ideas behind a loess fit. It will plot a set of data and the loess fit, then when you click on a point it | What is the difference between simple linear model and loess model?
The loess.demo function in the TeachingDemos package for R will interactively demonstrate the ideas behind a loess fit. It will plot a set of data and the loess fit, then when you click on a point it will show the window used to fit at that point, the relative weights of the points within the window, and the "linear model" fit to that weighted data. Clicking on additional points will then update the display to show the general concept of the loess fit.
This may help explain what loess does and may help in an explanation of the difference. | What is the difference between simple linear model and loess model?
The loess.demo function in the TeachingDemos package for R will interactively demonstrate the ideas behind a loess fit. It will plot a set of data and the loess fit, then when you click on a point it |
34,075 | What is the difference between simple linear model and loess model? | Here is a simple but detailed response.
A linear model fits a relationship through all of the data points. This model can be first order (another meaning of "linear") or polynomial to account for curvature, or with splines to account for different regions having a different governing model.
A LOESS fit is a locally moving weighted regression based on the original data points. What's that mean?
A LOESS fit inputs the original X and Y values, plus a set of output X values for which to compute new Y values (usually the same X values are used for both, but often fewer X values are used for fitted X-Y pairs because of the increased computation required).
For each output X value, a portion of the input data is used to compute a fit. The portion of the data, generally 25% to 100% but typically 33% or 50%, is local, meaning it is that portion of the original data closest to each particular output X value. It is a moving fit, because each output X value requires a different subset of the original data, with different weights (see next paragraph).
This subset of input data points is used to perform a weighted regression, with points closest to the output X value given greater weight. This regression is usually first order; second order or higher is possible, but require greater computation power. The Y value of this weighted regression calculated at the output X is used as the model's Y value for this X value.
The regression is recomputed at each output X value to produce a full set of output Y values. | What is the difference between simple linear model and loess model? | Here is a simple but detailed response.
A linear model fits a relationship through all of the data points. This model can be first order (another meaning of "linear") or polynomial to account for curv | What is the difference between simple linear model and loess model?
Here is a simple but detailed response.
A linear model fits a relationship through all of the data points. This model can be first order (another meaning of "linear") or polynomial to account for curvature, or with splines to account for different regions having a different governing model.
A LOESS fit is a locally moving weighted regression based on the original data points. What's that mean?
A LOESS fit inputs the original X and Y values, plus a set of output X values for which to compute new Y values (usually the same X values are used for both, but often fewer X values are used for fitted X-Y pairs because of the increased computation required).
For each output X value, a portion of the input data is used to compute a fit. The portion of the data, generally 25% to 100% but typically 33% or 50%, is local, meaning it is that portion of the original data closest to each particular output X value. It is a moving fit, because each output X value requires a different subset of the original data, with different weights (see next paragraph).
This subset of input data points is used to perform a weighted regression, with points closest to the output X value given greater weight. This regression is usually first order; second order or higher is possible, but require greater computation power. The Y value of this weighted regression calculated at the output X is used as the model's Y value for this X value.
The regression is recomputed at each output X value to produce a full set of output Y values. | What is the difference between simple linear model and loess model?
Here is a simple but detailed response.
A linear model fits a relationship through all of the data points. This model can be first order (another meaning of "linear") or polynomial to account for curv |
34,076 | Does an exact test always yield a higher P value then an approximated test? | No, the p-value from an asymptotically valid distribution is not always smaller than an exact p-value. Consider two examples from traditional "non-parametric" tests:
The Wilcoxon Rank-Sum Test for location shift (e.g, median) for two independent samples of size $n_{1}$ and $n_{2}$ calculates the test statistic as follows:
put all observed values into one large sample of size $N = n_{1} + n_{2}$
rank these values from $1, \ldots, N$
sum the ranks for the first group, call this $L_{N}^{+}$. Often, the test statistic is defined as $W = L_{N}^{+} - \frac{n_{1} (n_{1} + 1)}{2}$ (this test statistic is then identical to Mann-Whitney's U), but this doesn't matter for the distribution shape.
The exact distribution for $L_{N}^{+}$ for fixed $n_{1}$ and $n_{2}$ is found by generating all ${N \choose n_{1}}$ possible combinations of ranks for the first group, and calculating the sum in each case. The asymptotic approximation uses $z := \frac{L_{n}^{+} - n_{1} (N+1) / 2}{\sqrt{(n_{1} n_{2} (N+1)) / 12}} \sim N(0, 1)$, i.e., a standard-normal approximation of the $z$-transformed test statistic.
Similarly, the Kruskal-Wallis-H-Test for location shift (e.g., median) for $p$ independent samples uses a test statistic based on the rank-sums $R_{+j}$ in each group $j$: $H := \frac{12}{N (N+1)} \sum\limits_{j=1}^{p}{\frac{1}{n_{j}} \left(R_{+j} - n_{j} \frac{N+1}{2}\right)^{2}}$. Again, the exact distribution for H is found by generating all combinations of ranks for the groups. For 3 groups, there are ${N \choose n_{1}} {N-n_{1} \choose n_{2}}$ such combinations. The asymptotic approximation uses a $\chi^{2}_{p-1}$ distribution.
Now we can compare the distribution shapes in terms of the cumulative distribution function $F()$ for given group sizes. The (right-sided) p-value for a given value $t$ of the test-statistic equals $1-F(t)$ for the continuous distribution. In the discrete case, the p-value for $t_{m}$ (the $m$-th possible value for the test statistic) is $1-F(t_{m-1})$. The diagram shows that the exact distribution produces sometimes larger, sometimes smaller p-values, in the H-test: For $H = 5$ (the 32nd of 36 possible H-values), the exact p-value is 0.075 (sum(dKWH_08[names(dKWH_08) >= 5]) with the code below), while the approximate p-value is 0.082085 (1-pchisq(5, P-1)). For $H = 2$ (15th possible value), the exact p-value is 0.425 (sum(dKWH_08[names(dKWH_08) >= 2])), the approximate equals 0.3678794 (1-pchisq(2, P-1)).
#### Wilcoxon-Rank-Sum-Test: exact distribution
n1 <- 5 # group size 1
n2 <- 4 # group size 2
N <- n1 + n2 # total sample size
ranks <- t(combn(1:N, n1)) # all possible ranks for group 1
LnPl <- apply(ranks, 1, sum) # all possible rank sums for group 1 (Ln+)
dWRS_9 <- table(LnPl) / choose(N, n1) # exact probability function for Ln+
pWRS_9 <- cumsum(dWRS_9) # exact cumulative distribution function for Ln+
muLnPl <- (n1 * (N+1)) / 2 # normal approximation: theoretical mean
varLnPl <- (n1*n2 * (N+1)) / 12 # normal approximation: theoretical variance
#### Kruskal-Wallis-H-Test: exact distribution
P <- 3 # number of groups
Nj <- c(3, 3, 2) # group sizes
N <- sum(Nj) # total sample size
IV <- rep(1:P, Nj) # factor group membership
library(e1071) # for permutations()
permMat <- permutations(N) # all permutations of total sample
getH <- function(rankAll) { # function to calc H for one permutation
Rj <- tapply(rankAll, IV, sum)
H <- (12 / (N*(N+1))) * sum((1/Nj) * (Rj-(Nj*(N+1) / 2))^2)
}
Hscores <- apply(permMat, 1, getH) # all possible H values for given group sizes
dKWH_08 <- table(round(Hscores, 4)) / factorial(N) # exact probability function
pKWH_08 <- cumsum(dKWH_08) # exact cumulative distribution function
Note that I calculate the exact distribution for H by generating all permutations, not all combinations. This is unnecessary, and computationally much more expensive, but it's simpler to write down in the general case... Now do the plot comparing the function shapes.
dev.new(width=12, height=6.5)
par(mfrow=c(1, 2), cex.main=1.2, cex.lab=1.2)
plot(names(pWRS_9), pWRS_9, main="Wilcoxon RST, N=(5, 4): exact vs. asymptotic",
type="n", xlab="ln+", ylab="P(Ln+ <= ln+)", cex.lab=1.4)
curve(pnorm(x, mean=muLnPl, sd=sqrt(varLnPl)), lwd=2, n=200, add=TRUE)
points(names(pWRS_9), pWRS_9, pch=16, col="red")
abline(h=0.95, col="blue")
legend(x="bottomright", legend=c("exact", "asymptotic"),
pch=c(16, NA), col=c("red", "black"), lty=c(NA, 1), lwd=c(NA, 2))
plot(names(pKWH_08), pKWH_08, type="n", main="Kruskal-Wallis-H, N=(3, 3, 2):
exact vs. asymptotic", xlab="h", ylab="P(H <= h)", cex.lab=1.4)
curve(pchisq(x, P-1), lwd=2, n=200, add=TRUE)
points(names(pKWH_08), pKWH_08, pch=16, col="red")
abline(h=0.95, col="blue")
legend(x="bottomright", legend=c("exakt", "asymptotic"),
pch=c(16, NA), col=c("red", "black"), lty=c(NA, 1), lwd=c(NA, 2))
Note that these tests require that the distributions have the same shape in each group, otherwise they are not a test for location alone. | Does an exact test always yield a higher P value then an approximated test? | No, the p-value from an asymptotically valid distribution is not always smaller than an exact p-value. Consider two examples from traditional "non-parametric" tests:
The Wilcoxon Rank-Sum Test for loc | Does an exact test always yield a higher P value then an approximated test?
No, the p-value from an asymptotically valid distribution is not always smaller than an exact p-value. Consider two examples from traditional "non-parametric" tests:
The Wilcoxon Rank-Sum Test for location shift (e.g, median) for two independent samples of size $n_{1}$ and $n_{2}$ calculates the test statistic as follows:
put all observed values into one large sample of size $N = n_{1} + n_{2}$
rank these values from $1, \ldots, N$
sum the ranks for the first group, call this $L_{N}^{+}$. Often, the test statistic is defined as $W = L_{N}^{+} - \frac{n_{1} (n_{1} + 1)}{2}$ (this test statistic is then identical to Mann-Whitney's U), but this doesn't matter for the distribution shape.
The exact distribution for $L_{N}^{+}$ for fixed $n_{1}$ and $n_{2}$ is found by generating all ${N \choose n_{1}}$ possible combinations of ranks for the first group, and calculating the sum in each case. The asymptotic approximation uses $z := \frac{L_{n}^{+} - n_{1} (N+1) / 2}{\sqrt{(n_{1} n_{2} (N+1)) / 12}} \sim N(0, 1)$, i.e., a standard-normal approximation of the $z$-transformed test statistic.
Similarly, the Kruskal-Wallis-H-Test for location shift (e.g., median) for $p$ independent samples uses a test statistic based on the rank-sums $R_{+j}$ in each group $j$: $H := \frac{12}{N (N+1)} \sum\limits_{j=1}^{p}{\frac{1}{n_{j}} \left(R_{+j} - n_{j} \frac{N+1}{2}\right)^{2}}$. Again, the exact distribution for H is found by generating all combinations of ranks for the groups. For 3 groups, there are ${N \choose n_{1}} {N-n_{1} \choose n_{2}}$ such combinations. The asymptotic approximation uses a $\chi^{2}_{p-1}$ distribution.
Now we can compare the distribution shapes in terms of the cumulative distribution function $F()$ for given group sizes. The (right-sided) p-value for a given value $t$ of the test-statistic equals $1-F(t)$ for the continuous distribution. In the discrete case, the p-value for $t_{m}$ (the $m$-th possible value for the test statistic) is $1-F(t_{m-1})$. The diagram shows that the exact distribution produces sometimes larger, sometimes smaller p-values, in the H-test: For $H = 5$ (the 32nd of 36 possible H-values), the exact p-value is 0.075 (sum(dKWH_08[names(dKWH_08) >= 5]) with the code below), while the approximate p-value is 0.082085 (1-pchisq(5, P-1)). For $H = 2$ (15th possible value), the exact p-value is 0.425 (sum(dKWH_08[names(dKWH_08) >= 2])), the approximate equals 0.3678794 (1-pchisq(2, P-1)).
#### Wilcoxon-Rank-Sum-Test: exact distribution
n1 <- 5 # group size 1
n2 <- 4 # group size 2
N <- n1 + n2 # total sample size
ranks <- t(combn(1:N, n1)) # all possible ranks for group 1
LnPl <- apply(ranks, 1, sum) # all possible rank sums for group 1 (Ln+)
dWRS_9 <- table(LnPl) / choose(N, n1) # exact probability function for Ln+
pWRS_9 <- cumsum(dWRS_9) # exact cumulative distribution function for Ln+
muLnPl <- (n1 * (N+1)) / 2 # normal approximation: theoretical mean
varLnPl <- (n1*n2 * (N+1)) / 12 # normal approximation: theoretical variance
#### Kruskal-Wallis-H-Test: exact distribution
P <- 3 # number of groups
Nj <- c(3, 3, 2) # group sizes
N <- sum(Nj) # total sample size
IV <- rep(1:P, Nj) # factor group membership
library(e1071) # for permutations()
permMat <- permutations(N) # all permutations of total sample
getH <- function(rankAll) { # function to calc H for one permutation
Rj <- tapply(rankAll, IV, sum)
H <- (12 / (N*(N+1))) * sum((1/Nj) * (Rj-(Nj*(N+1) / 2))^2)
}
Hscores <- apply(permMat, 1, getH) # all possible H values for given group sizes
dKWH_08 <- table(round(Hscores, 4)) / factorial(N) # exact probability function
pKWH_08 <- cumsum(dKWH_08) # exact cumulative distribution function
Note that I calculate the exact distribution for H by generating all permutations, not all combinations. This is unnecessary, and computationally much more expensive, but it's simpler to write down in the general case... Now do the plot comparing the function shapes.
dev.new(width=12, height=6.5)
par(mfrow=c(1, 2), cex.main=1.2, cex.lab=1.2)
plot(names(pWRS_9), pWRS_9, main="Wilcoxon RST, N=(5, 4): exact vs. asymptotic",
type="n", xlab="ln+", ylab="P(Ln+ <= ln+)", cex.lab=1.4)
curve(pnorm(x, mean=muLnPl, sd=sqrt(varLnPl)), lwd=2, n=200, add=TRUE)
points(names(pWRS_9), pWRS_9, pch=16, col="red")
abline(h=0.95, col="blue")
legend(x="bottomright", legend=c("exact", "asymptotic"),
pch=c(16, NA), col=c("red", "black"), lty=c(NA, 1), lwd=c(NA, 2))
plot(names(pKWH_08), pKWH_08, type="n", main="Kruskal-Wallis-H, N=(3, 3, 2):
exact vs. asymptotic", xlab="h", ylab="P(H <= h)", cex.lab=1.4)
curve(pchisq(x, P-1), lwd=2, n=200, add=TRUE)
points(names(pKWH_08), pKWH_08, pch=16, col="red")
abline(h=0.95, col="blue")
legend(x="bottomright", legend=c("exakt", "asymptotic"),
pch=c(16, NA), col=c("red", "black"), lty=c(NA, 1), lwd=c(NA, 2))
Note that these tests require that the distributions have the same shape in each group, otherwise they are not a test for location alone. | Does an exact test always yield a higher P value then an approximated test?
No, the p-value from an asymptotically valid distribution is not always smaller than an exact p-value. Consider two examples from traditional "non-parametric" tests:
The Wilcoxon Rank-Sum Test for loc |
34,077 | Does an exact test always yield a higher P value then an approximated test? | Not always although usually. I guess it depends on the sort of the statistic, the test. I just sat and tried Pearson chi-square and Likelihood ratio chi-square on 20 through 100 cases datasets. For Pearson, I found exact significance to be smaller than asymptotic significance about 10% of the time. For LR - 0%. Below is an example frequency table and the tests, where Pearson chi-square has the exact sig. lesser than the asymptotic sig.
7 12 4
26 12 17
6 10 6
Chi-Square Tests
Value df Asymp. Sig. (2-sided) Exact Sig. (2-sided)
Pearson Chi-Square 8.756(a) 4 .068 .067
Likelihood Ratio 8.876 4 .064 .073
a 0 cells (.0%) have expected count less than 5. The minimum expected count is 5.94. | Does an exact test always yield a higher P value then an approximated test? | Not always although usually. I guess it depends on the sort of the statistic, the test. I just sat and tried Pearson chi-square and Likelihood ratio chi-square on 20 through 100 cases datasets. For Pe | Does an exact test always yield a higher P value then an approximated test?
Not always although usually. I guess it depends on the sort of the statistic, the test. I just sat and tried Pearson chi-square and Likelihood ratio chi-square on 20 through 100 cases datasets. For Pearson, I found exact significance to be smaller than asymptotic significance about 10% of the time. For LR - 0%. Below is an example frequency table and the tests, where Pearson chi-square has the exact sig. lesser than the asymptotic sig.
7 12 4
26 12 17
6 10 6
Chi-Square Tests
Value df Asymp. Sig. (2-sided) Exact Sig. (2-sided)
Pearson Chi-Square 8.756(a) 4 .068 .067
Likelihood Ratio 8.876 4 .064 .073
a 0 cells (.0%) have expected count less than 5. The minimum expected count is 5.94. | Does an exact test always yield a higher P value then an approximated test?
Not always although usually. I guess it depends on the sort of the statistic, the test. I just sat and tried Pearson chi-square and Likelihood ratio chi-square on 20 through 100 cases datasets. For Pe |
34,078 | Hypothesis testing terminology surrounding null | With most tests, it is impossible to control both types of errors. The way (nearly) all tests are set up, is like this: We check the probability of a certain outcome (test statistic) or worse, under the assumption that the null hypothesis is true. Now, we will reject this null hypothesis if that probability is very low (typically < 5%), because we do observe that outcome, and the null hypothesis makes that outcome unlikely (the underlying idea is that there is probably some other 'hypothesis' (e.g. some other value of the mean) that makes our outcome more likely).
So, if this probability is low, due to the construction, we can truly say: there is less than 5 % chance that this would happen if the null hypothesis were true, so it makes sense to reject the null hypothesis.
The problem is: what happens if that probability is (for example) 6 %? Now, we don't reject the null hypothesis, because it doesn't fall below the threshold. But on the other hand, we might test 10 similar hypotheses (10 different values of a mean), and they might all return a probability above 5 %. Clearly, it is impossible to say, then, that we 'accept' all of those 10 hypotheses, right? Otherwise, we would be stating that we accept 10 different values for the mean. The fact that we only do 1 test instead of 10, doesn't change this: just because we have an outcome that could very well happen given the null hypothesis, that value could just as well happen with other hypotheses, so we can never 'accept' the null hypothesis. Best we can do, is say that we see no reason to reject it. | Hypothesis testing terminology surrounding null | With most tests, it is impossible to control both types of errors. The way (nearly) all tests are set up, is like this: We check the probability of a certain outcome (test statistic) or worse, under t | Hypothesis testing terminology surrounding null
With most tests, it is impossible to control both types of errors. The way (nearly) all tests are set up, is like this: We check the probability of a certain outcome (test statistic) or worse, under the assumption that the null hypothesis is true. Now, we will reject this null hypothesis if that probability is very low (typically < 5%), because we do observe that outcome, and the null hypothesis makes that outcome unlikely (the underlying idea is that there is probably some other 'hypothesis' (e.g. some other value of the mean) that makes our outcome more likely).
So, if this probability is low, due to the construction, we can truly say: there is less than 5 % chance that this would happen if the null hypothesis were true, so it makes sense to reject the null hypothesis.
The problem is: what happens if that probability is (for example) 6 %? Now, we don't reject the null hypothesis, because it doesn't fall below the threshold. But on the other hand, we might test 10 similar hypotheses (10 different values of a mean), and they might all return a probability above 5 %. Clearly, it is impossible to say, then, that we 'accept' all of those 10 hypotheses, right? Otherwise, we would be stating that we accept 10 different values for the mean. The fact that we only do 1 test instead of 10, doesn't change this: just because we have an outcome that could very well happen given the null hypothesis, that value could just as well happen with other hypotheses, so we can never 'accept' the null hypothesis. Best we can do, is say that we see no reason to reject it. | Hypothesis testing terminology surrounding null
With most tests, it is impossible to control both types of errors. The way (nearly) all tests are set up, is like this: We check the probability of a certain outcome (test statistic) or worse, under t |
34,079 | Hypothesis testing terminology surrounding null | A useful article to read is:
Murdock, D, Tsai, Y-L, and Adcock, J (2008) P-Values are Random
Variables. The American Statistician. vol. 62, no. 3, 242-245.
This talks about how p-values are random variables which if the null hypothesis is true follow a uniform distribution. This means that you have the exact same chance of getting data that will result in a p-value of 0.9 as you do of a p-value of 0.1 (when the null is true). When the null is not true then the p-values near 0 are more likely than those near 1 (but in some cases not by much).
You can see this by simulation of cases under the null, cases where the null is false but there is very low power (the truth is very close to the null), and cases where the null is very far from the truth (one tool to help with this is the Pvalue.norm.sim function in the TeachingDemos package for R).
We prefer the "Do not reject" term because it better demonstrates that while the null could be true, it is also possible that it is false, we just don't have enough data to prove it. | Hypothesis testing terminology surrounding null | A useful article to read is:
Murdock, D, Tsai, Y-L, and Adcock, J (2008) P-Values are Random
Variables. The American Statistician. vol. 62, no. 3, 242-245.
This talks about how p-values are random | Hypothesis testing terminology surrounding null
A useful article to read is:
Murdock, D, Tsai, Y-L, and Adcock, J (2008) P-Values are Random
Variables. The American Statistician. vol. 62, no. 3, 242-245.
This talks about how p-values are random variables which if the null hypothesis is true follow a uniform distribution. This means that you have the exact same chance of getting data that will result in a p-value of 0.9 as you do of a p-value of 0.1 (when the null is true). When the null is not true then the p-values near 0 are more likely than those near 1 (but in some cases not by much).
You can see this by simulation of cases under the null, cases where the null is false but there is very low power (the truth is very close to the null), and cases where the null is very far from the truth (one tool to help with this is the Pvalue.norm.sim function in the TeachingDemos package for R).
We prefer the "Do not reject" term because it better demonstrates that while the null could be true, it is also possible that it is false, we just don't have enough data to prove it. | Hypothesis testing terminology surrounding null
A useful article to read is:
Murdock, D, Tsai, Y-L, and Adcock, J (2008) P-Values are Random
Variables. The American Statistician. vol. 62, no. 3, 242-245.
This talks about how p-values are random |
34,080 | Hypothesis testing terminology surrounding null | In many circumstances neither is really the best approach. Consider using the P value as an index of the evidence against the null and make conclusions in the realm of the real experimental hypothesis rather than in the realm of the statistical hypothesis. Usually the former is much more important. | Hypothesis testing terminology surrounding null | In many circumstances neither is really the best approach. Consider using the P value as an index of the evidence against the null and make conclusions in the realm of the real experimental hypothesis | Hypothesis testing terminology surrounding null
In many circumstances neither is really the best approach. Consider using the P value as an index of the evidence against the null and make conclusions in the realm of the real experimental hypothesis rather than in the realm of the statistical hypothesis. Usually the former is much more important. | Hypothesis testing terminology surrounding null
In many circumstances neither is really the best approach. Consider using the P value as an index of the evidence against the null and make conclusions in the realm of the real experimental hypothesis |
34,081 | Estimating linear regression with OLS vs. ML | Using the usual notations, the log-likelihood of the ML method is
$l(\beta_0, \beta_1 ; y_1, \ldots, y_n) = \sum_{i=1}^n \left\{ -\frac{1}{2} \log (2\pi\sigma^2) - \frac{(y_{i} - (\beta_0 + \beta_1 x_{i}))^{2}}{2 \sigma^2} \right\}$.
It has to be maximised with respect to $\beta_0$ and $\beta_1$.
But, it is easy to see that this is equivalent to minimising
$\sum_{i=1}^{n} (y_{i} - (\beta_0 + \beta_1 x_{i}))^{2} $.
Hence, both ML and OLS lead to the same solution.
More details are provided in these nice lecture notes. | Estimating linear regression with OLS vs. ML | Using the usual notations, the log-likelihood of the ML method is
$l(\beta_0, \beta_1 ; y_1, \ldots, y_n) = \sum_{i=1}^n \left\{ -\frac{1}{2} \log (2\pi\sigma^2) - \frac{(y_{i} - (\beta_0 + \beta_1 x_ | Estimating linear regression with OLS vs. ML
Using the usual notations, the log-likelihood of the ML method is
$l(\beta_0, \beta_1 ; y_1, \ldots, y_n) = \sum_{i=1}^n \left\{ -\frac{1}{2} \log (2\pi\sigma^2) - \frac{(y_{i} - (\beta_0 + \beta_1 x_{i}))^{2}}{2 \sigma^2} \right\}$.
It has to be maximised with respect to $\beta_0$ and $\beta_1$.
But, it is easy to see that this is equivalent to minimising
$\sum_{i=1}^{n} (y_{i} - (\beta_0 + \beta_1 x_{i}))^{2} $.
Hence, both ML and OLS lead to the same solution.
More details are provided in these nice lecture notes. | Estimating linear regression with OLS vs. ML
Using the usual notations, the log-likelihood of the ML method is
$l(\beta_0, \beta_1 ; y_1, \ldots, y_n) = \sum_{i=1}^n \left\{ -\frac{1}{2} \log (2\pi\sigma^2) - \frac{(y_{i} - (\beta_0 + \beta_1 x_ |
34,082 | Estimating linear regression with OLS vs. ML | You are focusing on the wrong part of the concept in your question. The beauty of least squares is that it gives a nice easy answer regaurdless of the distribution, and if the true distribution happens to be normal, then it is the maiximum likelihood answer as well (I think this is the Gauss-Markov thereom). When you have a distribution other than the normal then ML and OLS will give different answers (but if the true distribution is close to normal then the answers will be similar). | Estimating linear regression with OLS vs. ML | You are focusing on the wrong part of the concept in your question. The beauty of least squares is that it gives a nice easy answer regaurdless of the distribution, and if the true distribution happe | Estimating linear regression with OLS vs. ML
You are focusing on the wrong part of the concept in your question. The beauty of least squares is that it gives a nice easy answer regaurdless of the distribution, and if the true distribution happens to be normal, then it is the maiximum likelihood answer as well (I think this is the Gauss-Markov thereom). When you have a distribution other than the normal then ML and OLS will give different answers (but if the true distribution is close to normal then the answers will be similar). | Estimating linear regression with OLS vs. ML
You are focusing on the wrong part of the concept in your question. The beauty of least squares is that it gives a nice easy answer regaurdless of the distribution, and if the true distribution happe |
34,083 | Estimating linear regression with OLS vs. ML | the only difference for finite samples is, that the ML-estimator for the residual variance is biased. It does not account for the number of regressors used in the model. | Estimating linear regression with OLS vs. ML | the only difference for finite samples is, that the ML-estimator for the residual variance is biased. It does not account for the number of regressors used in the model. | Estimating linear regression with OLS vs. ML
the only difference for finite samples is, that the ML-estimator for the residual variance is biased. It does not account for the number of regressors used in the model. | Estimating linear regression with OLS vs. ML
the only difference for finite samples is, that the ML-estimator for the residual variance is biased. It does not account for the number of regressors used in the model. |
34,084 | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$ | Error propagation via Taylor's rule (aka "delta" method) --
$$\operatorname{Var}(X^2) \approx 4\operatorname{\mathbb{E}}(X)^2 \operatorname{Var}(X)$$ | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$ | Error propagation via Taylor's rule (aka "delta" method) --
$$\operatorname{Var}(X^2) \approx 4\operatorname{\mathbb{E}}(X)^2 \operatorname{Var}(X)$$ | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$
Error propagation via Taylor's rule (aka "delta" method) --
$$\operatorname{Var}(X^2) \approx 4\operatorname{\mathbb{E}}(X)^2 \operatorname{Var}(X)$$ | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$
Error propagation via Taylor's rule (aka "delta" method) --
$$\operatorname{Var}(X^2) \approx 4\operatorname{\mathbb{E}}(X)^2 \operatorname{Var}(X)$$ |
34,085 | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$ | As a simple example of the responses of @user2168 and @mpiktas:
The variance of the set of values 1,2,3 is 0.67, while the variance of its square is 10.89. On the other hand, the variance of 2,3,4 is also 0.67, but the variance of the squares is 24.22.
These are just variances for finite sets of data, but the idea extends to distributions. | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$ | As a simple example of the responses of @user2168 and @mpiktas:
The variance of the set of values 1,2,3 is 0.67, while the variance of its square is 10.89. On the other hand, the variance of 2,3,4 is | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$
As a simple example of the responses of @user2168 and @mpiktas:
The variance of the set of values 1,2,3 is 0.67, while the variance of its square is 10.89. On the other hand, the variance of 2,3,4 is also 0.67, but the variance of the squares is 24.22.
These are just variances for finite sets of data, but the idea extends to distributions. | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$
As a simple example of the responses of @user2168 and @mpiktas:
The variance of the set of values 1,2,3 is 0.67, while the variance of its square is 10.89. On the other hand, the variance of 2,3,4 is |
34,086 | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$ | It's easy to see that the relationship between then is not constant by taking $X'=X+c$. Shifting a distribution by a constant doesn't affect the variance, but $Var((X+c)^2)$ can be made arbitrarily large. $Var(X^2)$ is a fourth-order statistic (i.e. is a combination of moments of order four and smaller), and cannot be written in terms of lower order statistics such as variance and mean. | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$ | It's easy to see that the relationship between then is not constant by taking $X'=X+c$. Shifting a distribution by a constant doesn't affect the variance, but $Var((X+c)^2)$ can be made arbitrarily la | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$
It's easy to see that the relationship between then is not constant by taking $X'=X+c$. Shifting a distribution by a constant doesn't affect the variance, but $Var((X+c)^2)$ can be made arbitrarily large. $Var(X^2)$ is a fourth-order statistic (i.e. is a combination of moments of order four and smaller), and cannot be written in terms of lower order statistics such as variance and mean. | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$
It's easy to see that the relationship between then is not constant by taking $X'=X+c$. Shifting a distribution by a constant doesn't affect the variance, but $Var((X+c)^2)$ can be made arbitrarily la |
34,087 | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$ | Error propagation via Taylor's rule (aka "delta" method) --
$$\operatorname{Var}(X^2) \approx 4\operatorname{\mathbb{E}}(X)^2 \operatorname{Var}(X) - \operatorname{Var}(X)^2 $$
Sorry i have expanded the taylor's rule in one extra order, because to just approximate the $\operatorname{Var}(X)$ linearly caused some problem with my algorithm, thought it would help other people to realize it's not linear... | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$ | Error propagation via Taylor's rule (aka "delta" method) --
$$\operatorname{Var}(X^2) \approx 4\operatorname{\mathbb{E}}(X)^2 \operatorname{Var}(X) - \operatorname{Var}(X)^2 $$
Sorry i have expanded | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$
Error propagation via Taylor's rule (aka "delta" method) --
$$\operatorname{Var}(X^2) \approx 4\operatorname{\mathbb{E}}(X)^2 \operatorname{Var}(X) - \operatorname{Var}(X)^2 $$
Sorry i have expanded the taylor's rule in one extra order, because to just approximate the $\operatorname{Var}(X)$ linearly caused some problem with my algorithm, thought it would help other people to realize it's not linear... | $\operatorname{Var}(X^2)$, if $\operatorname{Var}(X)=\sigma^2$
Error propagation via Taylor's rule (aka "delta" method) --
$$\operatorname{Var}(X^2) \approx 4\operatorname{\mathbb{E}}(X)^2 \operatorname{Var}(X) - \operatorname{Var}(X)^2 $$
Sorry i have expanded |
34,088 | R examples for Durbin & Koopman "Time Series Analysis by State Space Methods" | There is a package in CRAN (KFAS) which implements a good portion of the algorithms described in Durbin & Koopman, including "exact" non-informative distributions for the state vector, or parts of it.
Although it is not paticularly tied to Durbin & Koopman's book, you might also be interested in package dlm and the companion book Dynamic Linear Models with R. | R examples for Durbin & Koopman "Time Series Analysis by State Space Methods" | There is a package in CRAN (KFAS) which implements a good portion of the algorithms described in Durbin & Koopman, including "exact" non-informative distributions for the state vector, or parts of it. | R examples for Durbin & Koopman "Time Series Analysis by State Space Methods"
There is a package in CRAN (KFAS) which implements a good portion of the algorithms described in Durbin & Koopman, including "exact" non-informative distributions for the state vector, or parts of it.
Although it is not paticularly tied to Durbin & Koopman's book, you might also be interested in package dlm and the companion book Dynamic Linear Models with R. | R examples for Durbin & Koopman "Time Series Analysis by State Space Methods"
There is a package in CRAN (KFAS) which implements a good portion of the algorithms described in Durbin & Koopman, including "exact" non-informative distributions for the state vector, or parts of it. |
34,089 | R examples for Durbin & Koopman "Time Series Analysis by State Space Methods" | A walk through the Commandeur and Koopman's book with R examples is available here. Also check the official book's page where links to new software and tutorials are posted.
An entire JSS volume was dedicated to state space modelling in different software. See particularly the introductory paper and the R paper. Kalman Filtering in R has a good overview of available R packages for state space modeling.
Sections "Dynamic Regression Models" and "Multivariate Time Series Models" in TimeSeries CRAN View contain a few more references. | R examples for Durbin & Koopman "Time Series Analysis by State Space Methods" | A walk through the Commandeur and Koopman's book with R examples is available here. Also check the official book's page where links to new software and tutorials are posted.
An entire JSS volume was | R examples for Durbin & Koopman "Time Series Analysis by State Space Methods"
A walk through the Commandeur and Koopman's book with R examples is available here. Also check the official book's page where links to new software and tutorials are posted.
An entire JSS volume was dedicated to state space modelling in different software. See particularly the introductory paper and the R paper. Kalman Filtering in R has a good overview of available R packages for state space modeling.
Sections "Dynamic Regression Models" and "Multivariate Time Series Models" in TimeSeries CRAN View contain a few more references. | R examples for Durbin & Koopman "Time Series Analysis by State Space Methods"
A walk through the Commandeur and Koopman's book with R examples is available here. Also check the official book's page where links to new software and tutorials are posted.
An entire JSS volume was |
34,090 | Choosing $m$ value when using multiple imputation (MI) | I believe our current best practice is to use the two-step procedure described in von Hippel (2020) and his Statistical Horizons article, which is to estimate the fraction of missing information (FMI), which is distinct from the proportion of observations that are missing, and input that into the formula to compute the required number of imputations given the FMI and a user-supplied measure of the variability of the standard error estimate. That way, you can choose how to manage the tradeoff between time spent imputing and the precision of the resulting estimate of the standard error of your quantity of interest.
This methodology is also implemented in the R package howManyImputations. | Choosing $m$ value when using multiple imputation (MI) | I believe our current best practice is to use the two-step procedure described in von Hippel (2020) and his Statistical Horizons article, which is to estimate the fraction of missing information (FMI) | Choosing $m$ value when using multiple imputation (MI)
I believe our current best practice is to use the two-step procedure described in von Hippel (2020) and his Statistical Horizons article, which is to estimate the fraction of missing information (FMI), which is distinct from the proportion of observations that are missing, and input that into the formula to compute the required number of imputations given the FMI and a user-supplied measure of the variability of the standard error estimate. That way, you can choose how to manage the tradeoff between time spent imputing and the precision of the resulting estimate of the standard error of your quantity of interest.
This methodology is also implemented in the R package howManyImputations. | Choosing $m$ value when using multiple imputation (MI)
I believe our current best practice is to use the two-step procedure described in von Hippel (2020) and his Statistical Horizons article, which is to estimate the fraction of missing information (FMI) |
34,091 | Choosing $m$ value when using multiple imputation (MI) | While they don't provide a strict criterion in their study, Graham et al., 2007 did a Monte Carlo simulation of different $m$ values and came up with a table of estimates based off that data. Here $\gamma$ represents the proportion of missing information and $m$ equals the number of imputations. It seemed based off their study that the combination of $m$ x $\gamma$ predicted the power of the study, with less issue in setting $m$ at 5 when $\gamma$ was lower.
Results of Monte Carlo simulation
m
Power
b
SE
t
df
p
$\gamma$
SD$\gamma$
MSE ($\times10^3$)
($\gamma$=0.10)
100
0.7910
0.0972
0.0353
2.76
10.8 K
0.049
0.101
0.0194
1.2022
40
0.7880
0.0969
0.0353
2.75
4,527
0.050
0.102
0.0250
1.2270
20
0.7846
0.0972
0.0353
2.76
2,454
0.050
0.105
0.0332
1.2203
10
0.7799
0.0968
0.0354
2.74
1,711
0.052
0.109
0.0483
1.2429
5
0.7760
0.0968
0.0355
2.73
4,714
0.052
0.119
0.0766
1.2288
3
0.7620
0.0967
0.0357
2.72
5,562 K
0.056
0.131
0.1143
1.2967
($\gamma$=0.30)
100
0.7881
0.0969
0.0353
2.75
1137
0.048
0.303
0.0353
1.1954
40
0.7873
0.0974
0.0353
2.77
471
0.049
0.306
0.0524
1.2120
20
0.7824
0.0975
0.0355
2.76
249
0.051
0.311
0.0726
1.2339
10
0.7613
0.0963
0.0356
2.72
157
0.056
0.320
0.1064
1.2346
5
0.7308
0.0965
0.0360
2.72
370
0.062
0.337
0.1611
1.2880
3
0.6873
0.0971
0.0364
2.75
173 K
0.071
0.348
0.2215
1.3106
($\gamma$=0.50)
100
0.7809
0.0965
0.0353
2.74
403
0.051
0.503
0.0399
1.2247
40
0.7763
0.0970
0.0354
2.75
164
0.052
0.506
0.0596
1.2390
20
0.7719
0.0978
0.0356
2.77
84
0.053
0.512
0.0851
1.2494
10
0.7479
0.0974
0.0359
2.76
47
0.059
0.521
0.1243
1.2709
5
0.6819
0.0967
0.0361
2.76
62
0.071
0.525
0.1840
1.3545
3
0.5863
0.0972
0.0368
2.80
48 K
.093
.523
.2543
1.4361
($\gamma$=0.70)
100
0.7780
0.0971
0.0354
2.75
203
0.052
0.703
0.0327
1.2451
40
0.7710
0.0967
0.0353
2.76
82
0.055
0.704
0.0505
1.2602
20
0.7486
0.0965
0.0356
2.75
41
0.059
0.709
0.0721
1.2753
10
0.7116
0.0966
0.0358
2.77
21
0.066
0.712
0.1056
1.2878
5
0.6096
0.0969
0.0366
2.82
25
0.087
0.713
0.1660
1.3872
3
0.4930
0.0962
0.0368
2.93
1,413 K
0.118
0.688
0.2403
1.4836
($\gamma$=0.90)
100
0.7756
0.0964
0.0353
2.75
122
0.053
0.901
0.0136
1.2057
40
0.7618
0.0970
0.0355
2.77
48
0.055
0.902
0.0211
1.2507
20
0.7291
0.0968
0.0356
2.78
24
0.063
0.903
0.0322
1.3216
10
0.6689
0.0967
0.0360
2.83
12
0.075
0.903
0.0520
1.3517
5
0.5334
0.0966
0.0365
2.97
6
0.102
0.895
0.0997
1.4009
3
0.3876
0.0969
0.0364
3.33
236
0.147
0.862
0.1782
1.6662
Figures for each cell were based on 8,000 replications. The population
$r=b=0.0969$. Theoretical power=0.7839 for $N=800$. Power for
equivalent FIML analysis was also 0.7839 (for all levels for
$\gamma$).
Original image of the table:
Citation
Graham, J. W., Olchowski, A. E., & Gilreath, T. D. (2007). How Many Imputations are Really Needed? Some Practical Clarifications of Multiple Imputation Theory. Prevention Science, 8(3), 206–213. https://doi.org/10.1007/s11121-007-0070-9 | Choosing $m$ value when using multiple imputation (MI) | While they don't provide a strict criterion in their study, Graham et al., 2007 did a Monte Carlo simulation of different $m$ values and came up with a table of estimates based off that data. Here $\g | Choosing $m$ value when using multiple imputation (MI)
While they don't provide a strict criterion in their study, Graham et al., 2007 did a Monte Carlo simulation of different $m$ values and came up with a table of estimates based off that data. Here $\gamma$ represents the proportion of missing information and $m$ equals the number of imputations. It seemed based off their study that the combination of $m$ x $\gamma$ predicted the power of the study, with less issue in setting $m$ at 5 when $\gamma$ was lower.
Results of Monte Carlo simulation
m
Power
b
SE
t
df
p
$\gamma$
SD$\gamma$
MSE ($\times10^3$)
($\gamma$=0.10)
100
0.7910
0.0972
0.0353
2.76
10.8 K
0.049
0.101
0.0194
1.2022
40
0.7880
0.0969
0.0353
2.75
4,527
0.050
0.102
0.0250
1.2270
20
0.7846
0.0972
0.0353
2.76
2,454
0.050
0.105
0.0332
1.2203
10
0.7799
0.0968
0.0354
2.74
1,711
0.052
0.109
0.0483
1.2429
5
0.7760
0.0968
0.0355
2.73
4,714
0.052
0.119
0.0766
1.2288
3
0.7620
0.0967
0.0357
2.72
5,562 K
0.056
0.131
0.1143
1.2967
($\gamma$=0.30)
100
0.7881
0.0969
0.0353
2.75
1137
0.048
0.303
0.0353
1.1954
40
0.7873
0.0974
0.0353
2.77
471
0.049
0.306
0.0524
1.2120
20
0.7824
0.0975
0.0355
2.76
249
0.051
0.311
0.0726
1.2339
10
0.7613
0.0963
0.0356
2.72
157
0.056
0.320
0.1064
1.2346
5
0.7308
0.0965
0.0360
2.72
370
0.062
0.337
0.1611
1.2880
3
0.6873
0.0971
0.0364
2.75
173 K
0.071
0.348
0.2215
1.3106
($\gamma$=0.50)
100
0.7809
0.0965
0.0353
2.74
403
0.051
0.503
0.0399
1.2247
40
0.7763
0.0970
0.0354
2.75
164
0.052
0.506
0.0596
1.2390
20
0.7719
0.0978
0.0356
2.77
84
0.053
0.512
0.0851
1.2494
10
0.7479
0.0974
0.0359
2.76
47
0.059
0.521
0.1243
1.2709
5
0.6819
0.0967
0.0361
2.76
62
0.071
0.525
0.1840
1.3545
3
0.5863
0.0972
0.0368
2.80
48 K
.093
.523
.2543
1.4361
($\gamma$=0.70)
100
0.7780
0.0971
0.0354
2.75
203
0.052
0.703
0.0327
1.2451
40
0.7710
0.0967
0.0353
2.76
82
0.055
0.704
0.0505
1.2602
20
0.7486
0.0965
0.0356
2.75
41
0.059
0.709
0.0721
1.2753
10
0.7116
0.0966
0.0358
2.77
21
0.066
0.712
0.1056
1.2878
5
0.6096
0.0969
0.0366
2.82
25
0.087
0.713
0.1660
1.3872
3
0.4930
0.0962
0.0368
2.93
1,413 K
0.118
0.688
0.2403
1.4836
($\gamma$=0.90)
100
0.7756
0.0964
0.0353
2.75
122
0.053
0.901
0.0136
1.2057
40
0.7618
0.0970
0.0355
2.77
48
0.055
0.902
0.0211
1.2507
20
0.7291
0.0968
0.0356
2.78
24
0.063
0.903
0.0322
1.3216
10
0.6689
0.0967
0.0360
2.83
12
0.075
0.903
0.0520
1.3517
5
0.5334
0.0966
0.0365
2.97
6
0.102
0.895
0.0997
1.4009
3
0.3876
0.0969
0.0364
3.33
236
0.147
0.862
0.1782
1.6662
Figures for each cell were based on 8,000 replications. The population
$r=b=0.0969$. Theoretical power=0.7839 for $N=800$. Power for
equivalent FIML analysis was also 0.7839 (for all levels for
$\gamma$).
Original image of the table:
Citation
Graham, J. W., Olchowski, A. E., & Gilreath, T. D. (2007). How Many Imputations are Really Needed? Some Practical Clarifications of Multiple Imputation Theory. Prevention Science, 8(3), 206–213. https://doi.org/10.1007/s11121-007-0070-9 | Choosing $m$ value when using multiple imputation (MI)
While they don't provide a strict criterion in their study, Graham et al., 2007 did a Monte Carlo simulation of different $m$ values and came up with a table of estimates based off that data. Here $\g |
34,092 | Interpret neural network like the linear regression equation such as how much will Y change if we change X1 and keep the other variables fixed | One of the issues when you introduce nonlinearities and interactions is that the change resulting in a change in a variable of interest depends on the starting value of that variable of interest and of the other variables in the model.
For instance, consider a model like $\hat y = x_1-x_2+x_1^2x_2$. If you want to know by how much $y$ changes upon changing $x_1$ by one unit, take the derivative.
$$
\dfrac{
\partial \hat y
}{
\partial x_1
} = 1 + 2x_1x_2
$$
You cannot answer the question (with a single number) unless you know $x_1$ and $x_2$.
Neural networks are no different. We can take partial derivatives (making use of the chain rule) and interpret those derivatives as slopes just like normal. However, those slopes are likely to depend on the values of all variables (just like above), including the variable of interest.
Consequently, there is no simple interpretation like, “When $x_1$ increases one unit, our predicted $y$ increases by $\hat\beta_1$ units.”
If $A$ is an activation function, a simple neural network with two features and two neurons (with activation function $A$) in the hidden layer is:
$$
\hat y = \hat b_{2,1} + \hat w_{2,1}A\bigg(\hat b_{1,1}+\hat w_{1,1}x_1 + \hat b_{1,3}x_2\bigg) + \hat w_{2,2} A\bigg(\hat b_{1,2} + \hat w_{1,2}x_1 + \hat w_{1,4}x_2\bigg)
$$
For a nonlinear activation function $A$, the partial derivatives with respect to $x_1$ and $x_2$ can involve both $x_1$ and $x_2$, meaning that you must know the point where you want to talk about changes in order to talk about changes. | Interpret neural network like the linear regression equation such as how much will Y change if we ch | One of the issues when you introduce nonlinearities and interactions is that the change resulting in a change in a variable of interest depends on the starting value of that variable of interest and o | Interpret neural network like the linear regression equation such as how much will Y change if we change X1 and keep the other variables fixed
One of the issues when you introduce nonlinearities and interactions is that the change resulting in a change in a variable of interest depends on the starting value of that variable of interest and of the other variables in the model.
For instance, consider a model like $\hat y = x_1-x_2+x_1^2x_2$. If you want to know by how much $y$ changes upon changing $x_1$ by one unit, take the derivative.
$$
\dfrac{
\partial \hat y
}{
\partial x_1
} = 1 + 2x_1x_2
$$
You cannot answer the question (with a single number) unless you know $x_1$ and $x_2$.
Neural networks are no different. We can take partial derivatives (making use of the chain rule) and interpret those derivatives as slopes just like normal. However, those slopes are likely to depend on the values of all variables (just like above), including the variable of interest.
Consequently, there is no simple interpretation like, “When $x_1$ increases one unit, our predicted $y$ increases by $\hat\beta_1$ units.”
If $A$ is an activation function, a simple neural network with two features and two neurons (with activation function $A$) in the hidden layer is:
$$
\hat y = \hat b_{2,1} + \hat w_{2,1}A\bigg(\hat b_{1,1}+\hat w_{1,1}x_1 + \hat b_{1,3}x_2\bigg) + \hat w_{2,2} A\bigg(\hat b_{1,2} + \hat w_{1,2}x_1 + \hat w_{1,4}x_2\bigg)
$$
For a nonlinear activation function $A$, the partial derivatives with respect to $x_1$ and $x_2$ can involve both $x_1$ and $x_2$, meaning that you must know the point where you want to talk about changes in order to talk about changes. | Interpret neural network like the linear regression equation such as how much will Y change if we ch
One of the issues when you introduce nonlinearities and interactions is that the change resulting in a change in a variable of interest depends on the starting value of that variable of interest and o |
34,093 | Interpret neural network like the linear regression equation such as how much will Y change if we change X1 and keep the other variables fixed | This is a nice question, that touches on some interesting points in the history of neural networks (which I can only briefly mention here).
First, what you say is absolutely right if and only if the nodes in your network have linear activation functions, e.g. $b_{1,1} = x_1w_1 + x_2w_2 + x_3w_3$.
However, as explained here, if your network only has linear activation functions, you can simplify the equations so that your multilayer network can be replaced with a simple network with no hidden layers where the input nodes connect directly to the outputs, and this simple network is basically just a linear regression model, $y = x_1b_1 + x_2b_2 + \dots + x_nb_n$.
This is why most useful neural networks use non-linear activation functions, and adding making the model non-linear means the equation you want can no longer be calculated: the effect of changing the value of x1 will depend on the values of all the other inputs.
What you can do, however, is compute the average effect of changing x1 in your training data quite easily: by modifying the values of x1 in your data and calculating the average change in y. | Interpret neural network like the linear regression equation such as how much will Y change if we ch | This is a nice question, that touches on some interesting points in the history of neural networks (which I can only briefly mention here).
First, what you say is absolutely right if and only if the n | Interpret neural network like the linear regression equation such as how much will Y change if we change X1 and keep the other variables fixed
This is a nice question, that touches on some interesting points in the history of neural networks (which I can only briefly mention here).
First, what you say is absolutely right if and only if the nodes in your network have linear activation functions, e.g. $b_{1,1} = x_1w_1 + x_2w_2 + x_3w_3$.
However, as explained here, if your network only has linear activation functions, you can simplify the equations so that your multilayer network can be replaced with a simple network with no hidden layers where the input nodes connect directly to the outputs, and this simple network is basically just a linear regression model, $y = x_1b_1 + x_2b_2 + \dots + x_nb_n$.
This is why most useful neural networks use non-linear activation functions, and adding making the model non-linear means the equation you want can no longer be calculated: the effect of changing the value of x1 will depend on the values of all the other inputs.
What you can do, however, is compute the average effect of changing x1 in your training data quite easily: by modifying the values of x1 in your data and calculating the average change in y. | Interpret neural network like the linear regression equation such as how much will Y change if we ch
This is a nice question, that touches on some interesting points in the history of neural networks (which I can only briefly mention here).
First, what you say is absolutely right if and only if the n |
34,094 | Interpret neural network like the linear regression equation such as how much will Y change if we change X1 and keep the other variables fixed | You can interpret NN like that but it is pointless generally. The seeming utility in doing so for OLS is in decoupling of the partial derivative from other variables, I.e. $\partial/\partial x_1 f(x_1,\dots,x_2)=\beta_1$.
With a useful NN you won’t get this decoupling and the partial ends up being a nonlinear function of all inputs $\beta(x_1,\dots,x_2) $ ,which you may have thousands of. So, the sensitivity to the variables is not the constant and as such not a simple intuitive concept to start with. Consider also that if you add interaction and polynomial terms to the OLS the sensitivity becomes more complicated and less intuitive for a linear regression too.
Note, that your example is NN with linear activation in inner layers, not a useful contraption as it turns out. | Interpret neural network like the linear regression equation such as how much will Y change if we ch | You can interpret NN like that but it is pointless generally. The seeming utility in doing so for OLS is in decoupling of the partial derivative from other variables, I.e. $\partial/\partial x_1 f(x_1 | Interpret neural network like the linear regression equation such as how much will Y change if we change X1 and keep the other variables fixed
You can interpret NN like that but it is pointless generally. The seeming utility in doing so for OLS is in decoupling of the partial derivative from other variables, I.e. $\partial/\partial x_1 f(x_1,\dots,x_2)=\beta_1$.
With a useful NN you won’t get this decoupling and the partial ends up being a nonlinear function of all inputs $\beta(x_1,\dots,x_2) $ ,which you may have thousands of. So, the sensitivity to the variables is not the constant and as such not a simple intuitive concept to start with. Consider also that if you add interaction and polynomial terms to the OLS the sensitivity becomes more complicated and less intuitive for a linear regression too.
Note, that your example is NN with linear activation in inner layers, not a useful contraption as it turns out. | Interpret neural network like the linear regression equation such as how much will Y change if we ch
You can interpret NN like that but it is pointless generally. The seeming utility in doing so for OLS is in decoupling of the partial derivative from other variables, I.e. $\partial/\partial x_1 f(x_1 |
34,095 | Does introduction of new variable always increase the p-val of existing ones? | Definitely not, and there is a sense in which this is why we do regression.
An example is analysis of covariance (ANCOVA), which is the usual ANOVA but with an additional variable that typically is called a covariate.
I’ll give an example with two groups.
set.seed(2022)
N <- 100
g <- rep(c(0, 1), c(N, N)) # Group
x <- rep(seq(0, 1, 1/(N - 1)), 2) # Covariate
y <- x + g + rnorm(N, 0, 3)
L1 <- lm(y ~ g)
L2 <- lm(y ~ g + x)
summary(L1)
summary(L2)
In the first regression, I get a p-value of about $0.025$ for the group variable, while the second regression gives a p-value of about $0.018$ for the group variable.
The reason that I say this is why we do regression is because this is helping us increase the signal-to-noise ratio, thus allowing patterns (signal) to become apparent. If your threshold for evidence of a difference is a p-value under $0.02$, then the first regression gives insufficient evidence that there is a difference between the groups. However, once we use that covariate to explain some of the variability (noise), the pattern jumps out from the background.
EDIT
While this was not the original question, for completeness, I will add that adding a variable does not have to lower the p-value. One way for this to happen is if the new variable is correlated with an existing variable.
library(MASS)
set.seed(2022)
N <- 100
X <- MASS::mvrnorm(N, c(0, 0), matrix(c(1, 0.9, 0.9, 1), 2, 2))
x1 <- X[, 1]
x2 <- X[, 2]
y <- x1 + x2 + rnorm(N, 0, 3)
L1 <- lm(y ~ x1)
L2 <- lm(y ~ x1 + x2)
summary(L1)
summary(L2)
This goes from a tiny p-value on the order of $10^{-12}$ to a p-value above our usual threshold of $0.05$. | Does introduction of new variable always increase the p-val of existing ones? | Definitely not, and there is a sense in which this is why we do regression.
An example is analysis of covariance (ANCOVA), which is the usual ANOVA but with an additional variable that typically is ca | Does introduction of new variable always increase the p-val of existing ones?
Definitely not, and there is a sense in which this is why we do regression.
An example is analysis of covariance (ANCOVA), which is the usual ANOVA but with an additional variable that typically is called a covariate.
I’ll give an example with two groups.
set.seed(2022)
N <- 100
g <- rep(c(0, 1), c(N, N)) # Group
x <- rep(seq(0, 1, 1/(N - 1)), 2) # Covariate
y <- x + g + rnorm(N, 0, 3)
L1 <- lm(y ~ g)
L2 <- lm(y ~ g + x)
summary(L1)
summary(L2)
In the first regression, I get a p-value of about $0.025$ for the group variable, while the second regression gives a p-value of about $0.018$ for the group variable.
The reason that I say this is why we do regression is because this is helping us increase the signal-to-noise ratio, thus allowing patterns (signal) to become apparent. If your threshold for evidence of a difference is a p-value under $0.02$, then the first regression gives insufficient evidence that there is a difference between the groups. However, once we use that covariate to explain some of the variability (noise), the pattern jumps out from the background.
EDIT
While this was not the original question, for completeness, I will add that adding a variable does not have to lower the p-value. One way for this to happen is if the new variable is correlated with an existing variable.
library(MASS)
set.seed(2022)
N <- 100
X <- MASS::mvrnorm(N, c(0, 0), matrix(c(1, 0.9, 0.9, 1), 2, 2))
x1 <- X[, 1]
x2 <- X[, 2]
y <- x1 + x2 + rnorm(N, 0, 3)
L1 <- lm(y ~ x1)
L2 <- lm(y ~ x1 + x2)
summary(L1)
summary(L2)
This goes from a tiny p-value on the order of $10^{-12}$ to a p-value above our usual threshold of $0.05$. | Does introduction of new variable always increase the p-val of existing ones?
Definitely not, and there is a sense in which this is why we do regression.
An example is analysis of covariance (ANCOVA), which is the usual ANOVA but with an additional variable that typically is ca |
34,096 | Does introduction of new variable always increase the p-val of existing ones? | @Dave explains that mathematically p-values can get bigger or smaller with more predictors because adding a predictor changes the model.
But there is a fundamental problem with your argument: it is based on a fallacy about p-values.
Your argument boils down to: "A large p-value means the null hypothesis is true." However, p-values can be large for many reasons, including small sample size: the data are consistent with the null hypothesis as well as other possible explanations. The conclusion we draw from a non-significant p-value is that we don't reject the null hypothesis. "Not reject" is not the same as "accept", in null hypothesis statistical testing at least.
In short, even if you could prove that adding an extra variable increases the p-value of log(Price), you cannot make the interpretation you propose.
So rather than evidence that in some European countries demand is not sensitive to gas prices, it may be the case that you don't have much information about demand elasticity in these countries. [You offer no details about your analysis but a hierarchical model — with partial pooling of price elasticities among European countries — may be an interesting approach to consider.]
You can learn more about significance in a multiple regression in these CV discussions:
Does adding more variables into a multivariable regression change coefficients of existing variables?
What is the effect of having correlated predictors in a multiple regression model?
How can adding a 2nd IV make the 1st IV significant? | Does introduction of new variable always increase the p-val of existing ones? | @Dave explains that mathematically p-values can get bigger or smaller with more predictors because adding a predictor changes the model.
But there is a fundamental problem with your argument: it is ba | Does introduction of new variable always increase the p-val of existing ones?
@Dave explains that mathematically p-values can get bigger or smaller with more predictors because adding a predictor changes the model.
But there is a fundamental problem with your argument: it is based on a fallacy about p-values.
Your argument boils down to: "A large p-value means the null hypothesis is true." However, p-values can be large for many reasons, including small sample size: the data are consistent with the null hypothesis as well as other possible explanations. The conclusion we draw from a non-significant p-value is that we don't reject the null hypothesis. "Not reject" is not the same as "accept", in null hypothesis statistical testing at least.
In short, even if you could prove that adding an extra variable increases the p-value of log(Price), you cannot make the interpretation you propose.
So rather than evidence that in some European countries demand is not sensitive to gas prices, it may be the case that you don't have much information about demand elasticity in these countries. [You offer no details about your analysis but a hierarchical model — with partial pooling of price elasticities among European countries — may be an interesting approach to consider.]
You can learn more about significance in a multiple regression in these CV discussions:
Does adding more variables into a multivariable regression change coefficients of existing variables?
What is the effect of having correlated predictors in a multiple regression model?
How can adding a 2nd IV make the 1st IV significant? | Does introduction of new variable always increase the p-val of existing ones?
@Dave explains that mathematically p-values can get bigger or smaller with more predictors because adding a predictor changes the model.
But there is a fundamental problem with your argument: it is ba |
34,097 | Objective criteria for assumption violations that do not utilize p-values? | This is a good question, as it acknowledges that the issue is not whether model assumptions are fulfilled or not (they never are), but rather whether violations of the model assumption matter (in terms of misleading conclusions).
Unfortunately I tend to answer this question with "no". A problem is this: The statistical problem of interest is well defined within the framework of the assumed model, but if model assumptions are violated, there is no unique objective way to define what it actually means to say that conclusions are misled.
Here is an illustration. Let's say you are running a test about the mean of a normal distribution, but the underlying distribution is in fact skew. Now your sample size may be fairly large and there may not be any indication that second moments do "explode", so the Central Limit Theorem may justify normal theory to hold approximately (violation of normality could therefore be seen as not problematic). However, in most skew distributions mean, mode, and median are different, whereas in the normal distribution they are the same, meaning that even though the CLT authorises inference about the mean, it isn't clear whether in your specific application you should rather be interested in median or mode in order to summarise your distribution. Under the normal assumption this doesn't matter, but if the underlying distribution is in fact skew, it usually does, and the answer whether the normal assumption theory is fine or not depends on this.
Here is a paper I had my hand in on investigating the quality of formal misspecification tests for assumptions in testing, with connected considerations. Overall we're not as negative about this approach as some others, even though we agree that in a good number of situations it is not very good. But sometimes it's fine. Unfortunately this depends on a number of specifics of the situation.
M. I. Shamsudheen & C. Hennig: Should we test the model assumptions before running a model-based test?
https://arxiv.org/abs/1908.02218
Two maybe interesting papers that we cite:
Zimmerman DW (2011) A simple and effective decision rule for choosing a significance test to protect against non-normality. British Journal of Mathematical and Statistical Psychology 64:388-409 (Here an objective rule different from a formal assumptions test is proposed to choose between a t-test and a nonparametric test; namely to use the nonparametric test in case they have very different results.)
Spanos A (2018) Mis-specification testing in retrospect. Journal of Economic Surveys 32:541–577 (good and thoughtful survey paper even though I don't agree with everything)
I believe that developing decision rules between model-based and alternative procedures that have better performance than standard misspecification tests is a very promising research area (even though there will always have to be some "subjective" decision making, see above), but as far as I know there isn't much.
PS: Regarding the Zimmerman paper, I have seen a similar suggestion for linear regression somewhere, namely to run a least squares and a robust regression, and to use the least squares one if both are reasonably in line (of course one can define this "objectively"), and otherwise to use the robust fit. I don't remember exactly where that was anymore, somewhere in the robustness literature, and as far as I remember, it was defined but not much (or even nothing) was done to compare its quality to alternative approaches including running either least squares or robust fit all the time. | Objective criteria for assumption violations that do not utilize p-values? | This is a good question, as it acknowledges that the issue is not whether model assumptions are fulfilled or not (they never are), but rather whether violations of the model assumption matter (in term | Objective criteria for assumption violations that do not utilize p-values?
This is a good question, as it acknowledges that the issue is not whether model assumptions are fulfilled or not (they never are), but rather whether violations of the model assumption matter (in terms of misleading conclusions).
Unfortunately I tend to answer this question with "no". A problem is this: The statistical problem of interest is well defined within the framework of the assumed model, but if model assumptions are violated, there is no unique objective way to define what it actually means to say that conclusions are misled.
Here is an illustration. Let's say you are running a test about the mean of a normal distribution, but the underlying distribution is in fact skew. Now your sample size may be fairly large and there may not be any indication that second moments do "explode", so the Central Limit Theorem may justify normal theory to hold approximately (violation of normality could therefore be seen as not problematic). However, in most skew distributions mean, mode, and median are different, whereas in the normal distribution they are the same, meaning that even though the CLT authorises inference about the mean, it isn't clear whether in your specific application you should rather be interested in median or mode in order to summarise your distribution. Under the normal assumption this doesn't matter, but if the underlying distribution is in fact skew, it usually does, and the answer whether the normal assumption theory is fine or not depends on this.
Here is a paper I had my hand in on investigating the quality of formal misspecification tests for assumptions in testing, with connected considerations. Overall we're not as negative about this approach as some others, even though we agree that in a good number of situations it is not very good. But sometimes it's fine. Unfortunately this depends on a number of specifics of the situation.
M. I. Shamsudheen & C. Hennig: Should we test the model assumptions before running a model-based test?
https://arxiv.org/abs/1908.02218
Two maybe interesting papers that we cite:
Zimmerman DW (2011) A simple and effective decision rule for choosing a significance test to protect against non-normality. British Journal of Mathematical and Statistical Psychology 64:388-409 (Here an objective rule different from a formal assumptions test is proposed to choose between a t-test and a nonparametric test; namely to use the nonparametric test in case they have very different results.)
Spanos A (2018) Mis-specification testing in retrospect. Journal of Economic Surveys 32:541–577 (good and thoughtful survey paper even though I don't agree with everything)
I believe that developing decision rules between model-based and alternative procedures that have better performance than standard misspecification tests is a very promising research area (even though there will always have to be some "subjective" decision making, see above), but as far as I know there isn't much.
PS: Regarding the Zimmerman paper, I have seen a similar suggestion for linear regression somewhere, namely to run a least squares and a robust regression, and to use the least squares one if both are reasonably in line (of course one can define this "objectively"), and otherwise to use the robust fit. I don't remember exactly where that was anymore, somewhere in the robustness literature, and as far as I remember, it was defined but not much (or even nothing) was done to compare its quality to alternative approaches including running either least squares or robust fit all the time. | Objective criteria for assumption violations that do not utilize p-values?
This is a good question, as it acknowledges that the issue is not whether model assumptions are fulfilled or not (they never are), but rather whether violations of the model assumption matter (in term |
34,098 | Objective criteria for assumption violations that do not utilize p-values? | This is not a complete answer, and it's not exactly "objective", but a useful tool is what is known as posterior predictive checks in a Bayesian context (but probably by other names elsewhere). In this, you simulate data from the distribution implied by your model, and compare it to your actual data, usually by plotting them side-by-side in whatever fashion makes sense for your problem. Mismatches then suggest assumptions that don't hold - e.g. your simulated data is symmetrical where the real data is skewed, or the real data has fatter tails. | Objective criteria for assumption violations that do not utilize p-values? | This is not a complete answer, and it's not exactly "objective", but a useful tool is what is known as posterior predictive checks in a Bayesian context (but probably by other names elsewhere). In thi | Objective criteria for assumption violations that do not utilize p-values?
This is not a complete answer, and it's not exactly "objective", but a useful tool is what is known as posterior predictive checks in a Bayesian context (but probably by other names elsewhere). In this, you simulate data from the distribution implied by your model, and compare it to your actual data, usually by plotting them side-by-side in whatever fashion makes sense for your problem. Mismatches then suggest assumptions that don't hold - e.g. your simulated data is symmetrical where the real data is skewed, or the real data has fatter tails. | Objective criteria for assumption violations that do not utilize p-values?
This is not a complete answer, and it's not exactly "objective", but a useful tool is what is known as posterior predictive checks in a Bayesian context (but probably by other names elsewhere). In thi |
34,099 | Why can we ignore missing data if it's missing at random? | In the context of regression analysis, all of our inferences are conditional on the explanatory variables. Consequently, if the missingness is random when conditioning on these explanatory variables (which is the case for MAR) this is sufficient to ensure that estimators retain the properties they would usually have under MCAR. The basic intuition for this is that if the missingness distribution only depends on the explanatory variables then it is essentially "fixed" when we condition on these variables.
The theory of missingness is usually shown in a more generalised setting than linear regression, and its main theorems are usually established directly with respect to the likelihood function in a highly general form of analysis. A good expository paper on the concept (with theorems and proofs) is Seaman et al (2013) (version without paywall here). Below I will adapt some material from this paper to show how MAR works in the context of regression analysis. This will show that ---under the assumption of MAR--- the likelihood function for the regression parameters is proportionate to the version that "ignores" the missingness mechanism.
Setting up the problem: Consider a problem involving a set of values $(\mathbf{x}_1, \mathbf{y}_1),...,(\mathbf{x}_n, \mathbf{y}_n)$ where the conditional distribution for $\mathbf{y}|\mathbf{x}$ uses the density $f_\theta$ which depends on a parameter $\theta$. Suppose we observe this process subject to MAR with missingness indicators $\mathbf{m}_1,...,\mathbf{m}_n$ that have a conditional distribution that uses the density $g_\phi$ that depends on a parameter $\phi$. Since the sampling and missingness determine the observed outcomes, there is a mapping $H$ from any vectors of explanatory and response variables and any vector of corresponding missingness indicators to the observed vectors of explanatory and response variables.
To facilitate our analysis, let $\mathbf{x}_*$ and $\mathbf{y}_*$ denote the actual vectors of explanatory and response variables and let $\mathbf{m}_*$ denote the missingness vector that leads to the observed values. Then let $\mathbf{x}_\text{obs}$ and $\mathbf{y}_\text{obs}$ denote the observed vectors of explanatory and response variables. These latter vectors are obtained by:
$$(\mathbf{x}_\text{obs}, \mathbf{y}_\text{obs}) = H(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*).$$
Without loss of generality, we will suppose that there are $k = n-\sum_i m_{*i}$ observed values in the observe vectors and $n-k = \sum_i m_{*i}$ missing values that do not appear in these vectors.
Likelihood analysis: If we were to ignore the missingness mechanism in the sampling method, and just treat this as if we sampled the observed outcomes at random without any missing data, our likelihood function for inferences about $\theta$ would be:
$$L_{\mathbf{x}_\text{obs}, \mathbf{y}_\text{obs}}(\theta) = \prod_{i=1}^k f_\theta(\mathbf{y}_{\text{obs}, i}|\mathbf{x}_{\text{obs}, i}).$$
However, with the missingness mechanism the actual likelihood function is:
$$\tilde{L}_{\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*}(\theta, \phi)
= \int \limits_{\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)} \bigg( \prod_{i=1}^n f_\theta(\mathbf{y}_i|\mathbf{x}_{*i})^{1-m_{*i}} \bigg) \cdot g_\phi(\mathbf{m}_*|\mathbf{x}_*, \mathbf{y}) \ d \mathbf{y},$$
where we define the space $\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)
\equiv \{ \mathbf{y} | H(\mathbf{x}_*, \mathbf{y}, \mathbf{m}_*) = H(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*) \}$.
Now, obviously these are very different likelihood functions. However, if missingness-at-random (MAR) holds then the distribution of the missingness vector depends on $(\mathbf{x},\mathbf{y})$ only through $\mathbf{x}$. Under this assumption we have $g_\phi(\mathbf{m}|\mathbf{x}, \mathbf{y}) = g_\phi(\mathbf{m}|\mathbf{x})$ for all $\mathbf{x},\mathbf{y},\mathbf{m}$, which then gives:
$$\begin{align}
\tilde{L}_{\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*}(\theta, \phi)
&= \int \limits_{\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)} \bigg( \prod_{i=1}^n f_\theta(\mathbf{y}_i|\mathbf{x}_{*i})^{1-m_{*i}} \bigg) \cdot g_\phi(\mathbf{m}_*|\mathbf{x}_*, \mathbf{y}) \ d \mathbf{y} \\[6pt]
&= g_\phi(\mathbf{m}_*|\mathbf{x}_*) \int \limits_{\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)}\bigg( \prod_{i=1}^n f_\theta(\mathbf{y}_i|\mathbf{x}_{*i})^{1-m_{*i}} \bigg) \ d \mathbf{y} \\[6pt]
&= g_\phi(\mathbf{m}_*|\mathbf{x}_*) \int \limits_{\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)}\bigg( \prod_{i=1}^k f_\theta(\mathbf{y}_{\text{obs}, i}|\mathbf{x}_{\text{obs}, i}) \bigg) \ d \mathbf{y} \\[6pt]
&= g_\phi(\mathbf{m}_*|\mathbf{x}) \cdot \bigg( \prod_{i=1}^k f_\theta(\mathbf{y}_{\text{obs}, i}|\mathbf{x}_{\text{obs}, i}) \bigg) \cdot |\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)| \\[6pt]
&\propto g_\phi(\mathbf{m}_*|\mathbf{x}) \cdot \bigg( \prod_{i=1}^k f_\theta(\mathbf{y}_{\text{obs}, i}|\mathbf{x}_{\text{obs}, i}) \bigg) \\[12pt]
&= g_\phi(\mathbf{m}_*|\mathbf{x}) \cdot L_{\mathbf{x}_\text{obs}, \mathbf{y}_\text{obs}}(\theta). \\[6pt]
\end{align}$$
If we are only concerned with making inferences about $\theta$ (i.e., if $\phi$ s a nuisance parameter) then we can make use of the fact that:
$$\tilde{L}_{\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*}(\theta, \phi) \overset{\theta}{\propto} L_{\mathbf{x}_\text{obs}, \mathbf{y}_\text{obs}}(\theta).$$
As you can see, this means that the true likelihood/profile likelihood function for the paramater $\theta$ (the one that does not ignore the missingness mechanism) is proportionate to the sipler likelihood function obtained by ignoring the missingness mechanism. If you look through the mathematics above you will see that this occurs because the equation $g_\phi(\mathbf{m}|\mathbf{x}, \mathbf{y}) = g_\phi(\mathbf{m}|\mathbf{x})$ allows us to "separate" this part from the part that depends on $\theta$ ---i.e., the MAR assumption makes the true likelihood function "seperable" with respect to the parameters $\theta$ and $\phi$. | Why can we ignore missing data if it's missing at random? | In the context of regression analysis, all of our inferences are conditional on the explanatory variables. Consequently, if the missingness is random when conditioning on these explanatory variables | Why can we ignore missing data if it's missing at random?
In the context of regression analysis, all of our inferences are conditional on the explanatory variables. Consequently, if the missingness is random when conditioning on these explanatory variables (which is the case for MAR) this is sufficient to ensure that estimators retain the properties they would usually have under MCAR. The basic intuition for this is that if the missingness distribution only depends on the explanatory variables then it is essentially "fixed" when we condition on these variables.
The theory of missingness is usually shown in a more generalised setting than linear regression, and its main theorems are usually established directly with respect to the likelihood function in a highly general form of analysis. A good expository paper on the concept (with theorems and proofs) is Seaman et al (2013) (version without paywall here). Below I will adapt some material from this paper to show how MAR works in the context of regression analysis. This will show that ---under the assumption of MAR--- the likelihood function for the regression parameters is proportionate to the version that "ignores" the missingness mechanism.
Setting up the problem: Consider a problem involving a set of values $(\mathbf{x}_1, \mathbf{y}_1),...,(\mathbf{x}_n, \mathbf{y}_n)$ where the conditional distribution for $\mathbf{y}|\mathbf{x}$ uses the density $f_\theta$ which depends on a parameter $\theta$. Suppose we observe this process subject to MAR with missingness indicators $\mathbf{m}_1,...,\mathbf{m}_n$ that have a conditional distribution that uses the density $g_\phi$ that depends on a parameter $\phi$. Since the sampling and missingness determine the observed outcomes, there is a mapping $H$ from any vectors of explanatory and response variables and any vector of corresponding missingness indicators to the observed vectors of explanatory and response variables.
To facilitate our analysis, let $\mathbf{x}_*$ and $\mathbf{y}_*$ denote the actual vectors of explanatory and response variables and let $\mathbf{m}_*$ denote the missingness vector that leads to the observed values. Then let $\mathbf{x}_\text{obs}$ and $\mathbf{y}_\text{obs}$ denote the observed vectors of explanatory and response variables. These latter vectors are obtained by:
$$(\mathbf{x}_\text{obs}, \mathbf{y}_\text{obs}) = H(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*).$$
Without loss of generality, we will suppose that there are $k = n-\sum_i m_{*i}$ observed values in the observe vectors and $n-k = \sum_i m_{*i}$ missing values that do not appear in these vectors.
Likelihood analysis: If we were to ignore the missingness mechanism in the sampling method, and just treat this as if we sampled the observed outcomes at random without any missing data, our likelihood function for inferences about $\theta$ would be:
$$L_{\mathbf{x}_\text{obs}, \mathbf{y}_\text{obs}}(\theta) = \prod_{i=1}^k f_\theta(\mathbf{y}_{\text{obs}, i}|\mathbf{x}_{\text{obs}, i}).$$
However, with the missingness mechanism the actual likelihood function is:
$$\tilde{L}_{\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*}(\theta, \phi)
= \int \limits_{\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)} \bigg( \prod_{i=1}^n f_\theta(\mathbf{y}_i|\mathbf{x}_{*i})^{1-m_{*i}} \bigg) \cdot g_\phi(\mathbf{m}_*|\mathbf{x}_*, \mathbf{y}) \ d \mathbf{y},$$
where we define the space $\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)
\equiv \{ \mathbf{y} | H(\mathbf{x}_*, \mathbf{y}, \mathbf{m}_*) = H(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*) \}$.
Now, obviously these are very different likelihood functions. However, if missingness-at-random (MAR) holds then the distribution of the missingness vector depends on $(\mathbf{x},\mathbf{y})$ only through $\mathbf{x}$. Under this assumption we have $g_\phi(\mathbf{m}|\mathbf{x}, \mathbf{y}) = g_\phi(\mathbf{m}|\mathbf{x})$ for all $\mathbf{x},\mathbf{y},\mathbf{m}$, which then gives:
$$\begin{align}
\tilde{L}_{\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*}(\theta, \phi)
&= \int \limits_{\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)} \bigg( \prod_{i=1}^n f_\theta(\mathbf{y}_i|\mathbf{x}_{*i})^{1-m_{*i}} \bigg) \cdot g_\phi(\mathbf{m}_*|\mathbf{x}_*, \mathbf{y}) \ d \mathbf{y} \\[6pt]
&= g_\phi(\mathbf{m}_*|\mathbf{x}_*) \int \limits_{\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)}\bigg( \prod_{i=1}^n f_\theta(\mathbf{y}_i|\mathbf{x}_{*i})^{1-m_{*i}} \bigg) \ d \mathbf{y} \\[6pt]
&= g_\phi(\mathbf{m}_*|\mathbf{x}_*) \int \limits_{\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)}\bigg( \prod_{i=1}^k f_\theta(\mathbf{y}_{\text{obs}, i}|\mathbf{x}_{\text{obs}, i}) \bigg) \ d \mathbf{y} \\[6pt]
&= g_\phi(\mathbf{m}_*|\mathbf{x}) \cdot \bigg( \prod_{i=1}^k f_\theta(\mathbf{y}_{\text{obs}, i}|\mathbf{x}_{\text{obs}, i}) \bigg) \cdot |\mathscr{H}(\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*)| \\[6pt]
&\propto g_\phi(\mathbf{m}_*|\mathbf{x}) \cdot \bigg( \prod_{i=1}^k f_\theta(\mathbf{y}_{\text{obs}, i}|\mathbf{x}_{\text{obs}, i}) \bigg) \\[12pt]
&= g_\phi(\mathbf{m}_*|\mathbf{x}) \cdot L_{\mathbf{x}_\text{obs}, \mathbf{y}_\text{obs}}(\theta). \\[6pt]
\end{align}$$
If we are only concerned with making inferences about $\theta$ (i.e., if $\phi$ s a nuisance parameter) then we can make use of the fact that:
$$\tilde{L}_{\mathbf{x}_*, \mathbf{y}_*, \mathbf{m}_*}(\theta, \phi) \overset{\theta}{\propto} L_{\mathbf{x}_\text{obs}, \mathbf{y}_\text{obs}}(\theta).$$
As you can see, this means that the true likelihood/profile likelihood function for the paramater $\theta$ (the one that does not ignore the missingness mechanism) is proportionate to the sipler likelihood function obtained by ignoring the missingness mechanism. If you look through the mathematics above you will see that this occurs because the equation $g_\phi(\mathbf{m}|\mathbf{x}, \mathbf{y}) = g_\phi(\mathbf{m}|\mathbf{x})$ allows us to "separate" this part from the part that depends on $\theta$ ---i.e., the MAR assumption makes the true likelihood function "seperable" with respect to the parameters $\theta$ and $\phi$. | Why can we ignore missing data if it's missing at random?
In the context of regression analysis, all of our inferences are conditional on the explanatory variables. Consequently, if the missingness is random when conditioning on these explanatory variables |
34,100 | Why can we ignore missing data if it's missing at random? | Maybe a couple of examples will help convince you.
(1) Suppose I have a random sample of size $m = 50$ from the distribution $\mathsf{Binom}(n = 10, p = .8)$ with $\mu = 8.$
set.seed(2022) # for reproducibility
x = rbinom(50, 10, 0.8); x
[1] 7 8 9 8 9 8 10 10 9 7
[11] 10 9 9 8 8 9 7 8 8 7
[21] 7 8 8 9 9 6 8 4 8 7
[31] 8 8 9 8 9 10 7 8 7 7
[41] 8 8 8 8 7 10 6 8 9 7
The sample mean is $\bar X = 8.04,$ reasonably
close to $\mu = 8.$
mean(x)
[1] 8.04
Now, I sample indexes of four values at random to be 'missing'. The respective observations are $7, 9, 8, 7.$
sample(1:50, 4)
20 5 32 37
The mean of the remaining (non-missing) 46 observations
is $8.0652,$ which is not much different from
the mean $8.04$ of all 50 observations.
(sum(x) - 7 - 9 - 8 - 7)/46
[1] 8.065217
This is really too small a sample for a guaranteed
good example, especially with a relatively large
proportion (4 of 50) missing, but it worked pretty well.
(2) Suppose I have 1000 observations from $\mathsf{Norm}(100, 15)$ and randomly get rid of
50 observations.
This time I will randomize the order of the observations and leave off the last 50, because it would
be impractical to show 1000 observations.
I'll also
show that a few observations missing at random
doesn't change the standard deviation by much.
set.seed(1234)
y = sample(rnorm(1000, 100, 15)) # scranble
mean(y); mean(y[1:950])
[1] 99.60104 # mean of all 1000
[1] 99.71998 # mean with 50 missing @ rand
sd(y); sd(y[1:950])
[1] 14.96007 # SD of all 1000
[1] 14.86055 # SD with 50 missing @ rand
Boxplots of the entire sample (bottom) and of the sample with 50 missing observations look much the same.
boxplot(y, y[1:950], horizontal=T, col="skyblue2")
Note: By contrast, if I delete observations above 124, instead of deleting at random, then it makes a larger difference in means, SDs, and the appearance of the boxplot. The at random part of "missing at random" is crucial.
mean(y); mean(y[y<124])
[1] 99.60104
[1] 97.6231
sd(y); sd(y[y<124])
[1] 14.96007
[1] 13.17083 | Why can we ignore missing data if it's missing at random? | Maybe a couple of examples will help convince you.
(1) Suppose I have a random sample of size $m = 50$ from the distribution $\mathsf{Binom}(n = 10, p = .8)$ with $\mu = 8.$
set.seed(2022) # for repr | Why can we ignore missing data if it's missing at random?
Maybe a couple of examples will help convince you.
(1) Suppose I have a random sample of size $m = 50$ from the distribution $\mathsf{Binom}(n = 10, p = .8)$ with $\mu = 8.$
set.seed(2022) # for reproducibility
x = rbinom(50, 10, 0.8); x
[1] 7 8 9 8 9 8 10 10 9 7
[11] 10 9 9 8 8 9 7 8 8 7
[21] 7 8 8 9 9 6 8 4 8 7
[31] 8 8 9 8 9 10 7 8 7 7
[41] 8 8 8 8 7 10 6 8 9 7
The sample mean is $\bar X = 8.04,$ reasonably
close to $\mu = 8.$
mean(x)
[1] 8.04
Now, I sample indexes of four values at random to be 'missing'. The respective observations are $7, 9, 8, 7.$
sample(1:50, 4)
20 5 32 37
The mean of the remaining (non-missing) 46 observations
is $8.0652,$ which is not much different from
the mean $8.04$ of all 50 observations.
(sum(x) - 7 - 9 - 8 - 7)/46
[1] 8.065217
This is really too small a sample for a guaranteed
good example, especially with a relatively large
proportion (4 of 50) missing, but it worked pretty well.
(2) Suppose I have 1000 observations from $\mathsf{Norm}(100, 15)$ and randomly get rid of
50 observations.
This time I will randomize the order of the observations and leave off the last 50, because it would
be impractical to show 1000 observations.
I'll also
show that a few observations missing at random
doesn't change the standard deviation by much.
set.seed(1234)
y = sample(rnorm(1000, 100, 15)) # scranble
mean(y); mean(y[1:950])
[1] 99.60104 # mean of all 1000
[1] 99.71998 # mean with 50 missing @ rand
sd(y); sd(y[1:950])
[1] 14.96007 # SD of all 1000
[1] 14.86055 # SD with 50 missing @ rand
Boxplots of the entire sample (bottom) and of the sample with 50 missing observations look much the same.
boxplot(y, y[1:950], horizontal=T, col="skyblue2")
Note: By contrast, if I delete observations above 124, instead of deleting at random, then it makes a larger difference in means, SDs, and the appearance of the boxplot. The at random part of "missing at random" is crucial.
mean(y); mean(y[y<124])
[1] 99.60104
[1] 97.6231
sd(y); sd(y[y<124])
[1] 14.96007
[1] 13.17083 | Why can we ignore missing data if it's missing at random?
Maybe a couple of examples will help convince you.
(1) Suppose I have a random sample of size $m = 50$ from the distribution $\mathsf{Binom}(n = 10, p = .8)$ with $\mu = 8.$
set.seed(2022) # for repr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.