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
15,301
Can someone please explain dynamic time warping for determining time series similarity?
Dynamic time warping makes a particular assumption on your data set: one vector is a non-linear time-streteched series of the other. But it also assumes that the actual values are on the same scale. Lets say you have: $x=1..10000$, $a(x)=1\cdot\sin(0.01*x)$, $b(x)=1\cdot\sin(0.01234*x)$,$c(x)=1000\cdot\sin(0.01*x)$. Then for DTW, $a$ and $b$ will be extremely similar, while $a$ and $c$ differ almost as much as with Manhattan distance. If you however do a frequency analysis, $a$ and $c$ will be identical with respect to their frequencies, and only differ in magnitude, while $a$ and $b$ have a clearly different frequency. DTW is not your magic weapon to solve all your time series matching needs. It makes particular assumptions on the kind of similarity you are interested in. If that doesn't match your data, it will not work well. Judging from the data series you shared, you do not need temporal alignment (which DTW does), but actually some appropriate normalization and maybe fourier transformations instead. Treshhold crossing distances might also work well for you, see for example: Similarity Search on Time Series Based on Threshold Queries Johannes Aßfalg, Hans-Peter Kriegel, Peer Kröger, Peter Kunath, Alexey Pryakhin and Matthias Renz, EDBT 2006
Can someone please explain dynamic time warping for determining time series similarity?
Dynamic time warping makes a particular assumption on your data set: one vector is a non-linear time-streteched series of the other. But it also assumes that the actual values are on the same scale. L
Can someone please explain dynamic time warping for determining time series similarity? Dynamic time warping makes a particular assumption on your data set: one vector is a non-linear time-streteched series of the other. But it also assumes that the actual values are on the same scale. Lets say you have: $x=1..10000$, $a(x)=1\cdot\sin(0.01*x)$, $b(x)=1\cdot\sin(0.01234*x)$,$c(x)=1000\cdot\sin(0.01*x)$. Then for DTW, $a$ and $b$ will be extremely similar, while $a$ and $c$ differ almost as much as with Manhattan distance. If you however do a frequency analysis, $a$ and $c$ will be identical with respect to their frequencies, and only differ in magnitude, while $a$ and $b$ have a clearly different frequency. DTW is not your magic weapon to solve all your time series matching needs. It makes particular assumptions on the kind of similarity you are interested in. If that doesn't match your data, it will not work well. Judging from the data series you shared, you do not need temporal alignment (which DTW does), but actually some appropriate normalization and maybe fourier transformations instead. Treshhold crossing distances might also work well for you, see for example: Similarity Search on Time Series Based on Threshold Queries Johannes Aßfalg, Hans-Peter Kriegel, Peer Kröger, Peter Kunath, Alexey Pryakhin and Matthias Renz, EDBT 2006
Can someone please explain dynamic time warping for determining time series similarity? Dynamic time warping makes a particular assumption on your data set: one vector is a non-linear time-streteched series of the other. But it also assumes that the actual values are on the same scale. L
15,302
Can someone please explain dynamic time warping for determining time series similarity?
First, you say "dynamic time warping metric", however DTW is a distance measure, but not a metric (it does not obey the triangular inequality). Paper [a] compares DTW to 12 alternatives on 43 datasets, DTW really does work very well for most problems. If you want to learn more about DTW, you could glance at Keoghs tutorial http://www.cs.ucr.edu/~eamonn/Keogh_Time_Series_CDrom.zip (warning 500 meg) The pass is peggy. There is also a tutorial on SAX http://www.cs.ucr.edu/~eamonn/SIGKDD_2007.ppt [a] Xiaoyue Wang, Hui Ding, Goce Trajcevski, Peter Scheuermann, Eamonn J. Keogh: Experimental Comparison of Representation Methods and Distance Measures for Time Series Data CoRR abs/1012.2789: (2010)
Can someone please explain dynamic time warping for determining time series similarity?
First, you say "dynamic time warping metric", however DTW is a distance measure, but not a metric (it does not obey the triangular inequality). Paper [a] compares DTW to 12 alternatives on 43 datasets
Can someone please explain dynamic time warping for determining time series similarity? First, you say "dynamic time warping metric", however DTW is a distance measure, but not a metric (it does not obey the triangular inequality). Paper [a] compares DTW to 12 alternatives on 43 datasets, DTW really does work very well for most problems. If you want to learn more about DTW, you could glance at Keoghs tutorial http://www.cs.ucr.edu/~eamonn/Keogh_Time_Series_CDrom.zip (warning 500 meg) The pass is peggy. There is also a tutorial on SAX http://www.cs.ucr.edu/~eamonn/SIGKDD_2007.ppt [a] Xiaoyue Wang, Hui Ding, Goce Trajcevski, Peter Scheuermann, Eamonn J. Keogh: Experimental Comparison of Representation Methods and Distance Measures for Time Series Data CoRR abs/1012.2789: (2010)
Can someone please explain dynamic time warping for determining time series similarity? First, you say "dynamic time warping metric", however DTW is a distance measure, but not a metric (it does not obey the triangular inequality). Paper [a] compares DTW to 12 alternatives on 43 datasets
15,303
Can someone please explain dynamic time warping for determining time series similarity?
In the 1980s dynamic time warping was the method used for template matching in speech recognition. The aim was to try to match time series of analyzed speech to stored templates, usually of whole words. The difficulty is people speak at different rates. DTW was used to register the unknown pattern to the template. It was called "rubber sheet" matching. Basically you search through some constrained possibilities of how the time series can locally be stretched to optimize the global fit. This approach was shown to be pretty much the same thing as hidden Markov models.
Can someone please explain dynamic time warping for determining time series similarity?
In the 1980s dynamic time warping was the method used for template matching in speech recognition. The aim was to try to match time series of analyzed speech to stored templates, usually of whole word
Can someone please explain dynamic time warping for determining time series similarity? In the 1980s dynamic time warping was the method used for template matching in speech recognition. The aim was to try to match time series of analyzed speech to stored templates, usually of whole words. The difficulty is people speak at different rates. DTW was used to register the unknown pattern to the template. It was called "rubber sheet" matching. Basically you search through some constrained possibilities of how the time series can locally be stretched to optimize the global fit. This approach was shown to be pretty much the same thing as hidden Markov models.
Can someone please explain dynamic time warping for determining time series similarity? In the 1980s dynamic time warping was the method used for template matching in speech recognition. The aim was to try to match time series of analyzed speech to stored templates, usually of whole word
15,304
Why does chi-square testing use the expected count as the variance?
The general form for many test statistics is $\frac{observed - expected}{standard error}$ In the case of a normal variable the standard error is based on either the known population variance (z-stats) or the estimate from the sample (t-stats). With the binomial the standard error is based on the proportion (hypothesized proportion for tests). In a contingency table the count in each cell can be thought of as coming from a Poisson distribution with a mean equal to the expected value (under the null). The variance for the Poisson distribution is equal to the mean, so we use the expected value for the standard error calculation as well. I have seen a statistic that uses the observed instead, but it has less theoretical justification and does not converge as well to the $\chi^2$ distribution.
Why does chi-square testing use the expected count as the variance?
The general form for many test statistics is $\frac{observed - expected}{standard error}$ In the case of a normal variable the standard error is based on either the known population variance (z-stats
Why does chi-square testing use the expected count as the variance? The general form for many test statistics is $\frac{observed - expected}{standard error}$ In the case of a normal variable the standard error is based on either the known population variance (z-stats) or the estimate from the sample (t-stats). With the binomial the standard error is based on the proportion (hypothesized proportion for tests). In a contingency table the count in each cell can be thought of as coming from a Poisson distribution with a mean equal to the expected value (under the null). The variance for the Poisson distribution is equal to the mean, so we use the expected value for the standard error calculation as well. I have seen a statistic that uses the observed instead, but it has less theoretical justification and does not converge as well to the $\chi^2$ distribution.
Why does chi-square testing use the expected count as the variance? The general form for many test statistics is $\frac{observed - expected}{standard error}$ In the case of a normal variable the standard error is based on either the known population variance (z-stats
15,305
Why does chi-square testing use the expected count as the variance?
Let's handle the simplest case to try to provide the most intuition. Let $X_1, X_2, \ldots, X_n$ be an iid sample from a discrete distribution with $k$ outcomes. Let $\pi_1,\ldots,\pi_k$ be the probabilities of each particular outcome. We are interested in the (asymptotic) distribution of the chi-squared statistic $$ X^2 = \sum_{i=1}^k \frac{(S_i - n \pi_i)^2}{n\pi_i} \> . $$ Here $n \pi_i$ is the expected number of counts of the $i$th outcome. A suggestive heuristic Define $U_i = (S_i - n\pi_i) / \sqrt{n \pi_i}$, so that $X^2 = \sum_i U_i^2 = \newcommand{\U}{\mathbf{U}}\|\U\|^2_2$ where $\U = (U_1,\ldots,U_k)$. Since $S_i$ is $\mathrm{Bin}(n,\pi_i)$, then by the Central Limit Theorem, $$ \newcommand{\convd}{\xrightarrow{d}}\newcommand{\N}{\mathcal{N}} T_i = \frac{U_i}{\sqrt{1-\pi_i}} = \frac{S_i - n \pi_i}{\sqrt{ n\pi_i(1-\pi_i)}} \convd \N(0, 1) \>, $$ hence, we also have that, $U_i \convd \N(0, 1-\pi_i)$. Now, if the $T_i$ were (asymptotically) independent (which they aren't), then we could argue that $\sum_i T_i^2$ was asymptotically $\chi_k^2$ distributed. But, note that $T_k$ is a deterministic function of $(T_1,\ldots,T_{k-1})$ and so the $T_i$ variables can't possibly be independent. Hence, we must take into account the covariance between them somehow. It turns out that the "correct" way to do this is to use the $U_i$ instead, and the covariance between the components of $\U$ also changes the asymptotic distribution from what we might have thought was $\chi_{k}^2$ to what is, in fact, a $\chi_{k-1}^2$. Some details on this follow. A more rigorous treatment It is not hard to check that, in fact, $\newcommand{\Cov}{\mathrm{Cov}}\Cov(U_i, U_j) = - \sqrt{\pi_i \pi_j}$ for $i \neq j$. So, the covariance of $\U$ is $$ \newcommand{\sqpi}{\sqrt{\boldsymbol{\pi}}} \newcommand{\A}{\mathbf{A}} \A = \mathbf{I} - \sqpi \sqpi^T \>, $$ where $\sqpi = (\sqrt{\pi_1}, \ldots, \sqrt{\pi_k})$. Note that $\A$ is symmetric and idempotent, i.e., $\A = \A^2 = \A^T$. So, in particular, if $\newcommand{\Z}{\mathbf{Z}}\Z = (Z_1, \ldots, Z_k)$ has iid standard normal components, then $\A \Z \sim \N(0, \A)$. (NB The multivariate normal distribution in this case is degenerate.) Now, by the Multivariate Central Limit Theorem, the vector $\U$ has an asymptotic multivariate normal distribution with mean $0$ and covariance $\A$. So, $\U$ has the same asymptotic distribution as $\A \Z$, hence, the same asymptotic distribution of $X^2 = \U^T \U$ is the same as the distribution of $\Z^T \A^T \A \Z = \Z^T \A \Z$ by the continuous mapping theorem. But, $\A$ is symmetric and idempotent, so (a) it has orthogonal eigenvectors, (b) all of its eigenvalues are 0 or 1, and (c) the multiplicity of the eigenvalue of 1 is $\mathrm{rank}(\A)$. This means that $\A$ can be decomposed as $\A = \mathbf{Q D Q}^T$ where $\mathbf{Q}$ is orthogonal and $\mathbf{D}$ is a diagonal matrix with $\mathrm{rank}(\A)$ ones on the diagonal and the remaining diagonal entries being zero. Thus, $\Z^T \A \Z$ must be $\chi^2_{k-1}$ distributed since $\A$ has rank $k-1$ in our case. Other connections The chi-square statistic is also closely related to likelihood ratio statistics. Indeed, it is a Rao score statistic and can be viewed as a Taylor-series approximation of the likelihood ratio statistic. References This is my own development based on experience, but obviously influenced by classical texts. Good places to look to learn more are G. A. F. Seber and A. J. Lee (2003), Linear Regression Analysis, 2nd ed., Wiley. E. Lehmann and J. Romano (2005), Testing Statistical Hypotheses, 3rd ed., Springer. Section 14.3 in particular. D. R. Cox and D. V. Hinkley (1979), Theoretical Statistics, Chapman and Hall.
Why does chi-square testing use the expected count as the variance?
Let's handle the simplest case to try to provide the most intuition. Let $X_1, X_2, \ldots, X_n$ be an iid sample from a discrete distribution with $k$ outcomes. Let $\pi_1,\ldots,\pi_k$ be the probab
Why does chi-square testing use the expected count as the variance? Let's handle the simplest case to try to provide the most intuition. Let $X_1, X_2, \ldots, X_n$ be an iid sample from a discrete distribution with $k$ outcomes. Let $\pi_1,\ldots,\pi_k$ be the probabilities of each particular outcome. We are interested in the (asymptotic) distribution of the chi-squared statistic $$ X^2 = \sum_{i=1}^k \frac{(S_i - n \pi_i)^2}{n\pi_i} \> . $$ Here $n \pi_i$ is the expected number of counts of the $i$th outcome. A suggestive heuristic Define $U_i = (S_i - n\pi_i) / \sqrt{n \pi_i}$, so that $X^2 = \sum_i U_i^2 = \newcommand{\U}{\mathbf{U}}\|\U\|^2_2$ where $\U = (U_1,\ldots,U_k)$. Since $S_i$ is $\mathrm{Bin}(n,\pi_i)$, then by the Central Limit Theorem, $$ \newcommand{\convd}{\xrightarrow{d}}\newcommand{\N}{\mathcal{N}} T_i = \frac{U_i}{\sqrt{1-\pi_i}} = \frac{S_i - n \pi_i}{\sqrt{ n\pi_i(1-\pi_i)}} \convd \N(0, 1) \>, $$ hence, we also have that, $U_i \convd \N(0, 1-\pi_i)$. Now, if the $T_i$ were (asymptotically) independent (which they aren't), then we could argue that $\sum_i T_i^2$ was asymptotically $\chi_k^2$ distributed. But, note that $T_k$ is a deterministic function of $(T_1,\ldots,T_{k-1})$ and so the $T_i$ variables can't possibly be independent. Hence, we must take into account the covariance between them somehow. It turns out that the "correct" way to do this is to use the $U_i$ instead, and the covariance between the components of $\U$ also changes the asymptotic distribution from what we might have thought was $\chi_{k}^2$ to what is, in fact, a $\chi_{k-1}^2$. Some details on this follow. A more rigorous treatment It is not hard to check that, in fact, $\newcommand{\Cov}{\mathrm{Cov}}\Cov(U_i, U_j) = - \sqrt{\pi_i \pi_j}$ for $i \neq j$. So, the covariance of $\U$ is $$ \newcommand{\sqpi}{\sqrt{\boldsymbol{\pi}}} \newcommand{\A}{\mathbf{A}} \A = \mathbf{I} - \sqpi \sqpi^T \>, $$ where $\sqpi = (\sqrt{\pi_1}, \ldots, \sqrt{\pi_k})$. Note that $\A$ is symmetric and idempotent, i.e., $\A = \A^2 = \A^T$. So, in particular, if $\newcommand{\Z}{\mathbf{Z}}\Z = (Z_1, \ldots, Z_k)$ has iid standard normal components, then $\A \Z \sim \N(0, \A)$. (NB The multivariate normal distribution in this case is degenerate.) Now, by the Multivariate Central Limit Theorem, the vector $\U$ has an asymptotic multivariate normal distribution with mean $0$ and covariance $\A$. So, $\U$ has the same asymptotic distribution as $\A \Z$, hence, the same asymptotic distribution of $X^2 = \U^T \U$ is the same as the distribution of $\Z^T \A^T \A \Z = \Z^T \A \Z$ by the continuous mapping theorem. But, $\A$ is symmetric and idempotent, so (a) it has orthogonal eigenvectors, (b) all of its eigenvalues are 0 or 1, and (c) the multiplicity of the eigenvalue of 1 is $\mathrm{rank}(\A)$. This means that $\A$ can be decomposed as $\A = \mathbf{Q D Q}^T$ where $\mathbf{Q}$ is orthogonal and $\mathbf{D}$ is a diagonal matrix with $\mathrm{rank}(\A)$ ones on the diagonal and the remaining diagonal entries being zero. Thus, $\Z^T \A \Z$ must be $\chi^2_{k-1}$ distributed since $\A$ has rank $k-1$ in our case. Other connections The chi-square statistic is also closely related to likelihood ratio statistics. Indeed, it is a Rao score statistic and can be viewed as a Taylor-series approximation of the likelihood ratio statistic. References This is my own development based on experience, but obviously influenced by classical texts. Good places to look to learn more are G. A. F. Seber and A. J. Lee (2003), Linear Regression Analysis, 2nd ed., Wiley. E. Lehmann and J. Romano (2005), Testing Statistical Hypotheses, 3rd ed., Springer. Section 14.3 in particular. D. R. Cox and D. V. Hinkley (1979), Theoretical Statistics, Chapman and Hall.
Why does chi-square testing use the expected count as the variance? Let's handle the simplest case to try to provide the most intuition. Let $X_1, X_2, \ldots, X_n$ be an iid sample from a discrete distribution with $k$ outcomes. Let $\pi_1,\ldots,\pi_k$ be the probab
15,306
Why does chi-square testing use the expected count as the variance?
Why does chi-square testing use the expected count as the variance? You can make the jump from standardized residuals$$\epsilon_i = \frac{O_i-E_i}{\sqrt{N(E_i/N)(1-E_i/N)}}$$ to the terms as used in the $\chi^2$ expression $$x_i = \frac{O_i-E_i}{\sqrt{E_i}}$$ This is the topic of the question Obtaining the chi-squared test statistic via geometry and the approach by the answer from Aksakal and the article by Pearson from 1900. However, it might be easier to imagine the multinomial distribution as the joint distribution of Poisson distributed variables, $O_i \sim Poisson(Np_i)$, constrained by the total sum, $T = \sum_i O_i \sim Poisson(N)$ being equal to $N$. The unconstrained joint distribution is $$P(O_1=o_1,\dots,O_n=o_n) = \prod_{i=1}^n \frac{{(Np_i)}^{o_i} e^{-Np_i}}{o_i!}$$ and the constrained distribution is $$\begin{array}{} P(O_1=o_1,\dots,O_n=o_n| T=m)& = &\frac{P(O_1=o_1,\dots,O_n=o_n, T=N)}{P(T=N)} \\ &=& \frac{P(O_1=o_1,\dots,O_n=o_n)}{P(T=N)}\\& = &\frac{\prod_{i=1}^n \frac{{(Np_i)}^{o_i} e^{-Np_i}}{o_i!}}{\frac{{N}^{N} e^{-N}}{N!}} \\&=& \frac{N! }{\prod_{i=1}^n o_i!}\prod_{i=1}^n{p_i}^{o_i}\end{array}$$ When $N$ is large then we can approximate the Poisson distribution with a multivariate normal distribution with the same constraint. Following that we can normalize that multivariate normal distribution by using the divisions with $\sqrt{E_i}$ (which are not standard deviations of the multinomial distribution but they are the standard deviations of the joint Poisson distribution) The divisions with $\sqrt{E_i}$ changes the constraint $\sum_i O_i = N$ into a different (but still linear) constraint $\sum_i x_i \sqrt{E_i} = \sum_i O_i - E_i = 0$. The standardized multivariate normal distribution is spherically symmetric and the constraint $\sum_i x_i \sqrt{E_i} = 0$ is similar to constraining only a single variable. The distribution of the sum of squares of the remaining $n-1$ variables is $\chi^2$ distributed with $n-1$ degrees of freedom. Isn't the variance here clearly not simply the expected value? As a simple illustration of my confusion, what if we were testing whether two processes are significantly different, one that generates 500 As and 500 Bs with very small variance, and the other that generates 550 As and 450 Bs with very small variance (rarely generating 551 As and 449 Bs)? Isn't the variance here clearly not simply the expected value? The chi-squared test refers to multinomial distributed data or to count data, where each event, a specific count falling into a specific bin, is independent from the others. A process that generates these large numbers with such small variance, is likely a different type of process and the chi-squared test is not applicable. For the Poisson distribution and the Binomial/multinomial distribution, the mean and the variance are related and both can be estimated with a single observed count variable. With other distributions this is not the case and you need several observations from which you can estimate the variance.
Why does chi-square testing use the expected count as the variance?
Why does chi-square testing use the expected count as the variance? You can make the jump from standardized residuals$$\epsilon_i = \frac{O_i-E_i}{\sqrt{N(E_i/N)(1-E_i/N)}}$$ to the terms as used in t
Why does chi-square testing use the expected count as the variance? Why does chi-square testing use the expected count as the variance? You can make the jump from standardized residuals$$\epsilon_i = \frac{O_i-E_i}{\sqrt{N(E_i/N)(1-E_i/N)}}$$ to the terms as used in the $\chi^2$ expression $$x_i = \frac{O_i-E_i}{\sqrt{E_i}}$$ This is the topic of the question Obtaining the chi-squared test statistic via geometry and the approach by the answer from Aksakal and the article by Pearson from 1900. However, it might be easier to imagine the multinomial distribution as the joint distribution of Poisson distributed variables, $O_i \sim Poisson(Np_i)$, constrained by the total sum, $T = \sum_i O_i \sim Poisson(N)$ being equal to $N$. The unconstrained joint distribution is $$P(O_1=o_1,\dots,O_n=o_n) = \prod_{i=1}^n \frac{{(Np_i)}^{o_i} e^{-Np_i}}{o_i!}$$ and the constrained distribution is $$\begin{array}{} P(O_1=o_1,\dots,O_n=o_n| T=m)& = &\frac{P(O_1=o_1,\dots,O_n=o_n, T=N)}{P(T=N)} \\ &=& \frac{P(O_1=o_1,\dots,O_n=o_n)}{P(T=N)}\\& = &\frac{\prod_{i=1}^n \frac{{(Np_i)}^{o_i} e^{-Np_i}}{o_i!}}{\frac{{N}^{N} e^{-N}}{N!}} \\&=& \frac{N! }{\prod_{i=1}^n o_i!}\prod_{i=1}^n{p_i}^{o_i}\end{array}$$ When $N$ is large then we can approximate the Poisson distribution with a multivariate normal distribution with the same constraint. Following that we can normalize that multivariate normal distribution by using the divisions with $\sqrt{E_i}$ (which are not standard deviations of the multinomial distribution but they are the standard deviations of the joint Poisson distribution) The divisions with $\sqrt{E_i}$ changes the constraint $\sum_i O_i = N$ into a different (but still linear) constraint $\sum_i x_i \sqrt{E_i} = \sum_i O_i - E_i = 0$. The standardized multivariate normal distribution is spherically symmetric and the constraint $\sum_i x_i \sqrt{E_i} = 0$ is similar to constraining only a single variable. The distribution of the sum of squares of the remaining $n-1$ variables is $\chi^2$ distributed with $n-1$ degrees of freedom. Isn't the variance here clearly not simply the expected value? As a simple illustration of my confusion, what if we were testing whether two processes are significantly different, one that generates 500 As and 500 Bs with very small variance, and the other that generates 550 As and 450 Bs with very small variance (rarely generating 551 As and 449 Bs)? Isn't the variance here clearly not simply the expected value? The chi-squared test refers to multinomial distributed data or to count data, where each event, a specific count falling into a specific bin, is independent from the others. A process that generates these large numbers with such small variance, is likely a different type of process and the chi-squared test is not applicable. For the Poisson distribution and the Binomial/multinomial distribution, the mean and the variance are related and both can be estimated with a single observed count variable. With other distributions this is not the case and you need several observations from which you can estimate the variance.
Why does chi-square testing use the expected count as the variance? Why does chi-square testing use the expected count as the variance? You can make the jump from standardized residuals$$\epsilon_i = \frac{O_i-E_i}{\sqrt{N(E_i/N)(1-E_i/N)}}$$ to the terms as used in t
15,307
Conjoint Packages for R
I've never used R for conjoint analysis, but here are a couple of things I found when I hunted around. Aizaki and Nishimura (2008) have an article "Design and Analysis of Choice Experiments Using R: A brief introduction" (Free PDF available here). Perhaps check out the following packages: AlgDesign for constructing choice sets prefmod for analysing paired comparison data conf.design for constructing factorial designs
Conjoint Packages for R
I've never used R for conjoint analysis, but here are a couple of things I found when I hunted around. Aizaki and Nishimura (2008) have an article "Design and Analysis of Choice Experiments Using R:
Conjoint Packages for R I've never used R for conjoint analysis, but here are a couple of things I found when I hunted around. Aizaki and Nishimura (2008) have an article "Design and Analysis of Choice Experiments Using R: A brief introduction" (Free PDF available here). Perhaps check out the following packages: AlgDesign for constructing choice sets prefmod for analysing paired comparison data conf.design for constructing factorial designs
Conjoint Packages for R I've never used R for conjoint analysis, but here are a couple of things I found when I hunted around. Aizaki and Nishimura (2008) have an article "Design and Analysis of Choice Experiments Using R:
15,308
Conjoint Packages for R
mlogit is the best R package I've found for modelling discrete choice data. It supports the basic multinomial logit, as well as more advanced models such as multinomial probit and mixed logit. The package also includes specification tests to choose between different models.
Conjoint Packages for R
mlogit is the best R package I've found for modelling discrete choice data. It supports the basic multinomial logit, as well as more advanced models such as multinomial probit and mixed logit. The p
Conjoint Packages for R mlogit is the best R package I've found for modelling discrete choice data. It supports the basic multinomial logit, as well as more advanced models such as multinomial probit and mixed logit. The package also includes specification tests to choose between different models.
Conjoint Packages for R mlogit is the best R package I've found for modelling discrete choice data. It supports the basic multinomial logit, as well as more advanced models such as multinomial probit and mixed logit. The p
15,309
Conjoint Packages for R
You may want to use faisalconjoint package in R, it is tested with many published and research data, it works perfectly, one on important thing its works without design restriction and rank procedure. It works in all condition and provide accurate estimates.
Conjoint Packages for R
You may want to use faisalconjoint package in R, it is tested with many published and research data, it works perfectly, one on important thing its works without design restriction and rank procedure.
Conjoint Packages for R You may want to use faisalconjoint package in R, it is tested with many published and research data, it works perfectly, one on important thing its works without design restriction and rank procedure. It works in all condition and provide accurate estimates.
Conjoint Packages for R You may want to use faisalconjoint package in R, it is tested with many published and research data, it works perfectly, one on important thing its works without design restriction and rank procedure.
15,310
Conjoint Packages for R
The best in my opinion for R is a conjoint package from CRAN: http://cran.r-project.org/web/packages/conjoint/index.html
Conjoint Packages for R
The best in my opinion for R is a conjoint package from CRAN: http://cran.r-project.org/web/packages/conjoint/index.html
Conjoint Packages for R The best in my opinion for R is a conjoint package from CRAN: http://cran.r-project.org/web/packages/conjoint/index.html
Conjoint Packages for R The best in my opinion for R is a conjoint package from CRAN: http://cran.r-project.org/web/packages/conjoint/index.html
15,311
Conjoint Packages for R
If you are looking for models other than logit, you can use 'survival' package to build conditional multinomial logit model. you can use 'bayesm' package to build hierarchical bayesian(HB) model. Sawtoothsoftware asked the guy who created this package to help them build HB model in their software.
Conjoint Packages for R
If you are looking for models other than logit, you can use 'survival' package to build conditional multinomial logit model. you can use 'bayesm' package to build hierarchical bayesian(HB) model. Sa
Conjoint Packages for R If you are looking for models other than logit, you can use 'survival' package to build conditional multinomial logit model. you can use 'bayesm' package to build hierarchical bayesian(HB) model. Sawtoothsoftware asked the guy who created this package to help them build HB model in their software.
Conjoint Packages for R If you are looking for models other than logit, you can use 'survival' package to build conditional multinomial logit model. you can use 'bayesm' package to build hierarchical bayesian(HB) model. Sa
15,312
Conjoint Packages for R
Faisal Conjoint Model (FCM) is an integrated model of conjoint analysis and random utility models, developed by Faisal Afzal Sid- diqui, Ghulam Hussain, and Mudassir Uddin in 2012. Its algorithm was written in R statistical language and available in R [29]. Its design is independent of design structure. It could be used for any research design i.e. full pro le, orthogonal, factorial, supersaturated etc. Another important point about FCM is rank procedure. It works for every kind of ranks i.e. unique ranks, percentage ranks, tight ranks, missing ranks etc. It has been tested for many published data. Most of the times, FCM results are same with same magnitudes, often the rank
Conjoint Packages for R
Faisal Conjoint Model (FCM) is an integrated model of conjoint analysis and random utility models, developed by Faisal Afzal Sid- diqui, Ghulam Hussain, and Mudassir Uddin in 2012. Its algorithm was w
Conjoint Packages for R Faisal Conjoint Model (FCM) is an integrated model of conjoint analysis and random utility models, developed by Faisal Afzal Sid- diqui, Ghulam Hussain, and Mudassir Uddin in 2012. Its algorithm was written in R statistical language and available in R [29]. Its design is independent of design structure. It could be used for any research design i.e. full pro le, orthogonal, factorial, supersaturated etc. Another important point about FCM is rank procedure. It works for every kind of ranks i.e. unique ranks, percentage ranks, tight ranks, missing ranks etc. It has been tested for many published data. Most of the times, FCM results are same with same magnitudes, often the rank
Conjoint Packages for R Faisal Conjoint Model (FCM) is an integrated model of conjoint analysis and random utility models, developed by Faisal Afzal Sid- diqui, Ghulam Hussain, and Mudassir Uddin in 2012. Its algorithm was w
15,313
Conjoint Packages for R
There is a library 'Conjoint' with many features and sample to find utilities. For a quick preview check the link. This will help you get started. https://rpubs.com/haj3/conjoint
Conjoint Packages for R
There is a library 'Conjoint' with many features and sample to find utilities. For a quick preview check the link. This will help you get started. https://rpubs.com/haj3/conjoint
Conjoint Packages for R There is a library 'Conjoint' with many features and sample to find utilities. For a quick preview check the link. This will help you get started. https://rpubs.com/haj3/conjoint
Conjoint Packages for R There is a library 'Conjoint' with many features and sample to find utilities. For a quick preview check the link. This will help you get started. https://rpubs.com/haj3/conjoint
15,314
Conjoint Packages for R
For R: "survival" (clogit) for multinomial logit (MNL) model. "mlogit" for a wide range of models (MNL, nested logit, heteroscedastic logit, mixed logit (MXL) also known as random parameters logit, ...). In the same spirit you should take a look at "Rchoice" (file:///C:/Users/kruci/Downloads/v74i10.pdf). "bayesm" for bayesian version of MNL/MXL - However if you are interested in bayesian approach I would strongly recommand the great "RSGHB" package. "gmnl" for the generalised MNL model. "flexmix" for latent class logit (LCL) model. More generally it is important to keep in mind that choice models are a special case of multilevel (or hierarchical) models (you have choices nested within participants themselves nested within higher units: supermarkets, countries, etc.) - So everything that can be used for multilevel modelling (e.g., the great "lme4" package) and that can also accommodate the discrete nature of the choice variable would do the job. For example, you could use "lme4" if the choices are binary (Do you want this product? Yes/No) or made between 2 options (Which product do you want? A/B). With Stata, you have many commands useful for choice modelling: clogit for MNL mixlogit for MXL clogithet for heteroscedastic MNL lclogit for latent class logit gmnl for generalised MNL Many of these commands have been developped/refined by Arne HOLE (Great job!) http://www.stata.com/meeting/uk13/abstracts/materials/uk13_hole.pdf Choice modellers also use other software: nlogit (developped by W. Greene) biogeme (Thanks to M. Bierlaire) - Great tool but can only be used for choices modelling I've heard about LatentGOLD but not sure ... For those who want to use MATLAB, You got to take a look at: Mikołaj Czajkowski webiste (http://czaj.org/research/estimation-packages/dce) Kenneth TRAIN website (https://eml.berkeley.edu/~train/software.html) - Actually most of the choice functions come from Kenneth TRAIN's work Finally, for those who are willing to invest a significant amount of time in the coding of choice models, Chandra BHAT website is amazing (http://www.caee.utexas.edu/prof/bhat/FULL_CODES.htm) Many thanks to all these great researchers (Train, Bhat, Bierlaire, Hole, Croissant, Czajkowski, etc) who made this possible!
Conjoint Packages for R
For R: "survival" (clogit) for multinomial logit (MNL) model. "mlogit" for a wide range of models (MNL, nested logit, heteroscedastic logit, mixed logit (MXL) also known as random parameters logit, ..
Conjoint Packages for R For R: "survival" (clogit) for multinomial logit (MNL) model. "mlogit" for a wide range of models (MNL, nested logit, heteroscedastic logit, mixed logit (MXL) also known as random parameters logit, ...). In the same spirit you should take a look at "Rchoice" (file:///C:/Users/kruci/Downloads/v74i10.pdf). "bayesm" for bayesian version of MNL/MXL - However if you are interested in bayesian approach I would strongly recommand the great "RSGHB" package. "gmnl" for the generalised MNL model. "flexmix" for latent class logit (LCL) model. More generally it is important to keep in mind that choice models are a special case of multilevel (or hierarchical) models (you have choices nested within participants themselves nested within higher units: supermarkets, countries, etc.) - So everything that can be used for multilevel modelling (e.g., the great "lme4" package) and that can also accommodate the discrete nature of the choice variable would do the job. For example, you could use "lme4" if the choices are binary (Do you want this product? Yes/No) or made between 2 options (Which product do you want? A/B). With Stata, you have many commands useful for choice modelling: clogit for MNL mixlogit for MXL clogithet for heteroscedastic MNL lclogit for latent class logit gmnl for generalised MNL Many of these commands have been developped/refined by Arne HOLE (Great job!) http://www.stata.com/meeting/uk13/abstracts/materials/uk13_hole.pdf Choice modellers also use other software: nlogit (developped by W. Greene) biogeme (Thanks to M. Bierlaire) - Great tool but can only be used for choices modelling I've heard about LatentGOLD but not sure ... For those who want to use MATLAB, You got to take a look at: Mikołaj Czajkowski webiste (http://czaj.org/research/estimation-packages/dce) Kenneth TRAIN website (https://eml.berkeley.edu/~train/software.html) - Actually most of the choice functions come from Kenneth TRAIN's work Finally, for those who are willing to invest a significant amount of time in the coding of choice models, Chandra BHAT website is amazing (http://www.caee.utexas.edu/prof/bhat/FULL_CODES.htm) Many thanks to all these great researchers (Train, Bhat, Bierlaire, Hole, Croissant, Czajkowski, etc) who made this possible!
Conjoint Packages for R For R: "survival" (clogit) for multinomial logit (MNL) model. "mlogit" for a wide range of models (MNL, nested logit, heteroscedastic logit, mixed logit (MXL) also known as random parameters logit, ..
15,315
Is using both training and test sets for hyperparameter tuning overfitting?
The idea behind holdout and cross validation is to estimate the generalization performance of a learning algorithm--that is, the expected performance on unknown/unseen data drawn from the same distribution as the training data. This can be used to tune hyperparameters or report the final performance. The validity of this estimate depends on the independence of the data used for training and estimating performance. If this independence is violated, the performance estimate will be overoptimistically biased. The most egregious way this can happen is by estimating performance on data that has already been used for training or hyperpameter tuning, but there are many more subtle and insidious ways too. The procedure you asked about goes wrong in multiple ways. First, the same data is used for both training and hyperpameter tuning. The goal of hyperparameter tuning is to select hyperparameters that will give good generalization performance. Typically, this works by estimating the generalization performance for different choices of hyperparameters (e.g. using a validation set), and then choosing the best. But, as above, this estimate will be overoptimistic if the same data has been used for training. The consequence is that sub-optimal hyperparameters will be chosen. In particular, there will be a bias toward high capacity models that will overfit. Second, data that has already been used to tune hyperparameters is being re-used to estimate performance. This will give a deceptive estimate, as above. This isn't overfitting itself but it means that, if overfitting is happening (and it probably is, as above), then you won't know it. The remedy is to use three separate datasets: a training set for training, a validation set for hyperparameter tuning, and a test set for estimating the final performance. Or, use nested cross validation, which will give better estimates, and is necessary if there isn't enough data.
Is using both training and test sets for hyperparameter tuning overfitting?
The idea behind holdout and cross validation is to estimate the generalization performance of a learning algorithm--that is, the expected performance on unknown/unseen data drawn from the same distrib
Is using both training and test sets for hyperparameter tuning overfitting? The idea behind holdout and cross validation is to estimate the generalization performance of a learning algorithm--that is, the expected performance on unknown/unseen data drawn from the same distribution as the training data. This can be used to tune hyperparameters or report the final performance. The validity of this estimate depends on the independence of the data used for training and estimating performance. If this independence is violated, the performance estimate will be overoptimistically biased. The most egregious way this can happen is by estimating performance on data that has already been used for training or hyperpameter tuning, but there are many more subtle and insidious ways too. The procedure you asked about goes wrong in multiple ways. First, the same data is used for both training and hyperpameter tuning. The goal of hyperparameter tuning is to select hyperparameters that will give good generalization performance. Typically, this works by estimating the generalization performance for different choices of hyperparameters (e.g. using a validation set), and then choosing the best. But, as above, this estimate will be overoptimistic if the same data has been used for training. The consequence is that sub-optimal hyperparameters will be chosen. In particular, there will be a bias toward high capacity models that will overfit. Second, data that has already been used to tune hyperparameters is being re-used to estimate performance. This will give a deceptive estimate, as above. This isn't overfitting itself but it means that, if overfitting is happening (and it probably is, as above), then you won't know it. The remedy is to use three separate datasets: a training set for training, a validation set for hyperparameter tuning, and a test set for estimating the final performance. Or, use nested cross validation, which will give better estimates, and is necessary if there isn't enough data.
Is using both training and test sets for hyperparameter tuning overfitting? The idea behind holdout and cross validation is to estimate the generalization performance of a learning algorithm--that is, the expected performance on unknown/unseen data drawn from the same distrib
15,316
Is using both training and test sets for hyperparameter tuning overfitting?
Yes, you are overfitting. The test set should be used only for testing, not for parameter tuning. Searching for parameters on the test set will learn the rules that are present in the test set, and eventually overfit it.
Is using both training and test sets for hyperparameter tuning overfitting?
Yes, you are overfitting. The test set should be used only for testing, not for parameter tuning. Searching for parameters on the test set will learn the rules that are present in the test set, and ev
Is using both training and test sets for hyperparameter tuning overfitting? Yes, you are overfitting. The test set should be used only for testing, not for parameter tuning. Searching for parameters on the test set will learn the rules that are present in the test set, and eventually overfit it.
Is using both training and test sets for hyperparameter tuning overfitting? Yes, you are overfitting. The test set should be used only for testing, not for parameter tuning. Searching for parameters on the test set will learn the rules that are present in the test set, and ev
15,317
Is using both training and test sets for hyperparameter tuning overfitting?
I would say you are not necessarily overfitting, because overfitting is a term that is normally used to indicate that your model does not generalise well. E.g. If you would be doing linear regression on something like MNIST images, you are probably still underfitting (it does not generalise enough) when training on both training and test data. What you are doing, however, is still not a good thing. The test set is normally a part of the data that you want to use to check how good the final, trained model will perform on data it has never seen before. If you use this data to choose hyperparameters, you actually give the model a chance to "see" the test data and to develop a bias towards this test data. Therefore, you actually lose the possibility to find out how good your model would actually be on unseen data (because it has already seen the test data). It might be possible that you do not really care about how well your model performs, but then you would not need a test set either. Because in most scenarios you do want to have an idea how good a model is, it is best to lock the test data away before you start doing anything with the data. Something as little as using test data during pre-processing, will probably lead to a biased model. Now you might be asking yourself: "How should I find hyperparameters then?". The easiest way would be to split the available data (assuming that you already safely put away some data for testing) into a training set and a so-called validation set. If you have little data to work with, it probably makes more sense to take a look at cross validation
Is using both training and test sets for hyperparameter tuning overfitting?
I would say you are not necessarily overfitting, because overfitting is a term that is normally used to indicate that your model does not generalise well. E.g. If you would be doing linear regression
Is using both training and test sets for hyperparameter tuning overfitting? I would say you are not necessarily overfitting, because overfitting is a term that is normally used to indicate that your model does not generalise well. E.g. If you would be doing linear regression on something like MNIST images, you are probably still underfitting (it does not generalise enough) when training on both training and test data. What you are doing, however, is still not a good thing. The test set is normally a part of the data that you want to use to check how good the final, trained model will perform on data it has never seen before. If you use this data to choose hyperparameters, you actually give the model a chance to "see" the test data and to develop a bias towards this test data. Therefore, you actually lose the possibility to find out how good your model would actually be on unseen data (because it has already seen the test data). It might be possible that you do not really care about how well your model performs, but then you would not need a test set either. Because in most scenarios you do want to have an idea how good a model is, it is best to lock the test data away before you start doing anything with the data. Something as little as using test data during pre-processing, will probably lead to a biased model. Now you might be asking yourself: "How should I find hyperparameters then?". The easiest way would be to split the available data (assuming that you already safely put away some data for testing) into a training set and a so-called validation set. If you have little data to work with, it probably makes more sense to take a look at cross validation
Is using both training and test sets for hyperparameter tuning overfitting? I would say you are not necessarily overfitting, because overfitting is a term that is normally used to indicate that your model does not generalise well. E.g. If you would be doing linear regression
15,318
Is using both training and test sets for hyperparameter tuning overfitting?
It is not necessarily overfitting, but it also runs an unnecessary risk of overfitting, and you deprive yourself of the possibility to detect overfitting. Overfitting happens when your model is too complex/has too many degrees of freedom for the available training data. This includes degrees of freedom for the hyperparameter space you search. So if your data set is still large enough, you don't overfit (say, you have thousands of cases, just two variates to regress on and a single continuous hyperparameter to tune - that would likely still be OK. On the other hand, if you a handful of cases, hundreds or thousands of variates and a large hyperparameter search space, you run a huge risk of overfitting). But as all your data entered the training phase (during the hyperparameter optimization), you lost the chance to measure generalization error and thus cannot check/show that you do not overfit. Which is as bad as overfitting, unless you can give other evidence that you are not in a situation where overfitting can occur. Moreover, you traded in your ability to measure generalization error for at most a minute improvement in training: You could (and should) have done the whole training on the training set - that's what it is for. And training includes fixing the hyperparameters. From that point of view, the decision is really whether you need to have an error estimate based on unknown data or not (again based on the overall risk of overfitting - and in machine learning the decision would pretty much always be that unknown data performance is needed), and then either do the whole training on your data, or do the whole training on the training set and test with the test set. (Or possibly on multiple such train/test splits as in cross validation).
Is using both training and test sets for hyperparameter tuning overfitting?
It is not necessarily overfitting, but it also runs an unnecessary risk of overfitting, and you deprive yourself of the possibility to detect overfitting. Overfitting happens when your model is too
Is using both training and test sets for hyperparameter tuning overfitting? It is not necessarily overfitting, but it also runs an unnecessary risk of overfitting, and you deprive yourself of the possibility to detect overfitting. Overfitting happens when your model is too complex/has too many degrees of freedom for the available training data. This includes degrees of freedom for the hyperparameter space you search. So if your data set is still large enough, you don't overfit (say, you have thousands of cases, just two variates to regress on and a single continuous hyperparameter to tune - that would likely still be OK. On the other hand, if you a handful of cases, hundreds or thousands of variates and a large hyperparameter search space, you run a huge risk of overfitting). But as all your data entered the training phase (during the hyperparameter optimization), you lost the chance to measure generalization error and thus cannot check/show that you do not overfit. Which is as bad as overfitting, unless you can give other evidence that you are not in a situation where overfitting can occur. Moreover, you traded in your ability to measure generalization error for at most a minute improvement in training: You could (and should) have done the whole training on the training set - that's what it is for. And training includes fixing the hyperparameters. From that point of view, the decision is really whether you need to have an error estimate based on unknown data or not (again based on the overall risk of overfitting - and in machine learning the decision would pretty much always be that unknown data performance is needed), and then either do the whole training on your data, or do the whole training on the training set and test with the test set. (Or possibly on multiple such train/test splits as in cross validation).
Is using both training and test sets for hyperparameter tuning overfitting? It is not necessarily overfitting, but it also runs an unnecessary risk of overfitting, and you deprive yourself of the possibility to detect overfitting. Overfitting happens when your model is too
15,319
Is using both training and test sets for hyperparameter tuning overfitting?
It is an "in-sample" forecast since you eventually make the forecast on observations that are already part of your training set. Why not use n-fold cross-validation? By doing that, at each time, you are making "out-of" sample forecast, in which test set and training set are separate.
Is using both training and test sets for hyperparameter tuning overfitting?
It is an "in-sample" forecast since you eventually make the forecast on observations that are already part of your training set. Why not use n-fold cross-validation? By doing that, at each time, you a
Is using both training and test sets for hyperparameter tuning overfitting? It is an "in-sample" forecast since you eventually make the forecast on observations that are already part of your training set. Why not use n-fold cross-validation? By doing that, at each time, you are making "out-of" sample forecast, in which test set and training set are separate.
Is using both training and test sets for hyperparameter tuning overfitting? It is an "in-sample" forecast since you eventually make the forecast on observations that are already part of your training set. Why not use n-fold cross-validation? By doing that, at each time, you a
15,320
Is using both training and test sets for hyperparameter tuning overfitting?
The idea of CV is to overcome the weaknesses of Train-Test split (loss of information, only a part being used for testing etc.). Hence, CV ensures that all parts of data falls into training and testing folds in the successive iterations. This ensures that we get a balanced picture of whatever we are trying to evaluate (choice of hyperparameter, algorithms etc.). Given this situation, you should use entire dataset for tuning. If you use only train fold, the tuned hyperparameter would be specific to Train fold; not the whole data. My experience is that the model would exhibit overfitting even after tuning using only Train set. imho, practitioners are going overboard with the term 'data leak'. In the effort to prevent data leak, they are giving too much importance to train-test split; which is just a chance. Judicious application of CV is the best approach. Not a combination of Train-Test split and CV.
Is using both training and test sets for hyperparameter tuning overfitting?
The idea of CV is to overcome the weaknesses of Train-Test split (loss of information, only a part being used for testing etc.). Hence, CV ensures that all parts of data falls into training and testin
Is using both training and test sets for hyperparameter tuning overfitting? The idea of CV is to overcome the weaknesses of Train-Test split (loss of information, only a part being used for testing etc.). Hence, CV ensures that all parts of data falls into training and testing folds in the successive iterations. This ensures that we get a balanced picture of whatever we are trying to evaluate (choice of hyperparameter, algorithms etc.). Given this situation, you should use entire dataset for tuning. If you use only train fold, the tuned hyperparameter would be specific to Train fold; not the whole data. My experience is that the model would exhibit overfitting even after tuning using only Train set. imho, practitioners are going overboard with the term 'data leak'. In the effort to prevent data leak, they are giving too much importance to train-test split; which is just a chance. Judicious application of CV is the best approach. Not a combination of Train-Test split and CV.
Is using both training and test sets for hyperparameter tuning overfitting? The idea of CV is to overcome the weaknesses of Train-Test split (loss of information, only a part being used for testing etc.). Hence, CV ensures that all parts of data falls into training and testin
15,321
In multiple linear regression, why does a plot of predicted points not lie in a straight line?
Suppose your multiple regression equation was $$\hat y = 2 x_1 + 5 x_2 + 3$$ where $\hat y$ means "predicted $y$". Now take just those points for which $x_2 = 1$. Then if you plot $\hat y$ against $x_1$, these points will satisfy the equation: $$\hat y = 2 x_1 + 5(1) + 3 = 2 x_1 + 8$$ So they must lie on a line of slope 2 and with $y$-intercept 8. Now take those points for which $x_2 = 2$. When you plot $\hat y$ against $x_1$, then these points satisfy: $$\hat y = 2 x_1 + 5(2) + 3 = 2 x_1 + 13$$ So that's a line of slope 2 and with $y$-intercept 13. You can verify for yourself that if $x_2=3$ then you get another line of slope 2 and $y$-intercept is 18. We see that points with different values of $x_2$ will lie on different lines, but all with the same gradient: the meaning of the coefficient of $2x_1$ in the original regression equation is that, ceteris paribus i.e. holding other predictors constant, a one unit increase in $x_1$ increases the predicted mean response $\hat y$ by two units, while the meaning of the intercept of $3$ in the regression equation was that when $x_1 = 0$ and $x_2 = 0$ then the predicted mean response is $3$. But not all your points have the same $x_2$, which means they lie on lines with a different intercept — the line would only have intercept $3$ for those points for which $x_2=0$. So rather than seeing a single line, you may see (if there are only certain values of $x_2$ that occur, for instance if $x_2$ is always integer) a series of diagonal "streaks". Consider the following data, where $\hat y = 2 x_1 + 5 x_2 + 3$. Here there are perceptible "streaks". Now if I colour in those points for which $x_2=1$ as red circles, $x_2=2$ as gold triangles and $x_2=3$ as blue squares we see they lie on three distinct lines, all of slope 2, and $y$-intercepts 8, 13 and 18 as calculated above. Of course, if $x_2$ wasn't constrained to take integer values, or the situation was complicated by other predictor variables being included in the regression, then the diagonal streaking would be less clear, but it would still be the case that each predicted point lies on a separate line based on the values of the other predictors not shown on the graph. If you were to plot a 3-dimensional graph of $y$ against $x_1$ and $x_2$, then your predicted points all lie in the two-dimensional plane with equation $\hat y = 2 x_1 + 5 x_2 + 3$. The $y$ versus $x_1$ graph I described above is a projection of that three-dimensional graph onto two dimensions — imagine lining yourself up with the $x_2$-axis so you are looking straight down it, while the $y$-axis points upwards and the $x_1$-axis points to your right. Note that all the points lie in a flat plane precisely because I have drawn the fitted (i.e. predicted) $y$ values. If we drew a plot using the observed $y$ values then these will lie vertically above or below these points, depending on whether the residual is positive or negative respectively. The relationship between $\hat y$ and $x_1$ is linear when $x_2$ is controlled for (i.e. for constant $x_2$, the relationship between $\hat y$ and $x_1$ is a straight line), which is often described as "partialling out" the effect of $x_2$. If you want to draw a plot showing the relationship between $y$ and $x_1$ taking into account the variation in $x_2$ then you can use a "partial regression plot" (also called "added variable plot"), where the relationship between $y$ and $x_1$ will be drawn as a single straight line. Code for R plots library(scatterplot3d) data.df <- data.frame( x1 = c(0,2,4,5,8, 1,3,4,7,8, 0,3,5,6,7), x2 = c(1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3) ) data.df$yhat <- with(data.df, 2*x1 + 5*x2 + 3) data1.df <- data.df[data.df$x2==1,] data2.df <- data.df[data.df$x2==2,] data3.df <- data.df[data.df$x2==3,] #Before lines added mar.default <- c(5,4,4,2) + 0.1 par(mar = mar.default + c(0, 1, 0, 0)) plot(data.df[c("x1","yhat")], main=expression("Predicted y against "*x[1]), xlab=expression(x[1]), ylab=expression(hat(y))) #After lines added plot(data.df[c("x1","yhat")], main=expression("Predicted y against "*x[1]), xlab=expression(x[1]), ylab=expression(hat(y)), pch=".") points(data1.df[c("x1","yhat")], pch=19, col="red") abline(lm(yhat ~ x1, data=data1.df), col="red") points(data2.df[c("x1","yhat")], pch=17, col="gold") abline(lm(yhat ~ x1, data=data2.df), col="gold") points(data3.df[c("x1","yhat")], pch=15, col="blue") abline(lm(yhat ~ x1, data=data3.df), col="blue") #3d plot myPlot <- scatterplot3d(data.df, pch=".", xlab=expression(x[1]), ylab=expression(x[2]), zlab=expression(hat(y)), main=expression("Predicted y against "*x[1]*" and "*x[2])) myPlot$plane3d(Intercept=3, x.coef=2, y.coef=5, col="darkgrey") myPlot$points3d(data1.df, pch=19, col="red") myPlot$points3d(data2.df, pch=17, col="gold") myPlot$points3d(data3.df, pch=15, col="blue") print(myPlot)
In multiple linear regression, why does a plot of predicted points not lie in a straight line?
Suppose your multiple regression equation was $$\hat y = 2 x_1 + 5 x_2 + 3$$ where $\hat y$ means "predicted $y$". Now take just those points for which $x_2 = 1$. Then if you plot $\hat y$ against $x
In multiple linear regression, why does a plot of predicted points not lie in a straight line? Suppose your multiple regression equation was $$\hat y = 2 x_1 + 5 x_2 + 3$$ where $\hat y$ means "predicted $y$". Now take just those points for which $x_2 = 1$. Then if you plot $\hat y$ against $x_1$, these points will satisfy the equation: $$\hat y = 2 x_1 + 5(1) + 3 = 2 x_1 + 8$$ So they must lie on a line of slope 2 and with $y$-intercept 8. Now take those points for which $x_2 = 2$. When you plot $\hat y$ against $x_1$, then these points satisfy: $$\hat y = 2 x_1 + 5(2) + 3 = 2 x_1 + 13$$ So that's a line of slope 2 and with $y$-intercept 13. You can verify for yourself that if $x_2=3$ then you get another line of slope 2 and $y$-intercept is 18. We see that points with different values of $x_2$ will lie on different lines, but all with the same gradient: the meaning of the coefficient of $2x_1$ in the original regression equation is that, ceteris paribus i.e. holding other predictors constant, a one unit increase in $x_1$ increases the predicted mean response $\hat y$ by two units, while the meaning of the intercept of $3$ in the regression equation was that when $x_1 = 0$ and $x_2 = 0$ then the predicted mean response is $3$. But not all your points have the same $x_2$, which means they lie on lines with a different intercept — the line would only have intercept $3$ for those points for which $x_2=0$. So rather than seeing a single line, you may see (if there are only certain values of $x_2$ that occur, for instance if $x_2$ is always integer) a series of diagonal "streaks". Consider the following data, where $\hat y = 2 x_1 + 5 x_2 + 3$. Here there are perceptible "streaks". Now if I colour in those points for which $x_2=1$ as red circles, $x_2=2$ as gold triangles and $x_2=3$ as blue squares we see they lie on three distinct lines, all of slope 2, and $y$-intercepts 8, 13 and 18 as calculated above. Of course, if $x_2$ wasn't constrained to take integer values, or the situation was complicated by other predictor variables being included in the regression, then the diagonal streaking would be less clear, but it would still be the case that each predicted point lies on a separate line based on the values of the other predictors not shown on the graph. If you were to plot a 3-dimensional graph of $y$ against $x_1$ and $x_2$, then your predicted points all lie in the two-dimensional plane with equation $\hat y = 2 x_1 + 5 x_2 + 3$. The $y$ versus $x_1$ graph I described above is a projection of that three-dimensional graph onto two dimensions — imagine lining yourself up with the $x_2$-axis so you are looking straight down it, while the $y$-axis points upwards and the $x_1$-axis points to your right. Note that all the points lie in a flat plane precisely because I have drawn the fitted (i.e. predicted) $y$ values. If we drew a plot using the observed $y$ values then these will lie vertically above or below these points, depending on whether the residual is positive or negative respectively. The relationship between $\hat y$ and $x_1$ is linear when $x_2$ is controlled for (i.e. for constant $x_2$, the relationship between $\hat y$ and $x_1$ is a straight line), which is often described as "partialling out" the effect of $x_2$. If you want to draw a plot showing the relationship between $y$ and $x_1$ taking into account the variation in $x_2$ then you can use a "partial regression plot" (also called "added variable plot"), where the relationship between $y$ and $x_1$ will be drawn as a single straight line. Code for R plots library(scatterplot3d) data.df <- data.frame( x1 = c(0,2,4,5,8, 1,3,4,7,8, 0,3,5,6,7), x2 = c(1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3) ) data.df$yhat <- with(data.df, 2*x1 + 5*x2 + 3) data1.df <- data.df[data.df$x2==1,] data2.df <- data.df[data.df$x2==2,] data3.df <- data.df[data.df$x2==3,] #Before lines added mar.default <- c(5,4,4,2) + 0.1 par(mar = mar.default + c(0, 1, 0, 0)) plot(data.df[c("x1","yhat")], main=expression("Predicted y against "*x[1]), xlab=expression(x[1]), ylab=expression(hat(y))) #After lines added plot(data.df[c("x1","yhat")], main=expression("Predicted y against "*x[1]), xlab=expression(x[1]), ylab=expression(hat(y)), pch=".") points(data1.df[c("x1","yhat")], pch=19, col="red") abline(lm(yhat ~ x1, data=data1.df), col="red") points(data2.df[c("x1","yhat")], pch=17, col="gold") abline(lm(yhat ~ x1, data=data2.df), col="gold") points(data3.df[c("x1","yhat")], pch=15, col="blue") abline(lm(yhat ~ x1, data=data3.df), col="blue") #3d plot myPlot <- scatterplot3d(data.df, pch=".", xlab=expression(x[1]), ylab=expression(x[2]), zlab=expression(hat(y)), main=expression("Predicted y against "*x[1]*" and "*x[2])) myPlot$plane3d(Intercept=3, x.coef=2, y.coef=5, col="darkgrey") myPlot$points3d(data1.df, pch=19, col="red") myPlot$points3d(data2.df, pch=17, col="gold") myPlot$points3d(data3.df, pch=15, col="blue") print(myPlot)
In multiple linear regression, why does a plot of predicted points not lie in a straight line? Suppose your multiple regression equation was $$\hat y = 2 x_1 + 5 x_2 + 3$$ where $\hat y$ means "predicted $y$". Now take just those points for which $x_2 = 1$. Then if you plot $\hat y$ against $x
15,322
Non-nested model selection
The LR (likelihood ratio) test actually is testing the hypothesis that a specified subset of the parameters equal some pre-specified values. In the case of model selection, generally (but not always) that means some of the parameters equal zero. If the models are nested, the parameters in the larger model that are not in the smaller model are the ones being tested, with values specified implicitly by their exclusion from the smaller model. If the models aren't nested, you aren't testing this any more, because BOTH models have parameters that aren't in the other model, so the LR test statistic doesn't have the asymptotic $\chi^2$ distribution that it (usually) does in the nested case. AIC, on the other hand, is not used for formal testing. It is used for informal comparisons of models with differing numbers of parameters. The penalty term in the expression for AIC is what allows this comparison. But no assumptions are made about the functional form of the asymptotic distribution of the differences between the AIC of two non-nested models when doing the model comparison, and the difference between two AICs is not treated as a test statistic. I'll add that there is some disagreement over the use of AIC with non-nested models, as the theory is worked out for nested models. Hence my emphasis on "not...formal" and "not...test statistic." I use it for non-nested models, but not in a hard-and-fast way, more as an important, but not the sole, input into the model building process.
Non-nested model selection
The LR (likelihood ratio) test actually is testing the hypothesis that a specified subset of the parameters equal some pre-specified values. In the case of model selection, generally (but not always)
Non-nested model selection The LR (likelihood ratio) test actually is testing the hypothesis that a specified subset of the parameters equal some pre-specified values. In the case of model selection, generally (but not always) that means some of the parameters equal zero. If the models are nested, the parameters in the larger model that are not in the smaller model are the ones being tested, with values specified implicitly by their exclusion from the smaller model. If the models aren't nested, you aren't testing this any more, because BOTH models have parameters that aren't in the other model, so the LR test statistic doesn't have the asymptotic $\chi^2$ distribution that it (usually) does in the nested case. AIC, on the other hand, is not used for formal testing. It is used for informal comparisons of models with differing numbers of parameters. The penalty term in the expression for AIC is what allows this comparison. But no assumptions are made about the functional form of the asymptotic distribution of the differences between the AIC of two non-nested models when doing the model comparison, and the difference between two AICs is not treated as a test statistic. I'll add that there is some disagreement over the use of AIC with non-nested models, as the theory is worked out for nested models. Hence my emphasis on "not...formal" and "not...test statistic." I use it for non-nested models, but not in a hard-and-fast way, more as an important, but not the sole, input into the model building process.
Non-nested model selection The LR (likelihood ratio) test actually is testing the hypothesis that a specified subset of the parameters equal some pre-specified values. In the case of model selection, generally (but not always)
15,323
Non-nested model selection
The derivation of AIC as an estimator of Kullback-Leibler information loss makes no assumptions of models being nested.
Non-nested model selection
The derivation of AIC as an estimator of Kullback-Leibler information loss makes no assumptions of models being nested.
Non-nested model selection The derivation of AIC as an estimator of Kullback-Leibler information loss makes no assumptions of models being nested.
Non-nested model selection The derivation of AIC as an estimator of Kullback-Leibler information loss makes no assumptions of models being nested.
15,324
Example when using accuracy as an outcome measure will lead to a wrong conclusion
I'll cheat. Specifically, I have argued often (e.g., here) that the statistical part of modeling and prediction extends only to making probabilistic predictions for class memberships (or giving predictive densities, in the case of numerical forecasting). Treating a specific instance as if it belonged to a specific class (or point predictions in the numerical case), is not properly statistics any more. It is part of the decision theoretic aspect. And decisions should not only be predicated on the probabilistic prediction, but also on costs of misclassifications, and on a host of other possible actions. For instance, even if you have only two possible classes, "sick" vs. "healthy", you could have a large range of possible actions depending on how likely it is that a patient suffers from the disease, from sending him home because he is almost certainly healthy, to giving him two aspirin, to running additional tests, to immediately calling an ambulance and putting him on life support. Assessing accuracy presupposes such a decision. Accuracy as a evaluation metric for classification is a category error. So, to answer your question, I will walk down the path of just such a category error. We will consider a simple scenario with balanced classes where classifying without regard for the costs of misclassification will indeed mislead us badly. Suppose an epidemic of Malignant Gutrot runs rampant in the population. Happily, we can screen everybody easily for some trait $t$ ($0\leq t \leq 1$), and we know that the probability of developing MG depends linearly on $t$, $p=\gamma t$ for some parameter $\gamma$ ($0\leq \gamma \leq 1$). The trait $t$ is uniformly distributed in the population. Fortunately, there is a vaccine. Unfortunately, it is expensive, and the side effects are very uncomfortable. (I'll let your imagination supply the details.) However, they are better than to suffer from MG. In the interest of abstraction, I posit that there are indeed only two possible courses of action for any given patient, given their trait value $t$: either vaccinate, or do not vaccinate. Thus, the question is: how should we decide who to vaccinate and who not to, given $t$? We will be utilitarian about this and aim at having the lowest total expected costs. It is obvious that this comes down to choosing a threshold $\theta$ and to vaccinate everyone with $t\geq\theta$. Model-and-decision 1 are accuracy-driven. Fit a model. Fortunately, we already know the model. Pick the threshold $\theta$ that maximizes accuracy when classifying patients, and vaccinate everyone with $t\geq \theta$. We easily see that $\theta=\frac{1}{2\gamma}$ is the magic number - everyone with $t\geq \theta$ has a higher chance of contracting MG than not, and vice versa, so this classification probability threshold will maximize accuracy. Assuming balanced classes, $\gamma=1$, we will vaccinate half the population. Funnily enough, if $\gamma<\frac{1}{2}$, we will vaccinate nobody. (We are mostly interested in balanced classes, so let's disregard that we just let part of the population die a Horrible Painful Death.) Needless to say, this does not take the differential costs of misclassification into account. Model-and-decision 2 leverage both our probabilistic prediction ("given your trait $t$, your probability of contracting MG is $\gamma t$") and the cost structure. First, here is a little graph. The horizontal axis gives the trait, the vertical axis the MG probability. The shaded triangle gives the proportion of the population who will contract MG. The vertical line gives some particular $\theta$. The horizontal dashed line at $\gamma\theta$ will make the calculations below a bit simpler to follow. We assume $\gamma>\frac{1}{2}$, just to make life easier. Let's give our costs names and calculate their contributions to total expected costs, given $\theta$ and $\gamma$ (and the fact that the trait is uniformly distributed in the population). Let $c^+_+$ denote the cost for a patient who is vaccinated and would have contracted MG. Given $\theta$, the proportion of the population who incurs this cost is the shaded trapezoid at the bottom right with area $$ (1-\theta)\gamma\theta + \frac{1}{2}(1-\theta)(\gamma-\gamma\theta). $$ Let $c^-_+$ denote the cost for a patient who is vaccinated and would not have contracted MG. Given $\theta$, the proportion of the population who incurs this cost is the unshaded trapezoid at the top right with area $$ (1-\theta)(1-\gamma) + \frac{1}{2}(1-\theta)(\gamma-\gamma\theta). $$ Let $c^-_-$ denote the cost for a patient who is not vaccinated and would not have contracted MG. Given $\theta$, the proportion of the population who incurs this cost is the unshaded trapezoid at the top left with area $$ \theta(1-\gamma\theta) + \frac{1}{2}\theta\gamma\theta. $$ Let $c^+_-$ denote the cost for a patient who is not vaccinated and would have contracted MG. Given $\theta$, the proportion of the population who incurs this cost is the shaded triangle at the bottom left with area $$ \frac{1}{2}\theta\gamma\theta. $$ (In each trapezoid, I first calculate the area of the rectangle, then add the area of the triangle.) Total expected costs are $$ c^+_+\bigg((1-\theta)\gamma\theta + \frac{1}{2}(1-\theta)(\gamma-\gamma\theta)\bigg) + c^-_+\bigg((1-\theta)(1-\gamma) + \frac{1}{2}(1-\theta)(\gamma-\gamma\theta)\bigg) + c^-_-\bigg(\theta(1-\gamma\theta) + \frac{1}{2}\theta\gamma\theta\bigg) + c^+_-\frac{1}{2}\theta\gamma\theta. $$ Differentiating and setting the derivative to zero, we obtain that expected costs are minimized by $$ \theta^\ast = \frac{c^-_+-c^-_-}{\gamma(c^+_-+c^-_+-c^+_+-c^-_-)}.$$ This is only equal to the accuracy maximizing value of $\theta$ for a very specific cost structure, namely if and only if $$ \frac{1}{2\gamma} = \frac{c^-_+-c^-_-}{\gamma(c^+_-+c^-_+-c^+_+-c^-_-)},$$ or $$ \frac{1}{2} = \frac{c^-_+-c^-_-}{c^+_-+c^-_+-c^+_+-c^-_-}.$$ As an example, suppose that $\gamma=1$ for balanced classes and that costs are $$ c^+_+ = 1, \quad c^-_+=2, \quad c^+_-=10, \quad c^-_-=0.$$ Then the accuracy maximizing $\theta=\frac{1}{2}$ will yield expected costs of $1.875$, whereas the cost minimizing $\theta=\frac{2}{11}$ will yield expected costs of $1.318$. In this example, basing our decisions on non-probabilistic classifications that maximized accuracy led to more vaccinations and higher costs than using a decision rule that explicitly used the differential cost structures in the context of a probabilistic prediction. Bottom line: accuracy is only a valid decision criterion if there is a one-to-one relationship between classes and possible actions and the costs of actions applied to classes follow a very specific structure. In the general case, evaluating accuracy asks a wrong question, and maximizing accuracy is a so-called type III error: providing the correct answer to the wrong question. R code: rm(list=ls()) gamma <- 0.7 cost_treated_positive <- 1 # cost of treatment, side effects unimportant cost_treated_negative <- 2 # cost of treatment, side effects unnecessary cost_untreated_positive <- 10 # horrible, painful death cost_untreated_negative <- 0 # nothing expected_cost <- function ( theta ) { cost_treated_positive * ( (1-theta)*theta*gamma + (1-theta)*(gamma-gamma*theta)/2 ) + cost_treated_negative * ( (1-theta)*(1-gamma) + (1-theta)*(gamma-gamma*theta)/2 ) + cost_untreated_negative *( theta*(1-gamma*theta) + theta*gamma*theta/2 ) + cost_untreated_positive * theta*gamma*theta/2 } (theta <- optim(par=0.5,fn=expected_cost,lower=0,upper=1,method="L-BFGS-B")$par) (cost_treated_negative-cost_untreated_negative)/ (gamma*(cost_treated_negative+cost_untreated_positive-cost_treated_positive-cost_untreated_negative)) plot(c(0,1),c(0,1),type="n",bty="n",xaxt="n",xlab="Trait t",yaxt="n",ylab="MG probability") rect(0,0,1,1) axis(1,c(0,theta,1),c(0,"theta",1),lty=0,line=-1) axis(2,c(0,1),lty=0,line=-1,las=1) axis(4,c(0,gamma,1),c(0,"gamma",1),lty=0,line=-1.8,las=1) polygon(c(0,1,1),c(0,0,gamma),col="lightgray") abline(v=theta,col="red",lwd=2) abline(h=gamma*theta,lty=2,col="red",lwd=2) expected_cost(1/(2*gamma)) expected_cost(theta)
Example when using accuracy as an outcome measure will lead to a wrong conclusion
I'll cheat. Specifically, I have argued often (e.g., here) that the statistical part of modeling and prediction extends only to making probabilistic predictions for class memberships (or giving predic
Example when using accuracy as an outcome measure will lead to a wrong conclusion I'll cheat. Specifically, I have argued often (e.g., here) that the statistical part of modeling and prediction extends only to making probabilistic predictions for class memberships (or giving predictive densities, in the case of numerical forecasting). Treating a specific instance as if it belonged to a specific class (or point predictions in the numerical case), is not properly statistics any more. It is part of the decision theoretic aspect. And decisions should not only be predicated on the probabilistic prediction, but also on costs of misclassifications, and on a host of other possible actions. For instance, even if you have only two possible classes, "sick" vs. "healthy", you could have a large range of possible actions depending on how likely it is that a patient suffers from the disease, from sending him home because he is almost certainly healthy, to giving him two aspirin, to running additional tests, to immediately calling an ambulance and putting him on life support. Assessing accuracy presupposes such a decision. Accuracy as a evaluation metric for classification is a category error. So, to answer your question, I will walk down the path of just such a category error. We will consider a simple scenario with balanced classes where classifying without regard for the costs of misclassification will indeed mislead us badly. Suppose an epidemic of Malignant Gutrot runs rampant in the population. Happily, we can screen everybody easily for some trait $t$ ($0\leq t \leq 1$), and we know that the probability of developing MG depends linearly on $t$, $p=\gamma t$ for some parameter $\gamma$ ($0\leq \gamma \leq 1$). The trait $t$ is uniformly distributed in the population. Fortunately, there is a vaccine. Unfortunately, it is expensive, and the side effects are very uncomfortable. (I'll let your imagination supply the details.) However, they are better than to suffer from MG. In the interest of abstraction, I posit that there are indeed only two possible courses of action for any given patient, given their trait value $t$: either vaccinate, or do not vaccinate. Thus, the question is: how should we decide who to vaccinate and who not to, given $t$? We will be utilitarian about this and aim at having the lowest total expected costs. It is obvious that this comes down to choosing a threshold $\theta$ and to vaccinate everyone with $t\geq\theta$. Model-and-decision 1 are accuracy-driven. Fit a model. Fortunately, we already know the model. Pick the threshold $\theta$ that maximizes accuracy when classifying patients, and vaccinate everyone with $t\geq \theta$. We easily see that $\theta=\frac{1}{2\gamma}$ is the magic number - everyone with $t\geq \theta$ has a higher chance of contracting MG than not, and vice versa, so this classification probability threshold will maximize accuracy. Assuming balanced classes, $\gamma=1$, we will vaccinate half the population. Funnily enough, if $\gamma<\frac{1}{2}$, we will vaccinate nobody. (We are mostly interested in balanced classes, so let's disregard that we just let part of the population die a Horrible Painful Death.) Needless to say, this does not take the differential costs of misclassification into account. Model-and-decision 2 leverage both our probabilistic prediction ("given your trait $t$, your probability of contracting MG is $\gamma t$") and the cost structure. First, here is a little graph. The horizontal axis gives the trait, the vertical axis the MG probability. The shaded triangle gives the proportion of the population who will contract MG. The vertical line gives some particular $\theta$. The horizontal dashed line at $\gamma\theta$ will make the calculations below a bit simpler to follow. We assume $\gamma>\frac{1}{2}$, just to make life easier. Let's give our costs names and calculate their contributions to total expected costs, given $\theta$ and $\gamma$ (and the fact that the trait is uniformly distributed in the population). Let $c^+_+$ denote the cost for a patient who is vaccinated and would have contracted MG. Given $\theta$, the proportion of the population who incurs this cost is the shaded trapezoid at the bottom right with area $$ (1-\theta)\gamma\theta + \frac{1}{2}(1-\theta)(\gamma-\gamma\theta). $$ Let $c^-_+$ denote the cost for a patient who is vaccinated and would not have contracted MG. Given $\theta$, the proportion of the population who incurs this cost is the unshaded trapezoid at the top right with area $$ (1-\theta)(1-\gamma) + \frac{1}{2}(1-\theta)(\gamma-\gamma\theta). $$ Let $c^-_-$ denote the cost for a patient who is not vaccinated and would not have contracted MG. Given $\theta$, the proportion of the population who incurs this cost is the unshaded trapezoid at the top left with area $$ \theta(1-\gamma\theta) + \frac{1}{2}\theta\gamma\theta. $$ Let $c^+_-$ denote the cost for a patient who is not vaccinated and would have contracted MG. Given $\theta$, the proportion of the population who incurs this cost is the shaded triangle at the bottom left with area $$ \frac{1}{2}\theta\gamma\theta. $$ (In each trapezoid, I first calculate the area of the rectangle, then add the area of the triangle.) Total expected costs are $$ c^+_+\bigg((1-\theta)\gamma\theta + \frac{1}{2}(1-\theta)(\gamma-\gamma\theta)\bigg) + c^-_+\bigg((1-\theta)(1-\gamma) + \frac{1}{2}(1-\theta)(\gamma-\gamma\theta)\bigg) + c^-_-\bigg(\theta(1-\gamma\theta) + \frac{1}{2}\theta\gamma\theta\bigg) + c^+_-\frac{1}{2}\theta\gamma\theta. $$ Differentiating and setting the derivative to zero, we obtain that expected costs are minimized by $$ \theta^\ast = \frac{c^-_+-c^-_-}{\gamma(c^+_-+c^-_+-c^+_+-c^-_-)}.$$ This is only equal to the accuracy maximizing value of $\theta$ for a very specific cost structure, namely if and only if $$ \frac{1}{2\gamma} = \frac{c^-_+-c^-_-}{\gamma(c^+_-+c^-_+-c^+_+-c^-_-)},$$ or $$ \frac{1}{2} = \frac{c^-_+-c^-_-}{c^+_-+c^-_+-c^+_+-c^-_-}.$$ As an example, suppose that $\gamma=1$ for balanced classes and that costs are $$ c^+_+ = 1, \quad c^-_+=2, \quad c^+_-=10, \quad c^-_-=0.$$ Then the accuracy maximizing $\theta=\frac{1}{2}$ will yield expected costs of $1.875$, whereas the cost minimizing $\theta=\frac{2}{11}$ will yield expected costs of $1.318$. In this example, basing our decisions on non-probabilistic classifications that maximized accuracy led to more vaccinations and higher costs than using a decision rule that explicitly used the differential cost structures in the context of a probabilistic prediction. Bottom line: accuracy is only a valid decision criterion if there is a one-to-one relationship between classes and possible actions and the costs of actions applied to classes follow a very specific structure. In the general case, evaluating accuracy asks a wrong question, and maximizing accuracy is a so-called type III error: providing the correct answer to the wrong question. R code: rm(list=ls()) gamma <- 0.7 cost_treated_positive <- 1 # cost of treatment, side effects unimportant cost_treated_negative <- 2 # cost of treatment, side effects unnecessary cost_untreated_positive <- 10 # horrible, painful death cost_untreated_negative <- 0 # nothing expected_cost <- function ( theta ) { cost_treated_positive * ( (1-theta)*theta*gamma + (1-theta)*(gamma-gamma*theta)/2 ) + cost_treated_negative * ( (1-theta)*(1-gamma) + (1-theta)*(gamma-gamma*theta)/2 ) + cost_untreated_negative *( theta*(1-gamma*theta) + theta*gamma*theta/2 ) + cost_untreated_positive * theta*gamma*theta/2 } (theta <- optim(par=0.5,fn=expected_cost,lower=0,upper=1,method="L-BFGS-B")$par) (cost_treated_negative-cost_untreated_negative)/ (gamma*(cost_treated_negative+cost_untreated_positive-cost_treated_positive-cost_untreated_negative)) plot(c(0,1),c(0,1),type="n",bty="n",xaxt="n",xlab="Trait t",yaxt="n",ylab="MG probability") rect(0,0,1,1) axis(1,c(0,theta,1),c(0,"theta",1),lty=0,line=-1) axis(2,c(0,1),lty=0,line=-1,las=1) axis(4,c(0,gamma,1),c(0,"gamma",1),lty=0,line=-1.8,las=1) polygon(c(0,1,1),c(0,0,gamma),col="lightgray") abline(v=theta,col="red",lwd=2) abline(h=gamma*theta,lty=2,col="red",lwd=2) expected_cost(1/(2*gamma)) expected_cost(theta)
Example when using accuracy as an outcome measure will lead to a wrong conclusion I'll cheat. Specifically, I have argued often (e.g., here) that the statistical part of modeling and prediction extends only to making probabilistic predictions for class memberships (or giving predic
15,325
Example when using accuracy as an outcome measure will lead to a wrong conclusion
It might worth adding another, perhaps more straightforward example to Stephen's excellent answer. Let's consider a medical test, the result of which is normally distributed, both in sick and in healthy people, with different parameters of course (but for simplicity, let's assume homoscedasticity, i.e., that the variance is the same): $$\begin{gather*}T \mid D \ominus \sim \mathcal{N}\left(\mu_{-},\sigma^2\right)\\T \mid D \oplus \sim \mathcal{N}\left(\mu_{+},\sigma^2\right)\end{gather*}.$$ Let's denote the prevalence of the disease with $p$ (i.e. $D\oplus\sim Bern\left(p\right)$), so this, together with the above, which are essentially conditional distributions, fully specifies the joint distribution. Thus the confusion matrix with threshold $b$ (i.e., those with test results above $b$ are classified as sick) is $$\begin{pmatrix} & D\oplus & D\ominus\\ T\oplus & p\left(1-\Phi_{+}\left(b\right)\right) & \left(1-p\right)\left(1-\Phi_{-}\left(b\right)\right)\\ T\ominus & p\Phi_{+}\left(b\right) & \left(1-p\right)\Phi_{-}\left(b\right)\\ \end{pmatrix}.$$ Accuracy-based approach The accuracy is $$p\left(1-\Phi_{+}\left(b\right)\right)+\left(1-p\right)\Phi_{-}\left(b\right),$$ we take its derivative w.r.t. $b$, set it equal to 0, multiply with $\sqrt{1\pi\sigma^2}$ and rearrange a bit: $$\begin{gather*} -p\varphi_{+}\left(b\right)+\varphi_{-}\left(b\right)-p\varphi_{-}\left(b\right)=0\\ e^{-\frac{\left(b-\mu_{-}\right)^2}{2\sigma^2}}\left[\left(1-p\right)-pe^{-\frac{2b\left(\mu_{-}-\mu_{+}\right)+\left(\mu_{+}^2-\mu_{-}^2\right)}{2\sigma^2}}\right]=0\end{gather*}$$ The first term can't be zero, so the only way the product can be zero is if the second term is zero: $$\begin{gather*}\left(1-p\right)-pe^{-\frac{2b\left(\mu_{-}-\mu_{+}\right)+\left(\mu_{+}^2-\mu_{-}^2\right)}{2\sigma^2}}=0\\-\frac{2b\left(\mu_{-}-\mu_{+}\right)+\left(\mu_{+}^2-\mu_{-}^2\right)}{2\sigma^2}=\log\frac{1-p}{p}\\ 2b\left(\mu_{+}-\mu_{-}\right)+\left(\mu_{-}^2-\mu_{+}^2\right)=2\sigma^2\log\frac{1-p}{p}\\ \end{gather*}$$ So the solution is $$b^{\ast}=\frac{\left(\mu_{+}^2-\mu_{-}^2\right)+2\sigma^2\log\frac{1-p}{p}}{2\left(\mu_{+}-\mu_{-}\right)}=\frac{\mu_{+}+\mu_{-}}{2}+\frac{\sigma^2}{\mu_{+}-\mu_{-}}\log\frac{1-p}{p}.$$ Note that this - of course - doesn't depend on the costs. If the classes are balanced, the optimum is the average of the mean test values in sick and healthy people, otherwise it is displaced based on the imbalance. Cost-based approach Using Stephen's notation, the expected overall cost is $$c_{+}^{+}p\left(1-\Phi_{+}\left(b\right)\right) + c_{+}^{-}\left(1-p\right)\left(1-\Phi_{-}\left(b\right)\right) + c_{-}^{+} p\Phi_{+}\left(b\right) + c_{-}^{-} \left(1-p\right)\Phi_{-}\left(b\right).$$ Take its derivate w.r.t $b$ and set it equal to zero: $$\begin{gather*} -c_{+}^{+} p \varphi_{+}\left(b\right)-c_{+}^{-}\left(1-p\right)\varphi_{-}\left(b\right)+c_{-}^{+}p\varphi_{+}\left(b\right)+c_{-}^{-}\left(1-p\right)\varphi_{-}\left(b\right)=\\ =\varphi_{+}\left(b\right)p\left(c_{-}^{+}-c_{+}^{+}\right)+\varphi_{-}\left(b\right)\left(1-p\right)\left(c_{-}^{-}-c_{+}^{-}\right)=\\ = \varphi_{+}\left(b\right)pc_d^{+}-\varphi_{-}\left(b\right)\left(1-p\right)c_d^{-}= 0,\end{gather*}$$ using the notation I introduced in my comments below Stephen's answer, i.e., $c_d^{+}=c_{-}^{+}-c_{+}^{+}$ and $c_d^{-}=c_{+}^{-}-c_{-}^{-}$. The optimal threshold is therefore given by the solution of the equation $$\boxed{\frac{\varphi_{+}\left(b\right)}{\varphi_{-}\left(b\right)}=\frac{\left(1-p\right)c_d^{-}}{pc_d^{+}}}.$$ Two things should be noted here: This results is totally generic and works for any distribution of the test results, not only normal. ($\varphi$ in that case of course means the probability density function of the distribution, not the normal density.) Whatever the solution for $b$ is, it is surely a function of $\frac{\left(1-p\right)c_d^{-}}{pc_d^{+}}$. (I.e., we immediately see how costs matter - in addition to class imbalance!) I'd be really interested to see if this equation has a generic solution for $b$ (parametrized by the $\varphi$s), but I would be surprised. Nevertheless, we can work it out for normal! $\sqrt{2\pi\sigma^2}$s cancel on the left hand side, so we have $$\begin{gather*} e^{-\frac{1}{2}\left(\frac{\left(b-\mu_{+}\right)^2}{\sigma^2}-\frac{\left(b-\mu_{-}\right)^2}{\sigma^2}\right)}=\frac{\left(1-p\right)c_d^{-}}{pc_d^{+}} \\ \left(b-\mu_{-}\right)^2-\left(b-\mu_{+}\right)^2 =2\sigma^2 \log \frac{\left(1-p\right)c_d^{-}}{pc_d^{+}} \\ 2b\left(\mu_{+}-\mu_{-}\right)+\left(\mu_{-}^2-\mu_{+}^2\right) =2\sigma^2 \log \frac{\left(1-p\right)c_d^{-}}{pc_d^{+}}\end{gather*}$$ therefore the solution is $$b^{\ast}=\frac{\left(\mu_{+}^2-\mu_{-}^2\right)+2\sigma^2 \log \frac{\left(1-p\right)c_d^{-}}{pc_d^{+}}}{2\left(\mu_{+}-\mu_{-}\right)}=\frac{\mu_{+}+\mu_{-}}{2}+\frac{\sigma^2}{\mu_{+}-\mu_{-}}\log \frac{\left(1-p\right)c_d^{-}}{pc_d^{+}}.$$ (Compare it the the previous result! We see that they are equal if and only if $c_d^{-}=c_d^{+}$, i.e. the differences in misclassification cost compared to the cost of correct classification is the same in sick and healthy people.) A short demonstration Let's say $c_{-}^{-}=0$ (it is quite natural medically), and that $c_{+}^{+}=1$ (we can always obtain it by dividing the costs with $c_{+}^{+}$, i.e., by measuring every cost in $c_{+}^{+}$ units). Let's say that the prevalence is $p=0.2$. Also, let's say that $\mu_{-}=9.5$, $\mu_{+}=10.5$ and $\sigma=1$. In this case: library( data.table ) library( lattice ) cminusminus <- 0 cplusplus <- 1 p <- 0.2 muminus <- 9.5 muplus <- 10.5 sigma <- 1 res <- data.table( expand.grid( b = seq( 6, 17, 0.1 ), cplusminus = c( 1, 5, 10, 50, 100 ), cminusplus = c( 2, 5, 10, 50, 100 ) ) ) res$cost <- cplusplus*p*( 1-pnorm( res$b, muplus, sigma ) ) + res$cplusminus*(1-p)*(1-pnorm( res$b, muminus, sigma ) ) + res$cminusplus*p*pnorm( res$b, muplus, sigma ) + cminusminus*(1-p)*pnorm( res$b, muminus, sigma ) xyplot( cost ~ b | factor( cminusplus ), groups = cplusminus, ylim = c( -1, 22 ), data = res, type = "l", xlab = "Threshold", ylab = "Expected overall cost", as.table = TRUE, abline = list( v = (muplus+muminus)/2+ sigma^2/(muplus-muminus)*log((1-p)/p) ), strip = strip.custom( var.name = expression( {"c"^{"+"}}["-"] ), strip.names = c( TRUE, TRUE ) ), auto.key = list( space = "right", points = FALSE, lines = TRUE, title = expression( {"c"^{"-"}}["+"] ) ), panel = panel.superpose, panel.groups = function( x, y, col.line, ... ) { panel.xyplot( x, y, col.line = col.line, ... ) panel.points( x[ which.min( y ) ], min( y ), pch = 19, col = col.line ) } ) The result is (points depict the minimum cost, and the vertical line shows the optimal threshold with the accuracy-based approach): We can very nicely see how cost-based optimum can be different than the accuracy-based optimum. It is instructive to think over why: if it is more costly to classify a sick people erroneously healthy than the other way around ($c_{-}^{+}$ is high, $c_{+}^{-}$ is low) than the threshold goes down, as we prefer to classify more easily into the category sick, on the other hand, if it is more costly to classify a healthy people erroneously sick than the other way around ($c_{-}^{+}$ is low, $c_{+}^{-}$ is high) than the threshold goes up, as we prefer to classify more easily into the category healthy. (Check these on the figure!) A real-life example Let's have a look at an empirical example, instead of a theoretical derivation. This example will be different basically from two aspects: Instead of assuming normality, we will simply use the empirical data without any such assumption. Instead of using one single test, and its results in its own units, we will use several tests (and combine them with a logistic regression). Threshold will be given to the final predicted probability. This is actually the preferred approach, see Chapter 19 - Diagnosis - in Frank Harrell's BBR. The dataset (acath from the package Hmisc) is from the Duke University Cardiovascular Disease Databank, and contains whether the patient had significant coronary disease, as assessed by cardiac catheterization, this will be our gold standard, i.e., the true disease status, and the "test" will be the combination of the subject's age, sex, cholesterol level and duration of symptoms: library( rms ) library( lattice ) library( latticeExtra ) library( data.table ) getHdata( "acath" ) acath <- acath[ !is.na( acath$choleste ), ] dd <- datadist( acath ) options( datadist = "dd" ) fit <- lrm( sigdz ~ rcs( age )*sex + rcs( choleste ) + cad.dur, data = acath ) It worth plotting the predicted risks on logit-scale, to see how normal they are (essentially, that was what we assumed previously, with one single test!): densityplot( ~predict( fit ), groups = acath$sigdz, plot.points = FALSE, ref = TRUE, auto.key = list( columns = 2 ) ) Well, they're hardly normal... Let's go on and calculate the expected overall cost: ExpectedOverallCost <- function( b, p, y, cplusminus, cminusplus, cplusplus = 1, cminusminus = 0 ) { sum( table( factor( p>b, levels = c( FALSE, TRUE ) ), y )*matrix( c( cminusminus, cplusminus, cminusplus, cplusplus ), nc = 2 ) ) } table( predict( fit, type = "fitted" )>0.5, acath$sigdz ) ExpectedOverallCost( 0.5, predict( fit, type = "fitted" ), acath$sigdz, 2, 4 ) And let's plot it for all possible costs (a computational note: we don't need to mindlessly iterate through numbers from 0 to 1, we can perfectly reconstruct the curve by calculating it for all unique values of predicted probabilities): ps <- sort( unique( c( 0, 1, predict( fit, type = "fitted" ) ) ) ) xyplot( sapply( ps, ExpectedOverallCost, p = predict( fit, type = "fitted" ), y = acath$sigdz, cplusminus = 2, cminusplus = 4 ) ~ ps, type = "l", xlab = "Threshold", ylab = "Expected overall cost", panel = function( x, y, ... ) { panel.xyplot( x, y, ... ) panel.points( x[ which.min( y ) ], min( y ), pch = 19, cex = 1.1 ) panel.text( x[ which.min( y ) ], min( y ), round( x[ which.min( y ) ], 3 ), pos = 3 ) } ) We can very well see where we should put the threshold to optimize the expected overall cost (without using sensitivity, specificity or predictive values anywhere!). This is the correct approach. It is especially instructive to contrast these metrics: ExpectedOverallCost2 <- function( b, p, y, cplusminus, cminusplus, cplusplus = 1, cminusminus = 0 ) { tab <- table( factor( p>b, levels = c( FALSE, TRUE ) ), y ) sens <- tab[ 2, 2 ] / sum( tab[ , 2 ] ) spec <- tab[ 1, 1 ] / sum( tab[ , 1 ] ) c( `Expected overall cost` = sum( tab*matrix( c( cminusminus, cplusminus, cminusplus, cplusplus ), nc = 2 ) ), Sensitivity = sens, Specificity = spec, PPV = tab[ 2, 2 ] / sum( tab[ 2, ] ), NPV = tab[ 1, 1 ] / sum( tab[ 1, ] ), Accuracy = 1 - ( tab[ 1, 1 ] + tab[ 2, 2 ] )/sum( tab ), Youden = 1 - ( sens + spec - 1 ), Topleft = ( 1-sens )^2 + ( 1-spec )^2 ) } ExpectedOverallCost2( 0.5, predict( fit, type = "fitted" ), acath$sigdz, 2, 4 ) res <- melt( data.table( ps, t( sapply( ps, ExpectedOverallCost2, p = predict( fit, type = "fitted" ), y = acath$sigdz, cplusminus = 2, cminusplus = 4 ) ) ), id.vars = "ps" ) p1 <- xyplot( value ~ ps, data = res, subset = variable=="Expected overall cost", type = "l", xlab = "Threshold", ylab = "Expected overall cost", panel=function( x, y, ... ) { panel.xyplot( x, y, ... ) panel.abline( v = x[ which.min( y ) ], col = trellis.par.get()$plot.line$col ) panel.points( x[ which.min( y ) ], min( y ), pch = 19 ) } ) p2 <- xyplot( value ~ ps, groups = variable, data = droplevels( res[ variable%in%c( "Expected overall cost", "Sensitivity", "Specificity", "PPV", "NPV" ) ] ), subset = variable%in%c( "Sensitivity", "Specificity", "PPV", "NPV" ), type = "l", xlab = "Threshold", ylab = "Sensitivity/Specificity/PPV/NPV", auto.key = list( columns = 3, points = FALSE, lines = TRUE ) ) doubleYScale( p1, p2, use.style = FALSE, add.ylab2 = TRUE ) We can now analyze those metrics that are sometimes specifically advertised as being able to come up with an optimal cutoff without costs, and contrast it with our cost-based approach! Let's use the three most often used metrics: Accuracy (maximize accuracy) Youden rule (maximize $Sens+Spec-1$) Topleft rule (minimize $\left(1-Sens\right)^2+\left(1-Spec\right)^2$) (For simplicity, we will subtract the above values from 1 for the Youden and the Accuracy rule so that we have a minimization problem everywhere.) Let's see the results: p3 <- xyplot( value ~ ps, groups = variable, data = droplevels( res[ variable%in%c( "Expected overall cost", "Accuracy", "Youden", "Topleft" ) ] ), subset = variable%in%c( "Accuracy", "Youden", "Topleft" ), type = "l", xlab = "Threshold", ylab = "Accuracy/Youden/Topleft", auto.key = list( columns = 3, points = FALSE, lines = TRUE ), panel = panel.superpose, panel.groups = function( x, y, col.line, ... ) { panel.xyplot( x, y, col.line = col.line, ... ) panel.abline( v = x[ which.min( y ) ], col = col.line ) panel.points( x[ which.min( y ) ], min( y ), pch = 19, col = col.line ) } ) doubleYScale( p1, p3, use.style = FALSE, add.ylab2 = TRUE ) This of course pertains to one specific cost structure, $c_{-}^{-}=0$, $c_{+}^{+}=1$, $c_{+}^{-}=2$, $c_{-}^{+}=4$ (this obviously matters only for the optimal cost decision). To investigate the effect of cost structure, let's pick just the optimal threshold (instead of tracing the whole curve), but plot it as a function of costs. More specifically, as we have already seen, the optimal threshold depends on the four costs only through the $c_d^{-}/c_d^{+}$ ratio, so let's plot the optimal cutoff as a function of this, along with the typically used metrics that don't use costs: res2 <- data.frame( rat = 10^( seq( log10( 0.02 ), log10( 50 ), length.out = 500 ) ) ) res2$OptThreshold <- sapply( res2$rat, function( rat ) ps[ which.min( sapply( ps, Vectorize( ExpectedOverallCost, "b" ), p = predict( fit, type = "fitted" ), y = acath$sigdz, cplusminus = rat, cminusplus = 1, cplusplus = 0 ) ) ] ) xyplot( OptThreshold ~ rat, data = res2, type = "l", ylim = c( -0.1, 1.1 ), xlab = expression( {"c"^{"-"}}["d"]/{"c"^{"+"}}["d"] ), ylab = "Optimal threshold", scales = list( x = list( log = 10, at = c( 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50 ) ) ), panel = function( x, y, resin = res[ ,.( ps[ which.min( value ) ] ), .( variable ) ], ... ) { panel.xyplot( x, y, ... ) panel.abline( h = resin[variable=="Youden"] ) panel.text( log10( 0.02 ), resin[variable=="Youden"], "Y", pos = 3 ) panel.abline( h = resin[variable=="Accuracy"] ) panel.text( log10( 0.02 ), resin[variable=="Accuracy"], "A", pos = 3 ) panel.abline( h = resin[variable=="Topleft"] ) panel.text( log10( 0.02 ), resin[variable=="Topleft"], "TL", pos = 1 ) } ) Horizontal lines indicate the approaches that don't use costs (and are therefore constant). Again, we nicely see that as the additional cost of misclassification in the healthy group rises compared to that of the diseased group, the optimal threshold increases: if we really don't want healthy people to be classified as sick, we will use higher cutoff (and the other way around, of course!). And, finally, we yet again see why those methods that don't use costs are not (and can't!) be always optimal.
Example when using accuracy as an outcome measure will lead to a wrong conclusion
It might worth adding another, perhaps more straightforward example to Stephen's excellent answer. Let's consider a medical test, the result of which is normally distributed, both in sick and in healt
Example when using accuracy as an outcome measure will lead to a wrong conclusion It might worth adding another, perhaps more straightforward example to Stephen's excellent answer. Let's consider a medical test, the result of which is normally distributed, both in sick and in healthy people, with different parameters of course (but for simplicity, let's assume homoscedasticity, i.e., that the variance is the same): $$\begin{gather*}T \mid D \ominus \sim \mathcal{N}\left(\mu_{-},\sigma^2\right)\\T \mid D \oplus \sim \mathcal{N}\left(\mu_{+},\sigma^2\right)\end{gather*}.$$ Let's denote the prevalence of the disease with $p$ (i.e. $D\oplus\sim Bern\left(p\right)$), so this, together with the above, which are essentially conditional distributions, fully specifies the joint distribution. Thus the confusion matrix with threshold $b$ (i.e., those with test results above $b$ are classified as sick) is $$\begin{pmatrix} & D\oplus & D\ominus\\ T\oplus & p\left(1-\Phi_{+}\left(b\right)\right) & \left(1-p\right)\left(1-\Phi_{-}\left(b\right)\right)\\ T\ominus & p\Phi_{+}\left(b\right) & \left(1-p\right)\Phi_{-}\left(b\right)\\ \end{pmatrix}.$$ Accuracy-based approach The accuracy is $$p\left(1-\Phi_{+}\left(b\right)\right)+\left(1-p\right)\Phi_{-}\left(b\right),$$ we take its derivative w.r.t. $b$, set it equal to 0, multiply with $\sqrt{1\pi\sigma^2}$ and rearrange a bit: $$\begin{gather*} -p\varphi_{+}\left(b\right)+\varphi_{-}\left(b\right)-p\varphi_{-}\left(b\right)=0\\ e^{-\frac{\left(b-\mu_{-}\right)^2}{2\sigma^2}}\left[\left(1-p\right)-pe^{-\frac{2b\left(\mu_{-}-\mu_{+}\right)+\left(\mu_{+}^2-\mu_{-}^2\right)}{2\sigma^2}}\right]=0\end{gather*}$$ The first term can't be zero, so the only way the product can be zero is if the second term is zero: $$\begin{gather*}\left(1-p\right)-pe^{-\frac{2b\left(\mu_{-}-\mu_{+}\right)+\left(\mu_{+}^2-\mu_{-}^2\right)}{2\sigma^2}}=0\\-\frac{2b\left(\mu_{-}-\mu_{+}\right)+\left(\mu_{+}^2-\mu_{-}^2\right)}{2\sigma^2}=\log\frac{1-p}{p}\\ 2b\left(\mu_{+}-\mu_{-}\right)+\left(\mu_{-}^2-\mu_{+}^2\right)=2\sigma^2\log\frac{1-p}{p}\\ \end{gather*}$$ So the solution is $$b^{\ast}=\frac{\left(\mu_{+}^2-\mu_{-}^2\right)+2\sigma^2\log\frac{1-p}{p}}{2\left(\mu_{+}-\mu_{-}\right)}=\frac{\mu_{+}+\mu_{-}}{2}+\frac{\sigma^2}{\mu_{+}-\mu_{-}}\log\frac{1-p}{p}.$$ Note that this - of course - doesn't depend on the costs. If the classes are balanced, the optimum is the average of the mean test values in sick and healthy people, otherwise it is displaced based on the imbalance. Cost-based approach Using Stephen's notation, the expected overall cost is $$c_{+}^{+}p\left(1-\Phi_{+}\left(b\right)\right) + c_{+}^{-}\left(1-p\right)\left(1-\Phi_{-}\left(b\right)\right) + c_{-}^{+} p\Phi_{+}\left(b\right) + c_{-}^{-} \left(1-p\right)\Phi_{-}\left(b\right).$$ Take its derivate w.r.t $b$ and set it equal to zero: $$\begin{gather*} -c_{+}^{+} p \varphi_{+}\left(b\right)-c_{+}^{-}\left(1-p\right)\varphi_{-}\left(b\right)+c_{-}^{+}p\varphi_{+}\left(b\right)+c_{-}^{-}\left(1-p\right)\varphi_{-}\left(b\right)=\\ =\varphi_{+}\left(b\right)p\left(c_{-}^{+}-c_{+}^{+}\right)+\varphi_{-}\left(b\right)\left(1-p\right)\left(c_{-}^{-}-c_{+}^{-}\right)=\\ = \varphi_{+}\left(b\right)pc_d^{+}-\varphi_{-}\left(b\right)\left(1-p\right)c_d^{-}= 0,\end{gather*}$$ using the notation I introduced in my comments below Stephen's answer, i.e., $c_d^{+}=c_{-}^{+}-c_{+}^{+}$ and $c_d^{-}=c_{+}^{-}-c_{-}^{-}$. The optimal threshold is therefore given by the solution of the equation $$\boxed{\frac{\varphi_{+}\left(b\right)}{\varphi_{-}\left(b\right)}=\frac{\left(1-p\right)c_d^{-}}{pc_d^{+}}}.$$ Two things should be noted here: This results is totally generic and works for any distribution of the test results, not only normal. ($\varphi$ in that case of course means the probability density function of the distribution, not the normal density.) Whatever the solution for $b$ is, it is surely a function of $\frac{\left(1-p\right)c_d^{-}}{pc_d^{+}}$. (I.e., we immediately see how costs matter - in addition to class imbalance!) I'd be really interested to see if this equation has a generic solution for $b$ (parametrized by the $\varphi$s), but I would be surprised. Nevertheless, we can work it out for normal! $\sqrt{2\pi\sigma^2}$s cancel on the left hand side, so we have $$\begin{gather*} e^{-\frac{1}{2}\left(\frac{\left(b-\mu_{+}\right)^2}{\sigma^2}-\frac{\left(b-\mu_{-}\right)^2}{\sigma^2}\right)}=\frac{\left(1-p\right)c_d^{-}}{pc_d^{+}} \\ \left(b-\mu_{-}\right)^2-\left(b-\mu_{+}\right)^2 =2\sigma^2 \log \frac{\left(1-p\right)c_d^{-}}{pc_d^{+}} \\ 2b\left(\mu_{+}-\mu_{-}\right)+\left(\mu_{-}^2-\mu_{+}^2\right) =2\sigma^2 \log \frac{\left(1-p\right)c_d^{-}}{pc_d^{+}}\end{gather*}$$ therefore the solution is $$b^{\ast}=\frac{\left(\mu_{+}^2-\mu_{-}^2\right)+2\sigma^2 \log \frac{\left(1-p\right)c_d^{-}}{pc_d^{+}}}{2\left(\mu_{+}-\mu_{-}\right)}=\frac{\mu_{+}+\mu_{-}}{2}+\frac{\sigma^2}{\mu_{+}-\mu_{-}}\log \frac{\left(1-p\right)c_d^{-}}{pc_d^{+}}.$$ (Compare it the the previous result! We see that they are equal if and only if $c_d^{-}=c_d^{+}$, i.e. the differences in misclassification cost compared to the cost of correct classification is the same in sick and healthy people.) A short demonstration Let's say $c_{-}^{-}=0$ (it is quite natural medically), and that $c_{+}^{+}=1$ (we can always obtain it by dividing the costs with $c_{+}^{+}$, i.e., by measuring every cost in $c_{+}^{+}$ units). Let's say that the prevalence is $p=0.2$. Also, let's say that $\mu_{-}=9.5$, $\mu_{+}=10.5$ and $\sigma=1$. In this case: library( data.table ) library( lattice ) cminusminus <- 0 cplusplus <- 1 p <- 0.2 muminus <- 9.5 muplus <- 10.5 sigma <- 1 res <- data.table( expand.grid( b = seq( 6, 17, 0.1 ), cplusminus = c( 1, 5, 10, 50, 100 ), cminusplus = c( 2, 5, 10, 50, 100 ) ) ) res$cost <- cplusplus*p*( 1-pnorm( res$b, muplus, sigma ) ) + res$cplusminus*(1-p)*(1-pnorm( res$b, muminus, sigma ) ) + res$cminusplus*p*pnorm( res$b, muplus, sigma ) + cminusminus*(1-p)*pnorm( res$b, muminus, sigma ) xyplot( cost ~ b | factor( cminusplus ), groups = cplusminus, ylim = c( -1, 22 ), data = res, type = "l", xlab = "Threshold", ylab = "Expected overall cost", as.table = TRUE, abline = list( v = (muplus+muminus)/2+ sigma^2/(muplus-muminus)*log((1-p)/p) ), strip = strip.custom( var.name = expression( {"c"^{"+"}}["-"] ), strip.names = c( TRUE, TRUE ) ), auto.key = list( space = "right", points = FALSE, lines = TRUE, title = expression( {"c"^{"-"}}["+"] ) ), panel = panel.superpose, panel.groups = function( x, y, col.line, ... ) { panel.xyplot( x, y, col.line = col.line, ... ) panel.points( x[ which.min( y ) ], min( y ), pch = 19, col = col.line ) } ) The result is (points depict the minimum cost, and the vertical line shows the optimal threshold with the accuracy-based approach): We can very nicely see how cost-based optimum can be different than the accuracy-based optimum. It is instructive to think over why: if it is more costly to classify a sick people erroneously healthy than the other way around ($c_{-}^{+}$ is high, $c_{+}^{-}$ is low) than the threshold goes down, as we prefer to classify more easily into the category sick, on the other hand, if it is more costly to classify a healthy people erroneously sick than the other way around ($c_{-}^{+}$ is low, $c_{+}^{-}$ is high) than the threshold goes up, as we prefer to classify more easily into the category healthy. (Check these on the figure!) A real-life example Let's have a look at an empirical example, instead of a theoretical derivation. This example will be different basically from two aspects: Instead of assuming normality, we will simply use the empirical data without any such assumption. Instead of using one single test, and its results in its own units, we will use several tests (and combine them with a logistic regression). Threshold will be given to the final predicted probability. This is actually the preferred approach, see Chapter 19 - Diagnosis - in Frank Harrell's BBR. The dataset (acath from the package Hmisc) is from the Duke University Cardiovascular Disease Databank, and contains whether the patient had significant coronary disease, as assessed by cardiac catheterization, this will be our gold standard, i.e., the true disease status, and the "test" will be the combination of the subject's age, sex, cholesterol level and duration of symptoms: library( rms ) library( lattice ) library( latticeExtra ) library( data.table ) getHdata( "acath" ) acath <- acath[ !is.na( acath$choleste ), ] dd <- datadist( acath ) options( datadist = "dd" ) fit <- lrm( sigdz ~ rcs( age )*sex + rcs( choleste ) + cad.dur, data = acath ) It worth plotting the predicted risks on logit-scale, to see how normal they are (essentially, that was what we assumed previously, with one single test!): densityplot( ~predict( fit ), groups = acath$sigdz, plot.points = FALSE, ref = TRUE, auto.key = list( columns = 2 ) ) Well, they're hardly normal... Let's go on and calculate the expected overall cost: ExpectedOverallCost <- function( b, p, y, cplusminus, cminusplus, cplusplus = 1, cminusminus = 0 ) { sum( table( factor( p>b, levels = c( FALSE, TRUE ) ), y )*matrix( c( cminusminus, cplusminus, cminusplus, cplusplus ), nc = 2 ) ) } table( predict( fit, type = "fitted" )>0.5, acath$sigdz ) ExpectedOverallCost( 0.5, predict( fit, type = "fitted" ), acath$sigdz, 2, 4 ) And let's plot it for all possible costs (a computational note: we don't need to mindlessly iterate through numbers from 0 to 1, we can perfectly reconstruct the curve by calculating it for all unique values of predicted probabilities): ps <- sort( unique( c( 0, 1, predict( fit, type = "fitted" ) ) ) ) xyplot( sapply( ps, ExpectedOverallCost, p = predict( fit, type = "fitted" ), y = acath$sigdz, cplusminus = 2, cminusplus = 4 ) ~ ps, type = "l", xlab = "Threshold", ylab = "Expected overall cost", panel = function( x, y, ... ) { panel.xyplot( x, y, ... ) panel.points( x[ which.min( y ) ], min( y ), pch = 19, cex = 1.1 ) panel.text( x[ which.min( y ) ], min( y ), round( x[ which.min( y ) ], 3 ), pos = 3 ) } ) We can very well see where we should put the threshold to optimize the expected overall cost (without using sensitivity, specificity or predictive values anywhere!). This is the correct approach. It is especially instructive to contrast these metrics: ExpectedOverallCost2 <- function( b, p, y, cplusminus, cminusplus, cplusplus = 1, cminusminus = 0 ) { tab <- table( factor( p>b, levels = c( FALSE, TRUE ) ), y ) sens <- tab[ 2, 2 ] / sum( tab[ , 2 ] ) spec <- tab[ 1, 1 ] / sum( tab[ , 1 ] ) c( `Expected overall cost` = sum( tab*matrix( c( cminusminus, cplusminus, cminusplus, cplusplus ), nc = 2 ) ), Sensitivity = sens, Specificity = spec, PPV = tab[ 2, 2 ] / sum( tab[ 2, ] ), NPV = tab[ 1, 1 ] / sum( tab[ 1, ] ), Accuracy = 1 - ( tab[ 1, 1 ] + tab[ 2, 2 ] )/sum( tab ), Youden = 1 - ( sens + spec - 1 ), Topleft = ( 1-sens )^2 + ( 1-spec )^2 ) } ExpectedOverallCost2( 0.5, predict( fit, type = "fitted" ), acath$sigdz, 2, 4 ) res <- melt( data.table( ps, t( sapply( ps, ExpectedOverallCost2, p = predict( fit, type = "fitted" ), y = acath$sigdz, cplusminus = 2, cminusplus = 4 ) ) ), id.vars = "ps" ) p1 <- xyplot( value ~ ps, data = res, subset = variable=="Expected overall cost", type = "l", xlab = "Threshold", ylab = "Expected overall cost", panel=function( x, y, ... ) { panel.xyplot( x, y, ... ) panel.abline( v = x[ which.min( y ) ], col = trellis.par.get()$plot.line$col ) panel.points( x[ which.min( y ) ], min( y ), pch = 19 ) } ) p2 <- xyplot( value ~ ps, groups = variable, data = droplevels( res[ variable%in%c( "Expected overall cost", "Sensitivity", "Specificity", "PPV", "NPV" ) ] ), subset = variable%in%c( "Sensitivity", "Specificity", "PPV", "NPV" ), type = "l", xlab = "Threshold", ylab = "Sensitivity/Specificity/PPV/NPV", auto.key = list( columns = 3, points = FALSE, lines = TRUE ) ) doubleYScale( p1, p2, use.style = FALSE, add.ylab2 = TRUE ) We can now analyze those metrics that are sometimes specifically advertised as being able to come up with an optimal cutoff without costs, and contrast it with our cost-based approach! Let's use the three most often used metrics: Accuracy (maximize accuracy) Youden rule (maximize $Sens+Spec-1$) Topleft rule (minimize $\left(1-Sens\right)^2+\left(1-Spec\right)^2$) (For simplicity, we will subtract the above values from 1 for the Youden and the Accuracy rule so that we have a minimization problem everywhere.) Let's see the results: p3 <- xyplot( value ~ ps, groups = variable, data = droplevels( res[ variable%in%c( "Expected overall cost", "Accuracy", "Youden", "Topleft" ) ] ), subset = variable%in%c( "Accuracy", "Youden", "Topleft" ), type = "l", xlab = "Threshold", ylab = "Accuracy/Youden/Topleft", auto.key = list( columns = 3, points = FALSE, lines = TRUE ), panel = panel.superpose, panel.groups = function( x, y, col.line, ... ) { panel.xyplot( x, y, col.line = col.line, ... ) panel.abline( v = x[ which.min( y ) ], col = col.line ) panel.points( x[ which.min( y ) ], min( y ), pch = 19, col = col.line ) } ) doubleYScale( p1, p3, use.style = FALSE, add.ylab2 = TRUE ) This of course pertains to one specific cost structure, $c_{-}^{-}=0$, $c_{+}^{+}=1$, $c_{+}^{-}=2$, $c_{-}^{+}=4$ (this obviously matters only for the optimal cost decision). To investigate the effect of cost structure, let's pick just the optimal threshold (instead of tracing the whole curve), but plot it as a function of costs. More specifically, as we have already seen, the optimal threshold depends on the four costs only through the $c_d^{-}/c_d^{+}$ ratio, so let's plot the optimal cutoff as a function of this, along with the typically used metrics that don't use costs: res2 <- data.frame( rat = 10^( seq( log10( 0.02 ), log10( 50 ), length.out = 500 ) ) ) res2$OptThreshold <- sapply( res2$rat, function( rat ) ps[ which.min( sapply( ps, Vectorize( ExpectedOverallCost, "b" ), p = predict( fit, type = "fitted" ), y = acath$sigdz, cplusminus = rat, cminusplus = 1, cplusplus = 0 ) ) ] ) xyplot( OptThreshold ~ rat, data = res2, type = "l", ylim = c( -0.1, 1.1 ), xlab = expression( {"c"^{"-"}}["d"]/{"c"^{"+"}}["d"] ), ylab = "Optimal threshold", scales = list( x = list( log = 10, at = c( 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50 ) ) ), panel = function( x, y, resin = res[ ,.( ps[ which.min( value ) ] ), .( variable ) ], ... ) { panel.xyplot( x, y, ... ) panel.abline( h = resin[variable=="Youden"] ) panel.text( log10( 0.02 ), resin[variable=="Youden"], "Y", pos = 3 ) panel.abline( h = resin[variable=="Accuracy"] ) panel.text( log10( 0.02 ), resin[variable=="Accuracy"], "A", pos = 3 ) panel.abline( h = resin[variable=="Topleft"] ) panel.text( log10( 0.02 ), resin[variable=="Topleft"], "TL", pos = 1 ) } ) Horizontal lines indicate the approaches that don't use costs (and are therefore constant). Again, we nicely see that as the additional cost of misclassification in the healthy group rises compared to that of the diseased group, the optimal threshold increases: if we really don't want healthy people to be classified as sick, we will use higher cutoff (and the other way around, of course!). And, finally, we yet again see why those methods that don't use costs are not (and can't!) be always optimal.
Example when using accuracy as an outcome measure will lead to a wrong conclusion It might worth adding another, perhaps more straightforward example to Stephen's excellent answer. Let's consider a medical test, the result of which is normally distributed, both in sick and in healt
15,326
Why is Ordinary Least Squares performing better than Poisson regression?
I suspect that part of the problem may lie in your choice of performance metric. If you measure test performance using RMSE then training the model to minimise the MSE matches the test criterion, giving a hint as to what is considered important. You may find that if you measure the test performance using the negative log-likelihood of the test set using a Poisson likelihood that the Poisson model works better (as might be expected). This may be a minor issue compared with the other issues raised, but it might be a useful sanity check.
Why is Ordinary Least Squares performing better than Poisson regression?
I suspect that part of the problem may lie in your choice of performance metric. If you measure test performance using RMSE then training the model to minimise the MSE matches the test criterion, giv
Why is Ordinary Least Squares performing better than Poisson regression? I suspect that part of the problem may lie in your choice of performance metric. If you measure test performance using RMSE then training the model to minimise the MSE matches the test criterion, giving a hint as to what is considered important. You may find that if you measure the test performance using the negative log-likelihood of the test set using a Poisson likelihood that the Poisson model works better (as might be expected). This may be a minor issue compared with the other issues raised, but it might be a useful sanity check.
Why is Ordinary Least Squares performing better than Poisson regression? I suspect that part of the problem may lie in your choice of performance metric. If you measure test performance using RMSE then training the model to minimise the MSE matches the test criterion, giv
15,327
Why is Ordinary Least Squares performing better than Poisson regression?
First, with such data I would expect overdispersion (if you don't know what that is, see https://stats.stackexchange.com/search?q=what+is+overdispersion%3F ). That would have to be addressed with a Poisson glm, but is not an issue with usual linear regression. As said in a comment, with a poisson glm you want to include $\log(\text{DistrictSize})$ as an offset, with a linear regression you will need to use as response variable $\frac{\text{Nr. homicides}}{\text{District Size}}$. One possible reason for the discrepancy of results is that you have treated this problem differently in the two cases. You could post here some plots of results, like residual plots, so we can see what is happening. Or you could post your data as a table in the original post .... could be interesting to have a look. Another issue is the transformation you used with the linear regression. The usual variance stabilizing transformation used with count data is the square root, not the logarithm. Another issue is the choice of transformation used with linear regression. When using as response $Y_i/x_i$, you wil need weighted linear regression. Assuming as an approximation that $Y_i \sim \text{Poisson}(\lambda x_i)$, we have $$ \DeclareMathOperator{\E}{\mathbb{E}} \DeclareMathOperator{\V}{\mathbb{V}} \E \frac{Y_i}{x_i} \propto \lambda \\ \V \frac{Y_i}{x_i} \propto x_i^{-1} $$ So you should use weighted linear regression with $x_i$ as weight. A simple analysis shows that, as an approximation, the same weights are appropriate with $\sqrt{Y_i/x_i}$ or $\log (Y_i/x_i +1)$ as responses. EDIT As for your additional analysis in the post, note that rmse's cannot be compared directly between the two models, as different responses are used! To make a direct comparison, you will need to backtransform the predicted values to the original scale. Then you can calculate rmse's yourself, and see. But note that predictions obtained after backtransformation can be biased, because of nonlinearities. So some adjustment to the backtransformed predictions could make them more useful. In some cases, such could be calculated theoretically, ot you could just use a bootstrap.
Why is Ordinary Least Squares performing better than Poisson regression?
First, with such data I would expect overdispersion (if you don't know what that is, see https://stats.stackexchange.com/search?q=what+is+overdispersion%3F ). That would have to be addressed with a P
Why is Ordinary Least Squares performing better than Poisson regression? First, with such data I would expect overdispersion (if you don't know what that is, see https://stats.stackexchange.com/search?q=what+is+overdispersion%3F ). That would have to be addressed with a Poisson glm, but is not an issue with usual linear regression. As said in a comment, with a poisson glm you want to include $\log(\text{DistrictSize})$ as an offset, with a linear regression you will need to use as response variable $\frac{\text{Nr. homicides}}{\text{District Size}}$. One possible reason for the discrepancy of results is that you have treated this problem differently in the two cases. You could post here some plots of results, like residual plots, so we can see what is happening. Or you could post your data as a table in the original post .... could be interesting to have a look. Another issue is the transformation you used with the linear regression. The usual variance stabilizing transformation used with count data is the square root, not the logarithm. Another issue is the choice of transformation used with linear regression. When using as response $Y_i/x_i$, you wil need weighted linear regression. Assuming as an approximation that $Y_i \sim \text{Poisson}(\lambda x_i)$, we have $$ \DeclareMathOperator{\E}{\mathbb{E}} \DeclareMathOperator{\V}{\mathbb{V}} \E \frac{Y_i}{x_i} \propto \lambda \\ \V \frac{Y_i}{x_i} \propto x_i^{-1} $$ So you should use weighted linear regression with $x_i$ as weight. A simple analysis shows that, as an approximation, the same weights are appropriate with $\sqrt{Y_i/x_i}$ or $\log (Y_i/x_i +1)$ as responses. EDIT As for your additional analysis in the post, note that rmse's cannot be compared directly between the two models, as different responses are used! To make a direct comparison, you will need to backtransform the predicted values to the original scale. Then you can calculate rmse's yourself, and see. But note that predictions obtained after backtransformation can be biased, because of nonlinearities. So some adjustment to the backtransformed predictions could make them more useful. In some cases, such could be calculated theoretically, ot you could just use a bootstrap.
Why is Ordinary Least Squares performing better than Poisson regression? First, with such data I would expect overdispersion (if you don't know what that is, see https://stats.stackexchange.com/search?q=what+is+overdispersion%3F ). That would have to be addressed with a P
15,328
Why is Ordinary Least Squares performing better than Poisson regression?
There are lots of choices of pseudo $R^2$'s. Lots of them are very flawed. Generally speaking, there's usually no reason that the $R^2$ produced from OLS will be a comparable value to a given pseudo $R^2$; rather, pseudo $R^2$'s are typically used for comparing models of the same distributional family.
Why is Ordinary Least Squares performing better than Poisson regression?
There are lots of choices of pseudo $R^2$'s. Lots of them are very flawed. Generally speaking, there's usually no reason that the $R^2$ produced from OLS will be a comparable value to a given pseudo $
Why is Ordinary Least Squares performing better than Poisson regression? There are lots of choices of pseudo $R^2$'s. Lots of them are very flawed. Generally speaking, there's usually no reason that the $R^2$ produced from OLS will be a comparable value to a given pseudo $R^2$; rather, pseudo $R^2$'s are typically used for comparing models of the same distributional family.
Why is Ordinary Least Squares performing better than Poisson regression? There are lots of choices of pseudo $R^2$'s. Lots of them are very flawed. Generally speaking, there's usually no reason that the $R^2$ produced from OLS will be a comparable value to a given pseudo $
15,329
Why is Ordinary Least Squares performing better than Poisson regression?
It is true that your data is not Normally distributed (which I presume is why you also ran a Poisson regression) but your data is likely not a Poisson distribution either. The Poisson distribution assumes that the mean and the variance are the same, which is likely not the case (as mentioned in other answers - you can capture this discrepancy and incorporate it into the model). Since your data isn't really a perfect fit for either model, it makes sense that OLS may perform better. Another thing to note is that the ordinary least squares estimates are robust to non-Normality which may be why you're getting a reasonable model. The Gauss-Markov Theorem tells us that OLS coefficients estimates are the best (in terms of mean squared error) linear unbiased estimators (BLUE) under the following assumptions, The errors have a mean of zero The observations are uncorrelated The errors have have constant variance There is no assumption of Normality here so your data can very well be reasonable for this model! With that being said, I would look into a Poisson model with an over-dispersion parameter baked in there and you should get better results.
Why is Ordinary Least Squares performing better than Poisson regression?
It is true that your data is not Normally distributed (which I presume is why you also ran a Poisson regression) but your data is likely not a Poisson distribution either. The Poisson distribution ass
Why is Ordinary Least Squares performing better than Poisson regression? It is true that your data is not Normally distributed (which I presume is why you also ran a Poisson regression) but your data is likely not a Poisson distribution either. The Poisson distribution assumes that the mean and the variance are the same, which is likely not the case (as mentioned in other answers - you can capture this discrepancy and incorporate it into the model). Since your data isn't really a perfect fit for either model, it makes sense that OLS may perform better. Another thing to note is that the ordinary least squares estimates are robust to non-Normality which may be why you're getting a reasonable model. The Gauss-Markov Theorem tells us that OLS coefficients estimates are the best (in terms of mean squared error) linear unbiased estimators (BLUE) under the following assumptions, The errors have a mean of zero The observations are uncorrelated The errors have have constant variance There is no assumption of Normality here so your data can very well be reasonable for this model! With that being said, I would look into a Poisson model with an over-dispersion parameter baked in there and you should get better results.
Why is Ordinary Least Squares performing better than Poisson regression? It is true that your data is not Normally distributed (which I presume is why you also ran a Poisson regression) but your data is likely not a Poisson distribution either. The Poisson distribution ass
15,330
Confidence intervals for median
Summary When you can assume little or nothing about the true probability law, and can infer little about it--which is the case for small samples of $n$ observations--then a suitably chosen pair of order statistics will constitute a confidence interval for the median. Which order statistics to choose can easily be found with a quick analysis of the Binomial$(n, 1/2)$ distribution. There are some choices to be made in practice: these are discussed and illustrated at the end of this post. Incidentally, the same analysis can be used to construct confidence intervals for any quantile $q$ (of which the median, corresponding to $q=50\%$, is one example). The Binomial$(n, q)$ distribution governs the solution in this case. Introduction Recall what a confidence interval (CI) means. The setting is an independent random sample $X = (X_1, X_2, \ldots, X_n)$ with each $X_i$ governed by the same distribution $F$. It is assumed only that $F$ is one element of a set $\Omega$ of possible distributions. Each of them has a median $F_{1/2}$. For any fixed $\alpha$ between $0$ and $1$, a CI of level $\alpha$ is a pair of functions (aka "statistics"), $L$ and $U$, such that $${\Pr}_F(L(X)\le F_{1/2} \le U(X)) \ge 1 - \alpha.$$ The right hand side is the coverage of the CI for the distribution $F$. Aside: for this to be useful, we also prefer that (1) the infimum of the coverages over $F\in\Omega$ be as small as possible and (2) the expected length of the interval, $\mathbb{E}_F(U(X)-L(X))$, should tend to be short for all or "most" $F\in\Omega$. Analysis Suppose we assume nothing about $\Omega$. In this situation we can still exploit the order statistics. These are the specific values in the sorted sample. To simplify the notation, let's sort the sample once and for all so that $$X_1 \le X_2 \le \cdots \le X_n.$$ The value $X_i$ is the $i^\text{th}$ order statistic of the sample. Since we're assuming nothing about $\Omega$, we know nothing about $F$ at first, so we can't infer much about the likely intervals between each $X_i$ and its neighbor $X_{i+1}$. However, we can still reason quantitatively about the individual values: what is the chance that $X_i$ does not exceed the median of $F$? To figure this out, let $Y$ be a random variable governed by $F$, and let $$\pi_F = {\Pr}_F(Y \le F_{1/2})$$ be the chance that $Y$ does not exceed the median of $F$. Then when $X_i \le F_{1/2}$ we know (since $X_1\le \cdots \le X_i \le F_{1/2}$) that our original unordered sample of $n$ values must have contained at least $i$ values not exceeding $F_{1/2}$. This is a Binomial problem. Formally, if we define the random variable $Z$ to equal $1$ when $Y \le F_{1/2}$ and $0$ otherwise, the foregoing shows that $Z$ has a Bernoulli distribution with parameter $\pi_F$. A "success" consists in observing a value at or below the median. Therefore $\Pr(X_i \gt F_{1/2})$ is given by the Binomial probability associated with fewer than $i$ successes: $$\Pr(X_i \gt F_{1/2}) = \sum_{j=0}^{i-1} \binom{n}{j} \pi_F^j(1-\pi_F)^{n-j}.$$ You probably noticed that $\pi_F \ge 1/2$. In fact, for many distributions the two values are equal: they differ only when $F$ assigns positive probability to the median $F_{1/2}$. To analyze the difference, write $\pi_F = 1/2 + \varepsilon$ for $\varepsilon \ge 0$. For $2(j-1) \le n$ this implies $$\eqalign{ \pi_F^j(1-\pi_F)^{n-j} &= (1/2+\varepsilon)^j(1/2-\varepsilon)^{n-j} = (1/2+\varepsilon)^j[(1/2-\varepsilon)^j(1/2-\varepsilon)^{n-2j}]\\ &=(1/4-\varepsilon^2)^j(1/2-\varepsilon)^{n-2j} \le (1/4)^j(1/2)^{n-2j}=2^{-n}. }$$ Consequently, when $2(i-1) \le n$, we may get rid of the dependence of the sum on $F$, at the cost of replacing the equality by an inequality: $$\Pr(X_i \gt F_{1/2}) \le 2^{-n}\sum_{j=0}^{i-1} \binom{n}{j}.$$ Exactly the same argument (applied by reversing the order statistics) shows that when $2(i+1) \ge n$, $$\Pr(X_i \lt F_{1/2}) \le 2^{-n}\sum_{j=i+1}^n \binom{n}{j}.$$ The right hand sides reduce to zero whenever $i \le 0$ (in the first case) or $i \ge n$ (in the second). Therefore, it is always possible to find indexes $l \le u$ for which $$\eqalign{ \Pr(X_l \gt F_{1/2} \text{ or } X_u \lt F_{1/2}) &= \Pr(X_l \gt F_{1/2}) + \Pr( X_u \lt F_{1/2}) \\ &\le 2^{-n}\left(\sum_{j=0}^{l-1} \binom{n}{j} + \sum_{j=u+1}^n \binom{n}{j}\right). }$$ Solution This is the complement of the defining condition for a confidence interval, and therefore equivalent to it: $$\Pr(X_l \le F_{1/2}\le X_u ) \ge 2^{-n}\sum_{j=l}^u \binom{n}{j}.$$ By selecting $l \le u$ to make the right hand side at least $1-\alpha$, we will have found a confidence interval procedure whose level is at least $1-\alpha$. In other words, upon choosing such indexes $l$ and $u$, by setting $L(X) = X_l$ and $U(X) = X_u$, the interval $[L(X), U(X)]$ will be a CI for the median $F_{1/2}$ having coverage at least $1-\alpha$. You can compute its actual coverage in terms of Binomial probabilities. This coverage will be attained for any distribution $F$ which assigns zero probability to $F_{1/2}$ (which includes all continuous distributions). It will be exceeded by any $F$ which assigns nonzero probability to $F_{1/2}$. Discussion At this point we have some choices. The commonest is to make the limits symmetric by setting $u$ reasonably close to $n+1-l$. In fact, by stipulating $u=n+1-l$, the confidence limits can be found for any $n$ with a quick search or by applying the Binomial quantile function. For example, let $n=10$ and $\alpha=10\%$ (to illustrate a $1-\alpha=90\%$ CI procedure). Let's tally the lower part of the cumulative Binomial distribution with parameters $10$ and $1/2$: > i <- 0:5; names(i) <- i; print(pbinom(i, 10, 1/2), digits=1) 0 1 2 3 4 5 0.001 0.011 0.055 0.172 0.377 0.623 (This is an R command and its response.) Because the value at $2$, equal to $5.5\%$, is close to $\alpha/2$, it is tempting to take $l=3$ and $u=10+1-3=8$, for then the coverage will be $1 - 0.055 - 0.055 = 0.89$ which is close to the target of $90\%$. If you must achieve the desired coverage, then you need to take $l=2$ and $u=8$ or $l=3$ and $u=9$, both with coverage $1 - 0.011 - .055 = 0.935$. As a check, let's simulate a lot of datasets from any distribution whatsoever, compute these CIs for the datasets, and tally the proportion of CIs that do cover the true median. This R example uses a Normal distribution: n <- 10 n.sim <- 1e4 x <- apply(matrix(rnorm(n*n.sim), nrow=n), 2, sort) covers <- function(x, l, u) mean(x[l, ] <= 0 & x[u, ] >= 0) c(l3.u8=covers(x,3,8), l2.u8=covers(x,2,8), l3.u9=covers(x,3,9)) The output is l3.u8 l2.u8 l3.u9 0.8904 0.9357 0.9319 The coverages agree closely with the theoretical values. As another example, let's draw samples from a discrete distribution, such as a Poisson: lambda <- 2 x <- apply(matrix(rpois(n*n.sim, 2), nrow=n), 2, sort) med <- round(lambda + 1/3 - 0.02/lambda) c(l3.u8=covers(x,3,8), l2.u8=covers(x,2,8), l3.u9=covers(x,3,9)) l3.u8 l2.u8 l3.u9 0.9830 0.9845 0.9964 This time the coverages are much higher than anticipated. The reason is that there is a $27\%$ chance that a random value equals the median. This greatly increases the chance that the CI covers the median. This is not a problem or a paradox. By definition, the coverage has to be at least $1-\alpha$ no matter what the distribution $F$ is--but it's possible (as in this case) that the coverage for particular distributions is substantially greater than $1-\alpha$. Therein lies the tradeoff: when you assume nothing about $F$, the CI based on order statistics is the only one you can construct. Its coverage for your true (but unknown) $F$ might be quite a bit higher than you expect. That means your CI will be wider than if you had made some stronger assumptions about $\Omega$ by limiting the possibilities for $F$.
Confidence intervals for median
Summary When you can assume little or nothing about the true probability law, and can infer little about it--which is the case for small samples of $n$ observations--then a suitably chosen pair of ord
Confidence intervals for median Summary When you can assume little or nothing about the true probability law, and can infer little about it--which is the case for small samples of $n$ observations--then a suitably chosen pair of order statistics will constitute a confidence interval for the median. Which order statistics to choose can easily be found with a quick analysis of the Binomial$(n, 1/2)$ distribution. There are some choices to be made in practice: these are discussed and illustrated at the end of this post. Incidentally, the same analysis can be used to construct confidence intervals for any quantile $q$ (of which the median, corresponding to $q=50\%$, is one example). The Binomial$(n, q)$ distribution governs the solution in this case. Introduction Recall what a confidence interval (CI) means. The setting is an independent random sample $X = (X_1, X_2, \ldots, X_n)$ with each $X_i$ governed by the same distribution $F$. It is assumed only that $F$ is one element of a set $\Omega$ of possible distributions. Each of them has a median $F_{1/2}$. For any fixed $\alpha$ between $0$ and $1$, a CI of level $\alpha$ is a pair of functions (aka "statistics"), $L$ and $U$, such that $${\Pr}_F(L(X)\le F_{1/2} \le U(X)) \ge 1 - \alpha.$$ The right hand side is the coverage of the CI for the distribution $F$. Aside: for this to be useful, we also prefer that (1) the infimum of the coverages over $F\in\Omega$ be as small as possible and (2) the expected length of the interval, $\mathbb{E}_F(U(X)-L(X))$, should tend to be short for all or "most" $F\in\Omega$. Analysis Suppose we assume nothing about $\Omega$. In this situation we can still exploit the order statistics. These are the specific values in the sorted sample. To simplify the notation, let's sort the sample once and for all so that $$X_1 \le X_2 \le \cdots \le X_n.$$ The value $X_i$ is the $i^\text{th}$ order statistic of the sample. Since we're assuming nothing about $\Omega$, we know nothing about $F$ at first, so we can't infer much about the likely intervals between each $X_i$ and its neighbor $X_{i+1}$. However, we can still reason quantitatively about the individual values: what is the chance that $X_i$ does not exceed the median of $F$? To figure this out, let $Y$ be a random variable governed by $F$, and let $$\pi_F = {\Pr}_F(Y \le F_{1/2})$$ be the chance that $Y$ does not exceed the median of $F$. Then when $X_i \le F_{1/2}$ we know (since $X_1\le \cdots \le X_i \le F_{1/2}$) that our original unordered sample of $n$ values must have contained at least $i$ values not exceeding $F_{1/2}$. This is a Binomial problem. Formally, if we define the random variable $Z$ to equal $1$ when $Y \le F_{1/2}$ and $0$ otherwise, the foregoing shows that $Z$ has a Bernoulli distribution with parameter $\pi_F$. A "success" consists in observing a value at or below the median. Therefore $\Pr(X_i \gt F_{1/2})$ is given by the Binomial probability associated with fewer than $i$ successes: $$\Pr(X_i \gt F_{1/2}) = \sum_{j=0}^{i-1} \binom{n}{j} \pi_F^j(1-\pi_F)^{n-j}.$$ You probably noticed that $\pi_F \ge 1/2$. In fact, for many distributions the two values are equal: they differ only when $F$ assigns positive probability to the median $F_{1/2}$. To analyze the difference, write $\pi_F = 1/2 + \varepsilon$ for $\varepsilon \ge 0$. For $2(j-1) \le n$ this implies $$\eqalign{ \pi_F^j(1-\pi_F)^{n-j} &= (1/2+\varepsilon)^j(1/2-\varepsilon)^{n-j} = (1/2+\varepsilon)^j[(1/2-\varepsilon)^j(1/2-\varepsilon)^{n-2j}]\\ &=(1/4-\varepsilon^2)^j(1/2-\varepsilon)^{n-2j} \le (1/4)^j(1/2)^{n-2j}=2^{-n}. }$$ Consequently, when $2(i-1) \le n$, we may get rid of the dependence of the sum on $F$, at the cost of replacing the equality by an inequality: $$\Pr(X_i \gt F_{1/2}) \le 2^{-n}\sum_{j=0}^{i-1} \binom{n}{j}.$$ Exactly the same argument (applied by reversing the order statistics) shows that when $2(i+1) \ge n$, $$\Pr(X_i \lt F_{1/2}) \le 2^{-n}\sum_{j=i+1}^n \binom{n}{j}.$$ The right hand sides reduce to zero whenever $i \le 0$ (in the first case) or $i \ge n$ (in the second). Therefore, it is always possible to find indexes $l \le u$ for which $$\eqalign{ \Pr(X_l \gt F_{1/2} \text{ or } X_u \lt F_{1/2}) &= \Pr(X_l \gt F_{1/2}) + \Pr( X_u \lt F_{1/2}) \\ &\le 2^{-n}\left(\sum_{j=0}^{l-1} \binom{n}{j} + \sum_{j=u+1}^n \binom{n}{j}\right). }$$ Solution This is the complement of the defining condition for a confidence interval, and therefore equivalent to it: $$\Pr(X_l \le F_{1/2}\le X_u ) \ge 2^{-n}\sum_{j=l}^u \binom{n}{j}.$$ By selecting $l \le u$ to make the right hand side at least $1-\alpha$, we will have found a confidence interval procedure whose level is at least $1-\alpha$. In other words, upon choosing such indexes $l$ and $u$, by setting $L(X) = X_l$ and $U(X) = X_u$, the interval $[L(X), U(X)]$ will be a CI for the median $F_{1/2}$ having coverage at least $1-\alpha$. You can compute its actual coverage in terms of Binomial probabilities. This coverage will be attained for any distribution $F$ which assigns zero probability to $F_{1/2}$ (which includes all continuous distributions). It will be exceeded by any $F$ which assigns nonzero probability to $F_{1/2}$. Discussion At this point we have some choices. The commonest is to make the limits symmetric by setting $u$ reasonably close to $n+1-l$. In fact, by stipulating $u=n+1-l$, the confidence limits can be found for any $n$ with a quick search or by applying the Binomial quantile function. For example, let $n=10$ and $\alpha=10\%$ (to illustrate a $1-\alpha=90\%$ CI procedure). Let's tally the lower part of the cumulative Binomial distribution with parameters $10$ and $1/2$: > i <- 0:5; names(i) <- i; print(pbinom(i, 10, 1/2), digits=1) 0 1 2 3 4 5 0.001 0.011 0.055 0.172 0.377 0.623 (This is an R command and its response.) Because the value at $2$, equal to $5.5\%$, is close to $\alpha/2$, it is tempting to take $l=3$ and $u=10+1-3=8$, for then the coverage will be $1 - 0.055 - 0.055 = 0.89$ which is close to the target of $90\%$. If you must achieve the desired coverage, then you need to take $l=2$ and $u=8$ or $l=3$ and $u=9$, both with coverage $1 - 0.011 - .055 = 0.935$. As a check, let's simulate a lot of datasets from any distribution whatsoever, compute these CIs for the datasets, and tally the proportion of CIs that do cover the true median. This R example uses a Normal distribution: n <- 10 n.sim <- 1e4 x <- apply(matrix(rnorm(n*n.sim), nrow=n), 2, sort) covers <- function(x, l, u) mean(x[l, ] <= 0 & x[u, ] >= 0) c(l3.u8=covers(x,3,8), l2.u8=covers(x,2,8), l3.u9=covers(x,3,9)) The output is l3.u8 l2.u8 l3.u9 0.8904 0.9357 0.9319 The coverages agree closely with the theoretical values. As another example, let's draw samples from a discrete distribution, such as a Poisson: lambda <- 2 x <- apply(matrix(rpois(n*n.sim, 2), nrow=n), 2, sort) med <- round(lambda + 1/3 - 0.02/lambda) c(l3.u8=covers(x,3,8), l2.u8=covers(x,2,8), l3.u9=covers(x,3,9)) l3.u8 l2.u8 l3.u9 0.9830 0.9845 0.9964 This time the coverages are much higher than anticipated. The reason is that there is a $27\%$ chance that a random value equals the median. This greatly increases the chance that the CI covers the median. This is not a problem or a paradox. By definition, the coverage has to be at least $1-\alpha$ no matter what the distribution $F$ is--but it's possible (as in this case) that the coverage for particular distributions is substantially greater than $1-\alpha$. Therein lies the tradeoff: when you assume nothing about $F$, the CI based on order statistics is the only one you can construct. Its coverage for your true (but unknown) $F$ might be quite a bit higher than you expect. That means your CI will be wider than if you had made some stronger assumptions about $\Omega$ by limiting the possibilities for $F$.
Confidence intervals for median Summary When you can assume little or nothing about the true probability law, and can infer little about it--which is the case for small samples of $n$ observations--then a suitably chosen pair of ord
15,331
Confidence intervals for median
If you wish to use numerical methods, you may generate an estimate of the samping distribution of medians by using bootstrap. Repeatedly resample your sample and compute many medians. The stdev of these medians serves as an estimate of the stdev of the sampling distribution of medians. I used a similar method to compute the uncertainty of chess game outcomes in my paper on chess gambits which may be found here https://sonoma.academia.edu/JamalMunshi/papers
Confidence intervals for median
If you wish to use numerical methods, you may generate an estimate of the samping distribution of medians by using bootstrap. Repeatedly resample your sample and compute many medians. The stdev of the
Confidence intervals for median If you wish to use numerical methods, you may generate an estimate of the samping distribution of medians by using bootstrap. Repeatedly resample your sample and compute many medians. The stdev of these medians serves as an estimate of the stdev of the sampling distribution of medians. I used a similar method to compute the uncertainty of chess game outcomes in my paper on chess gambits which may be found here https://sonoma.academia.edu/JamalMunshi/papers
Confidence intervals for median If you wish to use numerical methods, you may generate an estimate of the samping distribution of medians by using bootstrap. Repeatedly resample your sample and compute many medians. The stdev of the
15,332
Why don't we use significant digits?
Significant digits are used in some fields (I learned about them in Chemistry) to indicate the degree of meaningful precision that exists in a number. This is an important topic in statistics as well, so in fact we report this constantly--we just report it in a different form. Specifically, we report confidence intervals, which indicate the level of precision of an estimate (such as a mean). Once you've listed the 95% CI for an estimate, such as $(-0.12, 1.12)$, you can list as many digits for your mean as you might like, such as $0.50129519823975923$, and there is no problem. In fact, the statistician Andrew Gelman has recommended that you list at least four (2009, p. 4).
Why don't we use significant digits?
Significant digits are used in some fields (I learned about them in Chemistry) to indicate the degree of meaningful precision that exists in a number. This is an important topic in statistics as well
Why don't we use significant digits? Significant digits are used in some fields (I learned about them in Chemistry) to indicate the degree of meaningful precision that exists in a number. This is an important topic in statistics as well, so in fact we report this constantly--we just report it in a different form. Specifically, we report confidence intervals, which indicate the level of precision of an estimate (such as a mean). Once you've listed the 95% CI for an estimate, such as $(-0.12, 1.12)$, you can list as many digits for your mean as you might like, such as $0.50129519823975923$, and there is no problem. In fact, the statistician Andrew Gelman has recommended that you list at least four (2009, p. 4).
Why don't we use significant digits? Significant digits are used in some fields (I learned about them in Chemistry) to indicate the degree of meaningful precision that exists in a number. This is an important topic in statistics as well
15,333
Why don't we use significant digits?
One reason for restricting the number of digits reported in many estimates, p-values, etc. is based on perception. Reporting something like p = 0.04872429 implies a level of precision in the results that causes them to be perceived as more accurate. Essentially, the use of high numbers of digits in reporting statistical results tastes too many of trying to cloak your findings in an undeserved air of authority.
Why don't we use significant digits?
One reason for restricting the number of digits reported in many estimates, p-values, etc. is based on perception. Reporting something like p = 0.04872429 implies a level of precision in the results t
Why don't we use significant digits? One reason for restricting the number of digits reported in many estimates, p-values, etc. is based on perception. Reporting something like p = 0.04872429 implies a level of precision in the results that causes them to be perceived as more accurate. Essentially, the use of high numbers of digits in reporting statistical results tastes too many of trying to cloak your findings in an undeserved air of authority.
Why don't we use significant digits? One reason for restricting the number of digits reported in many estimates, p-values, etc. is based on perception. Reporting something like p = 0.04872429 implies a level of precision in the results t
15,334
Why don't we use significant digits?
Are you talking about rounding your data to some number of significant digits or rounding your final answer? If you round your data you can get into situations where you've thrown away noise that statistical calculations need to use.
Why don't we use significant digits?
Are you talking about rounding your data to some number of significant digits or rounding your final answer? If you round your data you can get into situations where you've thrown away noise that sta
Why don't we use significant digits? Are you talking about rounding your data to some number of significant digits or rounding your final answer? If you round your data you can get into situations where you've thrown away noise that statistical calculations need to use.
Why don't we use significant digits? Are you talking about rounding your data to some number of significant digits or rounding your final answer? If you round your data you can get into situations where you've thrown away noise that sta
15,335
Why don't we use significant digits?
I think it really depends upon the level of confidence required, fewer digits for significance are appropriate for 95%, as opposed to 99.999% or greater, for example, as used by CERN for many of their results.
Why don't we use significant digits?
I think it really depends upon the level of confidence required, fewer digits for significance are appropriate for 95%, as opposed to 99.999% or greater, for example, as used by CERN for many of their
Why don't we use significant digits? I think it really depends upon the level of confidence required, fewer digits for significance are appropriate for 95%, as opposed to 99.999% or greater, for example, as used by CERN for many of their results.
Why don't we use significant digits? I think it really depends upon the level of confidence required, fewer digits for significance are appropriate for 95%, as opposed to 99.999% or greater, for example, as used by CERN for many of their
15,336
Examples of processes that are not Poisson?
Number of cigarettes smoked in a period of time: this requires a zero-inflated process (e.g. zero-inflated Poisson or zero-inflated negative binomial) because not everyone smokes cigarettes.
Examples of processes that are not Poisson?
Number of cigarettes smoked in a period of time: this requires a zero-inflated process (e.g. zero-inflated Poisson or zero-inflated negative binomial) because not everyone smokes cigarettes.
Examples of processes that are not Poisson? Number of cigarettes smoked in a period of time: this requires a zero-inflated process (e.g. zero-inflated Poisson or zero-inflated negative binomial) because not everyone smokes cigarettes.
Examples of processes that are not Poisson? Number of cigarettes smoked in a period of time: this requires a zero-inflated process (e.g. zero-inflated Poisson or zero-inflated negative binomial) because not everyone smokes cigarettes.
15,337
Examples of processes that are not Poisson?
Do you mean positive count data? Unbounded? The negative binomial is popular. Another good model is the Poisson with inflated 0. That model assumes that either something is happening or it isn't - and if it is, it follows a Poisson. I saw an example recently. Nurses who treated AIDS patients were asked how often they experienced stigmatizing behaviours from others as a result of their involvement with AIDS patients. A large number had never had such experiences, possibly because of where they worked or lived. Of those that did, the number of stigmatizing experiences varied. There were more 0's reported than you would expect from a straight Poisson, basically because a certain proportion of the group under study were simply not in an environment that exposed them to such behaviours. A mixture of Poisson's would also give you a point process.
Examples of processes that are not Poisson?
Do you mean positive count data? Unbounded? The negative binomial is popular. Another good model is the Poisson with inflated 0. That model assumes that either something is happening or it isn't - an
Examples of processes that are not Poisson? Do you mean positive count data? Unbounded? The negative binomial is popular. Another good model is the Poisson with inflated 0. That model assumes that either something is happening or it isn't - and if it is, it follows a Poisson. I saw an example recently. Nurses who treated AIDS patients were asked how often they experienced stigmatizing behaviours from others as a result of their involvement with AIDS patients. A large number had never had such experiences, possibly because of where they worked or lived. Of those that did, the number of stigmatizing experiences varied. There were more 0's reported than you would expect from a straight Poisson, basically because a certain proportion of the group under study were simply not in an environment that exposed them to such behaviours. A mixture of Poisson's would also give you a point process.
Examples of processes that are not Poisson? Do you mean positive count data? Unbounded? The negative binomial is popular. Another good model is the Poisson with inflated 0. That model assumes that either something is happening or it isn't - an
15,338
Examples of processes that are not Poisson?
Counting processes that aren't Poisson? Well, any finite sample space process like binomial or discrete uniform. You get a Poisson counting process from counting events having independent interarrival times which are exponentially distributed, so a whole host of generalizations fall out of that such as having gamma or lognormal or Weibull distributed interarrival times, or any kind of abstract non-parametric interarrival time distribution.
Examples of processes that are not Poisson?
Counting processes that aren't Poisson? Well, any finite sample space process like binomial or discrete uniform. You get a Poisson counting process from counting events having independent interarrival
Examples of processes that are not Poisson? Counting processes that aren't Poisson? Well, any finite sample space process like binomial or discrete uniform. You get a Poisson counting process from counting events having independent interarrival times which are exponentially distributed, so a whole host of generalizations fall out of that such as having gamma or lognormal or Weibull distributed interarrival times, or any kind of abstract non-parametric interarrival time distribution.
Examples of processes that are not Poisson? Counting processes that aren't Poisson? Well, any finite sample space process like binomial or discrete uniform. You get a Poisson counting process from counting events having independent interarrival
15,339
Examples of processes that are not Poisson?
It's unclear if you want counting processes or not. If I interpret the 'teaching' tag to mean you are teaching the Poisson process then, for teaching about a process in general, the Bernoulli process is an easy random process to explain and visualize and is related to the Poisson process. The Bernoulli process is the discrete analog so it might be a helpful companion concept. Its just that instead of continuous time we have discrete intervals of time. An example might be a door to door sales man where we are counting successes by homes that make a purchase. The number of successes in the first n trials, has a binomial distribution B(n, p) instead of a Poisson The number of trials needed to get r successes, has a negative binomial distribution NB(r, p) instead of a gamma distribution The number of trials needed to get one success, the waiting time, has a geometric distribution NB(1, p), which is the discrete analog of the exponential. That's the approach Bertsekas and Tsitsiklis use in Introduction To Probability, 2nd ed., introducing the Bernoulli process before the Poisson process. In their textbook there are more extensions to Bernoulli process that are applicable to the Poisson process such as merging them or partitioning them, as well as problems sets with solutions. If you are looking for examples of random processes, and you just want to throw the names out there, there are quite a few. The Gaussian process is a significant one in applications. The Weiner process in particular, which is a type of Gaussian process, is also called standard Brownian motion and has applications in finance and physics.
Examples of processes that are not Poisson?
It's unclear if you want counting processes or not. If I interpret the 'teaching' tag to mean you are teaching the Poisson process then, for teaching about a process in general, the Bernoulli process
Examples of processes that are not Poisson? It's unclear if you want counting processes or not. If I interpret the 'teaching' tag to mean you are teaching the Poisson process then, for teaching about a process in general, the Bernoulli process is an easy random process to explain and visualize and is related to the Poisson process. The Bernoulli process is the discrete analog so it might be a helpful companion concept. Its just that instead of continuous time we have discrete intervals of time. An example might be a door to door sales man where we are counting successes by homes that make a purchase. The number of successes in the first n trials, has a binomial distribution B(n, p) instead of a Poisson The number of trials needed to get r successes, has a negative binomial distribution NB(r, p) instead of a gamma distribution The number of trials needed to get one success, the waiting time, has a geometric distribution NB(1, p), which is the discrete analog of the exponential. That's the approach Bertsekas and Tsitsiklis use in Introduction To Probability, 2nd ed., introducing the Bernoulli process before the Poisson process. In their textbook there are more extensions to Bernoulli process that are applicable to the Poisson process such as merging them or partitioning them, as well as problems sets with solutions. If you are looking for examples of random processes, and you just want to throw the names out there, there are quite a few. The Gaussian process is a significant one in applications. The Weiner process in particular, which is a type of Gaussian process, is also called standard Brownian motion and has applications in finance and physics.
Examples of processes that are not Poisson? It's unclear if you want counting processes or not. If I interpret the 'teaching' tag to mean you are teaching the Poisson process then, for teaching about a process in general, the Bernoulli process
15,340
Examples of processes that are not Poisson?
As an property/casualty actuary, I deal with real-life examples of discrete processes which are non-Poisson all the time. For high-severity, low-frequency lines of business, the Poisson distribution is ill-suited as it demands a variance-to-mean ratio of 1. The negative binomial distribution, mentioned above, is much more commonly used, and the Delaporte distributions is used in some of the literature, though less often in standard North American actuarial practice. Why this is so is a deeper question. Is the negative binomial so much better because it represents a Poisson process for which the mean parameter is itself gamma distributed? Or is it because loss occurrences fail independence (as earthquake events do under current theory that the longer one waits for the earth to slip, the more likely it is due to the build-up in pressure), is it non-stationary (the intervals cannot be subdivided into sequences, each of which is stationary, which would allow the use of a non-homogeneous Poisson), and certainly some lines of business allow for simultaneous occurrences (e.g. medical malpractice with multiple doctors covered by the policy).
Examples of processes that are not Poisson?
As an property/casualty actuary, I deal with real-life examples of discrete processes which are non-Poisson all the time. For high-severity, low-frequency lines of business, the Poisson distribution i
Examples of processes that are not Poisson? As an property/casualty actuary, I deal with real-life examples of discrete processes which are non-Poisson all the time. For high-severity, low-frequency lines of business, the Poisson distribution is ill-suited as it demands a variance-to-mean ratio of 1. The negative binomial distribution, mentioned above, is much more commonly used, and the Delaporte distributions is used in some of the literature, though less often in standard North American actuarial practice. Why this is so is a deeper question. Is the negative binomial so much better because it represents a Poisson process for which the mean parameter is itself gamma distributed? Or is it because loss occurrences fail independence (as earthquake events do under current theory that the longer one waits for the earth to slip, the more likely it is due to the build-up in pressure), is it non-stationary (the intervals cannot be subdivided into sequences, each of which is stationary, which would allow the use of a non-homogeneous Poisson), and certainly some lines of business allow for simultaneous occurrences (e.g. medical malpractice with multiple doctors covered by the policy).
Examples of processes that are not Poisson? As an property/casualty actuary, I deal with real-life examples of discrete processes which are non-Poisson all the time. For high-severity, low-frequency lines of business, the Poisson distribution i
15,341
Examples of processes that are not Poisson?
Others have mentioned several examples of point process that are not Poisson. Because the Poisson corresponds to exponential interarrival times if you pick any interarrival time distribution that is no exponential the resulting point process is not Poisson. AdamO pointed out the Weibull. You could use gamma, lognormal, or beta as possible choices. The Poisson has the property that its mean is equal to its variance. A point process which has variance greater than the mean is sometimes referred to as overdispersed and if the mean is larger than the variance it is underdispersed. These terms are used to relate the process to a Poisson. The negative binomial is often used because it can be overdispersed or underdispersed depending on its parameters. The Poisson has a variance that is constant. A point process that fits the Poisson conditions except for not having a constant rate parameter and consequently a time varying mean and variance is called an inhomogeneous Poisson. A process with interarrival times exponential but can have multiple events at the arrival time is called a compound Poisson. Though similar to the Poisson process and having a name with the word Poisson in it, inhomogeneous and compound Poisson processes are different from a Poisson point process.
Examples of processes that are not Poisson?
Others have mentioned several examples of point process that are not Poisson. Because the Poisson corresponds to exponential interarrival times if you pick any interarrival time distribution that is
Examples of processes that are not Poisson? Others have mentioned several examples of point process that are not Poisson. Because the Poisson corresponds to exponential interarrival times if you pick any interarrival time distribution that is no exponential the resulting point process is not Poisson. AdamO pointed out the Weibull. You could use gamma, lognormal, or beta as possible choices. The Poisson has the property that its mean is equal to its variance. A point process which has variance greater than the mean is sometimes referred to as overdispersed and if the mean is larger than the variance it is underdispersed. These terms are used to relate the process to a Poisson. The negative binomial is often used because it can be overdispersed or underdispersed depending on its parameters. The Poisson has a variance that is constant. A point process that fits the Poisson conditions except for not having a constant rate parameter and consequently a time varying mean and variance is called an inhomogeneous Poisson. A process with interarrival times exponential but can have multiple events at the arrival time is called a compound Poisson. Though similar to the Poisson process and having a name with the word Poisson in it, inhomogeneous and compound Poisson processes are different from a Poisson point process.
Examples of processes that are not Poisson? Others have mentioned several examples of point process that are not Poisson. Because the Poisson corresponds to exponential interarrival times if you pick any interarrival time distribution that is
15,342
Examples of processes that are not Poisson?
Another interesting example of non-Poisson counting process is represented by the zero-truncated Poisson distribution (ZTPD). ZTPD can fit data concerning the number of languages subjects can speak in physiological conditions. In this instance, Poisson distribution is ill-behaving, because the number of spoken languages is by definition >=1: hence 0 is ruled out a priori.
Examples of processes that are not Poisson?
Another interesting example of non-Poisson counting process is represented by the zero-truncated Poisson distribution (ZTPD). ZTPD can fit data concerning the number of languages subjects can speak in
Examples of processes that are not Poisson? Another interesting example of non-Poisson counting process is represented by the zero-truncated Poisson distribution (ZTPD). ZTPD can fit data concerning the number of languages subjects can speak in physiological conditions. In this instance, Poisson distribution is ill-behaving, because the number of spoken languages is by definition >=1: hence 0 is ruled out a priori.
Examples of processes that are not Poisson? Another interesting example of non-Poisson counting process is represented by the zero-truncated Poisson distribution (ZTPD). ZTPD can fit data concerning the number of languages subjects can speak in
15,343
Examples of processes that are not Poisson?
I believe that you could take your customer-arrival Poisson process and tweak it in two different ways: 1) customer arrivals are measured 24-hours a day, but the store is not actually open all day, and 2) imagine two competing stores with Poisson process customer arrival times and look at the difference between the arrivals at the two stores. (Example #2 is from my understanding of the Springer Handbook of Engineering Statistics, Part A Property 1.4.)
Examples of processes that are not Poisson?
I believe that you could take your customer-arrival Poisson process and tweak it in two different ways: 1) customer arrivals are measured 24-hours a day, but the store is not actually open all day, an
Examples of processes that are not Poisson? I believe that you could take your customer-arrival Poisson process and tweak it in two different ways: 1) customer arrivals are measured 24-hours a day, but the store is not actually open all day, and 2) imagine two competing stores with Poisson process customer arrival times and look at the difference between the arrivals at the two stores. (Example #2 is from my understanding of the Springer Handbook of Engineering Statistics, Part A Property 1.4.)
Examples of processes that are not Poisson? I believe that you could take your customer-arrival Poisson process and tweak it in two different ways: 1) customer arrivals are measured 24-hours a day, but the store is not actually open all day, an
15,344
Examples of processes that are not Poisson?
You might want to reconsider the soccer example. It seems that the scoring rates for both teams increase as the match goes on, & that they change when teams change their attacking/defending priorities in response to the current score. Or rather, use it as an example of how simple models can perform surprisingly well, stimulating interest in statistical investigation of some phenomenon, & providing a benchmark for future studies that collect more data to investigate discrepancies & propose elaborations. Dixon & Robinson (1998), "A Birth Process Model for Association Football Matches", The Statistician, 47, 3.
Examples of processes that are not Poisson?
You might want to reconsider the soccer example. It seems that the scoring rates for both teams increase as the match goes on, & that they change when teams change their attacking/defending priorities
Examples of processes that are not Poisson? You might want to reconsider the soccer example. It seems that the scoring rates for both teams increase as the match goes on, & that they change when teams change their attacking/defending priorities in response to the current score. Or rather, use it as an example of how simple models can perform surprisingly well, stimulating interest in statistical investigation of some phenomenon, & providing a benchmark for future studies that collect more data to investigate discrepancies & propose elaborations. Dixon & Robinson (1998), "A Birth Process Model for Association Football Matches", The Statistician, 47, 3.
Examples of processes that are not Poisson? You might want to reconsider the soccer example. It seems that the scoring rates for both teams increase as the match goes on, & that they change when teams change their attacking/defending priorities
15,345
Examples of processes that are not Poisson?
Since the question is related to making the Poisson distribution more understandable, I'll give it a go, since I recently looked into this somewhat for call center incoming call patterns (which follow a memory-less, exponential distribution as time goes on). I think delving into another tangential model that essentially requires knowledge of Poisson to realize how it isn't one may be somewhat confusing, but that's just me. I think the trouble with understanding Poisson is the continuous time axis it's on --- as every second goes on, the event is no more likely to occur --- but the further out in the future you go, the more certain it is of happening. Really, I think it simplifies the understanding if you just trade the 'time' axis for 'trials' or 'events'. Someone can correct me if this is way off base, as I feel it's an easy explanation, but I think you can replace the flip of a coin, or the toss of a dice, with 'time until a phone call arrives' (what I typically use for Erlang C/ call center staffing). Instead of 'time until a phone calls arrive' ---- you can replace it with ... 'rolls until a dice hits six'. That follows the same general logic. The probability (like any gambling) is completely independent every roll (or minute) and is memory-less. However, the likelihood of 'no 6' decreases ever slower but surely towards 0 as you increase number of trials. It's easier if you see both graphs (likelihood of call with time, vs. likelihood of six with rolls). I don't know if that makes sense --- that's what helped me put it together into concrete terms. Now, the poisson distribution is a count rather than 'time between calls' or 'trials until rolling a six' -- but it relies on this likelihood.
Examples of processes that are not Poisson?
Since the question is related to making the Poisson distribution more understandable, I'll give it a go, since I recently looked into this somewhat for call center incoming call patterns (which follow
Examples of processes that are not Poisson? Since the question is related to making the Poisson distribution more understandable, I'll give it a go, since I recently looked into this somewhat for call center incoming call patterns (which follow a memory-less, exponential distribution as time goes on). I think delving into another tangential model that essentially requires knowledge of Poisson to realize how it isn't one may be somewhat confusing, but that's just me. I think the trouble with understanding Poisson is the continuous time axis it's on --- as every second goes on, the event is no more likely to occur --- but the further out in the future you go, the more certain it is of happening. Really, I think it simplifies the understanding if you just trade the 'time' axis for 'trials' or 'events'. Someone can correct me if this is way off base, as I feel it's an easy explanation, but I think you can replace the flip of a coin, or the toss of a dice, with 'time until a phone call arrives' (what I typically use for Erlang C/ call center staffing). Instead of 'time until a phone calls arrive' ---- you can replace it with ... 'rolls until a dice hits six'. That follows the same general logic. The probability (like any gambling) is completely independent every roll (or minute) and is memory-less. However, the likelihood of 'no 6' decreases ever slower but surely towards 0 as you increase number of trials. It's easier if you see both graphs (likelihood of call with time, vs. likelihood of six with rolls). I don't know if that makes sense --- that's what helped me put it together into concrete terms. Now, the poisson distribution is a count rather than 'time between calls' or 'trials until rolling a six' -- but it relies on this likelihood.
Examples of processes that are not Poisson? Since the question is related to making the Poisson distribution more understandable, I'll give it a go, since I recently looked into this somewhat for call center incoming call patterns (which follow
15,346
Examples of processes that are not Poisson?
Number of visits by an individual customer to the grocery store within a given time interval. After you have been to the grocery store, you are unlikely to return for a while unless you made a planning mistake. I think the Negative Binomial distribution could be used here, but it is discrete, whereas the visits are in continuous time.
Examples of processes that are not Poisson?
Number of visits by an individual customer to the grocery store within a given time interval. After you have been to the grocery store, you are unlikely to return for a while unless you made a plannin
Examples of processes that are not Poisson? Number of visits by an individual customer to the grocery store within a given time interval. After you have been to the grocery store, you are unlikely to return for a while unless you made a planning mistake. I think the Negative Binomial distribution could be used here, but it is discrete, whereas the visits are in continuous time.
Examples of processes that are not Poisson? Number of visits by an individual customer to the grocery store within a given time interval. After you have been to the grocery store, you are unlikely to return for a while unless you made a plannin
15,347
How to correctly word a frequentist confidence interval
There are various ways you can reasonably word a confidence interval statement, but any variation on the statements below would be fine. (Since you did not specify to the contrary, I am assuming that this was a 95% confidence interval. If not then you should make the appropriate changes in the statement.) What is important is that you clearly give your confidence level and the interval of interest. You should also make sure that you properly distinguish between notation for estimates and notation for true parameter values. Our estimate of the slope is $\hat{\beta} = 3.4$ ($\text{95%CI} = [0.5, 5.6]$). With 95% confidence we infer that the true slope value is somewhere in the interval $0.5 \leqslant \beta \leqslant 5.6$. With 95% confidence we find that $0.5 \leqslant \beta \leqslant 5.6$. The concept of "confidence" has a clear and well-known meaning in classical statistics, so if you refer to having a certain level of confidence that a parameter falls within an interval then that will automatically be understood as reporting a confidence interval. There is no need for you to worry about staying faithful to a particular framework --- there is only one framework of probability theory used in practice$^\dagger$ and only one meaning of a confidence interval. Indeed, when other frameworks develop analogous ideas in (e.g., "credible intervals" in Bayesian inference) they make sure to use different terminology precisely to avoid confusion on this topic. If you are just doing applied statistical work then there is no need to specify the exact statistical meaning of "confidence". It is subtle and confusing to most readers, and you can reasonably put the onus on them to read up on it if they are interested. Many people with an applied science background in any field will have done some introductory statistical courses, where they learned and then forgot what a confidence interval means. Most readers will just be satisfied with the fact that the statistical profession has given their imprimatur to the concept. For statistical experts, they will know the exact meaning of the concept, and be happy with your summary report just the same. Worrying about the proper interpretation of "probability" is another order removed from this, and it is certainly not something you need to concern yourself with in reporting statistical analysis of data. Interested readers can dive down the rabbit-hole of philosophy and the foundations of probability theory if they really wish to do so. $^\dagger$ There are occasional papers in academic literature that examine non-standard versions of "probability" (e.g., using complex numbers, etc.) but these are basically all bunk.
How to correctly word a frequentist confidence interval
There are various ways you can reasonably word a confidence interval statement, but any variation on the statements below would be fine. (Since you did not specify to the contrary, I am assuming that
How to correctly word a frequentist confidence interval There are various ways you can reasonably word a confidence interval statement, but any variation on the statements below would be fine. (Since you did not specify to the contrary, I am assuming that this was a 95% confidence interval. If not then you should make the appropriate changes in the statement.) What is important is that you clearly give your confidence level and the interval of interest. You should also make sure that you properly distinguish between notation for estimates and notation for true parameter values. Our estimate of the slope is $\hat{\beta} = 3.4$ ($\text{95%CI} = [0.5, 5.6]$). With 95% confidence we infer that the true slope value is somewhere in the interval $0.5 \leqslant \beta \leqslant 5.6$. With 95% confidence we find that $0.5 \leqslant \beta \leqslant 5.6$. The concept of "confidence" has a clear and well-known meaning in classical statistics, so if you refer to having a certain level of confidence that a parameter falls within an interval then that will automatically be understood as reporting a confidence interval. There is no need for you to worry about staying faithful to a particular framework --- there is only one framework of probability theory used in practice$^\dagger$ and only one meaning of a confidence interval. Indeed, when other frameworks develop analogous ideas in (e.g., "credible intervals" in Bayesian inference) they make sure to use different terminology precisely to avoid confusion on this topic. If you are just doing applied statistical work then there is no need to specify the exact statistical meaning of "confidence". It is subtle and confusing to most readers, and you can reasonably put the onus on them to read up on it if they are interested. Many people with an applied science background in any field will have done some introductory statistical courses, where they learned and then forgot what a confidence interval means. Most readers will just be satisfied with the fact that the statistical profession has given their imprimatur to the concept. For statistical experts, they will know the exact meaning of the concept, and be happy with your summary report just the same. Worrying about the proper interpretation of "probability" is another order removed from this, and it is certainly not something you need to concern yourself with in reporting statistical analysis of data. Interested readers can dive down the rabbit-hole of philosophy and the foundations of probability theory if they really wish to do so. $^\dagger$ There are occasional papers in academic literature that examine non-standard versions of "probability" (e.g., using complex numbers, etc.) but these are basically all bunk.
How to correctly word a frequentist confidence interval There are various ways you can reasonably word a confidence interval statement, but any variation on the statements below would be fine. (Since you did not specify to the contrary, I am assuming that
15,348
How to correctly word a frequentist confidence interval
I agree with Ben that normally, you would just say, "Our estimate of the slope is $\hat{\beta}=3.4\ (95\%\ {\rm CI}=[0.5,5.6])$." If you really need to explain to someone what a confidence interval is, I would probably not use your formulation, "If we ran many experiments 95% of the 95% intervals constructed would contain the true value of $β$." I do say that when I teach (although I supplement that with additional explanations and activities), but I never say it to clients. That just isn't a statement that works for many people. To be honest, it's uncommon that I find I need to provide a definition for a confidence interval. If I do, what I say is some version of either: If our null hypothesis had been any value within this interval, we would not have been able to rule it out. or the inverse: If our null hypothesis had been any value outside this interval, we could have ruled it out.
How to correctly word a frequentist confidence interval
I agree with Ben that normally, you would just say, "Our estimate of the slope is $\hat{\beta}=3.4\ (95\%\ {\rm CI}=[0.5,5.6])$." If you really need to explain to someone what a confidence interval is
How to correctly word a frequentist confidence interval I agree with Ben that normally, you would just say, "Our estimate of the slope is $\hat{\beta}=3.4\ (95\%\ {\rm CI}=[0.5,5.6])$." If you really need to explain to someone what a confidence interval is, I would probably not use your formulation, "If we ran many experiments 95% of the 95% intervals constructed would contain the true value of $β$." I do say that when I teach (although I supplement that with additional explanations and activities), but I never say it to clients. That just isn't a statement that works for many people. To be honest, it's uncommon that I find I need to provide a definition for a confidence interval. If I do, what I say is some version of either: If our null hypothesis had been any value within this interval, we would not have been able to rule it out. or the inverse: If our null hypothesis had been any value outside this interval, we could have ruled it out.
How to correctly word a frequentist confidence interval I agree with Ben that normally, you would just say, "Our estimate of the slope is $\hat{\beta}=3.4\ (95\%\ {\rm CI}=[0.5,5.6])$." If you really need to explain to someone what a confidence interval is
15,349
How to correctly word a frequentist confidence interval
This post is such a goldmine if information. Its worth a read on its own. Confidence interval interpretation is a practice in the Precision-Usefulness trade off: You can state what a confidence interval is precisely, and it will not be useful. As you relax the precision, it becomes more and more useful. However, this loss of precision is a cost, and the more useful you make your interpretation of a confidence interval the more people will disagree with you (due to the loss of precision). One popular way of interpreting a confidence interval is as follows (as per that linked post): The compatibility interval indicates a wide range of plausible true treatment effects. Or put differently, "those parameters within the interval indicate plausible true values of the parameter". I'm not completely sold on this interpretation. Here "true" depends on the selected $\alpha$, and I don't find it compelling to take $\alpha = 0.05$ as corresponding to truth. With that in mind, perhaps a good revision would be The compatibility interval indicates a range of plausible true treatment effects in accordance with our allowed false positive rate. If its one thing I've learned doing and tweeting about statistics, its that people still disagree on the interpretation of the confidence interval. To avoid getting into conversations about this (again and again and again), I simply state that The confidence interval summarizes regions of parameter space which are consistent with the data I find this interpretation is a sufficiently good balance of usefulness and precision.
How to correctly word a frequentist confidence interval
This post is such a goldmine if information. Its worth a read on its own. Confidence interval interpretation is a practice in the Precision-Usefulness trade off: You can state what a confidence interv
How to correctly word a frequentist confidence interval This post is such a goldmine if information. Its worth a read on its own. Confidence interval interpretation is a practice in the Precision-Usefulness trade off: You can state what a confidence interval is precisely, and it will not be useful. As you relax the precision, it becomes more and more useful. However, this loss of precision is a cost, and the more useful you make your interpretation of a confidence interval the more people will disagree with you (due to the loss of precision). One popular way of interpreting a confidence interval is as follows (as per that linked post): The compatibility interval indicates a wide range of plausible true treatment effects. Or put differently, "those parameters within the interval indicate plausible true values of the parameter". I'm not completely sold on this interpretation. Here "true" depends on the selected $\alpha$, and I don't find it compelling to take $\alpha = 0.05$ as corresponding to truth. With that in mind, perhaps a good revision would be The compatibility interval indicates a range of plausible true treatment effects in accordance with our allowed false positive rate. If its one thing I've learned doing and tweeting about statistics, its that people still disagree on the interpretation of the confidence interval. To avoid getting into conversations about this (again and again and again), I simply state that The confidence interval summarizes regions of parameter space which are consistent with the data I find this interpretation is a sufficiently good balance of usefulness and precision.
How to correctly word a frequentist confidence interval This post is such a goldmine if information. Its worth a read on its own. Confidence interval interpretation is a practice in the Precision-Usefulness trade off: You can state what a confidence interv
15,350
How to correctly word a frequentist confidence interval
How about: "A procedure which constructs an interval from an experiment, having the property that the interval constructed by the procedure contains the true value of $\beta$ in 95% of cases, was applied to this experiment, for which the estimated value of $\beta$ was $\widehat{\beta} = 3.4$. The interval constructed by the procedure was $[0.5, 5.6]$."
How to correctly word a frequentist confidence interval
How about: "A procedure which constructs an interval from an experiment, having the property that the interval constructed by the procedure contains the true value of $\beta$ in 95% of cases, was appl
How to correctly word a frequentist confidence interval How about: "A procedure which constructs an interval from an experiment, having the property that the interval constructed by the procedure contains the true value of $\beta$ in 95% of cases, was applied to this experiment, for which the estimated value of $\beta$ was $\widehat{\beta} = 3.4$. The interval constructed by the procedure was $[0.5, 5.6]$."
How to correctly word a frequentist confidence interval How about: "A procedure which constructs an interval from an experiment, having the property that the interval constructed by the procedure contains the true value of $\beta$ in 95% of cases, was appl
15,351
Interpretation of non-significant results as "trends"
This is a great question; the answer depends a lot on context. In general I would say you are right: making an unqualified general claim like "group A used X more often than group B" is misleading. It would be better to say something like in our experiment group A used X more often than group B, but we're very uncertain how this will play out in the general population or although group A used X 13% more often than group B in our experiment, our estimate of the difference in the general population is not clear: the plausible values range from A using X 5% less often than group B to A using X 21% more often than group B or group A used X 13% more often than group B, but the difference was not statistically significant (95% CI -5% to 21%; p=0.75) On the other hand: your co-workers are right that in this particular experiment, group A used X more often than group B. However, people rarely care about the participants in a particular experiment; they want to know how your results will generalize to a larger population, and in this case the general answer is that you can't say with confidence whether a randomly selected group A will use X more or less often than a randomly selected group B. If you needed to make a choice today about whether to use treatment A or treatment B to increase the usage of X, in the absence of any other information or differences in costs etc., then choosing A would be your best bet. But if you wanted be comfortable that you were probably making the right choice, you would need more information. Note that you should not say "there is no difference between group A and group B in their usage of X", or "group A and group B use X the same amount". This is true neither of the participants in your experiment (where A used X 13% more) or in the general population; in most real-world contexts, you know that there must really be some effect (no matter how slight) of A vs. B; you just don't know which direction it goes.
Interpretation of non-significant results as "trends"
This is a great question; the answer depends a lot on context. In general I would say you are right: making an unqualified general claim like "group A used X more often than group B" is misleading. It
Interpretation of non-significant results as "trends" This is a great question; the answer depends a lot on context. In general I would say you are right: making an unqualified general claim like "group A used X more often than group B" is misleading. It would be better to say something like in our experiment group A used X more often than group B, but we're very uncertain how this will play out in the general population or although group A used X 13% more often than group B in our experiment, our estimate of the difference in the general population is not clear: the plausible values range from A using X 5% less often than group B to A using X 21% more often than group B or group A used X 13% more often than group B, but the difference was not statistically significant (95% CI -5% to 21%; p=0.75) On the other hand: your co-workers are right that in this particular experiment, group A used X more often than group B. However, people rarely care about the participants in a particular experiment; they want to know how your results will generalize to a larger population, and in this case the general answer is that you can't say with confidence whether a randomly selected group A will use X more or less often than a randomly selected group B. If you needed to make a choice today about whether to use treatment A or treatment B to increase the usage of X, in the absence of any other information or differences in costs etc., then choosing A would be your best bet. But if you wanted be comfortable that you were probably making the right choice, you would need more information. Note that you should not say "there is no difference between group A and group B in their usage of X", or "group A and group B use X the same amount". This is true neither of the participants in your experiment (where A used X 13% more) or in the general population; in most real-world contexts, you know that there must really be some effect (no matter how slight) of A vs. B; you just don't know which direction it goes.
Interpretation of non-significant results as "trends" This is a great question; the answer depends a lot on context. In general I would say you are right: making an unqualified general claim like "group A used X more often than group B" is misleading. It
15,352
Interpretation of non-significant results as "trends"
That's a tough question! First things first, any threshold you may choose to determine statistical significance is arbitrary. The fact that most people use a $5\%$ $p$-value does not make it more correct than any other. So, in some sense, you should think of statistical significance as a "spectrum" rather than a black-or-white subject. Let's assume we have a null hypothesis $H_0$ (for example, groups $A$ and $B$ show the same mean for variable $X$, or the population mean for variable $Y$ is below 5). You can think of the null hypothesis as the "no trend" hypothesis. We gather some data to check whether we can disprove $H_0$ (the null hypothesis is never "proved true"). With our sample, we make some statistics and eventually get a $p$-value. Put shortly, the $p$-value is the probability that pure chance would produce results equally (or more) extreme than those we got, assuming of course $H_0$ to be true (i.e., no trend). If we get a "low" $p$-value, we say that chance rarely produces results as those, therefore we reject $H_0$ (there's statistically significant evidence that $H_0$ could be false). If we get a "high" $p$-value, then the results are more likely to be a result of luck, rather than actual trend. We don't say $H_0$ is true, but rather, that further studying should take place in order to reject it. WARNING: A $p$-value of $23\%$ does not mean that there is a $23\%$ chance of there not being any trend, but rather, that chance generates results as those $23\%$ of the time, which sounds similar, but is a completely different thing. For example, if I claim something ridiculous, like "I can predict results of rolling dice an hour before they take place," we make an experiment to check the null hypothesis $H_0:=$"I cannot do such thing" and get a $0.5\%$ $p-$value, you would still have good reason not to believe me, despite the statistical significance. So, with these ideas in mind, let's go back to your main question. Let's say we want to check if increasing the dose of drug $X$ has an effect on the likelihood of patients that survive a certain disease. We perform an experiment, fit a logistic regression model (taking into account many other variables) and check for significance on the coefficient associated with the "dose" variable (calling that coefficient $\beta$, we'd test a null hypothesis $H_0:$ $\beta=0$ or maybe, $\beta \leq 0$. In English, "the drug has no effect" or "the drug has either no or negative effect." The results of the experiment throw a positive beta, but the test $\beta=0$ stays at 0.79. Can we say there is a trend? Well, that would really diminish the meaning of "trend". If we accept that kind of thing, basically half of all experiments we make would show "trends," even when testing for the most ridiculous things. So, in conclusion, I think it is dishonest to claim that our drug makes any difference. What we should say, instead, is that our drug should not be put into production unless further testing is made. Indeed, my say would be that we should still be careful about the claims we make even when statistical significance is reached. Would you take that drug if chance had a $4\%$ of generating those results? This is why research replication and peer-reviewing is critical. I hope this too-wordy explanation helps you sort your ideas. The summary is that you are absolutely right! We shouldn't fill our reports, whether it's for research, business, or whatever, with wild claims supported by little evidence. If you really think there is a trend, but you didn't reach statistical significance, then repeat the experiment with more data!
Interpretation of non-significant results as "trends"
That's a tough question! First things first, any threshold you may choose to determine statistical significance is arbitrary. The fact that most people use a $5\%$ $p$-value does not make it more corr
Interpretation of non-significant results as "trends" That's a tough question! First things first, any threshold you may choose to determine statistical significance is arbitrary. The fact that most people use a $5\%$ $p$-value does not make it more correct than any other. So, in some sense, you should think of statistical significance as a "spectrum" rather than a black-or-white subject. Let's assume we have a null hypothesis $H_0$ (for example, groups $A$ and $B$ show the same mean for variable $X$, or the population mean for variable $Y$ is below 5). You can think of the null hypothesis as the "no trend" hypothesis. We gather some data to check whether we can disprove $H_0$ (the null hypothesis is never "proved true"). With our sample, we make some statistics and eventually get a $p$-value. Put shortly, the $p$-value is the probability that pure chance would produce results equally (or more) extreme than those we got, assuming of course $H_0$ to be true (i.e., no trend). If we get a "low" $p$-value, we say that chance rarely produces results as those, therefore we reject $H_0$ (there's statistically significant evidence that $H_0$ could be false). If we get a "high" $p$-value, then the results are more likely to be a result of luck, rather than actual trend. We don't say $H_0$ is true, but rather, that further studying should take place in order to reject it. WARNING: A $p$-value of $23\%$ does not mean that there is a $23\%$ chance of there not being any trend, but rather, that chance generates results as those $23\%$ of the time, which sounds similar, but is a completely different thing. For example, if I claim something ridiculous, like "I can predict results of rolling dice an hour before they take place," we make an experiment to check the null hypothesis $H_0:=$"I cannot do such thing" and get a $0.5\%$ $p-$value, you would still have good reason not to believe me, despite the statistical significance. So, with these ideas in mind, let's go back to your main question. Let's say we want to check if increasing the dose of drug $X$ has an effect on the likelihood of patients that survive a certain disease. We perform an experiment, fit a logistic regression model (taking into account many other variables) and check for significance on the coefficient associated with the "dose" variable (calling that coefficient $\beta$, we'd test a null hypothesis $H_0:$ $\beta=0$ or maybe, $\beta \leq 0$. In English, "the drug has no effect" or "the drug has either no or negative effect." The results of the experiment throw a positive beta, but the test $\beta=0$ stays at 0.79. Can we say there is a trend? Well, that would really diminish the meaning of "trend". If we accept that kind of thing, basically half of all experiments we make would show "trends," even when testing for the most ridiculous things. So, in conclusion, I think it is dishonest to claim that our drug makes any difference. What we should say, instead, is that our drug should not be put into production unless further testing is made. Indeed, my say would be that we should still be careful about the claims we make even when statistical significance is reached. Would you take that drug if chance had a $4\%$ of generating those results? This is why research replication and peer-reviewing is critical. I hope this too-wordy explanation helps you sort your ideas. The summary is that you are absolutely right! We shouldn't fill our reports, whether it's for research, business, or whatever, with wild claims supported by little evidence. If you really think there is a trend, but you didn't reach statistical significance, then repeat the experiment with more data!
Interpretation of non-significant results as "trends" That's a tough question! First things first, any threshold you may choose to determine statistical significance is arbitrary. The fact that most people use a $5\%$ $p$-value does not make it more corr
15,353
Interpretation of non-significant results as "trends"
Significant effect just means that you measured an unlikely anomaly (unlikely if the null hypothesis, absence of effect, would be true). And as a consequence it must be doubted with high probability (although this probability is not equal to the p-value and also depends on prior believes). Depending on the quality of the experiment you could measure the same effect size, but it might not be an anomaly (not an unlikely result if the null hypothesis would be true). When you observe an effect but it is not significant then indeed it (the effect) can still be there, but it is only not significant (the measurements do not indicate that the null hypothesis should be doubted/rejected with high probability). It means that you should improve your experiment, gather more data, to be more sure. So instead of the dichotomy effect versus no-effect you should go for the following four categories: Image from https://en.wikipedia.org/wiki/Equivalence_test explaining the two one sided t-tests procedure (TOST) You seem to be in category D, the test is inconclusive. Your coworkers might be wrong to say that there is an effect. However, it is equally wrong to say that there is no effect!
Interpretation of non-significant results as "trends"
Significant effect just means that you measured an unlikely anomaly (unlikely if the null hypothesis, absence of effect, would be true). And as a consequence it must be doubted with high probability (
Interpretation of non-significant results as "trends" Significant effect just means that you measured an unlikely anomaly (unlikely if the null hypothesis, absence of effect, would be true). And as a consequence it must be doubted with high probability (although this probability is not equal to the p-value and also depends on prior believes). Depending on the quality of the experiment you could measure the same effect size, but it might not be an anomaly (not an unlikely result if the null hypothesis would be true). When you observe an effect but it is not significant then indeed it (the effect) can still be there, but it is only not significant (the measurements do not indicate that the null hypothesis should be doubted/rejected with high probability). It means that you should improve your experiment, gather more data, to be more sure. So instead of the dichotomy effect versus no-effect you should go for the following four categories: Image from https://en.wikipedia.org/wiki/Equivalence_test explaining the two one sided t-tests procedure (TOST) You seem to be in category D, the test is inconclusive. Your coworkers might be wrong to say that there is an effect. However, it is equally wrong to say that there is no effect!
Interpretation of non-significant results as "trends" Significant effect just means that you measured an unlikely anomaly (unlikely if the null hypothesis, absence of effect, would be true). And as a consequence it must be doubted with high probability (
15,354
Interpretation of non-significant results as "trends"
It sounds like they're arguing p-value vs. the definition of "Trend". If you plot the data out on a run chart, you may see a trend... a run of plot points that show a trend going up or down over time. But, when you do the statistics on it.. the p-value suggests it's not significant. For the p-value to show little significance, but for them to see a trend / run in the series of data ... that would have to be a very slight trend. So, if that was the case, I would fall back on the p-value.. IE: ok, yes, there's a trend / run in the data.. but it's so slight and insignificant that the statistics suggest it's not worth pursuing further analysis of. An insignificant trend is something that may be attributable to some kind of bias in the research.. maybe something very minor.. something that may just be a one time occurence in the experiment that happened to create a slight trend. If I was the manager of the group, I would tell them to stop wasting time and money digging into insignificant trends, and to look for more significant ones.
Interpretation of non-significant results as "trends"
It sounds like they're arguing p-value vs. the definition of "Trend". If you plot the data out on a run chart, you may see a trend... a run of plot points that show a trend going up or down over time.
Interpretation of non-significant results as "trends" It sounds like they're arguing p-value vs. the definition of "Trend". If you plot the data out on a run chart, you may see a trend... a run of plot points that show a trend going up or down over time. But, when you do the statistics on it.. the p-value suggests it's not significant. For the p-value to show little significance, but for them to see a trend / run in the series of data ... that would have to be a very slight trend. So, if that was the case, I would fall back on the p-value.. IE: ok, yes, there's a trend / run in the data.. but it's so slight and insignificant that the statistics suggest it's not worth pursuing further analysis of. An insignificant trend is something that may be attributable to some kind of bias in the research.. maybe something very minor.. something that may just be a one time occurence in the experiment that happened to create a slight trend. If I was the manager of the group, I would tell them to stop wasting time and money digging into insignificant trends, and to look for more significant ones.
Interpretation of non-significant results as "trends" It sounds like they're arguing p-value vs. the definition of "Trend". If you plot the data out on a run chart, you may see a trend... a run of plot points that show a trend going up or down over time.
15,355
Interpretation of non-significant results as "trends"
It sounds like in this case they have little justification for their claim and are just abusing statistics to reach the conclusion they already had. But there are times when it's ok to not be so strict with p-val cutoffs. This (how to use statistical significance and pval cutoffs) is a debate that has been raging since Fisher, Neyman, and Pearson first laid the foundations of statistical testing. Let's say you are building a model and you are deciding what variables in include. You gather a little bit of data to do some preliminary investigation into potential variables. Now there's this one variable that the business team really is interested in, but your preliminary investigation shows that the variable is not statistically significant. However, the 'direction' of the variable comports to what the business team expected, and although it didn't meet the threshold for significance, it was close. Perhaps it was suspected to have positive correlation to the outcome and you got a beta coefficient that was positive but the pval was just a bit above the .05 cutoff. In that case, you might go ahead and include it. It's sort of an informal bayesian statistics -- there was a strong prior belief that it is a useful variable and the initial investigation into it showed some evidence in that direction (but not statistically significant evidence!) so you give it the benefit of the doubt and keep it in the model. Perhaps with more data it will be more evident what relationship it has with the outcome of interest. Another example might be where you are building a new model and you look at the variables that were used in the previous model -- you might continue to include a marginal variable (one that is on the cusp of significance) to maintain some continuity from model to model. Basically, depending on what you are doing there are reasons to be more and less strict about these sorts of things. On the other hand, it's also important to keep in mind that statistical significance does not have to imply a practical significance! Remember that at the heart of all this is sample size. Collect enough data and the standard error of the estimate will shrink to 0. This will make any sort of difference, no matter how small, 'statistically significant' even if that difference might not amount to anything in the real world. For example, suppose the probability of a particular coin landing on heads was .500000000000001. This means that theoretically you could design an experiment which concludes that the coin is not fair, but for all intents and purposes the coin could be treated as a fair coin.
Interpretation of non-significant results as "trends"
It sounds like in this case they have little justification for their claim and are just abusing statistics to reach the conclusion they already had. But there are times when it's ok to not be so stric
Interpretation of non-significant results as "trends" It sounds like in this case they have little justification for their claim and are just abusing statistics to reach the conclusion they already had. But there are times when it's ok to not be so strict with p-val cutoffs. This (how to use statistical significance and pval cutoffs) is a debate that has been raging since Fisher, Neyman, and Pearson first laid the foundations of statistical testing. Let's say you are building a model and you are deciding what variables in include. You gather a little bit of data to do some preliminary investigation into potential variables. Now there's this one variable that the business team really is interested in, but your preliminary investigation shows that the variable is not statistically significant. However, the 'direction' of the variable comports to what the business team expected, and although it didn't meet the threshold for significance, it was close. Perhaps it was suspected to have positive correlation to the outcome and you got a beta coefficient that was positive but the pval was just a bit above the .05 cutoff. In that case, you might go ahead and include it. It's sort of an informal bayesian statistics -- there was a strong prior belief that it is a useful variable and the initial investigation into it showed some evidence in that direction (but not statistically significant evidence!) so you give it the benefit of the doubt and keep it in the model. Perhaps with more data it will be more evident what relationship it has with the outcome of interest. Another example might be where you are building a new model and you look at the variables that were used in the previous model -- you might continue to include a marginal variable (one that is on the cusp of significance) to maintain some continuity from model to model. Basically, depending on what you are doing there are reasons to be more and less strict about these sorts of things. On the other hand, it's also important to keep in mind that statistical significance does not have to imply a practical significance! Remember that at the heart of all this is sample size. Collect enough data and the standard error of the estimate will shrink to 0. This will make any sort of difference, no matter how small, 'statistically significant' even if that difference might not amount to anything in the real world. For example, suppose the probability of a particular coin landing on heads was .500000000000001. This means that theoretically you could design an experiment which concludes that the coin is not fair, but for all intents and purposes the coin could be treated as a fair coin.
Interpretation of non-significant results as "trends" It sounds like in this case they have little justification for their claim and are just abusing statistics to reach the conclusion they already had. But there are times when it's ok to not be so stric
15,356
How is adding noise to training data equivalent to regularization?
Adding noise to the regressors in the training data is similar to regularization because it leads to similar results to shrinkage. The linear regression is an interesting example. Suppose $(Y_i,X_i)_{i=1}^n$ is a set of i.i.d. observations and that $$ Y_i = \beta_0 + \beta_1X_i + U_i \qquad \mathbb{E}[U_i \mid X_i] = 0 $$ The population coefficient for $\beta_1$ is equal to $$ \beta_1 = \frac{Cov(Y_i,X_i)}{Var(X_i)} $$ The estimated OLS coefficient $\hat{\beta}_1$ can be written as a sample analog of $\beta_1$. Now suppose that we add white noise $Z_i = X_i + \varepsilon_i$ and assume that $\mathbb{E}[\varepsilon_i] = 0$, $Var(\varepsilon_i) = \sigma^2$, and that that $\varepsilon_i$ is independent of $Y_i,X_i$. I have made no other assumption about the distribution of $\varepsilon_i$. Then the population coefficient for a regression of $Y_i$ on $Z_i$ (the noisy regressor) is equal to, $$ \tilde{\beta}_1 = \frac{Cov(Y_i,Z_i)}{Var(Z_i)} = \frac{Cov(Y_i,X_i + \varepsilon_i)}{Var(X_i + \varepsilon_i)} = \frac{Cov(Y_i,X_i)}{Var(X_i) + \sigma^2} = \frac{Var(X_i)}{Var(X_i)+\sigma^2} \times \beta_1 $$ Therefore, $\tilde{\beta}_1$ shrinks to zero for higher values of $\sigma^2$. The estimator for $\tilde{\beta}_1$ will also shrink to zero. We can use the test data to choose a sequence $\sigma_n^2 \to 0$ that achieves the optimal bias-variance trade-off via cross-validation. If you want to do inference, you clearly need to do some form of adjustment both because the estimator is biased and the variance depends on $\sigma^2$. The process for selecting $\sigma^2$ can also distort the confidence intervals.
How is adding noise to training data equivalent to regularization?
Adding noise to the regressors in the training data is similar to regularization because it leads to similar results to shrinkage. The linear regression is an interesting example. Suppose $(Y_i,X_i)_{
How is adding noise to training data equivalent to regularization? Adding noise to the regressors in the training data is similar to regularization because it leads to similar results to shrinkage. The linear regression is an interesting example. Suppose $(Y_i,X_i)_{i=1}^n$ is a set of i.i.d. observations and that $$ Y_i = \beta_0 + \beta_1X_i + U_i \qquad \mathbb{E}[U_i \mid X_i] = 0 $$ The population coefficient for $\beta_1$ is equal to $$ \beta_1 = \frac{Cov(Y_i,X_i)}{Var(X_i)} $$ The estimated OLS coefficient $\hat{\beta}_1$ can be written as a sample analog of $\beta_1$. Now suppose that we add white noise $Z_i = X_i + \varepsilon_i$ and assume that $\mathbb{E}[\varepsilon_i] = 0$, $Var(\varepsilon_i) = \sigma^2$, and that that $\varepsilon_i$ is independent of $Y_i,X_i$. I have made no other assumption about the distribution of $\varepsilon_i$. Then the population coefficient for a regression of $Y_i$ on $Z_i$ (the noisy regressor) is equal to, $$ \tilde{\beta}_1 = \frac{Cov(Y_i,Z_i)}{Var(Z_i)} = \frac{Cov(Y_i,X_i + \varepsilon_i)}{Var(X_i + \varepsilon_i)} = \frac{Cov(Y_i,X_i)}{Var(X_i) + \sigma^2} = \frac{Var(X_i)}{Var(X_i)+\sigma^2} \times \beta_1 $$ Therefore, $\tilde{\beta}_1$ shrinks to zero for higher values of $\sigma^2$. The estimator for $\tilde{\beta}_1$ will also shrink to zero. We can use the test data to choose a sequence $\sigma_n^2 \to 0$ that achieves the optimal bias-variance trade-off via cross-validation. If you want to do inference, you clearly need to do some form of adjustment both because the estimator is biased and the variance depends on $\sigma^2$. The process for selecting $\sigma^2$ can also distort the confidence intervals.
How is adding noise to training data equivalent to regularization? Adding noise to the regressors in the training data is similar to regularization because it leads to similar results to shrinkage. The linear regression is an interesting example. Suppose $(Y_i,X_i)_{
15,357
How is adding noise to training data equivalent to regularization?
Overview: For linear regression, I'll show that $\ell_2$ regularization (a.k.a. ridge regression) arises from minimizing the expected squared error over random perturbations of the regressors. The distributional form of the perturbations doesn't matter beyond some minimal requirements (i.i.d., zero mean). The variance of the perturbations controls the regularization strength. Let $\big\{(x_i, y_i)\big\}_{i=1}^n$ be the data, with regressors $x_i \in \mathbb{R}^d$ and responses $y_i \in \mathbb{R}$. Suppose we first add random noise to the regressors, then compute predictions as a linear function of the perturbed regressors: $$\hat{y}_i = (x_i + \delta_i)^T w$$ $w \in \mathbb{R}^d$ are the regression coefficients and the perburbations $\{\delta_i\}$ are i.i.d. random vectors with mean $\vec{0}$ and covariance matrix $\lambda I$. It's not necessary to assume that perturbations are generated from any particular parametric family. We seek coefficients that minimize the expected squared error $L(w)$, where the expectation is taken over the random perturbations: $$L(w) = E \left[ \frac{1}{n} \sum_{i=1}^n (y_i - \hat{y}_i)^2 \right]$$ Plug in the above expression for $\hat{y}_i$ and expand: $$L(w) = E \left[ \frac{1}{n} \sum_{i=1}^n (y_i - x_i^T w)^2 - 2 \delta_i^T w (y_i - x_i^T w) + w^T \delta_i \delta_i^T w \right]$$ By linearity of expectation: $$L(w) = \frac{1}{n} \sum_{i=1}^n \left( (y_i - x_i^T w)^2 - 2 E \Big[ \delta_i \Big]^T w (y_i - x_i^T w) + w^T E \Big[ \delta_i \delta_i^T \Big] w \right)$$ Note that $E[\delta_i] = \vec{0}$ and $E[\delta_i \delta_i^T] = \lambda I$ are the mean and covariance matrix of the random perturbations: $$L(w) = \frac{1}{n} \sum_{i=1}^n \left( (y_i - x_i^T w)^2 + \lambda w^T w \right)$$ Simplify, noting that $w^T w = \|w\|_2^2$: $$L(w) = \frac{1}{n} \sum_{i=1}^n (y_i - x_i^T w)^2 + \lambda \|w\|_2^2$$ This is the mean squared prediction error for the original (non-perturbed) data, plus a penalty on the squared $\ell_2$ norm of the coefficients. Notice that it corresponds exactly to the cost function for ridge regression, with penalty strength $\lambda$.
How is adding noise to training data equivalent to regularization?
Overview: For linear regression, I'll show that $\ell_2$ regularization (a.k.a. ridge regression) arises from minimizing the expected squared error over random perturbations of the regressors. The dis
How is adding noise to training data equivalent to regularization? Overview: For linear regression, I'll show that $\ell_2$ regularization (a.k.a. ridge regression) arises from minimizing the expected squared error over random perturbations of the regressors. The distributional form of the perturbations doesn't matter beyond some minimal requirements (i.i.d., zero mean). The variance of the perturbations controls the regularization strength. Let $\big\{(x_i, y_i)\big\}_{i=1}^n$ be the data, with regressors $x_i \in \mathbb{R}^d$ and responses $y_i \in \mathbb{R}$. Suppose we first add random noise to the regressors, then compute predictions as a linear function of the perturbed regressors: $$\hat{y}_i = (x_i + \delta_i)^T w$$ $w \in \mathbb{R}^d$ are the regression coefficients and the perburbations $\{\delta_i\}$ are i.i.d. random vectors with mean $\vec{0}$ and covariance matrix $\lambda I$. It's not necessary to assume that perturbations are generated from any particular parametric family. We seek coefficients that minimize the expected squared error $L(w)$, where the expectation is taken over the random perturbations: $$L(w) = E \left[ \frac{1}{n} \sum_{i=1}^n (y_i - \hat{y}_i)^2 \right]$$ Plug in the above expression for $\hat{y}_i$ and expand: $$L(w) = E \left[ \frac{1}{n} \sum_{i=1}^n (y_i - x_i^T w)^2 - 2 \delta_i^T w (y_i - x_i^T w) + w^T \delta_i \delta_i^T w \right]$$ By linearity of expectation: $$L(w) = \frac{1}{n} \sum_{i=1}^n \left( (y_i - x_i^T w)^2 - 2 E \Big[ \delta_i \Big]^T w (y_i - x_i^T w) + w^T E \Big[ \delta_i \delta_i^T \Big] w \right)$$ Note that $E[\delta_i] = \vec{0}$ and $E[\delta_i \delta_i^T] = \lambda I$ are the mean and covariance matrix of the random perturbations: $$L(w) = \frac{1}{n} \sum_{i=1}^n \left( (y_i - x_i^T w)^2 + \lambda w^T w \right)$$ Simplify, noting that $w^T w = \|w\|_2^2$: $$L(w) = \frac{1}{n} \sum_{i=1}^n (y_i - x_i^T w)^2 + \lambda \|w\|_2^2$$ This is the mean squared prediction error for the original (non-perturbed) data, plus a penalty on the squared $\ell_2$ norm of the coefficients. Notice that it corresponds exactly to the cost function for ridge regression, with penalty strength $\lambda$.
How is adding noise to training data equivalent to regularization? Overview: For linear regression, I'll show that $\ell_2$ regularization (a.k.a. ridge regression) arises from minimizing the expected squared error over random perturbations of the regressors. The dis
15,358
How is adding noise to training data equivalent to regularization?
The basic concept behind regularization is that we start with our Bayesian prior for the coefficients being a decreasing function of the magnitude of the coefficient. That is, the Bayesian prior for the coefficient being large is smaller than the prior for the coefficient being small. If the basic loss function gives a large estimate for the coefficients, our final estimate is a balance between the Bayesian prior giving more weight to smaller estimates, and the data providing evidence for larger ones. If the random noise corresponds to coefficients being $0$, then it will also pull our final estimates towards being smaller; our actual data saying the coefficients are large will have to compete with the random noise saying the coefficients are small. Another way of looking it is that if we add noise that is generated according our priors, then that will decrease the degree to which our data causes our final estimates of the coefficients to deviate from our priors. Both regularization and random noise are ways of increasing the effects of our priors on our final estimates.
How is adding noise to training data equivalent to regularization?
The basic concept behind regularization is that we start with our Bayesian prior for the coefficients being a decreasing function of the magnitude of the coefficient. That is, the Bayesian prior for t
How is adding noise to training data equivalent to regularization? The basic concept behind regularization is that we start with our Bayesian prior for the coefficients being a decreasing function of the magnitude of the coefficient. That is, the Bayesian prior for the coefficient being large is smaller than the prior for the coefficient being small. If the basic loss function gives a large estimate for the coefficients, our final estimate is a balance between the Bayesian prior giving more weight to smaller estimates, and the data providing evidence for larger ones. If the random noise corresponds to coefficients being $0$, then it will also pull our final estimates towards being smaller; our actual data saying the coefficients are large will have to compete with the random noise saying the coefficients are small. Another way of looking it is that if we add noise that is generated according our priors, then that will decrease the degree to which our data causes our final estimates of the coefficients to deviate from our priors. Both regularization and random noise are ways of increasing the effects of our priors on our final estimates.
How is adding noise to training data equivalent to regularization? The basic concept behind regularization is that we start with our Bayesian prior for the coefficients being a decreasing function of the magnitude of the coefficient. That is, the Bayesian prior for t
15,359
In regression, why not use regularization by default?
In short, regularization changes the distribution of the test statistic, rendering tests of hypothesis moot. In instances where we want to use regression to make inferences about interventions, we want unbiasedness. Not everything to do with data is a prediction problem.
In regression, why not use regularization by default?
In short, regularization changes the distribution of the test statistic, rendering tests of hypothesis moot. In instances where we want to use regression to make inferences about interventions, we wa
In regression, why not use regularization by default? In short, regularization changes the distribution of the test statistic, rendering tests of hypothesis moot. In instances where we want to use regression to make inferences about interventions, we want unbiasedness. Not everything to do with data is a prediction problem.
In regression, why not use regularization by default? In short, regularization changes the distribution of the test statistic, rendering tests of hypothesis moot. In instances where we want to use regression to make inferences about interventions, we wa
15,360
In regression, why not use regularization by default?
People often assume that regularization is superior to un-regularized models because they reduce multicollinearity, reduce model overfitting, and improve forecasting. They also like regularization because it explicitly avoid the entire body of model testing associated with the Gauss-Markov Theorem and other related underlying assumptions of regular regression (testing for heteroskedasticity, autocorrelation, Normal distribution, and stationarity of residuals, etc.). In reality, regularization very often fails to deliver on any of the mentioned benefit above. You can do a search on the Internet for images of LASSO and Ridge Regression and you will readily see a bunch of dramatically failing regularization models. Check the graph of Mean Squared Error (MSE) on the Y-axis vs. the Lambda penalty factor (on the X-axis). And, you will find many regularization models whereby the MSE increases the minute the penalty factor is greater than zero. That means that such a regularization model is more inaccurate than the un-regularized model when forecasting (and most probably in in-sample backtesting too). It also means such a model has not decreased model overfitting; instead it has increased model under-fitting. Another graph to watch is the graph of coefficient paths with the penalty factor on the X-axis and the variables regression coefficient path on the Y-axis. You often will observe that the most influential variables at the onset see their coefficients shrunk much faster than far less influential variables (Ridge Regression) or in some cases such influential variables are entirely taken out of the model far faster than other variables (LASSO). Also, problematic is that often the variables coefficients will change signs as the penalty factor increases. In other word, whatever underlying explanatory logic you had embedded in your model, the regularization process has completely dismantled it. If a model process changes the directional sign of some of your most explanatory causal variable in your model... that's a big problem. LASSO is also promoted as a very good variable selection method (because it does not only shrink coefficients, it zeroes them out). Often, LASSO can make very erroneous variable selection. An easy way to check that is after having run LASSO, rerun your model using only the variables selected by LASSO. And, you may find that many of the variables are not statistically significant, or may have the wrong sign, or that too few or too many variables were selected in the model vs. other more robust variable selection methods. Why does regularization run into so many issues (model under-fitting, poor forecasting, dismantling underlying logic of a model, poor variable selection)? It may be due to the underlying algorithm of regularization models. This algorithm has two components. The first one is an error reduction mechanism such as MIN(SSE) to find the best fit (just like for un-regularized regression) and the second one is a penalty factor that penalizes higher regression coefficients. These two algorithms components push in opposite direction. And, a regularization model has no way of distinguishing between a variable that is very weak, non-causal, and has a very low coefficient vs. another one that is very influential or causal, and has a very high coefficient. The way regularization works, it is just as likely to prefer the weak non-causal variable over the more influential/causal variable. That's a real problem.
In regression, why not use regularization by default?
People often assume that regularization is superior to un-regularized models because they reduce multicollinearity, reduce model overfitting, and improve forecasting. They also like regularization be
In regression, why not use regularization by default? People often assume that regularization is superior to un-regularized models because they reduce multicollinearity, reduce model overfitting, and improve forecasting. They also like regularization because it explicitly avoid the entire body of model testing associated with the Gauss-Markov Theorem and other related underlying assumptions of regular regression (testing for heteroskedasticity, autocorrelation, Normal distribution, and stationarity of residuals, etc.). In reality, regularization very often fails to deliver on any of the mentioned benefit above. You can do a search on the Internet for images of LASSO and Ridge Regression and you will readily see a bunch of dramatically failing regularization models. Check the graph of Mean Squared Error (MSE) on the Y-axis vs. the Lambda penalty factor (on the X-axis). And, you will find many regularization models whereby the MSE increases the minute the penalty factor is greater than zero. That means that such a regularization model is more inaccurate than the un-regularized model when forecasting (and most probably in in-sample backtesting too). It also means such a model has not decreased model overfitting; instead it has increased model under-fitting. Another graph to watch is the graph of coefficient paths with the penalty factor on the X-axis and the variables regression coefficient path on the Y-axis. You often will observe that the most influential variables at the onset see their coefficients shrunk much faster than far less influential variables (Ridge Regression) or in some cases such influential variables are entirely taken out of the model far faster than other variables (LASSO). Also, problematic is that often the variables coefficients will change signs as the penalty factor increases. In other word, whatever underlying explanatory logic you had embedded in your model, the regularization process has completely dismantled it. If a model process changes the directional sign of some of your most explanatory causal variable in your model... that's a big problem. LASSO is also promoted as a very good variable selection method (because it does not only shrink coefficients, it zeroes them out). Often, LASSO can make very erroneous variable selection. An easy way to check that is after having run LASSO, rerun your model using only the variables selected by LASSO. And, you may find that many of the variables are not statistically significant, or may have the wrong sign, or that too few or too many variables were selected in the model vs. other more robust variable selection methods. Why does regularization run into so many issues (model under-fitting, poor forecasting, dismantling underlying logic of a model, poor variable selection)? It may be due to the underlying algorithm of regularization models. This algorithm has two components. The first one is an error reduction mechanism such as MIN(SSE) to find the best fit (just like for un-regularized regression) and the second one is a penalty factor that penalizes higher regression coefficients. These two algorithms components push in opposite direction. And, a regularization model has no way of distinguishing between a variable that is very weak, non-causal, and has a very low coefficient vs. another one that is very influential or causal, and has a very high coefficient. The way regularization works, it is just as likely to prefer the weak non-causal variable over the more influential/causal variable. That's a real problem.
In regression, why not use regularization by default? People often assume that regularization is superior to un-regularized models because they reduce multicollinearity, reduce model overfitting, and improve forecasting. They also like regularization be
15,361
In regression, why not use regularization by default?
My comment would be that all boils down to assumptions. While we would like a hard and fast rule to everything, the world is at the very least a little more complicated than this. Blindly applying either is bound to mislead our interpretation. While we cannot test if the data fits every possible model or assumption, nor should we, we can get into blindspots if we test one model or methodology only.
In regression, why not use regularization by default?
My comment would be that all boils down to assumptions. While we would like a hard and fast rule to everything, the world is at the very least a little more complicated than this. Blindly applying e
In regression, why not use regularization by default? My comment would be that all boils down to assumptions. While we would like a hard and fast rule to everything, the world is at the very least a little more complicated than this. Blindly applying either is bound to mislead our interpretation. While we cannot test if the data fits every possible model or assumption, nor should we, we can get into blindspots if we test one model or methodology only.
In regression, why not use regularization by default? My comment would be that all boils down to assumptions. While we would like a hard and fast rule to everything, the world is at the very least a little more complicated than this. Blindly applying e
15,362
In regression, why not use regularization by default?
another issue is that regression is often used to control for effects of other variables. Lets say I want to know if A is related to Y controlling for B, A and B are strongly correlated and my answer is no, however if I regularize A and B coefficients then my answer will be yes, which is wrong.
In regression, why not use regularization by default?
another issue is that regression is often used to control for effects of other variables. Lets say I want to know if A is related to Y controlling for B, A and B are strongly correlated and my answer
In regression, why not use regularization by default? another issue is that regression is often used to control for effects of other variables. Lets say I want to know if A is related to Y controlling for B, A and B are strongly correlated and my answer is no, however if I regularize A and B coefficients then my answer will be yes, which is wrong.
In regression, why not use regularization by default? another issue is that regression is often used to control for effects of other variables. Lets say I want to know if A is related to Y controlling for B, A and B are strongly correlated and my answer
15,363
Why not use the "normal equations" to find simple least squares coefficients?
For the problem $Ax \approx b$, forming the Normal equations squares the condition number of $A$ by forming $A^TA$. Roughly speaking $log_{10}(cond)$ is the number of digits you lose in your calculation if everything is done well. And this doesn't really have anything to do with forming the inverse of $A^TA$. No matter how $A^TAx = A^Tb$ is solved, you've already lost $log_{10}(cond(A^TA)) = 2*log_{10}(cond(A))$ digits of accuracy. I.e., forming the Normal equations has doubled the number of digits of accuracy lost, right off the bat. If the condition number is small (one is the best possible), it doesn't matter much. If the condition number = $10^8$ and you use a stable method such as QR or SVD, you may have about 8 digits of accuracy in double precision. If you form the Normal equations, you've squared the condition number to $10^{16}$, and you have essentially no accuracy in your answer. Sometimes you get away with the Normal equations, and sometimes you don't.
Why not use the "normal equations" to find simple least squares coefficients?
For the problem $Ax \approx b$, forming the Normal equations squares the condition number of $A$ by forming $A^TA$. Roughly speaking $log_{10}(cond)$ is the number of digits you lose in your calculati
Why not use the "normal equations" to find simple least squares coefficients? For the problem $Ax \approx b$, forming the Normal equations squares the condition number of $A$ by forming $A^TA$. Roughly speaking $log_{10}(cond)$ is the number of digits you lose in your calculation if everything is done well. And this doesn't really have anything to do with forming the inverse of $A^TA$. No matter how $A^TAx = A^Tb$ is solved, you've already lost $log_{10}(cond(A^TA)) = 2*log_{10}(cond(A))$ digits of accuracy. I.e., forming the Normal equations has doubled the number of digits of accuracy lost, right off the bat. If the condition number is small (one is the best possible), it doesn't matter much. If the condition number = $10^8$ and you use a stable method such as QR or SVD, you may have about 8 digits of accuracy in double precision. If you form the Normal equations, you've squared the condition number to $10^{16}$, and you have essentially no accuracy in your answer. Sometimes you get away with the Normal equations, and sometimes you don't.
Why not use the "normal equations" to find simple least squares coefficients? For the problem $Ax \approx b$, forming the Normal equations squares the condition number of $A$ by forming $A^TA$. Roughly speaking $log_{10}(cond)$ is the number of digits you lose in your calculati
15,364
Why not use the "normal equations" to find simple least squares coefficients?
If you only have to solve this one variable problem, then go ahead and use the formula. There's nothing wrong with it. I could see you writing a few lines of code in ASM for an embedded device, for instance. In fact, I used this kind of solution in some situations. You don't need to drag large statistical libraries just to solve this one little problem, of course. The numerical instability and performance are issues of larger problems and general setting. If you solve multivariate least squares etc. For a general problem you wouldn't use this, of course.
Why not use the "normal equations" to find simple least squares coefficients?
If you only have to solve this one variable problem, then go ahead and use the formula. There's nothing wrong with it. I could see you writing a few lines of code in ASM for an embedded device, for in
Why not use the "normal equations" to find simple least squares coefficients? If you only have to solve this one variable problem, then go ahead and use the formula. There's nothing wrong with it. I could see you writing a few lines of code in ASM for an embedded device, for instance. In fact, I used this kind of solution in some situations. You don't need to drag large statistical libraries just to solve this one little problem, of course. The numerical instability and performance are issues of larger problems and general setting. If you solve multivariate least squares etc. For a general problem you wouldn't use this, of course.
Why not use the "normal equations" to find simple least squares coefficients? If you only have to solve this one variable problem, then go ahead and use the formula. There's nothing wrong with it. I could see you writing a few lines of code in ASM for an embedded device, for in
15,365
Why not use the "normal equations" to find simple least squares coefficients?
No modern statistical package would solve a linear regression with the normal equations. The normal equations exist only in the statistical books. The normal equations shouldn't be used as computing the inverse of matrix is very problematic. Why use gradient descent for linear regression, when a closed-form math solution is available? ... although direct normal equation is available. Notice that in normal equation one has to invert a matrix. Now inverting a matrix costs O(N3) for computation where N is the number of rows in X matrix i.e. the observations. Moreover, if the X is ill conditioned then it will create computational errors in estimation...
Why not use the "normal equations" to find simple least squares coefficients?
No modern statistical package would solve a linear regression with the normal equations. The normal equations exist only in the statistical books. The normal equations shouldn't be used as computing t
Why not use the "normal equations" to find simple least squares coefficients? No modern statistical package would solve a linear regression with the normal equations. The normal equations exist only in the statistical books. The normal equations shouldn't be used as computing the inverse of matrix is very problematic. Why use gradient descent for linear regression, when a closed-form math solution is available? ... although direct normal equation is available. Notice that in normal equation one has to invert a matrix. Now inverting a matrix costs O(N3) for computation where N is the number of rows in X matrix i.e. the observations. Moreover, if the X is ill conditioned then it will create computational errors in estimation...
Why not use the "normal equations" to find simple least squares coefficients? No modern statistical package would solve a linear regression with the normal equations. The normal equations exist only in the statistical books. The normal equations shouldn't be used as computing t
15,366
Why does linear regression use a cost function based on the vertical distance between the hypothesis and the input data point?
When you have noise in both the dependent variable (vertical errors) and the independent variable (horizontal errors), the least squares objective function can be modified to incorporate these horizontal errors. The problem in how to weight these two types of errors. This weighting usually depends on the ratio of the variances of the two errors: If the variance of the vertical error is extremely large relative to the variance of the horizontal error, OLS is correct. If the variance of the horizontal error is extremely large relative to the variance of the vertical error, inverse least squares (in which $x$ is regressed on $y$ and the inverse of the coefficient estimate for $y$ is used as the estimate of $\beta$) is appropriate. If the ratio of the variance of the vertical error to the variance of the horizontal error is equal to the ratio of the variances of the dependent and independent variables, we have the case of "diagonal" regression, in which a consistent esti­mate turns out to be the geometric mean of the OLS and inverse least squares estimators. If the ratio of these error variances is one, then we have the case of "orthogonal" regression, in which the sum of squared errors measured along a line perpendicular to the estimating line is minimized. This is what you had in mind. In practice, the great drawback of this procedure is that the ratio of the error variances is not usually known and cannot usually be estimated, so the path forward is not clear.
Why does linear regression use a cost function based on the vertical distance between the hypothesis
When you have noise in both the dependent variable (vertical errors) and the independent variable (horizontal errors), the least squares objective function can be modified to incorporate these horizon
Why does linear regression use a cost function based on the vertical distance between the hypothesis and the input data point? When you have noise in both the dependent variable (vertical errors) and the independent variable (horizontal errors), the least squares objective function can be modified to incorporate these horizontal errors. The problem in how to weight these two types of errors. This weighting usually depends on the ratio of the variances of the two errors: If the variance of the vertical error is extremely large relative to the variance of the horizontal error, OLS is correct. If the variance of the horizontal error is extremely large relative to the variance of the vertical error, inverse least squares (in which $x$ is regressed on $y$ and the inverse of the coefficient estimate for $y$ is used as the estimate of $\beta$) is appropriate. If the ratio of the variance of the vertical error to the variance of the horizontal error is equal to the ratio of the variances of the dependent and independent variables, we have the case of "diagonal" regression, in which a consistent esti­mate turns out to be the geometric mean of the OLS and inverse least squares estimators. If the ratio of these error variances is one, then we have the case of "orthogonal" regression, in which the sum of squared errors measured along a line perpendicular to the estimating line is minimized. This is what you had in mind. In practice, the great drawback of this procedure is that the ratio of the error variances is not usually known and cannot usually be estimated, so the path forward is not clear.
Why does linear regression use a cost function based on the vertical distance between the hypothesis When you have noise in both the dependent variable (vertical errors) and the independent variable (horizontal errors), the least squares objective function can be modified to incorporate these horizon
15,367
Why does linear regression use a cost function based on the vertical distance between the hypothesis and the input data point?
One reason is that $$\sum_{i=1}^N(y_i-h_\theta(x_i))^2$$ is relatively easy to compute and optimize, while the proposed cost $$\sum_{i=1}^N \min_{x,y}\big[(y_i-h_\theta(x))^2+(x_i-x)^2\big]$$ has a nested minimization problem which may be quite hard depending on the choice of family for $h_\theta(x)$.
Why does linear regression use a cost function based on the vertical distance between the hypothesis
One reason is that $$\sum_{i=1}^N(y_i-h_\theta(x_i))^2$$ is relatively easy to compute and optimize, while the proposed cost $$\sum_{i=1}^N \min_{x,y}\big[(y_i-h_\theta(x))^2+(x_i-x)^2\big]$$ has a ne
Why does linear regression use a cost function based on the vertical distance between the hypothesis and the input data point? One reason is that $$\sum_{i=1}^N(y_i-h_\theta(x_i))^2$$ is relatively easy to compute and optimize, while the proposed cost $$\sum_{i=1}^N \min_{x,y}\big[(y_i-h_\theta(x))^2+(x_i-x)^2\big]$$ has a nested minimization problem which may be quite hard depending on the choice of family for $h_\theta(x)$.
Why does linear regression use a cost function based on the vertical distance between the hypothesis One reason is that $$\sum_{i=1}^N(y_i-h_\theta(x_i))^2$$ is relatively easy to compute and optimize, while the proposed cost $$\sum_{i=1}^N \min_{x,y}\big[(y_i-h_\theta(x))^2+(x_i-x)^2\big]$$ has a ne
15,368
Why does linear regression use a cost function based on the vertical distance between the hypothesis and the input data point?
At the risk of being prosaic, the reason for the error function is that the standard interpretation is that the x is given and one is trying to best describe (or predict) the y component. So there is no error in the 'x'. For example you might try and understand (or predict) the closing price of a stock tomorrow based on today's closing price . Similarly one could try and understand the average temperature tomorrow in terms of today's average temperature. Obviously these examples are simple minded, but that is the idea. Incidentally something most people don't realize, but I think is clear from your examples, is that if one regresses y against x the regression line doesn't have to have any particular resemblance to the regression of x against y. Orthogonal regression is the term for a regression where one tries to find the line that minimizes the distance of points from a line. For example if one was trying to understand the relationship between the price of IBM stock and the price of AAPL stock, that would be the appropriate method.
Why does linear regression use a cost function based on the vertical distance between the hypothesis
At the risk of being prosaic, the reason for the error function is that the standard interpretation is that the x is given and one is trying to best describe (or predict) the y component. So there is
Why does linear regression use a cost function based on the vertical distance between the hypothesis and the input data point? At the risk of being prosaic, the reason for the error function is that the standard interpretation is that the x is given and one is trying to best describe (or predict) the y component. So there is no error in the 'x'. For example you might try and understand (or predict) the closing price of a stock tomorrow based on today's closing price . Similarly one could try and understand the average temperature tomorrow in terms of today's average temperature. Obviously these examples are simple minded, but that is the idea. Incidentally something most people don't realize, but I think is clear from your examples, is that if one regresses y against x the regression line doesn't have to have any particular resemblance to the regression of x against y. Orthogonal regression is the term for a regression where one tries to find the line that minimizes the distance of points from a line. For example if one was trying to understand the relationship between the price of IBM stock and the price of AAPL stock, that would be the appropriate method.
Why does linear regression use a cost function based on the vertical distance between the hypothesis At the risk of being prosaic, the reason for the error function is that the standard interpretation is that the x is given and one is trying to best describe (or predict) the y component. So there is
15,369
Why does linear regression use a cost function based on the vertical distance between the hypothesis and the input data point?
The oversimplified version is that X is assumed to have no error. So if you look at point E in your plot for example, it's assumed that its X coordinate is precisely accurate. Typically this is the case when we can control X, in other words when we can set it to a specific value. In that case, the only error that can exist is in the Y direction, and that's why the error / cost function only includes the Y direction. Whenever that's not the case, whenever we don't control X and X can have error, people do incorporate the X direction in the error function in something called type II or model II regression, and its variants. It can be tricky to do this if X and Y have different scales, so then you have to think about normalizations and such.
Why does linear regression use a cost function based on the vertical distance between the hypothesis
The oversimplified version is that X is assumed to have no error. So if you look at point E in your plot for example, it's assumed that its X coordinate is precisely accurate. Typically this is the
Why does linear regression use a cost function based on the vertical distance between the hypothesis and the input data point? The oversimplified version is that X is assumed to have no error. So if you look at point E in your plot for example, it's assumed that its X coordinate is precisely accurate. Typically this is the case when we can control X, in other words when we can set it to a specific value. In that case, the only error that can exist is in the Y direction, and that's why the error / cost function only includes the Y direction. Whenever that's not the case, whenever we don't control X and X can have error, people do incorporate the X direction in the error function in something called type II or model II regression, and its variants. It can be tricky to do this if X and Y have different scales, so then you have to think about normalizations and such.
Why does linear regression use a cost function based on the vertical distance between the hypothesis The oversimplified version is that X is assumed to have no error. So if you look at point E in your plot for example, it's assumed that its X coordinate is precisely accurate. Typically this is the
15,370
Why does linear regression use a cost function based on the vertical distance between the hypothesis and the input data point?
You are right that, when fitting a line through points, the orthogonal distance is the most natural loss function that can be applied to arbitrary lines (note that the y-distance becomes meaningless for lines perpendicular to the x-axis). This problem is known under a number of names, e.g. "orthogonal regression", or (the most used term, AFAIK) "Principal Component Analysis" (PCA). For a discussion of this problem in arbitrary dimenstions, see Späth: "Orthogonal least squares fitting with linear manifolds." Numerische Mathematik 48, pp. 441–445, 1986 As @aginensky already pointed out, the idea behind Linear Regression is not to fit a line through points, but to predict y-values for given x-values. That's why only the distance in y is used, which is the prediction accuracy. Reformulating the problem of fitting a curve $\vec{x}(t)$ through points $\vec{p}_i$, $i=1\ldots N$ as a prediction problem makes things complicated, because the predictor $t$ is unknown and even to some degree arbitrary. For curves other than straight lines, this is still a problem that is subject to active research. One possible (incomplete) approach is described in the following article, which is incomplete because it does not provide a solution for finding an initial guess for the curve, but only how to iteratively improve such an initial guess: Wang, Pottmann, Liu: "Fitting B-spline curves to point clouds by curvature-based squared distance minimization." ACM Transactions on Graphics 25.2, pp. 214-238, 2006
Why does linear regression use a cost function based on the vertical distance between the hypothesis
You are right that, when fitting a line through points, the orthogonal distance is the most natural loss function that can be applied to arbitrary lines (note that the y-distance becomes meaningless f
Why does linear regression use a cost function based on the vertical distance between the hypothesis and the input data point? You are right that, when fitting a line through points, the orthogonal distance is the most natural loss function that can be applied to arbitrary lines (note that the y-distance becomes meaningless for lines perpendicular to the x-axis). This problem is known under a number of names, e.g. "orthogonal regression", or (the most used term, AFAIK) "Principal Component Analysis" (PCA). For a discussion of this problem in arbitrary dimenstions, see Späth: "Orthogonal least squares fitting with linear manifolds." Numerische Mathematik 48, pp. 441–445, 1986 As @aginensky already pointed out, the idea behind Linear Regression is not to fit a line through points, but to predict y-values for given x-values. That's why only the distance in y is used, which is the prediction accuracy. Reformulating the problem of fitting a curve $\vec{x}(t)$ through points $\vec{p}_i$, $i=1\ldots N$ as a prediction problem makes things complicated, because the predictor $t$ is unknown and even to some degree arbitrary. For curves other than straight lines, this is still a problem that is subject to active research. One possible (incomplete) approach is described in the following article, which is incomplete because it does not provide a solution for finding an initial guess for the curve, but only how to iteratively improve such an initial guess: Wang, Pottmann, Liu: "Fitting B-spline curves to point clouds by curvature-based squared distance minimization." ACM Transactions on Graphics 25.2, pp. 214-238, 2006
Why does linear regression use a cost function based on the vertical distance between the hypothesis You are right that, when fitting a line through points, the orthogonal distance is the most natural loss function that can be applied to arbitrary lines (note that the y-distance becomes meaningless f
15,371
How to evaluate the final model after k-fold cross-validation
When training on each fold (90%) of the data, you will then predict on the remaining 10%. With this 10% you will compute an error metric (RMSE, for example). This leaves you with: 10 values for RMSE, and 10 sets of corresponding predictions. There are 2 things to do this these results: Inspect the mean and standard deviation of your 10 RMSE values. k-fold takes random partitions of your data, and the error on each fold should not vary too greatly. If it does, your model (and its features, hyper-parameters etc.) cannot be expected to yield stable predictions on a test set. Aggregate your 10 sets of predictions into 1 set of predictions. For example, if your training set contains 1,000 data points, you will have 10 sets of 100 predictions (10*100 = 1000). When you stack these into 1 vector, you are now left with 1000 predictions: 1 for every observation in your original training set. These are called out-of-folds predictions. With these, you can compute the RMSE for your whole training set in one go, as rmse = compute_rmse(oof_predictions, y_train). This is the likely the cleanest way to evaluate the final predictor.
How to evaluate the final model after k-fold cross-validation
When training on each fold (90%) of the data, you will then predict on the remaining 10%. With this 10% you will compute an error metric (RMSE, for example). This leaves you with: 10 values for RMSE,
How to evaluate the final model after k-fold cross-validation When training on each fold (90%) of the data, you will then predict on the remaining 10%. With this 10% you will compute an error metric (RMSE, for example). This leaves you with: 10 values for RMSE, and 10 sets of corresponding predictions. There are 2 things to do this these results: Inspect the mean and standard deviation of your 10 RMSE values. k-fold takes random partitions of your data, and the error on each fold should not vary too greatly. If it does, your model (and its features, hyper-parameters etc.) cannot be expected to yield stable predictions on a test set. Aggregate your 10 sets of predictions into 1 set of predictions. For example, if your training set contains 1,000 data points, you will have 10 sets of 100 predictions (10*100 = 1000). When you stack these into 1 vector, you are now left with 1000 predictions: 1 for every observation in your original training set. These are called out-of-folds predictions. With these, you can compute the RMSE for your whole training set in one go, as rmse = compute_rmse(oof_predictions, y_train). This is the likely the cleanest way to evaluate the final predictor.
How to evaluate the final model after k-fold cross-validation When training on each fold (90%) of the data, you will then predict on the remaining 10%. With this 10% you will compute an error metric (RMSE, for example). This leaves you with: 10 values for RMSE,
15,372
How to evaluate the final model after k-fold cross-validation
Taking the average of the k accuracy scores is a macro-average. Taking the average of the 1000 individual predictions (as described in cavaunpeu's answer) is a micro-average. Both are legitimate and should be broadly similar to each other, so you can use whichever is more convenient - or report both for completeness.
How to evaluate the final model after k-fold cross-validation
Taking the average of the k accuracy scores is a macro-average. Taking the average of the 1000 individual predictions (as described in cavaunpeu's answer) is a micro-average. Both are legitimate and s
How to evaluate the final model after k-fold cross-validation Taking the average of the k accuracy scores is a macro-average. Taking the average of the 1000 individual predictions (as described in cavaunpeu's answer) is a micro-average. Both are legitimate and should be broadly similar to each other, so you can use whichever is more convenient - or report both for completeness.
How to evaluate the final model after k-fold cross-validation Taking the average of the k accuracy scores is a macro-average. Taking the average of the 1000 individual predictions (as described in cavaunpeu's answer) is a micro-average. Both are legitimate and s
15,373
Back transformation of an MLR model [duplicate]
This is called the re-transformation problem. I'm going to make your model a little simpler to talk about it: $\ln{Y} = \beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2 + \epsilon$ Now, that model does not make predictions for $Y$, it makes predictions for $\ln{Y}$. It is tempting to make predictions for $Y$ by just taking predictions for $\ln{Y}$ and exponentiating them like $\hat{Y}=\exp(\widehat{\ln{Y}})$. This is wrong (i.e. biased), though: $\begin{align} \ln{Y} &= \beta_0 + \beta_1X_1 + \beta_2X_2 +\beta_3X_2^2 + \epsilon\\ Y &= \exp(\beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2)\exp(\epsilon)\\ \mathrm{E}\{ Y|X\} &= \exp(\beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2)\,\mathrm{E}\{\exp(\epsilon)|X\}\\ \hat{\mathrm{E}}\{ Y|X\} &= \exp(\widehat{\ln{Y}})\,\mathrm{E}\{\exp(\epsilon)|X\} \end{align}$ The best predictor of $Y$ is its expectation. If we could conclude that $\mathrm{E}\{\exp(\epsilon)|X\}=1$, then we could just exponentiate like you are suggesting above. But Jensen's inequality says that since $\mathrm{E}\{\epsilon|X\}=0$, it must be that $\mathrm{E}\{\exp(\epsilon)|X\}>1$. So, we have to use some kind of adjustment. The adjustment is called Duan's Smearing Estimator. It is just the sample mean of the exponentiated prediction errors (residuals) from the original model, $(1/N)\sum \exp(e_i)$. So the right way to re-transform from the log model back to predictions on Y is: $$\hat{Y}_j = \exp(\widehat{\ln{Y}}_j) \cdot \frac{1}{N}\sum_{i=1}^N \exp(e_i)$$ To your questions. On the parameters, whether you need to re-transform depends on what you are trying to measure. The parameter $\beta_2$ measures the amount that $Y$ goes up (in percents) for a one unit increase in $X_1$. So, if $\beta_2=0.04$, that says that $Y$ goes up 4% for each one unit $X_1$ goes up. Similarly, for each unit $X_2$ goes up, $Y$ goes up $\beta_2+2\beta_3X_2$ percent. If you want to measure the amount that $Y$ goes up in units when $X_2$ goes up by one unit, then you need to re-transform: $\begin{align} Y &= \exp(\beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2)\exp(\epsilon)\\ \frac{\partial Y}{\partial X_1} &= \exp(\beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2)\exp(\epsilon)\beta_1\\ \hat{\mathrm{E}}\left\{ \frac{\partial Y}{\partial X_1} \right\} &= \exp(\widehat{\ln{Y}}) \cdot \frac{1}{N}\sum \exp(e_i) \cdot \beta_1 \end{align}$ Notice that the answer depends on $\hat{Y}$, totally unlike "regular" regression. You should expect this, though. The model is non-linear, so the derivative depends on the point of evaluation. For your more complicated model, you have to be careful to apply the chain rule properly---that is, where I have $\beta_1$, you will have a complicated expression with $\beta$s and powers of your various $X$s and such. For the confidence intervals, again, the question is what you are trying to measure. If you are happy with knowing how many percents $Y$ goes up when $X_1$ goes up by one, then the "regular" confidence intervals you get from the usual regression output are fine. If you want to measure the number of units that $Y$ goes up when $X_1$ goes up by one, then it's more complicated. Actually, it's very complicated in that case---you should use bootstrapping to do it. You can use something called the delta method, but it is a pain. Root mean squared error of the prediction is easy to calculate, once you have re-transformed back to predicted $Y$: $$\mathrm{RMSEP} = \sqrt {\frac{1}{N-1} \sum (\hat{Y}_i-Y_i)^2}$$ where $\hat{Y}_i$ comes from the formula above.
Back transformation of an MLR model [duplicate]
This is called the re-transformation problem. I'm going to make your model a little simpler to talk about it: $\ln{Y} = \beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2 + \epsilon$ Now, that model do
Back transformation of an MLR model [duplicate] This is called the re-transformation problem. I'm going to make your model a little simpler to talk about it: $\ln{Y} = \beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2 + \epsilon$ Now, that model does not make predictions for $Y$, it makes predictions for $\ln{Y}$. It is tempting to make predictions for $Y$ by just taking predictions for $\ln{Y}$ and exponentiating them like $\hat{Y}=\exp(\widehat{\ln{Y}})$. This is wrong (i.e. biased), though: $\begin{align} \ln{Y} &= \beta_0 + \beta_1X_1 + \beta_2X_2 +\beta_3X_2^2 + \epsilon\\ Y &= \exp(\beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2)\exp(\epsilon)\\ \mathrm{E}\{ Y|X\} &= \exp(\beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2)\,\mathrm{E}\{\exp(\epsilon)|X\}\\ \hat{\mathrm{E}}\{ Y|X\} &= \exp(\widehat{\ln{Y}})\,\mathrm{E}\{\exp(\epsilon)|X\} \end{align}$ The best predictor of $Y$ is its expectation. If we could conclude that $\mathrm{E}\{\exp(\epsilon)|X\}=1$, then we could just exponentiate like you are suggesting above. But Jensen's inequality says that since $\mathrm{E}\{\epsilon|X\}=0$, it must be that $\mathrm{E}\{\exp(\epsilon)|X\}>1$. So, we have to use some kind of adjustment. The adjustment is called Duan's Smearing Estimator. It is just the sample mean of the exponentiated prediction errors (residuals) from the original model, $(1/N)\sum \exp(e_i)$. So the right way to re-transform from the log model back to predictions on Y is: $$\hat{Y}_j = \exp(\widehat{\ln{Y}}_j) \cdot \frac{1}{N}\sum_{i=1}^N \exp(e_i)$$ To your questions. On the parameters, whether you need to re-transform depends on what you are trying to measure. The parameter $\beta_2$ measures the amount that $Y$ goes up (in percents) for a one unit increase in $X_1$. So, if $\beta_2=0.04$, that says that $Y$ goes up 4% for each one unit $X_1$ goes up. Similarly, for each unit $X_2$ goes up, $Y$ goes up $\beta_2+2\beta_3X_2$ percent. If you want to measure the amount that $Y$ goes up in units when $X_2$ goes up by one unit, then you need to re-transform: $\begin{align} Y &= \exp(\beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2)\exp(\epsilon)\\ \frac{\partial Y}{\partial X_1} &= \exp(\beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2)\exp(\epsilon)\beta_1\\ \hat{\mathrm{E}}\left\{ \frac{\partial Y}{\partial X_1} \right\} &= \exp(\widehat{\ln{Y}}) \cdot \frac{1}{N}\sum \exp(e_i) \cdot \beta_1 \end{align}$ Notice that the answer depends on $\hat{Y}$, totally unlike "regular" regression. You should expect this, though. The model is non-linear, so the derivative depends on the point of evaluation. For your more complicated model, you have to be careful to apply the chain rule properly---that is, where I have $\beta_1$, you will have a complicated expression with $\beta$s and powers of your various $X$s and such. For the confidence intervals, again, the question is what you are trying to measure. If you are happy with knowing how many percents $Y$ goes up when $X_1$ goes up by one, then the "regular" confidence intervals you get from the usual regression output are fine. If you want to measure the number of units that $Y$ goes up when $X_1$ goes up by one, then it's more complicated. Actually, it's very complicated in that case---you should use bootstrapping to do it. You can use something called the delta method, but it is a pain. Root mean squared error of the prediction is easy to calculate, once you have re-transformed back to predicted $Y$: $$\mathrm{RMSEP} = \sqrt {\frac{1}{N-1} \sum (\hat{Y}_i-Y_i)^2}$$ where $\hat{Y}_i$ comes from the formula above.
Back transformation of an MLR model [duplicate] This is called the re-transformation problem. I'm going to make your model a little simpler to talk about it: $\ln{Y} = \beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_2^2 + \epsilon$ Now, that model do
15,374
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)?
To decide which point forecast error measure to use, we need to take a step back. Note that we don't know the future outcome perfectly, nor will we ever. So the future outcome follows a probability distribution. Some forecasting methods explicitly output such a full distribution, and some don't - but it is always there, if only implicitly. Now, we want to have a good error measure for a point forecast. Such a point forecast $F_t$ is our attempt to summarize what we know about the future distribution (i.e., the predictive distribution) at time $t$ using a single number, a so-called functional of the future density. The error measure then is a way to assess the quality of this single number summary. So you should choose an error measure that rewards "good" one number summaries of (unknown, possibly forecasted, but possibly only implicit) future densities. The challenge is that different error measures are minimized by different functionals. The expected MSE is minimized by the expected value of the future distribution. The expected MAD is minimized by the median of the future distribution. Thus, if you calibrate your forecasts to minimize the MAE, your point forecast will be the future median, not the future expected value, and your forecasts will be biased if your future distribution is not symmetric. This is most relevant for count data, which are typically skewed. In extreme cases (say, Poisson distributed sales with a mean below $\log 2\approx 0.69$), your MAE will be lowest for a flat zero forecast. See here or here or here for details. I give some more information and an illustration in What are the shortcomings of the Mean Absolute Percentage Error (MAPE)? That thread considers the mape, but also other error measures, and it contains links to other related threads. In the end, which error measure to use really depends on your Cost of Forecast Error, i.e., which kind of error is most painful. Without looking at the actual implications of forecast errors, any discussion about "better criteria" is basically meaningless. Measures of forecast accuracy were a big topic in the forecasting community some years back, and they still pop up now and then. One very good article to look at is Hyndman & Koehler "Another look at measures of forecast accuracy" (2006). Finally, one alternative is to calculate full predictive densities and assess these using proper scoring-rules.
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)?
To decide which point forecast error measure to use, we need to take a step back. Note that we don't know the future outcome perfectly, nor will we ever. So the future outcome follows a probability di
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)? To decide which point forecast error measure to use, we need to take a step back. Note that we don't know the future outcome perfectly, nor will we ever. So the future outcome follows a probability distribution. Some forecasting methods explicitly output such a full distribution, and some don't - but it is always there, if only implicitly. Now, we want to have a good error measure for a point forecast. Such a point forecast $F_t$ is our attempt to summarize what we know about the future distribution (i.e., the predictive distribution) at time $t$ using a single number, a so-called functional of the future density. The error measure then is a way to assess the quality of this single number summary. So you should choose an error measure that rewards "good" one number summaries of (unknown, possibly forecasted, but possibly only implicit) future densities. The challenge is that different error measures are minimized by different functionals. The expected MSE is minimized by the expected value of the future distribution. The expected MAD is minimized by the median of the future distribution. Thus, if you calibrate your forecasts to minimize the MAE, your point forecast will be the future median, not the future expected value, and your forecasts will be biased if your future distribution is not symmetric. This is most relevant for count data, which are typically skewed. In extreme cases (say, Poisson distributed sales with a mean below $\log 2\approx 0.69$), your MAE will be lowest for a flat zero forecast. See here or here or here for details. I give some more information and an illustration in What are the shortcomings of the Mean Absolute Percentage Error (MAPE)? That thread considers the mape, but also other error measures, and it contains links to other related threads. In the end, which error measure to use really depends on your Cost of Forecast Error, i.e., which kind of error is most painful. Without looking at the actual implications of forecast errors, any discussion about "better criteria" is basically meaningless. Measures of forecast accuracy were a big topic in the forecasting community some years back, and they still pop up now and then. One very good article to look at is Hyndman & Koehler "Another look at measures of forecast accuracy" (2006). Finally, one alternative is to calculate full predictive densities and assess these using proper scoring-rules.
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)? To decide which point forecast error measure to use, we need to take a step back. Note that we don't know the future outcome perfectly, nor will we ever. So the future outcome follows a probability di
15,375
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)?
The advantages of using MAE instead of MSE are explained in Davydenko and Fildes (2016), see Section 3.1: ...Some authors (e.g., Zellner, 1986) argue that the criterion by which we evaluate forecasts should correspond to the criterion by which we optimise forecasts. In other words, if we optimise estimates using some given loss function, we must use the same loss function for empirical evaluation in order to find out which model is better. Fitting a statistical model usually delivers forecasts optimal under quadratic loss. This, e.g., happens when we fit a linear regression. If our density forecast from statistical modelling is symmetric, then forecasts optimal under quadratic loss are also optimal under linear loss. But, if we stabilise the variance by log-transformations and then transform back forecasts by exponentiation, we get forecasts optimal only under linear loss. If we use another loss, we must first obtain the density forecast using a statistical model, and then adjust our estimate given our specific loss function (see examples of doing this in Goodwin, 2000). Let’s assume we want to empirically compare two methods and find out which method is better in terms of a symmetric linear loss (since this type of loss is commonly used in modelling). If we have only one time series, it seems natural to use a mean absolute error (MAE). Also, MAE is attractive as it is simple to understand and calculate (Hyndman, 2006)... References Davydenko, A., & Fildes, R. (2016). Forecast Error Measures: Critical Review and Practical Recommendations. In Business Forecasting: Practical Problems and Solutions. John Wiley & Sons
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)?
The advantages of using MAE instead of MSE are explained in Davydenko and Fildes (2016), see Section 3.1: ...Some authors (e.g., Zellner, 1986) argue that the criterion by which we evaluate forecas
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)? The advantages of using MAE instead of MSE are explained in Davydenko and Fildes (2016), see Section 3.1: ...Some authors (e.g., Zellner, 1986) argue that the criterion by which we evaluate forecasts should correspond to the criterion by which we optimise forecasts. In other words, if we optimise estimates using some given loss function, we must use the same loss function for empirical evaluation in order to find out which model is better. Fitting a statistical model usually delivers forecasts optimal under quadratic loss. This, e.g., happens when we fit a linear regression. If our density forecast from statistical modelling is symmetric, then forecasts optimal under quadratic loss are also optimal under linear loss. But, if we stabilise the variance by log-transformations and then transform back forecasts by exponentiation, we get forecasts optimal only under linear loss. If we use another loss, we must first obtain the density forecast using a statistical model, and then adjust our estimate given our specific loss function (see examples of doing this in Goodwin, 2000). Let’s assume we want to empirically compare two methods and find out which method is better in terms of a symmetric linear loss (since this type of loss is commonly used in modelling). If we have only one time series, it seems natural to use a mean absolute error (MAE). Also, MAE is attractive as it is simple to understand and calculate (Hyndman, 2006)... References Davydenko, A., & Fildes, R. (2016). Forecast Error Measures: Critical Review and Practical Recommendations. In Business Forecasting: Practical Problems and Solutions. John Wiley & Sons
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)? The advantages of using MAE instead of MSE are explained in Davydenko and Fildes (2016), see Section 3.1: ...Some authors (e.g., Zellner, 1986) argue that the criterion by which we evaluate forecas
15,376
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)?
Why not compare $RMSE = \sqrt{MSE}$ and $MAE = MAD$? Actually, $MAE \leq RMSE \leq \sqrt{n} MAE$ for regression models: lower bound: each case contributes the same absolute amount of error $e$: $RMSE = \sqrt{\frac{1}{n} \sum e_i^2} = \sqrt{\frac{1}{n} n e^2} = e = MAE$ upper bound: a single case having error $e$ while all other cases have 0 error: $MAE = \frac{e}{n}$ $RMSE = \sqrt{\frac{1}{n} \sum e_i^2} = \sqrt{\frac{1}{n} e^2} = \sqrt{\frac{1}{n} (n MAE)^2} = \sqrt{n} MAE$ ($MAE \leq RMSE \leq \sqrt{MAE}$ for classification with partial class memberships $y_i$ and/or $\hat y_i$ are $\in [0, 1]$ -- i.e. they can actually take values in between 0 and 1). upper bound: here, $e_i$ is $\leq 1$, so $MAE = \frac{n_{wrong}}{n}$ $RMSE = \sqrt{\frac{1}{n} \sum e_i^2} = \sqrt{\frac{1}{n} n_{wrong}} = \sqrt{MAE}$ (This upper bound occurs for integer $n_{wrong}$, if you go for partial/fractional class membership and thus also for $e_i \in [0, 1]$, things get a bit more complicated because you need to take into account that the maximum possible error can be less than 1, and you may have a "leftover" $e_i < 1$ which both lower the upper bound a bit further.) If the RMSE is close the MAE, you have many small deviations, if it is close to its upper bound, there are few grossly wrong predictions.
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)?
Why not compare $RMSE = \sqrt{MSE}$ and $MAE = MAD$? Actually, $MAE \leq RMSE \leq \sqrt{n} MAE$ for regression models: lower bound: each case contributes the same absolute amount of error $e$: $R
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)? Why not compare $RMSE = \sqrt{MSE}$ and $MAE = MAD$? Actually, $MAE \leq RMSE \leq \sqrt{n} MAE$ for regression models: lower bound: each case contributes the same absolute amount of error $e$: $RMSE = \sqrt{\frac{1}{n} \sum e_i^2} = \sqrt{\frac{1}{n} n e^2} = e = MAE$ upper bound: a single case having error $e$ while all other cases have 0 error: $MAE = \frac{e}{n}$ $RMSE = \sqrt{\frac{1}{n} \sum e_i^2} = \sqrt{\frac{1}{n} e^2} = \sqrt{\frac{1}{n} (n MAE)^2} = \sqrt{n} MAE$ ($MAE \leq RMSE \leq \sqrt{MAE}$ for classification with partial class memberships $y_i$ and/or $\hat y_i$ are $\in [0, 1]$ -- i.e. they can actually take values in between 0 and 1). upper bound: here, $e_i$ is $\leq 1$, so $MAE = \frac{n_{wrong}}{n}$ $RMSE = \sqrt{\frac{1}{n} \sum e_i^2} = \sqrt{\frac{1}{n} n_{wrong}} = \sqrt{MAE}$ (This upper bound occurs for integer $n_{wrong}$, if you go for partial/fractional class membership and thus also for $e_i \in [0, 1]$, things get a bit more complicated because you need to take into account that the maximum possible error can be less than 1, and you may have a "leftover" $e_i < 1$ which both lower the upper bound a bit further.) If the RMSE is close the MAE, you have many small deviations, if it is close to its upper bound, there are few grossly wrong predictions.
Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)? Why not compare $RMSE = \sqrt{MSE}$ and $MAE = MAD$? Actually, $MAE \leq RMSE \leq \sqrt{n} MAE$ for regression models: lower bound: each case contributes the same absolute amount of error $e$: $R
15,377
Cross validation and parameter optimization
Let us firstly distinguish between two sets of parameters: model parameters (e.g. weights for features in regression), and parameters to the learning algorithm (and hyperparameters). The purpose of cross-validation is to identify learning parameters that generalise well across the population samples we learn from in each fold. More specifically: We globally search over the space over learning parameters, but within each fold, we fix learning parameters and learn model parameters. The outcome should be learning parameters that produce on average the best performance in all folds. We can then use these to train a model on the entire dataset.
Cross validation and parameter optimization
Let us firstly distinguish between two sets of parameters: model parameters (e.g. weights for features in regression), and parameters to the learning algorithm (and hyperparameters). The purpose of cr
Cross validation and parameter optimization Let us firstly distinguish between two sets of parameters: model parameters (e.g. weights for features in regression), and parameters to the learning algorithm (and hyperparameters). The purpose of cross-validation is to identify learning parameters that generalise well across the population samples we learn from in each fold. More specifically: We globally search over the space over learning parameters, but within each fold, we fix learning parameters and learn model parameters. The outcome should be learning parameters that produce on average the best performance in all folds. We can then use these to train a model on the entire dataset.
Cross validation and parameter optimization Let us firstly distinguish between two sets of parameters: model parameters (e.g. weights for features in regression), and parameters to the learning algorithm (and hyperparameters). The purpose of cr
15,378
Cross validation and parameter optimization
I think the currently accepted answer is incomplete in an unfortunate way. I do not agree with the sentence The purpose of cross-validation is to identify learning parameters that generalise well across the population samples we learn from in each fold. This is indeed one very important application of cross validation, but not the only one. Usually, you want to do two things: Build the best model you can Get an accurate impression of how well it performs Now, to complete objective 1 depending on your algorithm you might need to tune some hyperparameters and this is indeed often done by cross validation. But this does not yet help you with objective 2. For this you need to basically nest the cross validation, like this: Seperate entire data into n folds For each, fold seperate the training data again into subfolds Use cross validation on the subfolds to learn good hyperparameters With these hyperparameter build a model on the training data of that fold Test the model on the test data Repeat on next fold To build a good model you just need the inner cross validation. You will still need to do so to get a good model. But to get a good estimate of your model performance you need to perform the entire process of model building inside a cross validation scheme. This also includes steps like imputation, etc.
Cross validation and parameter optimization
I think the currently accepted answer is incomplete in an unfortunate way. I do not agree with the sentence The purpose of cross-validation is to identify learning parameters that generalise well
Cross validation and parameter optimization I think the currently accepted answer is incomplete in an unfortunate way. I do not agree with the sentence The purpose of cross-validation is to identify learning parameters that generalise well across the population samples we learn from in each fold. This is indeed one very important application of cross validation, but not the only one. Usually, you want to do two things: Build the best model you can Get an accurate impression of how well it performs Now, to complete objective 1 depending on your algorithm you might need to tune some hyperparameters and this is indeed often done by cross validation. But this does not yet help you with objective 2. For this you need to basically nest the cross validation, like this: Seperate entire data into n folds For each, fold seperate the training data again into subfolds Use cross validation on the subfolds to learn good hyperparameters With these hyperparameter build a model on the training data of that fold Test the model on the test data Repeat on next fold To build a good model you just need the inner cross validation. You will still need to do so to get a good model. But to get a good estimate of your model performance you need to perform the entire process of model building inside a cross validation scheme. This also includes steps like imputation, etc.
Cross validation and parameter optimization I think the currently accepted answer is incomplete in an unfortunate way. I do not agree with the sentence The purpose of cross-validation is to identify learning parameters that generalise well
15,379
Estimating Markov transition probabilities from sequence data
Please, check the comments above. Here is a quick implementation in R. x <- c(1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3) p <- matrix(nrow = 4, ncol = 4, 0) for (t in 1:(length(x) - 1)) p[x[t], x[t + 1]] <- p[x[t], x[t + 1]] + 1 for (i in 1:4) p[i, ] <- p[i, ] / sum(p[i, ]) Results: > p [,1] [,2] [,3] [,4] [1,] 0.1666667 0.3333333 0.3333333 0.1666667 [2,] 0.2000000 0.2000000 0.4000000 0.2000000 [3,] 0.1428571 0.1428571 0.2857143 0.4285714 [4,] 0.2500000 0.1250000 0.2500000 0.3750000 A (probably dumb) implementation in MATLAB (which I have never used, so I don't know if this is going to work. I've just googled "declare vector matrix MATLAB" to get the syntax): x = [ 1, 2, 1, 1, 3, 4, 4, 1, 2, 4, 1, 4, 3, 4, 4, 4, 3, 1, 3, 2, 3, 3, 3, 4, 2, 2, 3 ] n = length(x) - 1 p = zeros(4,4) for t = 1:n p(x(t), x(t + 1)) = p(x(t), x(t + 1)) + 1 end for i = 1:4 p(i, :) = p(i, :) / sum(p(i, :)) end
Estimating Markov transition probabilities from sequence data
Please, check the comments above. Here is a quick implementation in R. x <- c(1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3) p <- matrix(nrow = 4, ncol = 4, 0) for (t in 1:(length(x) - 1)) p[x
Estimating Markov transition probabilities from sequence data Please, check the comments above. Here is a quick implementation in R. x <- c(1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3) p <- matrix(nrow = 4, ncol = 4, 0) for (t in 1:(length(x) - 1)) p[x[t], x[t + 1]] <- p[x[t], x[t + 1]] + 1 for (i in 1:4) p[i, ] <- p[i, ] / sum(p[i, ]) Results: > p [,1] [,2] [,3] [,4] [1,] 0.1666667 0.3333333 0.3333333 0.1666667 [2,] 0.2000000 0.2000000 0.4000000 0.2000000 [3,] 0.1428571 0.1428571 0.2857143 0.4285714 [4,] 0.2500000 0.1250000 0.2500000 0.3750000 A (probably dumb) implementation in MATLAB (which I have never used, so I don't know if this is going to work. I've just googled "declare vector matrix MATLAB" to get the syntax): x = [ 1, 2, 1, 1, 3, 4, 4, 1, 2, 4, 1, 4, 3, 4, 4, 4, 3, 1, 3, 2, 3, 3, 3, 4, 2, 2, 3 ] n = length(x) - 1 p = zeros(4,4) for t = 1:n p(x(t), x(t + 1)) = p(x(t), x(t + 1)) + 1 end for i = 1:4 p(i, :) = p(i, :) / sum(p(i, :)) end
Estimating Markov transition probabilities from sequence data Please, check the comments above. Here is a quick implementation in R. x <- c(1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3) p <- matrix(nrow = 4, ncol = 4, 0) for (t in 1:(length(x) - 1)) p[x
15,380
Estimating Markov transition probabilities from sequence data
Here is my implementation in R x <- c(1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3) xChar<-as.character(x) library(markovchain) mcX<-markovchainFit(xChar)$estimate mcX
Estimating Markov transition probabilities from sequence data
Here is my implementation in R x <- c(1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3) xChar<-as.character(x) library(markovchain) mcX<-markovchainFit(xChar)$estimate mcX
Estimating Markov transition probabilities from sequence data Here is my implementation in R x <- c(1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3) xChar<-as.character(x) library(markovchain) mcX<-markovchainFit(xChar)$estimate mcX
Estimating Markov transition probabilities from sequence data Here is my implementation in R x <- c(1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3) xChar<-as.character(x) library(markovchain) mcX<-markovchainFit(xChar)$estimate mcX
15,381
Estimating Markov transition probabilities from sequence data
Here is a way to do it in Matlab: x = [1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3]; counts_mat = full(sparse(x(1:end-1),x(2:end),1)); trans_mat = bsxfun(@rdivide,counts_mat,sum(counts_mat,2)) Acknowledgement owed to SomptingGuy: http://www.eng-tips.com/viewthread.cfm?qid=236532
Estimating Markov transition probabilities from sequence data
Here is a way to do it in Matlab: x = [1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3]; counts_mat = full(sparse(x(1:end-1),x(2:end),1)); trans_mat = bsxfun(@rdivide,counts_mat,sum(counts_mat,2
Estimating Markov transition probabilities from sequence data Here is a way to do it in Matlab: x = [1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3]; counts_mat = full(sparse(x(1:end-1),x(2:end),1)); trans_mat = bsxfun(@rdivide,counts_mat,sum(counts_mat,2)) Acknowledgement owed to SomptingGuy: http://www.eng-tips.com/viewthread.cfm?qid=236532
Estimating Markov transition probabilities from sequence data Here is a way to do it in Matlab: x = [1,2,1,1,3,4,4,1,2,4,1,4,3,4,4,4,3,1,3,2,3,3,3,4,2,2,3]; counts_mat = full(sparse(x(1:end-1),x(2:end),1)); trans_mat = bsxfun(@rdivide,counts_mat,sum(counts_mat,2
15,382
Calculating the 95th percentile: Comparing normal distribution, R Quantile, and Excel approaches
The first approach is completely wrong and has nothing to do with the 95th percentile, in my opinion. The second approach seems to be based on an assumption that the data is normally distributed, but it should be about 1.645 standard deviations above the mean, not 2 standard deviations, and it looks like you realised this. This is a poor method if the data is not normally distributed. If you want to work out the 95th percentile yourself, order the numbers from smallest to largest and find a value such that 95% of the data is below that value. R probably uses some sort of interpolation between data points. A simple approximation might be sort(data$V1)[0.95*length(data$V1)]. Edited after comment from @Macro.
Calculating the 95th percentile: Comparing normal distribution, R Quantile, and Excel approaches
The first approach is completely wrong and has nothing to do with the 95th percentile, in my opinion. The second approach seems to be based on an assumption that the data is normally distributed, but
Calculating the 95th percentile: Comparing normal distribution, R Quantile, and Excel approaches The first approach is completely wrong and has nothing to do with the 95th percentile, in my opinion. The second approach seems to be based on an assumption that the data is normally distributed, but it should be about 1.645 standard deviations above the mean, not 2 standard deviations, and it looks like you realised this. This is a poor method if the data is not normally distributed. If you want to work out the 95th percentile yourself, order the numbers from smallest to largest and find a value such that 95% of the data is below that value. R probably uses some sort of interpolation between data points. A simple approximation might be sort(data$V1)[0.95*length(data$V1)]. Edited after comment from @Macro.
Calculating the 95th percentile: Comparing normal distribution, R Quantile, and Excel approaches The first approach is completely wrong and has nothing to do with the 95th percentile, in my opinion. The second approach seems to be based on an assumption that the data is normally distributed, but
15,383
Calculating the 95th percentile: Comparing normal distribution, R Quantile, and Excel approaches
Here are a few points to supplement @mark999's answer. Wikipedia has an article on percentiles where it is noted that no standard definition of a percentile exists. However, several formulas are discussed. Crawford, J.; Garthwaite, P. & Slick, D. On percentile norms in neuropsychology: Proposed reporting standards and methods for quantifying the uncertainty over the percentile ranks of test scores The Clinical Neuropsychologist, Psychology Press, 2009, 23, 1173-1195 (FREE PDF) discusses calculation of percentiles within a psychology norming context. The following explores a few things in R: Get data and examine R quantile function > x <- c(93150, 93116, 93096, etc... [ABBREVIATED INPUT] > help(quantile) # Note the 9 quantile algorithms > rquantileest <- sapply(1:9, function(TYPE) quantile(x, .95, type=TYPE)) > rquantileest 95% 95% 95% 95% 95% 95% 79535.00 79535.00 79535.00 79524.00 79547.75 79570.70 95% 95% 95% 79526.20 79555.40 79553.49 > sapply(rquantileest, function(X) mean(x <= X)) 95% 95% 95% 95% 95% 0.9501859 0.9501859 0.9501859 0.9494424 0.9501859 95% 95% 95% 95% 0.9501859 0.9494424 0.9501859 0.9501859 help(quantile) shows that R has nine different quantile estimation algorithms. The other output shows the estimated value for the 9 algorithms and the proportion of the data that is less than or equal to the estimated value (i.e., all values are close to 95%). Compare with assuming normal distribution > # Estimate of the 95th percentile if the data was normally distributed > qnormest <- qnorm(.95, mean(x), sd(x)) > qnormest [1] 67076.4 > mean(x <= qnormest) [1] 0.8401487 A very different value is estimated for the 95th percentile of a normal distribution based on the sample mean and standard deviation. The value estimated is around the 84th percentile of the sample data. The plot below shows that the data is clearly not normally distributed, and thus estimates based on assuming normality are going to be a long way off. plot(density(x))
Calculating the 95th percentile: Comparing normal distribution, R Quantile, and Excel approaches
Here are a few points to supplement @mark999's answer. Wikipedia has an article on percentiles where it is noted that no standard definition of a percentile exists. However, several formulas are disc
Calculating the 95th percentile: Comparing normal distribution, R Quantile, and Excel approaches Here are a few points to supplement @mark999's answer. Wikipedia has an article on percentiles where it is noted that no standard definition of a percentile exists. However, several formulas are discussed. Crawford, J.; Garthwaite, P. & Slick, D. On percentile norms in neuropsychology: Proposed reporting standards and methods for quantifying the uncertainty over the percentile ranks of test scores The Clinical Neuropsychologist, Psychology Press, 2009, 23, 1173-1195 (FREE PDF) discusses calculation of percentiles within a psychology norming context. The following explores a few things in R: Get data and examine R quantile function > x <- c(93150, 93116, 93096, etc... [ABBREVIATED INPUT] > help(quantile) # Note the 9 quantile algorithms > rquantileest <- sapply(1:9, function(TYPE) quantile(x, .95, type=TYPE)) > rquantileest 95% 95% 95% 95% 95% 95% 79535.00 79535.00 79535.00 79524.00 79547.75 79570.70 95% 95% 95% 79526.20 79555.40 79553.49 > sapply(rquantileest, function(X) mean(x <= X)) 95% 95% 95% 95% 95% 0.9501859 0.9501859 0.9501859 0.9494424 0.9501859 95% 95% 95% 95% 0.9501859 0.9494424 0.9501859 0.9501859 help(quantile) shows that R has nine different quantile estimation algorithms. The other output shows the estimated value for the 9 algorithms and the proportion of the data that is less than or equal to the estimated value (i.e., all values are close to 95%). Compare with assuming normal distribution > # Estimate of the 95th percentile if the data was normally distributed > qnormest <- qnorm(.95, mean(x), sd(x)) > qnormest [1] 67076.4 > mean(x <= qnormest) [1] 0.8401487 A very different value is estimated for the 95th percentile of a normal distribution based on the sample mean and standard deviation. The value estimated is around the 84th percentile of the sample data. The plot below shows that the data is clearly not normally distributed, and thus estimates based on assuming normality are going to be a long way off. plot(density(x))
Calculating the 95th percentile: Comparing normal distribution, R Quantile, and Excel approaches Here are a few points to supplement @mark999's answer. Wikipedia has an article on percentiles where it is noted that no standard definition of a percentile exists. However, several formulas are disc
15,384
What is the difference between the "coef" and "(exp)coef" output of coxph in R?
If you have a single explanatory variable, say treatment group, a Cox's regression model is fitted with coxph(); the coefficient (coef) reads as a regression coefficient (in the context of the Cox model, described hereafter) and its exponential gives you the hazard in the treatment group (compared to the control or placebo group). For example, if $\hat\beta=-1.80$, then the hazard is $\exp(-1.80)=0.165$, that is 16.5%. As you may know, the hazard function is modeled as $$ h(t)=h_0(t)\exp(\beta'x) $$ where $h_0(t)$ is the baseline hazard. The hazards depend multiplicatively on the covariates, and $\exp(\beta_1)$ is the ratio of the hazards between two individuals whose values of $x_1$ differ by one unit when all other covariates are held constant. The ratio of the hazards of any two individuals $i$ and $j$ is $\exp\big(\beta'(x_i-x_j)\big)$, and is called the hazard ratio (or incidence rate ratio). This ratio is assumed to be constant over time, hence the name of proportional hazard. To echo your preceding question about survreg, here the form of $h_0(t)$ is left unspecified; more precisely, this is a semi-parametric model in that only the effects of covariates are parametrized, and not the hazard function. In other words, we don't make any distribution assumption about survival times. The regression parameters are estimated by maximizing the partial log-likelihood defined by $$ \ell=\sum_f\log\left(\frac{\exp(\beta'x_f)}{\sum_{r(f)}\exp(\beta'x_r)}\right) $$ where the first summation is over all deaths or failures $f$, and the second summation is over all subjects $r(f)$ still alive (but at risk) at the time of failure -- this is known as the risk set. In other words, $\ell$ can be interpreted as the log profile likelihood for $\beta$ after eliminating $h_0(t)$ (or in other words, the LL where the $h_0(t)$ have been replaced by functions of $\beta$ that maximize the likelihood with respect to $h_0(t)$ for a fixed vector $\beta$). About censoring, it is not clear whether you refer to left censoring (as might be the case if we consider an origin for the time scale that is earlier than the time when observation began, also called delayed entry), or right-censoring. In any case, more details about the computation of the regression coefficients and how the survival package handles censoring can be found in Therneau and Grambsch, Modeling Survival Data (Springer, 2000). Terry Therneau is the author of the former S package. An online tutorial is available. Survival Analysis in R, by David Diez, provides a good introduction to Survival Analysis in R. A brief overview of $\chi^2$ tests for regression parameters is given p. 10. Hopefully, this should help clarifying the on-line help quoted by @onestop, "coefficients the coefficients of the linear predictor, which multiply the columns of the model matrix." For an applied textbook, I recommend Analyzing Medical Data Using S-PLUS, by Everitt and Rabe-Hesketh (Springer, 2001, chap. 16 and 17), from which most of the above comes from. Another useful reference is John Fox's appendix on Cox Proportional-Hazards Regression for Survival Data.
What is the difference between the "coef" and "(exp)coef" output of coxph in R?
If you have a single explanatory variable, say treatment group, a Cox's regression model is fitted with coxph(); the coefficient (coef) reads as a regression coefficient (in the context of the Cox mod
What is the difference between the "coef" and "(exp)coef" output of coxph in R? If you have a single explanatory variable, say treatment group, a Cox's regression model is fitted with coxph(); the coefficient (coef) reads as a regression coefficient (in the context of the Cox model, described hereafter) and its exponential gives you the hazard in the treatment group (compared to the control or placebo group). For example, if $\hat\beta=-1.80$, then the hazard is $\exp(-1.80)=0.165$, that is 16.5%. As you may know, the hazard function is modeled as $$ h(t)=h_0(t)\exp(\beta'x) $$ where $h_0(t)$ is the baseline hazard. The hazards depend multiplicatively on the covariates, and $\exp(\beta_1)$ is the ratio of the hazards between two individuals whose values of $x_1$ differ by one unit when all other covariates are held constant. The ratio of the hazards of any two individuals $i$ and $j$ is $\exp\big(\beta'(x_i-x_j)\big)$, and is called the hazard ratio (or incidence rate ratio). This ratio is assumed to be constant over time, hence the name of proportional hazard. To echo your preceding question about survreg, here the form of $h_0(t)$ is left unspecified; more precisely, this is a semi-parametric model in that only the effects of covariates are parametrized, and not the hazard function. In other words, we don't make any distribution assumption about survival times. The regression parameters are estimated by maximizing the partial log-likelihood defined by $$ \ell=\sum_f\log\left(\frac{\exp(\beta'x_f)}{\sum_{r(f)}\exp(\beta'x_r)}\right) $$ where the first summation is over all deaths or failures $f$, and the second summation is over all subjects $r(f)$ still alive (but at risk) at the time of failure -- this is known as the risk set. In other words, $\ell$ can be interpreted as the log profile likelihood for $\beta$ after eliminating $h_0(t)$ (or in other words, the LL where the $h_0(t)$ have been replaced by functions of $\beta$ that maximize the likelihood with respect to $h_0(t)$ for a fixed vector $\beta$). About censoring, it is not clear whether you refer to left censoring (as might be the case if we consider an origin for the time scale that is earlier than the time when observation began, also called delayed entry), or right-censoring. In any case, more details about the computation of the regression coefficients and how the survival package handles censoring can be found in Therneau and Grambsch, Modeling Survival Data (Springer, 2000). Terry Therneau is the author of the former S package. An online tutorial is available. Survival Analysis in R, by David Diez, provides a good introduction to Survival Analysis in R. A brief overview of $\chi^2$ tests for regression parameters is given p. 10. Hopefully, this should help clarifying the on-line help quoted by @onestop, "coefficients the coefficients of the linear predictor, which multiply the columns of the model matrix." For an applied textbook, I recommend Analyzing Medical Data Using S-PLUS, by Everitt and Rabe-Hesketh (Springer, 2001, chap. 16 and 17), from which most of the above comes from. Another useful reference is John Fox's appendix on Cox Proportional-Hazards Regression for Survival Data.
What is the difference between the "coef" and "(exp)coef" output of coxph in R? If you have a single explanatory variable, say treatment group, a Cox's regression model is fitted with coxph(); the coefficient (coef) reads as a regression coefficient (in the context of the Cox mod
15,385
What is the difference between the "coef" and "(exp)coef" output of coxph in R?
To quote the documentation for the print method for a coxph object, obtained in R by typing ?survival::print.coxph: coefficients the coefficients of the linear predictor, which multiply the columns of the model matrix. That's all the documentation the author of the package provides. The package contains no user guide or package vignette. R is not designed to be user-friendly, and the documentation assumes you already have understand the statistical methods involved. I'd assume that the the coef column gives the above coefficients, and the exp(coef) column is the exponential of these. As Cox regression involves a log link function, the coefficients are the log hazard ratios. Exponentiating them therefore gives you back hazard ratios.
What is the difference between the "coef" and "(exp)coef" output of coxph in R?
To quote the documentation for the print method for a coxph object, obtained in R by typing ?survival::print.coxph: coefficients the coefficients of the linear predictor, which multiply the column
What is the difference between the "coef" and "(exp)coef" output of coxph in R? To quote the documentation for the print method for a coxph object, obtained in R by typing ?survival::print.coxph: coefficients the coefficients of the linear predictor, which multiply the columns of the model matrix. That's all the documentation the author of the package provides. The package contains no user guide or package vignette. R is not designed to be user-friendly, and the documentation assumes you already have understand the statistical methods involved. I'd assume that the the coef column gives the above coefficients, and the exp(coef) column is the exponential of these. As Cox regression involves a log link function, the coefficients are the log hazard ratios. Exponentiating them therefore gives you back hazard ratios.
What is the difference between the "coef" and "(exp)coef" output of coxph in R? To quote the documentation for the print method for a coxph object, obtained in R by typing ?survival::print.coxph: coefficients the coefficients of the linear predictor, which multiply the column
15,386
Poisson regression with large data: is it wrong to change the unit of measurement?
When you're dealing with a Poisson distribution with large values of \lambda (its parameter), it is common to use a normal approximation to the Poisson distribution. As this site mentions, it's all right to use the normal approximation when \lambda gets over 20, and the approximation improves as \lambda gets even higher. The Poisson distribution is defined only over the state space consisting of the non-negative integers, so rescaling and rounding is going to introduce odd things into your data. Using the normal approx. for large Poisson statistics is VERY common.
Poisson regression with large data: is it wrong to change the unit of measurement?
When you're dealing with a Poisson distribution with large values of \lambda (its parameter), it is common to use a normal approximation to the Poisson distribution. As this site mentions, it's all r
Poisson regression with large data: is it wrong to change the unit of measurement? When you're dealing with a Poisson distribution with large values of \lambda (its parameter), it is common to use a normal approximation to the Poisson distribution. As this site mentions, it's all right to use the normal approximation when \lambda gets over 20, and the approximation improves as \lambda gets even higher. The Poisson distribution is defined only over the state space consisting of the non-negative integers, so rescaling and rounding is going to introduce odd things into your data. Using the normal approx. for large Poisson statistics is VERY common.
Poisson regression with large data: is it wrong to change the unit of measurement? When you're dealing with a Poisson distribution with large values of \lambda (its parameter), it is common to use a normal approximation to the Poisson distribution. As this site mentions, it's all r
15,387
Poisson regression with large data: is it wrong to change the unit of measurement?
In case of Poisson it is bad, since counts are counts -- their unit is an unity. On the other hand, if you'd use some advanced software like R, its Poisson handling functions will be aware of such large numbers and would use some numerical tricks to handle them. Obviously I agree that normal approximation is another good approach.
Poisson regression with large data: is it wrong to change the unit of measurement?
In case of Poisson it is bad, since counts are counts -- their unit is an unity. On the other hand, if you'd use some advanced software like R, its Poisson handling functions will be aware of such lar
Poisson regression with large data: is it wrong to change the unit of measurement? In case of Poisson it is bad, since counts are counts -- their unit is an unity. On the other hand, if you'd use some advanced software like R, its Poisson handling functions will be aware of such large numbers and would use some numerical tricks to handle them. Obviously I agree that normal approximation is another good approach.
Poisson regression with large data: is it wrong to change the unit of measurement? In case of Poisson it is bad, since counts are counts -- their unit is an unity. On the other hand, if you'd use some advanced software like R, its Poisson handling functions will be aware of such lar
15,388
Poisson regression with large data: is it wrong to change the unit of measurement?
Most statistical packages have a function to calculate the natural logarithm of the factorial directly (e.g. the lfactorial() function in R, the lnfactorial() function in Stata). This allows you to include the constant term in the log-likelihood if you want.
Poisson regression with large data: is it wrong to change the unit of measurement?
Most statistical packages have a function to calculate the natural logarithm of the factorial directly (e.g. the lfactorial() function in R, the lnfactorial() function in Stata). This allows you to in
Poisson regression with large data: is it wrong to change the unit of measurement? Most statistical packages have a function to calculate the natural logarithm of the factorial directly (e.g. the lfactorial() function in R, the lnfactorial() function in Stata). This allows you to include the constant term in the log-likelihood if you want.
Poisson regression with large data: is it wrong to change the unit of measurement? Most statistical packages have a function to calculate the natural logarithm of the factorial directly (e.g. the lfactorial() function in R, the lnfactorial() function in Stata). This allows you to in
15,389
Poisson regression with large data: is it wrong to change the unit of measurement?
I'm afraid you can't do that. As @Baltimark states, with big lambda the distribution will be of more normal shape (symmetric), and with scaling it down it will no longer be poisson distrubution. Try the following code in R: poi1 = rpois(100000, lambda = 5) # poisson poi2 = rpois(100000, lambda = 100)/20 # scaled-down poisson poi2_dens = density(poi2) hist(poi1, breaks = 0:30, freq = F, ylim = range(poi2_dens$y)) lines(poi2_dens, col = "red") The result is below: You can see that the downscaled poisson (red line) is completely different from the poisson distribution.
Poisson regression with large data: is it wrong to change the unit of measurement?
I'm afraid you can't do that. As @Baltimark states, with big lambda the distribution will be of more normal shape (symmetric), and with scaling it down it will no longer be poisson distrubution. Try t
Poisson regression with large data: is it wrong to change the unit of measurement? I'm afraid you can't do that. As @Baltimark states, with big lambda the distribution will be of more normal shape (symmetric), and with scaling it down it will no longer be poisson distrubution. Try the following code in R: poi1 = rpois(100000, lambda = 5) # poisson poi2 = rpois(100000, lambda = 100)/20 # scaled-down poisson poi2_dens = density(poi2) hist(poi1, breaks = 0:30, freq = F, ylim = range(poi2_dens$y)) lines(poi2_dens, col = "red") The result is below: You can see that the downscaled poisson (red line) is completely different from the poisson distribution.
Poisson regression with large data: is it wrong to change the unit of measurement? I'm afraid you can't do that. As @Baltimark states, with big lambda the distribution will be of more normal shape (symmetric), and with scaling it down it will no longer be poisson distrubution. Try t
15,390
Poisson regression with large data: is it wrong to change the unit of measurement?
You can simply ignore the 'factorial' when using maximum likelihood. Here is the reasoning for your suicides example. Let: λ : Be the expected number of suicides per year ki: Be the number of suicides in year i. Then you would maximize the log-likelihood as: LL = ∑ ( ki log(λ) - λ - ki! ) Maximizing the above is equivalent to maximizing the following as ki! is a constant : LL' = ∑ ( ki log(λ) - λ ) Could explain why the factorial is an issue? Am I missing something?
Poisson regression with large data: is it wrong to change the unit of measurement?
You can simply ignore the 'factorial' when using maximum likelihood. Here is the reasoning for your suicides example. Let: λ : Be the expected number of suicides per year ki: Be the number of suicides
Poisson regression with large data: is it wrong to change the unit of measurement? You can simply ignore the 'factorial' when using maximum likelihood. Here is the reasoning for your suicides example. Let: λ : Be the expected number of suicides per year ki: Be the number of suicides in year i. Then you would maximize the log-likelihood as: LL = ∑ ( ki log(λ) - λ - ki! ) Maximizing the above is equivalent to maximizing the following as ki! is a constant : LL' = ∑ ( ki log(λ) - λ ) Could explain why the factorial is an issue? Am I missing something?
Poisson regression with large data: is it wrong to change the unit of measurement? You can simply ignore the 'factorial' when using maximum likelihood. Here is the reasoning for your suicides example. Let: λ : Be the expected number of suicides per year ki: Be the number of suicides
15,391
Why pure exponent is not used as activation function for neural networks?
I think the most prominent reason is stability. Think about having consequent layers with exponential activation, and what happens to the output when you input a small number to the NN (e.g. $x=1$), the forward calculation will look like: $$o=\exp(\exp(\exp(\exp(1))))\approx e^{3814279}$$ It can go crazy very quickly and I don't think you can train deep networks with this activation function unless you add other mechanisms like clipping.
Why pure exponent is not used as activation function for neural networks?
I think the most prominent reason is stability. Think about having consequent layers with exponential activation, and what happens to the output when you input a small number to the NN (e.g. $x=1$), t
Why pure exponent is not used as activation function for neural networks? I think the most prominent reason is stability. Think about having consequent layers with exponential activation, and what happens to the output when you input a small number to the NN (e.g. $x=1$), the forward calculation will look like: $$o=\exp(\exp(\exp(\exp(1))))\approx e^{3814279}$$ It can go crazy very quickly and I don't think you can train deep networks with this activation function unless you add other mechanisms like clipping.
Why pure exponent is not used as activation function for neural networks? I think the most prominent reason is stability. Think about having consequent layers with exponential activation, and what happens to the output when you input a small number to the NN (e.g. $x=1$), t
15,392
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate
This is an extremely interesting problem. I reviewed your code and can find no immediately obvious typo. I would like to see you redo this simulation but use the maximum likelihood test to make inference about the heterogeneity between groups. This would involve refitting a null model so that you can get estimates of the $\theta$s under the null hypothesis of homogeneity in rates between groups. I think this is necessary because the negative binomial model is not a linear model (the rate is parameterized linearly, but the $\theta$s are not). Therefore I am not convinced drop1 argument provides correct inference. Most tests for linear models do not require you to recompute the model under the null hypothesis. This is because you can calculate the geometric slope (score test) and approximate the width (Wald test) using parameter estimates and estimated covariance under the alternative hypothesis alone. Since negative binomial is not linear, I think you will need to fit a null model. EDIT: I edited the code and got the following: Edited code here: https://github.com/aomidpanah/simulations/blob/master/negativeBinomialML.r
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate
This is an extremely interesting problem. I reviewed your code and can find no immediately obvious typo. I would like to see you redo this simulation but use the maximum likelihood test to make infere
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate This is an extremely interesting problem. I reviewed your code and can find no immediately obvious typo. I would like to see you redo this simulation but use the maximum likelihood test to make inference about the heterogeneity between groups. This would involve refitting a null model so that you can get estimates of the $\theta$s under the null hypothesis of homogeneity in rates between groups. I think this is necessary because the negative binomial model is not a linear model (the rate is parameterized linearly, but the $\theta$s are not). Therefore I am not convinced drop1 argument provides correct inference. Most tests for linear models do not require you to recompute the model under the null hypothesis. This is because you can calculate the geometric slope (score test) and approximate the width (Wald test) using parameter estimates and estimated covariance under the alternative hypothesis alone. Since negative binomial is not linear, I think you will need to fit a null model. EDIT: I edited the code and got the following: Edited code here: https://github.com/aomidpanah/simulations/blob/master/negativeBinomialML.r
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate This is an extremely interesting problem. I reviewed your code and can find no immediately obvious typo. I would like to see you redo this simulation but use the maximum likelihood test to make infere
15,393
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate
The O'Hara and Kotze paper (Methods in Ecology and Evolution 1:118–122) is not a good starting point for discussion. My most serious concern is the claim in point 4 of the summary: We found that the transformations performed poorly, except . . .. The quasi-Poisson and negative binomial models ... [showed] little bias. The mean $\lambda$ for a Poisson or negative binomial distribution is for a distribution that, for values of $\theta$ <= 2 and for the range of values of the mean $\lambda$ that was investigated, is highly positively skew. The means of the fitted normal distributions are on a scale of log(y+c) (c is the offset), and estimate E(log(y+c)]. This distribution is much closer to symmetric than is the distribution of y. O'Hara and Kotze's simulations compare E(log(y+c)], as estimated by mean(log(y+c)), with log(E[y+c]). They can be, and in the cases noted are, very different. Their graphs do not compare a negative binomial with a log(y+c) fit, but rather compare mean(log(y+c)] with log(E[y+c]). On the log($\lambda$) scale shown in their graphs, it is actually the negative binomial fits that are more biased! The following R code illustrates the point: x <- rnbinom(10000, 0.5, mu=2) ## NB: Above, this 'mu' was our lambda. Confusing, is'nt it? log(mean(x+1)) [1] 1.09631 log(2+1) ## Check that this is about right [1] 1.098612 mean(log(x+1)) [1] 0.7317908 Or try log(mean(x+.5)) [1] 0.9135269 mean(log(x+.5)) [1] 0.3270837 The scale on which the parameters are estimated matters a great deal! If one samples from a Poisson, of course one expects the Poisson to do better, if judged by the criteria used to fit the Poisson. Ditto for a negative binomial. The difference may not be all that great, if the comparison is fair. Real data (e.g., maybe, in some genetic contexts) may sometimes be very close to Poisson. When they depart from Poisson, the negative binomial may or may not work well. Likewise, especially if $\lambda$ is of the order of maybe 10 or more, for modeling log(y+1) using standard normal theory. Note that standard diagnostics work better on a scale of log(x+c). The choice of c may not matter too much; often 0.5 or 1.0 make sense. Also it is a better starting point for investigating Box-Cox transformations, or the Yeo-Johnson variant of Box-Cox. [Yeo, I. and Johnson, R. (2000)]. See further the help page for powerTransform() in R’s car package. R's gamlss package makes it possible to fit negative binomial types I (the common variety) or II, or other distributions that model the dispersion as well as the mean, with power transform links of 0 (=log, i.e., log link) or more. Fits may not always converge. Example: Deaths vs Base Damage Data are for named Atlantic hurricanes that reached the US mainland. Data are available (name hurricNamed) from a recent release of the DAAG package for R. The help page for the data has details. The graph compares a fitted line obtained using a robust linear model fit, with the curve obtained by transforming a negative binomial fit with log link onto the log(count+1) scale used for the y-axis on the graph. (Note that one has to use something akin to a log(count+c) scale, with positive c, to show the points and the fitted "line" from the negative binomial fit on the same graph.) Note the large bias that is evident for the negative binomial fit on the log scale. The robust linear model fit is much less biased on this scale, if one assumes a negative binomial distribution for the counts. A linear model fit would be unbiased under the classical normal theory assumptions. I found the bias astonishing when I first created what was essentially the above graph! A curve would fit the data better, but the difference is within the bounds of the usual standards of statistical variability. The robust linear model fit does a poor job for counts at the low end of the scale. Note --- Studies with RNA-Seq Data: Comparison of the two styles of model has been of interest for analysis of count data from gene expression experiments. The following paper compares the use of a robust linear model, working with log(count+1), with the use of negative binomial fits (as in the Bioconductor package edgeR). Most counts, in the RNA-Seq application that is primarily in mind, are large enough that suitably weighed log-linear model fits work extremely well. Law, CW, Chen, Y, Shi, W, Smyth, GK (2014). Voom: precision weights unlock linear model analysis tools for RNA-seq read counts. Genome Biology 15, R29. http://genomebiology.com/2014/15/2/R29 NB also the recent paper: Schurch NJ, Schofield P, Gierliński M, Cole C, Sherstnev A, Singh V, Wrobel N, Gharbi K, Simpson GG, Owen-Hughes T, Blaxter M, Barton GJ (2016). How many biological replicates are needed in an RNA-seq experiment and which differential expression tool should you use? RNA http://www.rnajournal.org/cgi/doi/10.1261/rna.053959.115 It is interesting that the linear model fits using the limma package (like edgeR, from the WEHI group) stand up extremely well (in the sense of showing little evidence of bias), relative to results with many replicates, as the number of replicates is reduced. R code for the graph above: library(latticeExtra, quietly=TRUE) hurricNamed <- DAAG::hurricNamed ytxt <- c(0, 1, 3, 10, 30, 100, 300, 1000) xtxt <- c(1,10, 100, 1000, 10000, 100000, 1000000 ) funy <- function(y)log(y+1) gph <- xyplot(funy(deaths) ~ log(BaseDam2014), groups= mf, data=hurricNamed, scales=list(y=list(at=funy(ytxt), labels=paste(ytxt)), x=list(at=log(xtxt), labels=paste(xtxt))), xlab = "Base Damage (millions of 2014 US$); log transformed scale", ylab="Deaths; log transformed; offset=1", auto.key=list(columns=2), par.settings=simpleTheme(col=c("red","blue"), pch=16)) gph2 <- gph + layer(panel.text(x[c(13,84)], y[c(13,84)], labels=hurricNamed[c(13,84), "Name"], pos=3, col="gray30", cex=0.8), panel.text(x[c(13,84)], y[c(13,84)], labels=hurricNamed[c(13,84), "Year"], pos=1, col="gray30", cex=0.8)) ab <- coef(MASS::rlm(funy(deaths) ~ log(BaseDam2014), data=hurricNamed)) gph3 <- gph2+layer(panel.abline(ab[1], b=ab[2], col="gray30", alpha=0.4)) ## 100 points that are evenly spread on a log(BaseDam2014) scale x <- with(hurricNamed, pretty(log(BaseDam2014),100)) df <- data.frame(BaseDam2014=exp(x[x>0])) hurr.nb <- MASS::glm.nb(deaths~log(BaseDam2014), data=hurricNamed[-c(13,84),]) df[,'hatnb'] <- funy(predict(hurr.nb, newdata=df, type='response')) gph3 + latticeExtra::layer(data=df, panel.lines(log(BaseDam2014), hatnb, lwd=2, lty=2, alpha=0.5, col="gray30"))
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate
The O'Hara and Kotze paper (Methods in Ecology and Evolution 1:118–122) is not a good starting point for discussion. My most serious concern is the claim in point 4 of the summary: We found that the
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate The O'Hara and Kotze paper (Methods in Ecology and Evolution 1:118–122) is not a good starting point for discussion. My most serious concern is the claim in point 4 of the summary: We found that the transformations performed poorly, except . . .. The quasi-Poisson and negative binomial models ... [showed] little bias. The mean $\lambda$ for a Poisson or negative binomial distribution is for a distribution that, for values of $\theta$ <= 2 and for the range of values of the mean $\lambda$ that was investigated, is highly positively skew. The means of the fitted normal distributions are on a scale of log(y+c) (c is the offset), and estimate E(log(y+c)]. This distribution is much closer to symmetric than is the distribution of y. O'Hara and Kotze's simulations compare E(log(y+c)], as estimated by mean(log(y+c)), with log(E[y+c]). They can be, and in the cases noted are, very different. Their graphs do not compare a negative binomial with a log(y+c) fit, but rather compare mean(log(y+c)] with log(E[y+c]). On the log($\lambda$) scale shown in their graphs, it is actually the negative binomial fits that are more biased! The following R code illustrates the point: x <- rnbinom(10000, 0.5, mu=2) ## NB: Above, this 'mu' was our lambda. Confusing, is'nt it? log(mean(x+1)) [1] 1.09631 log(2+1) ## Check that this is about right [1] 1.098612 mean(log(x+1)) [1] 0.7317908 Or try log(mean(x+.5)) [1] 0.9135269 mean(log(x+.5)) [1] 0.3270837 The scale on which the parameters are estimated matters a great deal! If one samples from a Poisson, of course one expects the Poisson to do better, if judged by the criteria used to fit the Poisson. Ditto for a negative binomial. The difference may not be all that great, if the comparison is fair. Real data (e.g., maybe, in some genetic contexts) may sometimes be very close to Poisson. When they depart from Poisson, the negative binomial may or may not work well. Likewise, especially if $\lambda$ is of the order of maybe 10 or more, for modeling log(y+1) using standard normal theory. Note that standard diagnostics work better on a scale of log(x+c). The choice of c may not matter too much; often 0.5 or 1.0 make sense. Also it is a better starting point for investigating Box-Cox transformations, or the Yeo-Johnson variant of Box-Cox. [Yeo, I. and Johnson, R. (2000)]. See further the help page for powerTransform() in R’s car package. R's gamlss package makes it possible to fit negative binomial types I (the common variety) or II, or other distributions that model the dispersion as well as the mean, with power transform links of 0 (=log, i.e., log link) or more. Fits may not always converge. Example: Deaths vs Base Damage Data are for named Atlantic hurricanes that reached the US mainland. Data are available (name hurricNamed) from a recent release of the DAAG package for R. The help page for the data has details. The graph compares a fitted line obtained using a robust linear model fit, with the curve obtained by transforming a negative binomial fit with log link onto the log(count+1) scale used for the y-axis on the graph. (Note that one has to use something akin to a log(count+c) scale, with positive c, to show the points and the fitted "line" from the negative binomial fit on the same graph.) Note the large bias that is evident for the negative binomial fit on the log scale. The robust linear model fit is much less biased on this scale, if one assumes a negative binomial distribution for the counts. A linear model fit would be unbiased under the classical normal theory assumptions. I found the bias astonishing when I first created what was essentially the above graph! A curve would fit the data better, but the difference is within the bounds of the usual standards of statistical variability. The robust linear model fit does a poor job for counts at the low end of the scale. Note --- Studies with RNA-Seq Data: Comparison of the two styles of model has been of interest for analysis of count data from gene expression experiments. The following paper compares the use of a robust linear model, working with log(count+1), with the use of negative binomial fits (as in the Bioconductor package edgeR). Most counts, in the RNA-Seq application that is primarily in mind, are large enough that suitably weighed log-linear model fits work extremely well. Law, CW, Chen, Y, Shi, W, Smyth, GK (2014). Voom: precision weights unlock linear model analysis tools for RNA-seq read counts. Genome Biology 15, R29. http://genomebiology.com/2014/15/2/R29 NB also the recent paper: Schurch NJ, Schofield P, Gierliński M, Cole C, Sherstnev A, Singh V, Wrobel N, Gharbi K, Simpson GG, Owen-Hughes T, Blaxter M, Barton GJ (2016). How many biological replicates are needed in an RNA-seq experiment and which differential expression tool should you use? RNA http://www.rnajournal.org/cgi/doi/10.1261/rna.053959.115 It is interesting that the linear model fits using the limma package (like edgeR, from the WEHI group) stand up extremely well (in the sense of showing little evidence of bias), relative to results with many replicates, as the number of replicates is reduced. R code for the graph above: library(latticeExtra, quietly=TRUE) hurricNamed <- DAAG::hurricNamed ytxt <- c(0, 1, 3, 10, 30, 100, 300, 1000) xtxt <- c(1,10, 100, 1000, 10000, 100000, 1000000 ) funy <- function(y)log(y+1) gph <- xyplot(funy(deaths) ~ log(BaseDam2014), groups= mf, data=hurricNamed, scales=list(y=list(at=funy(ytxt), labels=paste(ytxt)), x=list(at=log(xtxt), labels=paste(xtxt))), xlab = "Base Damage (millions of 2014 US$); log transformed scale", ylab="Deaths; log transformed; offset=1", auto.key=list(columns=2), par.settings=simpleTheme(col=c("red","blue"), pch=16)) gph2 <- gph + layer(panel.text(x[c(13,84)], y[c(13,84)], labels=hurricNamed[c(13,84), "Name"], pos=3, col="gray30", cex=0.8), panel.text(x[c(13,84)], y[c(13,84)], labels=hurricNamed[c(13,84), "Year"], pos=1, col="gray30", cex=0.8)) ab <- coef(MASS::rlm(funy(deaths) ~ log(BaseDam2014), data=hurricNamed)) gph3 <- gph2+layer(panel.abline(ab[1], b=ab[2], col="gray30", alpha=0.4)) ## 100 points that are evenly spread on a log(BaseDam2014) scale x <- with(hurricNamed, pretty(log(BaseDam2014),100)) df <- data.frame(BaseDam2014=exp(x[x>0])) hurr.nb <- MASS::glm.nb(deaths~log(BaseDam2014), data=hurricNamed[-c(13,84),]) df[,'hatnb'] <- funy(predict(hurr.nb, newdata=df, type='response')) gph3 + latticeExtra::layer(data=df, panel.lines(log(BaseDam2014), hatnb, lwd=2, lty=2, alpha=0.5, col="gray30"))
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate The O'Hara and Kotze paper (Methods in Ecology and Evolution 1:118–122) is not a good starting point for discussion. My most serious concern is the claim in point 4 of the summary: We found that the
15,394
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate
The original post reflects Tony Ives' paper: Ives (2015). It's clear that significance testing gives different results to parameter estimation. John Maindonald explains why the estimates are biased, but his ignorance of the background is annoying - he criticises us for showing that a method we all agree is flawed is flawed. A lot of ecologists do blindly log transform, and we were trying to point out the problems with doing that. There's a more nuanced discussion here: Warton (2016) Ives, A. R. (2015), For testing the significance of regression coefficients, go ahead and log-transform count data. Methods Ecol Evol, 6: 828–835. doi:10.1111/2041-210X.12386 Warton, D. I., Lyons, M., Stoklosa, J. and Ives, A. R. (2016), Three points to consider when choosing a LM or GLM test for count data. Methods Ecol Evol. doi:10.1111/2041-210X.12552
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate
The original post reflects Tony Ives' paper: Ives (2015). It's clear that significance testing gives different results to parameter estimation. John Maindonald explains why the estimates are biased, b
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate The original post reflects Tony Ives' paper: Ives (2015). It's clear that significance testing gives different results to parameter estimation. John Maindonald explains why the estimates are biased, but his ignorance of the background is annoying - he criticises us for showing that a method we all agree is flawed is flawed. A lot of ecologists do blindly log transform, and we were trying to point out the problems with doing that. There's a more nuanced discussion here: Warton (2016) Ives, A. R. (2015), For testing the significance of regression coefficients, go ahead and log-transform count data. Methods Ecol Evol, 6: 828–835. doi:10.1111/2041-210X.12386 Warton, D. I., Lyons, M., Stoklosa, J. and Ives, A. R. (2016), Three points to consider when choosing a LM or GLM test for count data. Methods Ecol Evol. doi:10.1111/2041-210X.12552
Negative-binomial GLM vs. log-transforming for count data: increased Type I error rate The original post reflects Tony Ives' paper: Ives (2015). It's clear that significance testing gives different results to parameter estimation. John Maindonald explains why the estimates are biased, b
15,395
Strategy for editing comma separated value (CSV) files
If you are comfortable with R, you can create your basic data.frame and then use the fix() function on it to input data. Along the same line as #5, once you set up the data.frame you can use a series of readLines(n=1) (or whatever) to get your data in, validate it, and the provide the opportunity to add the next row. Then leave the fixing to fix(). See an implemented example below using scan(). Another option in excel would be messy, but you could type in 12/9, then have another column evaluate =IFERROR(MONTH(DateEntryCell)/DAY(DataEntryCell),DataEntryCell). But then you'll have to maintain the excel sheet AND the csv sheet and all of the complaining as you write the csv will persist. Alternatively, so long as your fields are relatively short and have a consistent length a regular text editor should serve you well with TSV. You can always load it up in excel when you are done and make sure the number of columns for each row is what you expect it to be. Emacs is available on a number of platforms and probably has something just for this, e.g. http://www.emacswiki.org/emacs/CsvMode. If you are a hearty soul, programming something quick up in a programming language to do the data entry is trivial, the data editing will be a lot harder. A quick google search shows software with just this purpose, but no free software seemed to be any good. It sounds insane, but someone on superuser suggested editing tables in access and then exporting them as CSV... that is just crazy enough to work. It doesn't stop excel from complaining as you save as .csv, but you can type a single apostrophe before your data entry field and that makes it leave it alone in terms of auto-formatting. Nicely, this (in Office 2007 at least) doesn't leave apostrophes in the csv file. Update: I've been poking around a lot on this problem because it is an issue I also have. So far the best/easiest solution for data-entry I've seen so far is KillinkCSV. It isn't "free" software, it is shareware with a 30 day trial duration and a reasonable price (~$27). I'm not sure how much I trust it for editing existing CSVs though - I handed it an insanely large (and presumably well formatted) CSV and it failed to read all of the rows. However it seemed to work well for one that was reasonably large (20 MB) and the problem with the larger file may be user error on my part. R Example: #This function takes a what argument like in scan, #a list with the types to be used, see usage example #at the end of this code block #dataEntry will keep reading in values until #the values it reads in matches what is in #"terminateon". #limitations: Many dataEntry <- function(what,terminateon) { CONTINUE <- TRUE #Make sure we start the loop data <- NULL #Create empty data so that the data.frame can define itself ti <- NULL while(CONTINUE) { ti <- NULL ti <- tryCatch( {as.data.frame(scan(what=what, nlines=1, multi.line=FALSE, comment.char="",quiet=TRUE))}, error=function (e) {print("Error in data entry! Line not stored.") return(NULL)}, warning=function(w) {print("Error in data entry! Line not stored.") return(NULL)}, finally={ti <- NULL} ) #Try getting the data according to the parameters in 'what' one row at a time. if (!is.null(ti)) { if ((ncol(ti)==length(what)) & (nrow(ti)==1)) { data <- rbind(data,ti) #If there wasn't an error, add ti to the previous value } else { print("Too many or not enough values on previous entry.") print("Tail of current data:") print(tail(data)) } } if (!is.null(ti) & all(ti == terminateon)) { CONTINUE <- FALSE data <- data[-c(nrow(data)),] } #if we've recieved the final value we won't continue and the last row is invalid so we remove it } return(data) } dataEntry(list(x=integer(), y=numeric(), z=character()),terminateon=c(999,999,"Z"))
Strategy for editing comma separated value (CSV) files
If you are comfortable with R, you can create your basic data.frame and then use the fix() function on it to input data. Along the same line as #5, once you set up the data.frame you can use a series
Strategy for editing comma separated value (CSV) files If you are comfortable with R, you can create your basic data.frame and then use the fix() function on it to input data. Along the same line as #5, once you set up the data.frame you can use a series of readLines(n=1) (or whatever) to get your data in, validate it, and the provide the opportunity to add the next row. Then leave the fixing to fix(). See an implemented example below using scan(). Another option in excel would be messy, but you could type in 12/9, then have another column evaluate =IFERROR(MONTH(DateEntryCell)/DAY(DataEntryCell),DataEntryCell). But then you'll have to maintain the excel sheet AND the csv sheet and all of the complaining as you write the csv will persist. Alternatively, so long as your fields are relatively short and have a consistent length a regular text editor should serve you well with TSV. You can always load it up in excel when you are done and make sure the number of columns for each row is what you expect it to be. Emacs is available on a number of platforms and probably has something just for this, e.g. http://www.emacswiki.org/emacs/CsvMode. If you are a hearty soul, programming something quick up in a programming language to do the data entry is trivial, the data editing will be a lot harder. A quick google search shows software with just this purpose, but no free software seemed to be any good. It sounds insane, but someone on superuser suggested editing tables in access and then exporting them as CSV... that is just crazy enough to work. It doesn't stop excel from complaining as you save as .csv, but you can type a single apostrophe before your data entry field and that makes it leave it alone in terms of auto-formatting. Nicely, this (in Office 2007 at least) doesn't leave apostrophes in the csv file. Update: I've been poking around a lot on this problem because it is an issue I also have. So far the best/easiest solution for data-entry I've seen so far is KillinkCSV. It isn't "free" software, it is shareware with a 30 day trial duration and a reasonable price (~$27). I'm not sure how much I trust it for editing existing CSVs though - I handed it an insanely large (and presumably well formatted) CSV and it failed to read all of the rows. However it seemed to work well for one that was reasonably large (20 MB) and the problem with the larger file may be user error on my part. R Example: #This function takes a what argument like in scan, #a list with the types to be used, see usage example #at the end of this code block #dataEntry will keep reading in values until #the values it reads in matches what is in #"terminateon". #limitations: Many dataEntry <- function(what,terminateon) { CONTINUE <- TRUE #Make sure we start the loop data <- NULL #Create empty data so that the data.frame can define itself ti <- NULL while(CONTINUE) { ti <- NULL ti <- tryCatch( {as.data.frame(scan(what=what, nlines=1, multi.line=FALSE, comment.char="",quiet=TRUE))}, error=function (e) {print("Error in data entry! Line not stored.") return(NULL)}, warning=function(w) {print("Error in data entry! Line not stored.") return(NULL)}, finally={ti <- NULL} ) #Try getting the data according to the parameters in 'what' one row at a time. if (!is.null(ti)) { if ((ncol(ti)==length(what)) & (nrow(ti)==1)) { data <- rbind(data,ti) #If there wasn't an error, add ti to the previous value } else { print("Too many or not enough values on previous entry.") print("Tail of current data:") print(tail(data)) } } if (!is.null(ti) & all(ti == terminateon)) { CONTINUE <- FALSE data <- data[-c(nrow(data)),] } #if we've recieved the final value we won't continue and the last row is invalid so we remove it } return(data) } dataEntry(list(x=integer(), y=numeric(), z=character()),terminateon=c(999,999,"Z"))
Strategy for editing comma separated value (CSV) files If you are comfortable with R, you can create your basic data.frame and then use the fix() function on it to input data. Along the same line as #5, once you set up the data.frame you can use a series
15,396
Strategy for editing comma separated value (CSV) files
Update: [Having been going through a large backlog of email from R-Help] I am reminded of the thread on "The behaviour of read.csv()". In this, Duncan Murdoch mentions that he prefers to use Data Interchange Format (DIF) files instead of csv for some of the reason Jeromy mentions. I just tried this and Gnumeric gets it wrong (loading 12/3 as a date), but OpenOffice.org reads this correctly and preserves the 12/3 information intact. (Anyone care to check this in MS Excel?) DIF files are plain text and can be read by spreadsheets and R (as long as you use a recent R revision (SVN revision >= r53778)) will read the data in in the correct format. Original: I would try to avoid using a spreadsheet full stop for data editing / manipulation whenever possible. It is incredibly difficult, if not impossible, to document any changes you make to an existing data set so that pretty much rules it out from a reproducible research point of view. At most, I use a spreadsheet to quickly view existing data. For data processing, I tend to write an R script that will take the raw csv file and apply all the necessary processing steps required. I heavily comment that script to explain exactly what I am doing at each stage and why. My data analysis script would then call the data processing script which loads and processes the data. For data entry, is it more hassle to enter the data in a text editor or in a spreadsheet? I suspect the problems you mention for the latter do not outweigh those of trying to enter CSV data into a text editor. You could try a better spreadsheet; OpenOffice.org refuses to stop formatting 12/3 as a date (or it converts it to the numeric representation) even if one formats the column as "numeric" first. Gnumeric on the other hand will leave 12/3 as it is if you format the column as "numeric" first. You can force OpenOffice.org to not reformat 12/3 as a date by prepending a ' to the entries, i.e. '12/3 will get displayed as 12/3 in the spreadsheet and saved out as text. This is probably quite safe to use. Not sure why you would want 12/3 stored numerically as 12/3 in the text file - how should something like R read this? Your comment on warnings about losing features or only saving the active sheet aren't really problems are they? (If they are, then I want your problems in my life ;-)
Strategy for editing comma separated value (CSV) files
Update: [Having been going through a large backlog of email from R-Help] I am reminded of the thread on "The behaviour of read.csv()". In this, Duncan Murdoch mentions that he prefers to use Data Inte
Strategy for editing comma separated value (CSV) files Update: [Having been going through a large backlog of email from R-Help] I am reminded of the thread on "The behaviour of read.csv()". In this, Duncan Murdoch mentions that he prefers to use Data Interchange Format (DIF) files instead of csv for some of the reason Jeromy mentions. I just tried this and Gnumeric gets it wrong (loading 12/3 as a date), but OpenOffice.org reads this correctly and preserves the 12/3 information intact. (Anyone care to check this in MS Excel?) DIF files are plain text and can be read by spreadsheets and R (as long as you use a recent R revision (SVN revision >= r53778)) will read the data in in the correct format. Original: I would try to avoid using a spreadsheet full stop for data editing / manipulation whenever possible. It is incredibly difficult, if not impossible, to document any changes you make to an existing data set so that pretty much rules it out from a reproducible research point of view. At most, I use a spreadsheet to quickly view existing data. For data processing, I tend to write an R script that will take the raw csv file and apply all the necessary processing steps required. I heavily comment that script to explain exactly what I am doing at each stage and why. My data analysis script would then call the data processing script which loads and processes the data. For data entry, is it more hassle to enter the data in a text editor or in a spreadsheet? I suspect the problems you mention for the latter do not outweigh those of trying to enter CSV data into a text editor. You could try a better spreadsheet; OpenOffice.org refuses to stop formatting 12/3 as a date (or it converts it to the numeric representation) even if one formats the column as "numeric" first. Gnumeric on the other hand will leave 12/3 as it is if you format the column as "numeric" first. You can force OpenOffice.org to not reformat 12/3 as a date by prepending a ' to the entries, i.e. '12/3 will get displayed as 12/3 in the spreadsheet and saved out as text. This is probably quite safe to use. Not sure why you would want 12/3 stored numerically as 12/3 in the text file - how should something like R read this? Your comment on warnings about losing features or only saving the active sheet aren't really problems are they? (If they are, then I want your problems in my life ;-)
Strategy for editing comma separated value (CSV) files Update: [Having been going through a large backlog of email from R-Help] I am reminded of the thread on "The behaviour of read.csv()". In this, Duncan Murdoch mentions that he prefers to use Data Inte
15,397
Strategy for editing comma separated value (CSV) files
I suggest you look at google refine (http://code.google.com/p/google-refine/). I think is a very good tool for editing CSV files
Strategy for editing comma separated value (CSV) files
I suggest you look at google refine (http://code.google.com/p/google-refine/). I think is a very good tool for editing CSV files
Strategy for editing comma separated value (CSV) files I suggest you look at google refine (http://code.google.com/p/google-refine/). I think is a very good tool for editing CSV files
Strategy for editing comma separated value (CSV) files I suggest you look at google refine (http://code.google.com/p/google-refine/). I think is a very good tool for editing CSV files
15,398
Strategy for editing comma separated value (CSV) files
I would avoid working with the CSV and TSV files all together. Instead learn to use SQL and operate only on a datamart or database (DB) copy of your data or you can use SAS or R with a passthru connection to your database. That way you can make bulk updates to your data instead of doing the dreaded find and replace in Excel (or whatever spreadsheet program you are using) or copying and pasting which can be prone to errors. The advantage of using a DB system too is that you can enable logging and quickly rollback changes you have made if they are made in error and all changes can be audited. In addition, integrity constraints can be placed on your DB tables to ensure you don't mistakenly update or change variables/column in ways you deem inappropriate (e.g. dates stay as dates and other information is type cast appropriately). I won't even get into the niceties of security of your data in a database versus a text file (it would be especially important to work with a DB and secure it appropriately if your data contains sensitive or personally identifying information). If you like spreadsheets because it somehow facilities your data entry, that can be overcome in every database I've ever used by using the graphical user interface tools/IDEs that come with databases (e.g. Microsoft's Management Studio) or by pulling in a linked version of your database into a system specifically designed for entering your data and enforcing data constraints (e.g. linked table forms in Access or a custom web interface). You can also use other programs that will allow you to get the best of both worlds and update data in Excel and have those change propagate to your database (see https://www.youtube.com/watch?v=5iyuF_mDSac for example).
Strategy for editing comma separated value (CSV) files
I would avoid working with the CSV and TSV files all together. Instead learn to use SQL and operate only on a datamart or database (DB) copy of your data or you can use SAS or R with a passthru conne
Strategy for editing comma separated value (CSV) files I would avoid working with the CSV and TSV files all together. Instead learn to use SQL and operate only on a datamart or database (DB) copy of your data or you can use SAS or R with a passthru connection to your database. That way you can make bulk updates to your data instead of doing the dreaded find and replace in Excel (or whatever spreadsheet program you are using) or copying and pasting which can be prone to errors. The advantage of using a DB system too is that you can enable logging and quickly rollback changes you have made if they are made in error and all changes can be audited. In addition, integrity constraints can be placed on your DB tables to ensure you don't mistakenly update or change variables/column in ways you deem inappropriate (e.g. dates stay as dates and other information is type cast appropriately). I won't even get into the niceties of security of your data in a database versus a text file (it would be especially important to work with a DB and secure it appropriately if your data contains sensitive or personally identifying information). If you like spreadsheets because it somehow facilities your data entry, that can be overcome in every database I've ever used by using the graphical user interface tools/IDEs that come with databases (e.g. Microsoft's Management Studio) or by pulling in a linked version of your database into a system specifically designed for entering your data and enforcing data constraints (e.g. linked table forms in Access or a custom web interface). You can also use other programs that will allow you to get the best of both worlds and update data in Excel and have those change propagate to your database (see https://www.youtube.com/watch?v=5iyuF_mDSac for example).
Strategy for editing comma separated value (CSV) files I would avoid working with the CSV and TSV files all together. Instead learn to use SQL and operate only on a datamart or database (DB) copy of your data or you can use SAS or R with a passthru conne
15,399
Strategy for editing comma separated value (CSV) files
After I asked this question, I started having a look at CSVed. From the website: CSVed is an easy and powerful CSV file editor, you can manipulate any CSV file, separated with any separator. I'm not sure if anyone has experience with it.
Strategy for editing comma separated value (CSV) files
After I asked this question, I started having a look at CSVed. From the website: CSVed is an easy and powerful CSV file editor, you can manipulate any CSV file, separated with any separator. I'm
Strategy for editing comma separated value (CSV) files After I asked this question, I started having a look at CSVed. From the website: CSVed is an easy and powerful CSV file editor, you can manipulate any CSV file, separated with any separator. I'm not sure if anyone has experience with it.
Strategy for editing comma separated value (CSV) files After I asked this question, I started having a look at CSVed. From the website: CSVed is an easy and powerful CSV file editor, you can manipulate any CSV file, separated with any separator. I'm
15,400
Strategy for editing comma separated value (CSV) files
Excel is not very CSV friendly. For example, if you were to enter "1,300" into Excel, and save that as a comma separated value, it would let you! This can be a big problem (I encounter it on a regular basis when receiving files from others). I personally use OpenOffice.org Calc, I also use many of the solutions listed above, however many of these don't have the functionality and the ease of use that are required for regular editing. OOO Calc is much more intelligent than Excel, although being a spreadsheet program, you will still have to enter "=12/3" instead of "12/3" otherwise you will be entering a value, rather than a calculation. Give it a whirl, you won't be disappointed.
Strategy for editing comma separated value (CSV) files
Excel is not very CSV friendly. For example, if you were to enter "1,300" into Excel, and save that as a comma separated value, it would let you! This can be a big problem (I encounter it on a regular
Strategy for editing comma separated value (CSV) files Excel is not very CSV friendly. For example, if you were to enter "1,300" into Excel, and save that as a comma separated value, it would let you! This can be a big problem (I encounter it on a regular basis when receiving files from others). I personally use OpenOffice.org Calc, I also use many of the solutions listed above, however many of these don't have the functionality and the ease of use that are required for regular editing. OOO Calc is much more intelligent than Excel, although being a spreadsheet program, you will still have to enter "=12/3" instead of "12/3" otherwise you will be entering a value, rather than a calculation. Give it a whirl, you won't be disappointed.
Strategy for editing comma separated value (CSV) files Excel is not very CSV friendly. For example, if you were to enter "1,300" into Excel, and save that as a comma separated value, it would let you! This can be a big problem (I encounter it on a regular