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
11,301
Blind source separation of convex mixture?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. It could be achieved by using an exponential non-linearity instead of the typical/default tanh(), if X is also non-negative. Formula 40 in https://www.cs.helsinki.fi/u/ahyvarin/papers/NN00new.pdf and available in most implementations. E.g. in sklearn simply use fun='exp' https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.FastICA.html
Blind source separation of convex mixture?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Blind source separation of convex mixture? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. It could be achieved by using an exponential non-linearity instead of the typical/default tanh(), if X is also non-negative. Formula 40 in https://www.cs.helsinki.fi/u/ahyvarin/papers/NN00new.pdf and available in most implementations. E.g. in sklearn simply use fun='exp' https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.FastICA.html
Blind source separation of convex mixture? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
11,302
Blind source separation of convex mixture?
Transformation of variables is a good option when that linearizes the problem. That procedure can be used to increase the correlations, reduce the residuals, and decrease the number of parameters needed to produce a good fit to the data. For example, $\ln Y=a_0+a_1\ln X_1+a_2\ln X_2\to Y=e^{a_0}X_1^{a_1}X_2^{a_2},$ might be vastly superior to $Y=a_0+a_1X_1+a_2X_2$. A hint as to what to do is often provided by examination of the data or its residuals. For example, if one has fan shaped heteroscedasticity of parameters, like in this paper That particular type of log-log transform may be of interest. More generally, there are lots of transforms to consider: taking square roots, exponentiation, taking reciprocals, and so forth. Another indication of how one should treat the data comes from considering the physics of the problem. For example, if a regression problem cannot take negative $Y$-values, that problem may not be linear, as lines may become negative.
Blind source separation of convex mixture?
Transformation of variables is a good option when that linearizes the problem. That procedure can be used to increase the correlations, reduce the residuals, and decrease the number of parameters need
Blind source separation of convex mixture? Transformation of variables is a good option when that linearizes the problem. That procedure can be used to increase the correlations, reduce the residuals, and decrease the number of parameters needed to produce a good fit to the data. For example, $\ln Y=a_0+a_1\ln X_1+a_2\ln X_2\to Y=e^{a_0}X_1^{a_1}X_2^{a_2},$ might be vastly superior to $Y=a_0+a_1X_1+a_2X_2$. A hint as to what to do is often provided by examination of the data or its residuals. For example, if one has fan shaped heteroscedasticity of parameters, like in this paper That particular type of log-log transform may be of interest. More generally, there are lots of transforms to consider: taking square roots, exponentiation, taking reciprocals, and so forth. Another indication of how one should treat the data comes from considering the physics of the problem. For example, if a regression problem cannot take negative $Y$-values, that problem may not be linear, as lines may become negative.
Blind source separation of convex mixture? Transformation of variables is a good option when that linearizes the problem. That procedure can be used to increase the correlations, reduce the residuals, and decrease the number of parameters need
11,303
Why is the use of high order polynomials for regression discouraged?
I cover this in some detail in Chapter 2 of RMS. Briefly, besides extrapolation problems, ordinary polynomials have these problems: The shape of the fit in one region of the data is influenced by far away points Polynomials cannot fit threshold effects, e.g., a nearly flat curve that suddenly accelerates Polynomials cannot fit logarithmic-looking relationships, e.g., ones that get progressively flatter over a long interval Polynomials can't have a very rapid turn These are reasons that regression splines are so popular, i.e., segmented polynomials tend to work better than unsegmented polynomials. You can also relax a continuity assumption for a spline if you want to have a discontinuous change point in the fit.
Why is the use of high order polynomials for regression discouraged?
I cover this in some detail in Chapter 2 of RMS. Briefly, besides extrapolation problems, ordinary polynomials have these problems: The shape of the fit in one region of the data is influenced by fa
Why is the use of high order polynomials for regression discouraged? I cover this in some detail in Chapter 2 of RMS. Briefly, besides extrapolation problems, ordinary polynomials have these problems: The shape of the fit in one region of the data is influenced by far away points Polynomials cannot fit threshold effects, e.g., a nearly flat curve that suddenly accelerates Polynomials cannot fit logarithmic-looking relationships, e.g., ones that get progressively flatter over a long interval Polynomials can't have a very rapid turn These are reasons that regression splines are so popular, i.e., segmented polynomials tend to work better than unsegmented polynomials. You can also relax a continuity assumption for a spline if you want to have a discontinuous change point in the fit.
Why is the use of high order polynomials for regression discouraged? I cover this in some detail in Chapter 2 of RMS. Briefly, besides extrapolation problems, ordinary polynomials have these problems: The shape of the fit in one region of the data is influenced by fa
11,304
Why is the use of high order polynomials for regression discouraged?
Yes, polynomials are also problematic in interpolation, because of overfitting and high variability. Here is an example. Assume your dependent variable $y$ is uniformly distributed on the interval $[0,1]$. You also have a "predictor" variable $x$, also uniformly distributed on the interval $[0,1]$. However, there is no relationship between the two. Thus, any regression of $y$ on any power of $x$ will be overfitting. Now, assume we draw 20 data points from this data generating process and fit $y\sim x^n$ for $n=1, 2, 3, 5$. Here are the fits: As you see, the fit gets "wigglier" for higher $n$. However, one key problem is that (of course) the fit will depend on the data we have randomly sampled from our data generating process. After all, we could have drawn 20 quite different pairs $(x,y)$. Let's repeat the exercise another three times, with new random samples each time. Below, the top row is the same as the previous plot, and the three other rows are just the fits based on new samples: The main problem is visible when you compare the left column (linear fits) and the right column ($x^5$ fits): the fit for a lower order polynomial is much less variable and dependent on the randomness in our data sampling than the fit for the high order polynomial. If we want to interpolate $y$ for some $x$ even somewhere in the middle of the interval, using a higher order polynomial will yield a fit that is much more wobbly than a lower order polynomial. R code: nn <- 20 xx <- seq(0,1,by=.01) png("sims_1.png",width=800,height=200) opar <- par(mfrow=c(1,4),mai=c(.3,.3,.3,.1),las=1) set.seed(1) obs <- data.frame(x=runif(nn),y=runif(nn)) for ( exponent in c(1,2,3,5) ) { model <- lm(y~poly(x,exponent),obs) plot(obs$x,obs$y,pch=19,xlab="",ylab="",main=paste("Exponent:",exponent),xlim=c(0,1),ylim=c(0,1)) lines(xx,predict(model,newdata=data.frame(x=xx)),col="red",lwd=2) } dev.off() png("sims_2.png",width=800,height=800) opar <- par(mfrow=c(4,4),mai=c(.3,.3,.3,.1),las=1) for ( jj in 1:4 ) { set.seed(jj) obs <- data.frame(x=runif(nn),y=runif(nn)) for ( exponent in c(1,2,3,5) ) { model <- lm(y~poly(x,exponent),obs) plot(obs$x,obs$y,pch=19,xlab="",ylab="",main=paste("Exponent:",exponent),xlim=c(0,1),ylim=c(0,1)) lines(xx,predict(model,newdata=data.frame(x=xx)),col="red",lwd=2) } } par(opar) dev.off()
Why is the use of high order polynomials for regression discouraged?
Yes, polynomials are also problematic in interpolation, because of overfitting and high variability. Here is an example. Assume your dependent variable $y$ is uniformly distributed on the interval $[0
Why is the use of high order polynomials for regression discouraged? Yes, polynomials are also problematic in interpolation, because of overfitting and high variability. Here is an example. Assume your dependent variable $y$ is uniformly distributed on the interval $[0,1]$. You also have a "predictor" variable $x$, also uniformly distributed on the interval $[0,1]$. However, there is no relationship between the two. Thus, any regression of $y$ on any power of $x$ will be overfitting. Now, assume we draw 20 data points from this data generating process and fit $y\sim x^n$ for $n=1, 2, 3, 5$. Here are the fits: As you see, the fit gets "wigglier" for higher $n$. However, one key problem is that (of course) the fit will depend on the data we have randomly sampled from our data generating process. After all, we could have drawn 20 quite different pairs $(x,y)$. Let's repeat the exercise another three times, with new random samples each time. Below, the top row is the same as the previous plot, and the three other rows are just the fits based on new samples: The main problem is visible when you compare the left column (linear fits) and the right column ($x^5$ fits): the fit for a lower order polynomial is much less variable and dependent on the randomness in our data sampling than the fit for the high order polynomial. If we want to interpolate $y$ for some $x$ even somewhere in the middle of the interval, using a higher order polynomial will yield a fit that is much more wobbly than a lower order polynomial. R code: nn <- 20 xx <- seq(0,1,by=.01) png("sims_1.png",width=800,height=200) opar <- par(mfrow=c(1,4),mai=c(.3,.3,.3,.1),las=1) set.seed(1) obs <- data.frame(x=runif(nn),y=runif(nn)) for ( exponent in c(1,2,3,5) ) { model <- lm(y~poly(x,exponent),obs) plot(obs$x,obs$y,pch=19,xlab="",ylab="",main=paste("Exponent:",exponent),xlim=c(0,1),ylim=c(0,1)) lines(xx,predict(model,newdata=data.frame(x=xx)),col="red",lwd=2) } dev.off() png("sims_2.png",width=800,height=800) opar <- par(mfrow=c(4,4),mai=c(.3,.3,.3,.1),las=1) for ( jj in 1:4 ) { set.seed(jj) obs <- data.frame(x=runif(nn),y=runif(nn)) for ( exponent in c(1,2,3,5) ) { model <- lm(y~poly(x,exponent),obs) plot(obs$x,obs$y,pch=19,xlab="",ylab="",main=paste("Exponent:",exponent),xlim=c(0,1),ylim=c(0,1)) lines(xx,predict(model,newdata=data.frame(x=xx)),col="red",lwd=2) } } par(opar) dev.off()
Why is the use of high order polynomials for regression discouraged? Yes, polynomials are also problematic in interpolation, because of overfitting and high variability. Here is an example. Assume your dependent variable $y$ is uniformly distributed on the interval $[0
11,305
Why is the use of high order polynomials for regression discouraged?
If your goal is interpolation, you typically want the simplest function that describes your observations and avoid overfitting. Given that it is unusual to see physical laws and relationships which contain powers higher than 3, using higher order polynomials when there is no intuitive justification is taken to be a sign of overfitting. See also this similar question.
Why is the use of high order polynomials for regression discouraged?
If your goal is interpolation, you typically want the simplest function that describes your observations and avoid overfitting. Given that it is unusual to see physical laws and relationships which co
Why is the use of high order polynomials for regression discouraged? If your goal is interpolation, you typically want the simplest function that describes your observations and avoid overfitting. Given that it is unusual to see physical laws and relationships which contain powers higher than 3, using higher order polynomials when there is no intuitive justification is taken to be a sign of overfitting. See also this similar question.
Why is the use of high order polynomials for regression discouraged? If your goal is interpolation, you typically want the simplest function that describes your observations and avoid overfitting. Given that it is unusual to see physical laws and relationships which co
11,306
Why is the use of high order polynomials for regression discouraged?
Runge's phenomenon can lead to high-degree polynomials being much wigglier than the variation actually suggested by the data. An appeal of splines as a substitute for high-degree polynomials, particularly natural splines, is to allow nonmonotonicity and varying slopes without varying too wildly. I would be hard-pressed to find an example of real data for which a fourth- or higher-degree polynomial seems a more reasonable choice than a spline.
Why is the use of high order polynomials for regression discouraged?
Runge's phenomenon can lead to high-degree polynomials being much wigglier than the variation actually suggested by the data. An appeal of splines as a substitute for high-degree polynomials, particul
Why is the use of high order polynomials for regression discouraged? Runge's phenomenon can lead to high-degree polynomials being much wigglier than the variation actually suggested by the data. An appeal of splines as a substitute for high-degree polynomials, particularly natural splines, is to allow nonmonotonicity and varying slopes without varying too wildly. I would be hard-pressed to find an example of real data for which a fourth- or higher-degree polynomial seems a more reasonable choice than a spline.
Why is the use of high order polynomials for regression discouraged? Runge's phenomenon can lead to high-degree polynomials being much wigglier than the variation actually suggested by the data. An appeal of splines as a substitute for high-degree polynomials, particul
11,307
Why is the use of high order polynomials for regression discouraged?
As an inveterate contrarian, I feel the need to amend the premise that high order polynomials shouldn't be used for interpolation. I would argue that the correct statement is "high order polynomials make poor interpolants unless properly regularized". Indeed, it is quite popular (at least in academic circles) to conduct interpolation with polynomials of infinite degree, which is referred to as Kriging when a particular regularizer is used (the so called Reproducing Kernel Hilbert Space regularization, which intuitively speaking penalizes both a function's $L_2$ norm and its tendency to oscillate). And, of course, by infinite degree, we mean it is possible to construct a sequence of arbitrarily high degree polynomials which converge to this reasonable interpolant. Additionally, recent work has shown that by increasing the degree to 2 or 3 times the size of the data (but keeping it finite), together with appropriate regularization, can still perform well. I can't find it just this moment, but this work was based on a similar discovery in the context of neural networks. Generically, regularization prevents many of the issues brought up by other answerers.
Why is the use of high order polynomials for regression discouraged?
As an inveterate contrarian, I feel the need to amend the premise that high order polynomials shouldn't be used for interpolation. I would argue that the correct statement is "high order polynomials m
Why is the use of high order polynomials for regression discouraged? As an inveterate contrarian, I feel the need to amend the premise that high order polynomials shouldn't be used for interpolation. I would argue that the correct statement is "high order polynomials make poor interpolants unless properly regularized". Indeed, it is quite popular (at least in academic circles) to conduct interpolation with polynomials of infinite degree, which is referred to as Kriging when a particular regularizer is used (the so called Reproducing Kernel Hilbert Space regularization, which intuitively speaking penalizes both a function's $L_2$ norm and its tendency to oscillate). And, of course, by infinite degree, we mean it is possible to construct a sequence of arbitrarily high degree polynomials which converge to this reasonable interpolant. Additionally, recent work has shown that by increasing the degree to 2 or 3 times the size of the data (but keeping it finite), together with appropriate regularization, can still perform well. I can't find it just this moment, but this work was based on a similar discovery in the context of neural networks. Generically, regularization prevents many of the issues brought up by other answerers.
Why is the use of high order polynomials for regression discouraged? As an inveterate contrarian, I feel the need to amend the premise that high order polynomials shouldn't be used for interpolation. I would argue that the correct statement is "high order polynomials m
11,308
Why is P(A,B|C)/P(B|C) = P(A|B,C)?
Any probability result that is true for unconditional probability remains true if everything is conditioned on some event. You know that by definition, $$P(A\mid B) = \frac{P(A\cap B)}{P(B)}\tag{1}$$ and so if we condition everything on $C$ having occurred, we get that $$P(A\mid (B \cap C)) = \frac{P((A\cap B)\mid C)}{P(B\mid C)}\tag{2}$$ which is the result that puzzles and surprises you; you think it should be $$P(A\mid (B \cap C)) = \frac{P(A\cap B \cap C)}{P(B\cap C)}.$$ So, let's start by setting $D = B\cap C$ write $P(A\mid (B \cap C)) = P(A\mid D)$ as in $(1)$ to get \begin{align} P(A\mid (B \cap C)) &= P(A\mid D)\\ &= \frac{P(A\cap D)}{P(D)}\\ &= \frac{P(A\cap (B \cap C))}{P(B\cap C)}\\ &= \frac{P(A\cap B \cap C)}{P(B\cap C)}\tag{3}\end{align} which is what you think the result should be. But observe that if you multiply and divide the right side of $(3)$ by $P(C))$, you can get \begin{align} P(A\mid (B \cap C)) &= \frac{P(A\cap B \cap C)}{P(B\cap C)}\times \frac{P(C)}{P(C)}\\ &= \dfrac{\dfrac{P(A\cap B \cap C)}{P(C)}}{\dfrac{P(B\cap C)}{P(C)}}\\ &= \dfrac{P(A\cap B \mid C)}{P(B\mid C)} \end{align} which is just $(2)$. In short, the intuition about $(2)$ is that it is just $(3)$ (which you agree with) re-written in terms of conditional probabilities conditioned on the same event $C$.
Why is P(A,B|C)/P(B|C) = P(A|B,C)?
Any probability result that is true for unconditional probability remains true if everything is conditioned on some event. You know that by definition, $$P(A\mid B) = \frac{P(A\cap B)}{P(B)}\tag{1}$$
Why is P(A,B|C)/P(B|C) = P(A|B,C)? Any probability result that is true for unconditional probability remains true if everything is conditioned on some event. You know that by definition, $$P(A\mid B) = \frac{P(A\cap B)}{P(B)}\tag{1}$$ and so if we condition everything on $C$ having occurred, we get that $$P(A\mid (B \cap C)) = \frac{P((A\cap B)\mid C)}{P(B\mid C)}\tag{2}$$ which is the result that puzzles and surprises you; you think it should be $$P(A\mid (B \cap C)) = \frac{P(A\cap B \cap C)}{P(B\cap C)}.$$ So, let's start by setting $D = B\cap C$ write $P(A\mid (B \cap C)) = P(A\mid D)$ as in $(1)$ to get \begin{align} P(A\mid (B \cap C)) &= P(A\mid D)\\ &= \frac{P(A\cap D)}{P(D)}\\ &= \frac{P(A\cap (B \cap C))}{P(B\cap C)}\\ &= \frac{P(A\cap B \cap C)}{P(B\cap C)}\tag{3}\end{align} which is what you think the result should be. But observe that if you multiply and divide the right side of $(3)$ by $P(C))$, you can get \begin{align} P(A\mid (B \cap C)) &= \frac{P(A\cap B \cap C)}{P(B\cap C)}\times \frac{P(C)}{P(C)}\\ &= \dfrac{\dfrac{P(A\cap B \cap C)}{P(C)}}{\dfrac{P(B\cap C)}{P(C)}}\\ &= \dfrac{P(A\cap B \mid C)}{P(B\mid C)} \end{align} which is just $(2)$. In short, the intuition about $(2)$ is that it is just $(3)$ (which you agree with) re-written in terms of conditional probabilities conditioned on the same event $C$.
Why is P(A,B|C)/P(B|C) = P(A|B,C)? Any probability result that is true for unconditional probability remains true if everything is conditioned on some event. You know that by definition, $$P(A\mid B) = \frac{P(A\cap B)}{P(B)}\tag{1}$$
11,309
Why is P(A,B|C)/P(B|C) = P(A|B,C)?
Just draw the Venn diagram. We then have $$\Pr[A \cap B \mid C] = \frac{\text{"1"}}{\text{"C"}}, \quad \Pr[B \mid C] = \frac{\text{"1"} + \text{"2"}}{\text{"C"}}, \quad \Pr[A \mid B \cap C] = \frac{\text{"1"}}{\text{"1"} + \text{"2"}},$$ and the relationship follows by dividing the first expression by the second.
Why is P(A,B|C)/P(B|C) = P(A|B,C)?
Just draw the Venn diagram. We then have $$\Pr[A \cap B \mid C] = \frac{\text{"1"}}{\text{"C"}}, \quad \Pr[B \mid C] = \frac{\text{"1"} + \text{"2"}}{\text{"C"}}, \quad \Pr[A \mid B \cap C] = \frac{\
Why is P(A,B|C)/P(B|C) = P(A|B,C)? Just draw the Venn diagram. We then have $$\Pr[A \cap B \mid C] = \frac{\text{"1"}}{\text{"C"}}, \quad \Pr[B \mid C] = \frac{\text{"1"} + \text{"2"}}{\text{"C"}}, \quad \Pr[A \mid B \cap C] = \frac{\text{"1"}}{\text{"1"} + \text{"2"}},$$ and the relationship follows by dividing the first expression by the second.
Why is P(A,B|C)/P(B|C) = P(A|B,C)? Just draw the Venn diagram. We then have $$\Pr[A \cap B \mid C] = \frac{\text{"1"}}{\text{"C"}}, \quad \Pr[B \mid C] = \frac{\text{"1"} + \text{"2"}}{\text{"C"}}, \quad \Pr[A \mid B \cap C] = \frac{\
11,310
Why is P(A,B|C)/P(B|C) = P(A|B,C)?
\begin{align*} \frac{P(A,B|C)}{P(B|C)} &= \frac{P(A,B,C)}{P(C)}\frac{P(C)}{P(B,C)} \\ &= \frac{P(A,B,C)}{P(B,C)} \\ &= P(A|B,C) \end{align*}
Why is P(A,B|C)/P(B|C) = P(A|B,C)?
\begin{align*} \frac{P(A,B|C)}{P(B|C)} &= \frac{P(A,B,C)}{P(C)}\frac{P(C)}{P(B,C)} \\ &= \frac{P(A,B,C)}{P(B,C)} \\ &= P(A|B,C) \end{align*}
Why is P(A,B|C)/P(B|C) = P(A|B,C)? \begin{align*} \frac{P(A,B|C)}{P(B|C)} &= \frac{P(A,B,C)}{P(C)}\frac{P(C)}{P(B,C)} \\ &= \frac{P(A,B,C)}{P(B,C)} \\ &= P(A|B,C) \end{align*}
Why is P(A,B|C)/P(B|C) = P(A|B,C)? \begin{align*} \frac{P(A,B|C)}{P(B|C)} &= \frac{P(A,B,C)}{P(C)}\frac{P(C)}{P(B,C)} \\ &= \frac{P(A,B,C)}{P(B,C)} \\ &= P(A|B,C) \end{align*}
11,311
Why is P(A,B|C)/P(B|C) = P(A|B,C)?
My intuition is the following ... Conditioning on $C$ means that we are considering only the cases when $C$ is given. Now, suppose that I live in a world where $C$ is always given. My pepole know nothing about and cannot imagine a world without $C$. For some reason, our mathematicians denote probability of $X$ by $\hat{P}(X)$. They have also already discovered the rule $$\hat P(A|B) = \frac{\hat P(A\cap B)}{\hat P(B)}\text{.}$$ Now, you as an Earthling, know a world where $C$ is not part of the assumptions in everyday life. So, when you come to our planet you can immediately notice, that every our probability $\hat P(X)$ actually correspond to your $P(X|C)$. You are immediately able to rewrite the RHS, following the upper discovery: $$\frac{P(A\cap B\mid C)}{P(B \mid C)}\text{.}$$ But ... What is the LHS? Well, what is the probability of $A$ when $B$ is given when $C$ is (also) given? Precisely $$P(A\mid B\cap C)\text{,}$$ hence the formula.
Why is P(A,B|C)/P(B|C) = P(A|B,C)?
My intuition is the following ... Conditioning on $C$ means that we are considering only the cases when $C$ is given. Now, suppose that I live in a world where $C$ is always given. My pepole know noth
Why is P(A,B|C)/P(B|C) = P(A|B,C)? My intuition is the following ... Conditioning on $C$ means that we are considering only the cases when $C$ is given. Now, suppose that I live in a world where $C$ is always given. My pepole know nothing about and cannot imagine a world without $C$. For some reason, our mathematicians denote probability of $X$ by $\hat{P}(X)$. They have also already discovered the rule $$\hat P(A|B) = \frac{\hat P(A\cap B)}{\hat P(B)}\text{.}$$ Now, you as an Earthling, know a world where $C$ is not part of the assumptions in everyday life. So, when you come to our planet you can immediately notice, that every our probability $\hat P(X)$ actually correspond to your $P(X|C)$. You are immediately able to rewrite the RHS, following the upper discovery: $$\frac{P(A\cap B\mid C)}{P(B \mid C)}\text{.}$$ But ... What is the LHS? Well, what is the probability of $A$ when $B$ is given when $C$ is (also) given? Precisely $$P(A\mid B\cap C)\text{,}$$ hence the formula.
Why is P(A,B|C)/P(B|C) = P(A|B,C)? My intuition is the following ... Conditioning on $C$ means that we are considering only the cases when $C$ is given. Now, suppose that I live in a world where $C$ is always given. My pepole know noth
11,312
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for curvilinear regression?
The remarks in the question about link functions and monotonicity are a red herring. Underlying them seems to be an implicit assumption that a generalized linear model (GLM), by expressing the expectation of a response $Y$ as a monotonic function $f$ of a linear combination $X\beta$ of explanatory variables $X$, is not flexible enough to account for non-monotonic responses. That's just not so. Perhaps a worked example will illuminate this point. In a 1948 study (published posthumously in 1977 and never peer-reviewed), J. Tolkien reported the results of a plant watering experiment in which 13 groups of 24 sunflowers (Helianthus Gondorensis) were given controlled amounts of water starting at germination through three months of growth. The total amounts applied varied from one inch to 25 inches in two-inch increments. There is a clear positive response to the watering and a strong negative response to over-watering. Earlier work, based on hypothetical kinetic models of ion transport, had hypothesized that two competing mechanisms might account for this behavior: one resulted in a linear response to small amounts of water (as measured in the log odds of survival), while the other--an inhibiting factor--acted exponentially (which is a strongly non-linear effect). With large amounts of water, the inhibiting factor would overwhelm the positive effects of the water and appreciably increase mortality. Let $\kappa$ be the (unknown) inhibition rate (per unit amount of water). This model asserts that the number $Y$ of survivors in a group of size $n$ receiving $x$ inches of water should have a $$\text{Binomial}\left(n, f(\beta_0 + \beta_1 x - \beta_2 \exp(\kappa x))\right)$$ distribution, where $f$ is the link function converting log odds back to a probability. This is a binomial GLM. As such, although it is manifestly nonlinear in $x$, given any value of $\kappa$ it is linear in its parameters $\beta_0$, $\beta_1$, and $\beta_2$. "Linearity" in the GLM setting has to be understood in the sense that $f^{-1}\left(\mathbb{E}[Y]\right)$ is a linear combination of these parameters whose coefficients are known for each $x$. And they are: they equal $1$ (the coefficient of $\beta_0$), $x$ itself (the coefficient of $\beta_1$), and $-\exp(\kappa x)$ (the coefficient of $\beta_2$). This model--although it is somewhat novel and not completely linear in its parameters--can be fit using standard software by maximizing the likelihood for arbitrary $\kappa$ and selecting the $\kappa$ for which this maximum is largest. Here is R code to do so, beginning with the data: water <- seq(1, 25, length.out=13) n.survived <- c(0, 3, 4, 12, 18, 21, 23, 24, 22, 23, 18, 3, 2) pop <- 24 counts <- cbind(n.survived, n.died=pop-n.survived) f <- function(k) { fit <- glm(counts ~ water + I(-exp(water * k)), family=binomial) list(AIC=AIC(fit), fit=fit) } k.est <- optim(0.1, function(k) f(k)$AIC, method="Brent", lower=0, upper=1)$par fit <- f(k.est)$fit There are no technical difficulties; the calculation takes only 1/30 second. The blue curve is the fitted expectation of the response, $\mathbb{E}[Y]$. Obviously (a) the fit is good and (b) it predicts a non-monotonic relationship between $\mathbb{E}[Y]$ and $x$ (an upside-down "bathtub" curve). To make this perfectly clear, here is the follow-up code in R used to compute and plot the fit: x.0 <- seq(min(water), max(water), length.out=100) p.0 <- cbind(rep(1, length(x.0)), x.0, -exp(k.est * x.0)) logistic <- function(x) 1 - 1/(1 + exp(x)) predicted <- pop * logistic(p.0 %*% coef(fit)) plot(water, n.survived / pop, main="Data and Fit", xlab="Total water (inches)", ylab="Proportion surviving at 3 months") lines(x.0, predicted / pop, col="#a0a0ff", lwd=2) The answers to the questions are: What terms should I search for in order to either find link functions that represent this class of functional relationships? None: that is not the purpose of the link function. What should I ... search for in order to ... extend existing [link functions] that currently are only for monotonic responses? Nothing: this is based on a misunderstanding of how responses are modeled. Evidently, one should first focus on what explanatory variables to use or construct when building a regression model. As suggested in this example, look for guidance from past experience and theory.
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for
The remarks in the question about link functions and monotonicity are a red herring. Underlying them seems to be an implicit assumption that a generalized linear model (GLM), by expressing the expect
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for curvilinear regression? The remarks in the question about link functions and monotonicity are a red herring. Underlying them seems to be an implicit assumption that a generalized linear model (GLM), by expressing the expectation of a response $Y$ as a monotonic function $f$ of a linear combination $X\beta$ of explanatory variables $X$, is not flexible enough to account for non-monotonic responses. That's just not so. Perhaps a worked example will illuminate this point. In a 1948 study (published posthumously in 1977 and never peer-reviewed), J. Tolkien reported the results of a plant watering experiment in which 13 groups of 24 sunflowers (Helianthus Gondorensis) were given controlled amounts of water starting at germination through three months of growth. The total amounts applied varied from one inch to 25 inches in two-inch increments. There is a clear positive response to the watering and a strong negative response to over-watering. Earlier work, based on hypothetical kinetic models of ion transport, had hypothesized that two competing mechanisms might account for this behavior: one resulted in a linear response to small amounts of water (as measured in the log odds of survival), while the other--an inhibiting factor--acted exponentially (which is a strongly non-linear effect). With large amounts of water, the inhibiting factor would overwhelm the positive effects of the water and appreciably increase mortality. Let $\kappa$ be the (unknown) inhibition rate (per unit amount of water). This model asserts that the number $Y$ of survivors in a group of size $n$ receiving $x$ inches of water should have a $$\text{Binomial}\left(n, f(\beta_0 + \beta_1 x - \beta_2 \exp(\kappa x))\right)$$ distribution, where $f$ is the link function converting log odds back to a probability. This is a binomial GLM. As such, although it is manifestly nonlinear in $x$, given any value of $\kappa$ it is linear in its parameters $\beta_0$, $\beta_1$, and $\beta_2$. "Linearity" in the GLM setting has to be understood in the sense that $f^{-1}\left(\mathbb{E}[Y]\right)$ is a linear combination of these parameters whose coefficients are known for each $x$. And they are: they equal $1$ (the coefficient of $\beta_0$), $x$ itself (the coefficient of $\beta_1$), and $-\exp(\kappa x)$ (the coefficient of $\beta_2$). This model--although it is somewhat novel and not completely linear in its parameters--can be fit using standard software by maximizing the likelihood for arbitrary $\kappa$ and selecting the $\kappa$ for which this maximum is largest. Here is R code to do so, beginning with the data: water <- seq(1, 25, length.out=13) n.survived <- c(0, 3, 4, 12, 18, 21, 23, 24, 22, 23, 18, 3, 2) pop <- 24 counts <- cbind(n.survived, n.died=pop-n.survived) f <- function(k) { fit <- glm(counts ~ water + I(-exp(water * k)), family=binomial) list(AIC=AIC(fit), fit=fit) } k.est <- optim(0.1, function(k) f(k)$AIC, method="Brent", lower=0, upper=1)$par fit <- f(k.est)$fit There are no technical difficulties; the calculation takes only 1/30 second. The blue curve is the fitted expectation of the response, $\mathbb{E}[Y]$. Obviously (a) the fit is good and (b) it predicts a non-monotonic relationship between $\mathbb{E}[Y]$ and $x$ (an upside-down "bathtub" curve). To make this perfectly clear, here is the follow-up code in R used to compute and plot the fit: x.0 <- seq(min(water), max(water), length.out=100) p.0 <- cbind(rep(1, length(x.0)), x.0, -exp(k.est * x.0)) logistic <- function(x) 1 - 1/(1 + exp(x)) predicted <- pop * logistic(p.0 %*% coef(fit)) plot(water, n.survived / pop, main="Data and Fit", xlab="Total water (inches)", ylab="Proportion surviving at 3 months") lines(x.0, predicted / pop, col="#a0a0ff", lwd=2) The answers to the questions are: What terms should I search for in order to either find link functions that represent this class of functional relationships? None: that is not the purpose of the link function. What should I ... search for in order to ... extend existing [link functions] that currently are only for monotonic responses? Nothing: this is based on a misunderstanding of how responses are modeled. Evidently, one should first focus on what explanatory variables to use or construct when building a regression model. As suggested in this example, look for guidance from past experience and theory.
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for The remarks in the question about link functions and monotonicity are a red herring. Underlying them seems to be an implicit assumption that a generalized linear model (GLM), by expressing the expect
11,313
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for curvilinear regression?
Looks guiltily at the dying plant on his desk....apparently not In the comments, @whuber says that "modeling choices ought to be informed by an understanding of what produced the data and motivated by theories in relevant disciplines", to which you asked how one goes about doing this. The Michaelis and Menten kinetics is actually a pretty useful example. Those equations can be derived by starting with some assumptions (e.g., the substrate is in equilibrium with its complex, the enzyme is not consumed) and some known principles (the law of mass action). Murray's Mathematical Biology: An Introduction walks through the derivation in chapter 6 (I would bet many other books do too!). More generally, it helps to build up a "repertoire" of models and assumptions. I'm sure your field has some commonly-accepted, time-tested models. For example, if something is charging or discharging, I would reach for an exponential to model its voltage as a function of time. Conversely, if I see an exponential-like shape in a voltage-time plot, my first guess would be that something in the circuit is capacitively discharging and, if I didn't know what it was, I would try to find it. Ideally, theory can both help you build the model and suggest new experiments. For your data, I'm not a botanist so I don't really know what to make of it. It could be a piecewise linear function (rise, plateau, falling). It could be a pair of exponentials (charging/discharging). I could even imagine that it's actually generated by something like $y= k-(x+h)^2$, with some clipping around the peak. I would suspect that having too little water and too much water affect plants differently, which might argue for a piecewise function with a "drought" component, a region where the plant is relatively happy, and then a "flood" region. The underlying mechanisms for drought (reduced $\textrm{CO}_2$ capture from less transpiration?) and flood (bacteria eating the roots?) might suggest a specific form for each piece.
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for
Looks guiltily at the dying plant on his desk....apparently not In the comments, @whuber says that "modeling choices ought to be informed by an understanding of what produced the data and motivated by
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for curvilinear regression? Looks guiltily at the dying plant on his desk....apparently not In the comments, @whuber says that "modeling choices ought to be informed by an understanding of what produced the data and motivated by theories in relevant disciplines", to which you asked how one goes about doing this. The Michaelis and Menten kinetics is actually a pretty useful example. Those equations can be derived by starting with some assumptions (e.g., the substrate is in equilibrium with its complex, the enzyme is not consumed) and some known principles (the law of mass action). Murray's Mathematical Biology: An Introduction walks through the derivation in chapter 6 (I would bet many other books do too!). More generally, it helps to build up a "repertoire" of models and assumptions. I'm sure your field has some commonly-accepted, time-tested models. For example, if something is charging or discharging, I would reach for an exponential to model its voltage as a function of time. Conversely, if I see an exponential-like shape in a voltage-time plot, my first guess would be that something in the circuit is capacitively discharging and, if I didn't know what it was, I would try to find it. Ideally, theory can both help you build the model and suggest new experiments. For your data, I'm not a botanist so I don't really know what to make of it. It could be a piecewise linear function (rise, plateau, falling). It could be a pair of exponentials (charging/discharging). I could even imagine that it's actually generated by something like $y= k-(x+h)^2$, with some clipping around the peak. I would suspect that having too little water and too much water affect plants differently, which might argue for a piecewise function with a "drought" component, a region where the plant is relatively happy, and then a "flood" region. The underlying mechanisms for drought (reduced $\textrm{CO}_2$ capture from less transpiration?) and flood (bacteria eating the roots?) might suggest a specific form for each piece.
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for Looks guiltily at the dying plant on his desk....apparently not In the comments, @whuber says that "modeling choices ought to be informed by an understanding of what produced the data and motivated by
11,314
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for curvilinear regression?
I have a rather informal response from the point of view of someone who spent half of his scientific life at the bench and the other half at the computer, playing with statistics. I tried to put in into a comment, but it was too long. You see, if I was a scientist observing the type of results that you are getting, I would be thrilled. The various monotonic relationships are boring and hardly distinguishable. However, the type of relationship that you show us suggest a very particular effect. It gives us a wonderful playground for the theoretician for putting forward hypotheses about what the relationship is, how it changes at the extremes. It gives a great playground for the bench scientist to figure out what is happening and experiment widely on the conditions. In a sense, I'd rather have the case you are showing and not know how to fit a simple model (but be able to work out a new hypothesis) than have a simple relationship, easy to model but harder to investigate mechanistically. However, I have not yet encountered a case like that in my practice. Finally, there is one more consideration. If you are looking for a test that shows that black is different from red (in your data) -- as a former bench scientist, I say why even bother? It's clear enough from the figure.
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for
I have a rather informal response from the point of view of someone who spent half of his scientific life at the bench and the other half at the computer, playing with statistics. I tried to put in in
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for curvilinear regression? I have a rather informal response from the point of view of someone who spent half of his scientific life at the bench and the other half at the computer, playing with statistics. I tried to put in into a comment, but it was too long. You see, if I was a scientist observing the type of results that you are getting, I would be thrilled. The various monotonic relationships are boring and hardly distinguishable. However, the type of relationship that you show us suggest a very particular effect. It gives us a wonderful playground for the theoretician for putting forward hypotheses about what the relationship is, how it changes at the extremes. It gives a great playground for the bench scientist to figure out what is happening and experiment widely on the conditions. In a sense, I'd rather have the case you are showing and not know how to fit a simple model (but be able to work out a new hypothesis) than have a simple relationship, easy to model but harder to investigate mechanistically. However, I have not yet encountered a case like that in my practice. Finally, there is one more consideration. If you are looking for a test that shows that black is different from red (in your data) -- as a former bench scientist, I say why even bother? It's clear enough from the figure.
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for I have a rather informal response from the point of view of someone who spent half of his scientific life at the bench and the other half at the computer, playing with statistics. I tried to put in in
11,315
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for curvilinear regression?
For data like that, I'd probably be at least considering linear splines. You can do those in lm or glm easily enough. If you take such an approach, your issue will be choosing number of knots and knot locations; one solution might be to consider a fair number of possible locations, and use something like the lasso or other methods of regularization and selection to identify a small set; you'll need to take into account the effect of such selection in the inference though.
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for
For data like that, I'd probably be at least considering linear splines. You can do those in lm or glm easily enough. If you take such an approach, your issue will be choosing number of knots and kn
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for curvilinear regression? For data like that, I'd probably be at least considering linear splines. You can do those in lm or glm easily enough. If you take such an approach, your issue will be choosing number of knots and knot locations; one solution might be to consider a fair number of possible locations, and use something like the lasso or other methods of regularization and selection to identify a small set; you'll need to take into account the effect of such selection in the inference though.
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for For data like that, I'd probably be at least considering linear splines. You can do those in lm or glm easily enough. If you take such an approach, your issue will be choosing number of knots and kn
11,316
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for curvilinear regression?
I didn't have time to read your whole post, but it seems that your main concern is that the functional forms of responses might shift with treatments. There are techniques for dealing with this, but they are data-intensive. To your specific example: G is growth W is water T is treatment library(mgcv) mod = gam(G ~ T + s(W, by=T) ) plot(mod, pages=1, all=TRUE) ?gam The last decade has seen a ton of research into semiparametric regression, and these beefs about functional forms are getting more and more manageable. But at the end of the day, stats is playing with numbers, and is only useful inasmuch as it builds intuition about the phenomena under observation. This in turn requires understand of the ways in which the numbers are being played with. The tone of your post indicate a willingness to throw the baby out with the bathwater.
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for
I didn't have time to read your whole post, but it seems that your main concern is that the functional forms of responses might shift with treatments. There are techniques for dealing with this, but
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for curvilinear regression? I didn't have time to read your whole post, but it seems that your main concern is that the functional forms of responses might shift with treatments. There are techniques for dealing with this, but they are data-intensive. To your specific example: G is growth W is water T is treatment library(mgcv) mod = gam(G ~ T + s(W, by=T) ) plot(mod, pages=1, all=TRUE) ?gam The last decade has seen a ton of research into semiparametric regression, and these beefs about functional forms are getting more and more manageable. But at the end of the day, stats is playing with numbers, and is only useful inasmuch as it builds intuition about the phenomena under observation. This in turn requires understand of the ways in which the numbers are being played with. The tone of your post indicate a willingness to throw the baby out with the bathwater.
Do statisticians assume one can't over-water a plant, or am I just using the wrong search terms for I didn't have time to read your whole post, but it seems that your main concern is that the functional forms of responses might shift with treatments. There are techniques for dealing with this, but
11,317
What exactly does a non-parametric test accomplish & What do you do with the results?
I know non-parametric relies on the median instead of the mean Hardly any nonparametric tests actually "rely on" medians in this sense. I can only think of a couple... and the only one I expect you'd be likely to have even heard of would be the sign test. to compare...something. If they relied on medians, presumably it would be to compare medians. But - in spite of what a number of sources try to tell you - tests like the signed rank test, or the Wilcoxon-Mann-Whitney or the Kruskal-Wallis are not really a test of medians at all; if you make some additional assumptions, you can regard the Wilcoxon-Mann-Whitney and the Kruskal-Wallis as tests of medians, but under the same assumptions (as long as the distributional means exist) you could equally regard them as a test of means. The actual location-estimate relevant to the Signed Rank test is the median of pairwise averages within-sample (over $\frac12 n(n+1)$ pairs including self-pairs), the one for the Wilcoxon-Mann-Whitney is the median of pairwise differences across-samples. I also believe it relies on "degrees of freedom?" instead of standard deviation. Correct me if I'm wrong though. Most nonparametric tests don't have 'degrees of freedom' in the specific sense that the chi-squared or the t-test of the F-test do (each of which has to do with the number of degrees of freedom in an estimate of variance), though the distribution of many change with sample size and you might regard that as somewhat akin to degrees of freedom in the sense that the tables change with sample size. The samples do of course retain their properties and have n degrees of freedom in that sense but the degrees of freedom in the distribution of a test statistic is not typically something we're concerned with. It can happen that you have something more like degrees of freedom - for example, you could certainly make an argument that the Kruskal-Wallis does have degrees of freedom in basically the same sense that a chi-square does, but it's usually not looked at that way (for example, if someone's talking about the degrees of freedom of a Kruskal-Wallis, they will nearly always mean the d.f. of the chi-square approximation to the distribution of the statistic). A good discussion of degrees of freedom may be found here/ I've done pretty good research, or so I've thought, trying to understand the concept, what the workings are behind it, what the test results really mean, and/or what to even do with the test results; however no one seems to ever venture into that area. I'm not sure what you mean by this. I could suggest some books, like Conover's Practical Nonparametric Statistics, and if you can get it, Neave and Worthington's book (Distribution-Free Tests), but there are many others - Marascuilo & McSweeney, Hollander & Wolfe, or Daniel's book for example. I suggest you read at least 3 or 4 of the ones that speak to you best, preferably ones that explain things as differently as possible (this would mean at least reading a little of perhaps 6 or 7 books to find say 3 that suit). For the sake of simplicity lets stick with the Mann Whitney U test, which I've noticed is quite popular It is, which is what puzzled me about your statement "no one seems to ever venture into that area" - many people who use these tests do 'venture into the area' you were talking about. - and also seemingly misused and overused I'd say nonparametric tests are generally underused if anything (including the Wilcoxon-Mann-Whitney) -- most especially permutation/randomization tests, though I wouldn't necessarily dispute that they're frequently misused (but so are parametric tests, even more so). Let's say I run a non-parametric test with my data and I get this result back: [snip...] I'm familiar with other methods, but what is different here? Which other methods do you mean? What do you want me to compare this to? Edit: You mention regression later; I assume then that you are familiar with a two-sample t-test (since it's really a special case of regression). Under the assumptions for the ordinary two-sample t-test, the null hypothesis has that the two populations are identical, against the alternative that one of the distributions has shifted. If you look at the first of the two sets of hypotheses for the Wilcoxon-Mann-Whitney below, the basic thing being tested there is almost identical; it's just that the t-test is based on assuming the samples come from identical normal distributions (apart from possible location-shift). If the null hypothesis is true, and the accompanying assumptions are true, the test statistic has a t-distribution. If the alternative hypothesis is true, then the test-statistic becomes more likely to take values that don't look consistent with the null hypothesis but do look consistent with the alternative -- we focus on the most unusual, or extreme outcomes (the ones most consistent with the alternative) - if they occur, we conclude that the samples we got would not have occurred by chance when the null was true (they could do, but the probability of a result at least that much consistent with the alternative is so low that we consider the alternative hypothesis a better explanation for what we observe than "the null hypothesis along with the operation of chance"). The situation is very similar with the Wilcoxon-Mann-Whitney, but it measures the deviation from the null somewhat differently. In fact, when the assumptions of the t-test are true*, it's almost as good as the best possible test (which is the t-test). *(which in practice is never, though that's not really as much of a problem as it sounds) Indeed, it's possible to consider the Wilcoxon-Mann-Whitney as effectively a "t-test" performed on the ranks of the data - though then it doesn't have a t-distribution; the statistic is a monotonic function of a two-sample t-statistic computed on the ranks of the data, so it induces the same ordering on the sample space (that is a "t-test" on the ranks - appropriately performed - would generate the same p-values as a Wilcoxon-Mann-Whitney), so it rejects exactly the same cases. [You'd think that just using the ranks would be throwing away a lot of information, but when the data are drawn from normal populations with the same variance, almost all the information about location-shift is in the patterns of the ranks. The actual data values (conditional on their ranks) add very little additional information to that. If you go heavier-tailed than normal, it's not long before the Wilcoxon-Mann-Whitney test has better power, as well as retaining its nominal significance level, so that 'extra' information above the ranks eventually becomes not just uninformative but in some sense, misleading. However, near-symmetric heavy-tailedness is a rare situation, outside some specific applications; what you often tend to see in practice is skewness.] The basic ideas are quite similar, the p-values have the same interpretation (the probability of a result as, or more extreme, if the null hypothesis were true) -- right down to the interpretation of a location-shift, if you make the requisite assumptions (see the discussion of the hypotheses near the end of this post). If I did the same simulation as in the plots above for the t-test, the plots would look very similar - the scale on the x- and y-axes would look different, but the basic appearance would be similar. Should we want the p-value to be lower than .05? You shouldn't "want" anything there. The idea is to find out if the samples are more different (in a location-sense) than can be explained by chance, not to 'wish' a particular outcome. If I say "Can you go see what color Raj's car is please?", if I want an unbiased assessment of it I don't want you to be going "Man, I really, really hope it's blue! It just has to be blue". Best to just see what the situation is, rather than to go in with some 'I need it to be something'. If your chosen significance level is 0.05, then you'll reject the null hypothesis when the p-value is ≤ 0.05. But failure to reject when you have a big enough sample size to nearly always detect relevant effect-sizes is at least as interesting, because it says that any differences that exist are small. What does the "mann whitley" number mean? The Mann-Whitney statistic. It's really only meaningful in comparison with the distribution of values it can take when the null hypothesis is true (see the above diagram), and that depends on which of several particular definitions any particular program might use. Is there any use for it? Usually you don't care about the exact value as such, but where it lies in the null-distribution (whether it's more or less typical of the values you should see when the null hypothesis is true, or whether it's more extreme) (Edit: You can obtain or work out some directly informative quantities when doing such a test - like the location shift or $P(X<Y)$ discussed below, and indeed you can work out the second one fairly directly from the statistic, but the statistic alone isn't a very informative number) Does this data here just verify or not verify that a particular source of data I have should or should not be used? This test doesn't say anything about "a particular source of data I have should or should not be used". See my discussion of the two ways of looking at the WMW hypotheses below. I have a reasonable amount of experience with regression and the basics, but am very curious about this "special" non-parametric stuff There's nothing particularly special about nonparametric tests (I'd say the 'standard' ones are in many ways even more basic than the typical parametric tests) -- as long as you actually understand hypothesis testing. That's probably a topic for another question, however. There are two main ways to look at the Wilcoxon-Mann-Whitney hypothesis test. i) One is to say "I'm interested in location-shift - that is that under the null hypothesis, the two populations have the same (continuous) distribution, against the alternative that one is 'shifted' up or down relative to the other" The Wilcoxon-Mann-Whitney works very well if you make this assumption (that your alternative is just a location shift) In this case, the Wilcoxon-Mann-Whitney actually is a test for medians ... but equally it's a test for means, or indeed any other location-equivariant statistic (90th percentiles, for example, or trimmed means, or any number of other things), since they're all affected the same way by location-shift. The nice thing about this is that it's very easily interpretable -- and it's easy to generate a confidence interval for this location-shift. However, the Wilcoxon-Mann-Whitney test is sensitive to other kinds of difference than a location shift. ii) The other is to take the fully general approach. You can characterize this as a test for the probability that a random value from population 1 is less than a random value from population 2 (and indeed, you can turn your Wilcoxon-Mann-Whitney statistic into a direct estimate of that probability, if you're so inclined; the Mann&Whitney formulation in terms of U-statistics counts the number of times one exceeds the other in the samples, you only need scale that to achieve an estimate of the probability); the null is that the population probability is $\frac{1}{2}$, against the alternative that it differs from $\frac{1}{2}$. However, while it can work okay in this situation, the test is formulated on the assumption of exchangability under the null. Among other things that would require that in the null case the two distributions are the same. If we don't have that, and are instead are in a slightly different situation like the one pictured above, we won't typically have a test with significance level $\alpha$. In the pictured case it would likely be a bit lower. So while it "works" in the sense that it tends not to reject when $H_0$ is true and tends to reject more when $H_0$ is false, you want the distributions to be pretty close to identical under the null or the test doesn't behave the way we would expect it to.
What exactly does a non-parametric test accomplish & What do you do with the results?
I know non-parametric relies on the median instead of the mean Hardly any nonparametric tests actually "rely on" medians in this sense. I can only think of a couple... and the only one I expect you'd
What exactly does a non-parametric test accomplish & What do you do with the results? I know non-parametric relies on the median instead of the mean Hardly any nonparametric tests actually "rely on" medians in this sense. I can only think of a couple... and the only one I expect you'd be likely to have even heard of would be the sign test. to compare...something. If they relied on medians, presumably it would be to compare medians. But - in spite of what a number of sources try to tell you - tests like the signed rank test, or the Wilcoxon-Mann-Whitney or the Kruskal-Wallis are not really a test of medians at all; if you make some additional assumptions, you can regard the Wilcoxon-Mann-Whitney and the Kruskal-Wallis as tests of medians, but under the same assumptions (as long as the distributional means exist) you could equally regard them as a test of means. The actual location-estimate relevant to the Signed Rank test is the median of pairwise averages within-sample (over $\frac12 n(n+1)$ pairs including self-pairs), the one for the Wilcoxon-Mann-Whitney is the median of pairwise differences across-samples. I also believe it relies on "degrees of freedom?" instead of standard deviation. Correct me if I'm wrong though. Most nonparametric tests don't have 'degrees of freedom' in the specific sense that the chi-squared or the t-test of the F-test do (each of which has to do with the number of degrees of freedom in an estimate of variance), though the distribution of many change with sample size and you might regard that as somewhat akin to degrees of freedom in the sense that the tables change with sample size. The samples do of course retain their properties and have n degrees of freedom in that sense but the degrees of freedom in the distribution of a test statistic is not typically something we're concerned with. It can happen that you have something more like degrees of freedom - for example, you could certainly make an argument that the Kruskal-Wallis does have degrees of freedom in basically the same sense that a chi-square does, but it's usually not looked at that way (for example, if someone's talking about the degrees of freedom of a Kruskal-Wallis, they will nearly always mean the d.f. of the chi-square approximation to the distribution of the statistic). A good discussion of degrees of freedom may be found here/ I've done pretty good research, or so I've thought, trying to understand the concept, what the workings are behind it, what the test results really mean, and/or what to even do with the test results; however no one seems to ever venture into that area. I'm not sure what you mean by this. I could suggest some books, like Conover's Practical Nonparametric Statistics, and if you can get it, Neave and Worthington's book (Distribution-Free Tests), but there are many others - Marascuilo & McSweeney, Hollander & Wolfe, or Daniel's book for example. I suggest you read at least 3 or 4 of the ones that speak to you best, preferably ones that explain things as differently as possible (this would mean at least reading a little of perhaps 6 or 7 books to find say 3 that suit). For the sake of simplicity lets stick with the Mann Whitney U test, which I've noticed is quite popular It is, which is what puzzled me about your statement "no one seems to ever venture into that area" - many people who use these tests do 'venture into the area' you were talking about. - and also seemingly misused and overused I'd say nonparametric tests are generally underused if anything (including the Wilcoxon-Mann-Whitney) -- most especially permutation/randomization tests, though I wouldn't necessarily dispute that they're frequently misused (but so are parametric tests, even more so). Let's say I run a non-parametric test with my data and I get this result back: [snip...] I'm familiar with other methods, but what is different here? Which other methods do you mean? What do you want me to compare this to? Edit: You mention regression later; I assume then that you are familiar with a two-sample t-test (since it's really a special case of regression). Under the assumptions for the ordinary two-sample t-test, the null hypothesis has that the two populations are identical, against the alternative that one of the distributions has shifted. If you look at the first of the two sets of hypotheses for the Wilcoxon-Mann-Whitney below, the basic thing being tested there is almost identical; it's just that the t-test is based on assuming the samples come from identical normal distributions (apart from possible location-shift). If the null hypothesis is true, and the accompanying assumptions are true, the test statistic has a t-distribution. If the alternative hypothesis is true, then the test-statistic becomes more likely to take values that don't look consistent with the null hypothesis but do look consistent with the alternative -- we focus on the most unusual, or extreme outcomes (the ones most consistent with the alternative) - if they occur, we conclude that the samples we got would not have occurred by chance when the null was true (they could do, but the probability of a result at least that much consistent with the alternative is so low that we consider the alternative hypothesis a better explanation for what we observe than "the null hypothesis along with the operation of chance"). The situation is very similar with the Wilcoxon-Mann-Whitney, but it measures the deviation from the null somewhat differently. In fact, when the assumptions of the t-test are true*, it's almost as good as the best possible test (which is the t-test). *(which in practice is never, though that's not really as much of a problem as it sounds) Indeed, it's possible to consider the Wilcoxon-Mann-Whitney as effectively a "t-test" performed on the ranks of the data - though then it doesn't have a t-distribution; the statistic is a monotonic function of a two-sample t-statistic computed on the ranks of the data, so it induces the same ordering on the sample space (that is a "t-test" on the ranks - appropriately performed - would generate the same p-values as a Wilcoxon-Mann-Whitney), so it rejects exactly the same cases. [You'd think that just using the ranks would be throwing away a lot of information, but when the data are drawn from normal populations with the same variance, almost all the information about location-shift is in the patterns of the ranks. The actual data values (conditional on their ranks) add very little additional information to that. If you go heavier-tailed than normal, it's not long before the Wilcoxon-Mann-Whitney test has better power, as well as retaining its nominal significance level, so that 'extra' information above the ranks eventually becomes not just uninformative but in some sense, misleading. However, near-symmetric heavy-tailedness is a rare situation, outside some specific applications; what you often tend to see in practice is skewness.] The basic ideas are quite similar, the p-values have the same interpretation (the probability of a result as, or more extreme, if the null hypothesis were true) -- right down to the interpretation of a location-shift, if you make the requisite assumptions (see the discussion of the hypotheses near the end of this post). If I did the same simulation as in the plots above for the t-test, the plots would look very similar - the scale on the x- and y-axes would look different, but the basic appearance would be similar. Should we want the p-value to be lower than .05? You shouldn't "want" anything there. The idea is to find out if the samples are more different (in a location-sense) than can be explained by chance, not to 'wish' a particular outcome. If I say "Can you go see what color Raj's car is please?", if I want an unbiased assessment of it I don't want you to be going "Man, I really, really hope it's blue! It just has to be blue". Best to just see what the situation is, rather than to go in with some 'I need it to be something'. If your chosen significance level is 0.05, then you'll reject the null hypothesis when the p-value is ≤ 0.05. But failure to reject when you have a big enough sample size to nearly always detect relevant effect-sizes is at least as interesting, because it says that any differences that exist are small. What does the "mann whitley" number mean? The Mann-Whitney statistic. It's really only meaningful in comparison with the distribution of values it can take when the null hypothesis is true (see the above diagram), and that depends on which of several particular definitions any particular program might use. Is there any use for it? Usually you don't care about the exact value as such, but where it lies in the null-distribution (whether it's more or less typical of the values you should see when the null hypothesis is true, or whether it's more extreme) (Edit: You can obtain or work out some directly informative quantities when doing such a test - like the location shift or $P(X<Y)$ discussed below, and indeed you can work out the second one fairly directly from the statistic, but the statistic alone isn't a very informative number) Does this data here just verify or not verify that a particular source of data I have should or should not be used? This test doesn't say anything about "a particular source of data I have should or should not be used". See my discussion of the two ways of looking at the WMW hypotheses below. I have a reasonable amount of experience with regression and the basics, but am very curious about this "special" non-parametric stuff There's nothing particularly special about nonparametric tests (I'd say the 'standard' ones are in many ways even more basic than the typical parametric tests) -- as long as you actually understand hypothesis testing. That's probably a topic for another question, however. There are two main ways to look at the Wilcoxon-Mann-Whitney hypothesis test. i) One is to say "I'm interested in location-shift - that is that under the null hypothesis, the two populations have the same (continuous) distribution, against the alternative that one is 'shifted' up or down relative to the other" The Wilcoxon-Mann-Whitney works very well if you make this assumption (that your alternative is just a location shift) In this case, the Wilcoxon-Mann-Whitney actually is a test for medians ... but equally it's a test for means, or indeed any other location-equivariant statistic (90th percentiles, for example, or trimmed means, or any number of other things), since they're all affected the same way by location-shift. The nice thing about this is that it's very easily interpretable -- and it's easy to generate a confidence interval for this location-shift. However, the Wilcoxon-Mann-Whitney test is sensitive to other kinds of difference than a location shift. ii) The other is to take the fully general approach. You can characterize this as a test for the probability that a random value from population 1 is less than a random value from population 2 (and indeed, you can turn your Wilcoxon-Mann-Whitney statistic into a direct estimate of that probability, if you're so inclined; the Mann&Whitney formulation in terms of U-statistics counts the number of times one exceeds the other in the samples, you only need scale that to achieve an estimate of the probability); the null is that the population probability is $\frac{1}{2}$, against the alternative that it differs from $\frac{1}{2}$. However, while it can work okay in this situation, the test is formulated on the assumption of exchangability under the null. Among other things that would require that in the null case the two distributions are the same. If we don't have that, and are instead are in a slightly different situation like the one pictured above, we won't typically have a test with significance level $\alpha$. In the pictured case it would likely be a bit lower. So while it "works" in the sense that it tends not to reject when $H_0$ is true and tends to reject more when $H_0$ is false, you want the distributions to be pretty close to identical under the null or the test doesn't behave the way we would expect it to.
What exactly does a non-parametric test accomplish & What do you do with the results? I know non-parametric relies on the median instead of the mean Hardly any nonparametric tests actually "rely on" medians in this sense. I can only think of a couple... and the only one I expect you'd
11,318
What exactly does a non-parametric test accomplish & What do you do with the results?
Suppose you and I are coaching track teams. Our athletes come from the same school, are similar ages, and the same gender (i.e., they're drawn from the same population), but I claim to have discovered a Revolutionary New Training System that will make my team members run much faster than yours. How can I convince you that it really does work? We have a race. Afterward, I sit down and compute the average time for the members of my team and the average time for the members of yours. I'll claim victory if the mean time for my athletes is not only faster than the mean for yours, but the difference is also large compared to the "scatter", or standard deviation, of our results. This is essentially a [$t$-test][1]. We're assuming that the data arises from distributions with specific parameters, in this case a mean and standard deviation. The test estimates those parameters and compares one of them (the mean). It is, consequently, called a parametric test, since we are comparing these parameters. "But Matt", you complain, "this isn't quite fair. Our teams are pretty similar, but you--due to pure chance--ended up with the fastest runner in the district. He's not in the same league as everyone else; he's practically a freak of Nature. He finished 3 minutes before the next-fastest finisher, which reduces your average time a lot, but the rest of the competitors are pretty evenly mixed. Let's look at the finish order instead. If your method really works, the earlier finishers should mostly be from your team, but if it doesn't the finish order should be pretty random. This doesn't give undue weight to your super-star!" This method is essentially the [Mann-Whitney U Test][2] (also called the Wilcoxon Rank Sum Test, Manning-Whitney-Wilcoxon Test, and several other permutations besides!). Note that unlike the $t$-test, we're not assuming that the data comes from specific distributions, nor are we computing any parameters for them. Instead, we're comparing the relative ranks of the data points directly. That's the major distinction--parametric tests model things with distributions and compare the parameters of these distributions; non-parametric tests....don't and operate more directly on the data. As with parametric tests, non-parametric test statistics are also constructed so that the $p$ values are uniformly distributed on [0,1] under the null hypothesis and clustered towards 0 in the presence of an effect. You would report and interpret them just like the results of a parametric test. I'm not sure about the relative popularity of parametric and non-parametric methods. Some non-parametric methods (e.g., histograms!) are in nearly universal use; others might be over or under-used. I suspect that the Mann-Whitney U Test ought to be used more, rather than less frequently. It's about as efficient as a $t$-test on normally distributed data and actually does better than the $t$-test on sufficiently non-normal data. It's also fairly robust to outliers. Plus, you can use it on ordinal data too (e.g., finish order rather than just finish time), which makes it more broadly applicable than a $t$-test.
What exactly does a non-parametric test accomplish & What do you do with the results?
Suppose you and I are coaching track teams. Our athletes come from the same school, are similar ages, and the same gender (i.e., they're drawn from the same population), but I claim to have discovered
What exactly does a non-parametric test accomplish & What do you do with the results? Suppose you and I are coaching track teams. Our athletes come from the same school, are similar ages, and the same gender (i.e., they're drawn from the same population), but I claim to have discovered a Revolutionary New Training System that will make my team members run much faster than yours. How can I convince you that it really does work? We have a race. Afterward, I sit down and compute the average time for the members of my team and the average time for the members of yours. I'll claim victory if the mean time for my athletes is not only faster than the mean for yours, but the difference is also large compared to the "scatter", or standard deviation, of our results. This is essentially a [$t$-test][1]. We're assuming that the data arises from distributions with specific parameters, in this case a mean and standard deviation. The test estimates those parameters and compares one of them (the mean). It is, consequently, called a parametric test, since we are comparing these parameters. "But Matt", you complain, "this isn't quite fair. Our teams are pretty similar, but you--due to pure chance--ended up with the fastest runner in the district. He's not in the same league as everyone else; he's practically a freak of Nature. He finished 3 minutes before the next-fastest finisher, which reduces your average time a lot, but the rest of the competitors are pretty evenly mixed. Let's look at the finish order instead. If your method really works, the earlier finishers should mostly be from your team, but if it doesn't the finish order should be pretty random. This doesn't give undue weight to your super-star!" This method is essentially the [Mann-Whitney U Test][2] (also called the Wilcoxon Rank Sum Test, Manning-Whitney-Wilcoxon Test, and several other permutations besides!). Note that unlike the $t$-test, we're not assuming that the data comes from specific distributions, nor are we computing any parameters for them. Instead, we're comparing the relative ranks of the data points directly. That's the major distinction--parametric tests model things with distributions and compare the parameters of these distributions; non-parametric tests....don't and operate more directly on the data. As with parametric tests, non-parametric test statistics are also constructed so that the $p$ values are uniformly distributed on [0,1] under the null hypothesis and clustered towards 0 in the presence of an effect. You would report and interpret them just like the results of a parametric test. I'm not sure about the relative popularity of parametric and non-parametric methods. Some non-parametric methods (e.g., histograms!) are in nearly universal use; others might be over or under-used. I suspect that the Mann-Whitney U Test ought to be used more, rather than less frequently. It's about as efficient as a $t$-test on normally distributed data and actually does better than the $t$-test on sufficiently non-normal data. It's also fairly robust to outliers. Plus, you can use it on ordinal data too (e.g., finish order rather than just finish time), which makes it more broadly applicable than a $t$-test.
What exactly does a non-parametric test accomplish & What do you do with the results? Suppose you and I are coaching track teams. Our athletes come from the same school, are similar ages, and the same gender (i.e., they're drawn from the same population), but I claim to have discovered
11,319
What exactly does a non-parametric test accomplish & What do you do with the results?
You asked to be corrected if wrong. Here are some comments under that heading to complement @Peter Flom's positive suggestions. "non-parametric relies on the median instead of the mean": often in practice, but that's not a definition. Several non-parametric tests (e.g. chi-square) have nothing to do with medians. relies on degrees of freedom instead of standard deviation; that's very confused. The idea of degrees of freedom is in no sense an alternative to standard deviation; degrees of freedom as an idea applies right across statistics. "a particular source of data I have should or should not be used": this question has nothing to do with the significance test you applied, which is just about the difference between subsets of data and is phrased in terms of difference between medians.
What exactly does a non-parametric test accomplish & What do you do with the results?
You asked to be corrected if wrong. Here are some comments under that heading to complement @Peter Flom's positive suggestions. "non-parametric relies on the median instead of the mean": often in pr
What exactly does a non-parametric test accomplish & What do you do with the results? You asked to be corrected if wrong. Here are some comments under that heading to complement @Peter Flom's positive suggestions. "non-parametric relies on the median instead of the mean": often in practice, but that's not a definition. Several non-parametric tests (e.g. chi-square) have nothing to do with medians. relies on degrees of freedom instead of standard deviation; that's very confused. The idea of degrees of freedom is in no sense an alternative to standard deviation; degrees of freedom as an idea applies right across statistics. "a particular source of data I have should or should not be used": this question has nothing to do with the significance test you applied, which is just about the difference between subsets of data and is phrased in terms of difference between medians.
What exactly does a non-parametric test accomplish & What do you do with the results? You asked to be corrected if wrong. Here are some comments under that heading to complement @Peter Flom's positive suggestions. "non-parametric relies on the median instead of the mean": often in pr
11,320
What exactly does a non-parametric test accomplish & What do you do with the results?
You "want" the same things from a p-value here that you want in any other test. The U statistic is the result of a calculation, just like the t statistic, the odds ratio, the F statistic, or what have you. The formula can be found lots of places. It's not very intuitive, but then, neither are other test statistics until you get used to them (we recognize a t of 2 as being in the significant range because we see them all the time). The rest of the output in your block text should be clear. For a more general introduction to nonparametric tests, I echo @NickCox .... get a good book. Non-parametric simply means "without parameters"; there are many non-parametric tests and statistics for a wide variety of purposes.
What exactly does a non-parametric test accomplish & What do you do with the results?
You "want" the same things from a p-value here that you want in any other test. The U statistic is the result of a calculation, just like the t statistic, the odds ratio, the F statistic, or what have
What exactly does a non-parametric test accomplish & What do you do with the results? You "want" the same things from a p-value here that you want in any other test. The U statistic is the result of a calculation, just like the t statistic, the odds ratio, the F statistic, or what have you. The formula can be found lots of places. It's not very intuitive, but then, neither are other test statistics until you get used to them (we recognize a t of 2 as being in the significant range because we see them all the time). The rest of the output in your block text should be clear. For a more general introduction to nonparametric tests, I echo @NickCox .... get a good book. Non-parametric simply means "without parameters"; there are many non-parametric tests and statistics for a wide variety of purposes.
What exactly does a non-parametric test accomplish & What do you do with the results? You "want" the same things from a p-value here that you want in any other test. The U statistic is the result of a calculation, just like the t statistic, the odds ratio, the F statistic, or what have
11,321
What exactly does a non-parametric test accomplish & What do you do with the results?
As a response to a recently closed question, this addresses the above as well. Below is a quote from Bradley's classic Distribution-Free Statistical Tests (1968, p. 15–16) which, while a bit long, is a pretty clear explanation, I believe. The terms nonparametric and distribution-free are not synonymous, and neitherterm provides an entirely satisfactory description of the class of statistics to which they are intended to refer.…Roughly speaking, a nonparametric test is one which makes no hypothesis about the value of a parameter in a statistical density function, whereas a distribution-free test is one which makes no assumptions about the precise form of the sampled population. The definitions are not mutually exclusive, and a test can be both distribution-free and parametric.…In order to be entirely clear about what is meant by distribution-free, it is necessary to distinguish between three distributions: (a) that of the sampled population; (b) that of the observation-characteristic actually used by the test; and (c) that of the test statistic. The distribution from which the tests are "free" is that of (a), the sampled population. And the freedom they enjoy is usually relative.…However the assumptions are never so elaborate as to imply a population whose distribution is completely specified.…The reason…is very simple: the magnitudes are not used as such in the [nonparametric] test, nor is any other strongly-linked population attribute of the variate. Instead sample-linked charachteristics of the obtained observations…provide the informatikon used by the test statistic.…Thus while both parametric and nonparametric tests require that the form f a distribution, associated with observations, be fully known, that knowledge, in the parametric case, is generally not forthcoming ad the required distribution of magnitudes must therefore be "assumed" or inferred on the basis of approximate or incomplete information. In the nonparametric case, on the other and, the distrbution of the observation characteristic is usually known precisely from a priori considerations and need not, therefore, be "assumed." The difference, then, is not one of requirement but rather of what is required and of certainty that the requirement will be met.
What exactly does a non-parametric test accomplish & What do you do with the results?
As a response to a recently closed question, this addresses the above as well. Below is a quote from Bradley's classic Distribution-Free Statistical Tests (1968, p. 15–16) which, while a bit long, is
What exactly does a non-parametric test accomplish & What do you do with the results? As a response to a recently closed question, this addresses the above as well. Below is a quote from Bradley's classic Distribution-Free Statistical Tests (1968, p. 15–16) which, while a bit long, is a pretty clear explanation, I believe. The terms nonparametric and distribution-free are not synonymous, and neitherterm provides an entirely satisfactory description of the class of statistics to which they are intended to refer.…Roughly speaking, a nonparametric test is one which makes no hypothesis about the value of a parameter in a statistical density function, whereas a distribution-free test is one which makes no assumptions about the precise form of the sampled population. The definitions are not mutually exclusive, and a test can be both distribution-free and parametric.…In order to be entirely clear about what is meant by distribution-free, it is necessary to distinguish between three distributions: (a) that of the sampled population; (b) that of the observation-characteristic actually used by the test; and (c) that of the test statistic. The distribution from which the tests are "free" is that of (a), the sampled population. And the freedom they enjoy is usually relative.…However the assumptions are never so elaborate as to imply a population whose distribution is completely specified.…The reason…is very simple: the magnitudes are not used as such in the [nonparametric] test, nor is any other strongly-linked population attribute of the variate. Instead sample-linked charachteristics of the obtained observations…provide the informatikon used by the test statistic.…Thus while both parametric and nonparametric tests require that the form f a distribution, associated with observations, be fully known, that knowledge, in the parametric case, is generally not forthcoming ad the required distribution of magnitudes must therefore be "assumed" or inferred on the basis of approximate or incomplete information. In the nonparametric case, on the other and, the distrbution of the observation characteristic is usually known precisely from a priori considerations and need not, therefore, be "assumed." The difference, then, is not one of requirement but rather of what is required and of certainty that the requirement will be met.
What exactly does a non-parametric test accomplish & What do you do with the results? As a response to a recently closed question, this addresses the above as well. Below is a quote from Bradley's classic Distribution-Free Statistical Tests (1968, p. 15–16) which, while a bit long, is
11,322
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$
Short Answer The pdf you describe is most appropriately known as a Subbotin distribution ... see the paper in 1923 by Subbotin which has exactly the same functional form, with say $Y = X-\mu$. Subbotin, M. T. (1923), On the law of frequency of error, Matematicheskii Sbornik, 31, 296-301. who enters the pdf at his equation 5, of form: $$f(y) = K \exp\left[-\left(\frac{|y|}{\sigma}\right)^p\right]$$ with constant of integration: $K = \large\frac{p}{2 \sigma \Gamma \left(\frac{1}{p}\right)}$, as per Xian's derivation where $\beta = \sigma^p$ Longer answer Wikipedia is unfortunately not always 'up to date', or accurate, or sometimes just 80 years behind the times. After Subbotin (1923), the distribution has been widely used in the literature, including: Diananda, P.H. (1949), Note on some properties of maximum likelihood estimates, Proceedings of the Cambridge Philosophical Society, 45, 536-544. Turner, M.E. (1960), On heuristic estimation methods, Biometrics, 16(2), 299-301. Zeckhauser, R. and Thompson, M. (1970), Linear regression with non-normal error terms, The Review of Economics and Statistics, 52, 280-286. McDonald, J.B. and Newey, W.K. (1988), Partially adaptive estimation of regression models via the generalized t distribution, Econometric Theory, 4, 428-457. Johnson, N. L., Kotz, S. and Balakrishnan, N. (1995), Continuous Univariate Distributions, volume 2, 2nd edition, Wiley: New York (1995, p.422) Mineo, A.M. and Ruggieri, M. (2005), A software tool for the Exponential Power distribution: the normalp package, Journal of Statistical Software, 12(4), 1-21. ... all before the paper referenced on Wiki. Aside from being 80 years out of date, the name used on Wiki 'a Generalised Normal' also seems inappropriate because there are an infinity of distributions that are generalisations of the Normal, and the name is, in any event, ambiguous to the literature. It also fails to acknowledge the original author.
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$
Short Answer The pdf you describe is most appropriately known as a Subbotin distribution ... see the paper in 1923 by Subbotin which has exactly the same functional form, with say $Y = X-\mu$. Subb
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$ Short Answer The pdf you describe is most appropriately known as a Subbotin distribution ... see the paper in 1923 by Subbotin which has exactly the same functional form, with say $Y = X-\mu$. Subbotin, M. T. (1923), On the law of frequency of error, Matematicheskii Sbornik, 31, 296-301. who enters the pdf at his equation 5, of form: $$f(y) = K \exp\left[-\left(\frac{|y|}{\sigma}\right)^p\right]$$ with constant of integration: $K = \large\frac{p}{2 \sigma \Gamma \left(\frac{1}{p}\right)}$, as per Xian's derivation where $\beta = \sigma^p$ Longer answer Wikipedia is unfortunately not always 'up to date', or accurate, or sometimes just 80 years behind the times. After Subbotin (1923), the distribution has been widely used in the literature, including: Diananda, P.H. (1949), Note on some properties of maximum likelihood estimates, Proceedings of the Cambridge Philosophical Society, 45, 536-544. Turner, M.E. (1960), On heuristic estimation methods, Biometrics, 16(2), 299-301. Zeckhauser, R. and Thompson, M. (1970), Linear regression with non-normal error terms, The Review of Economics and Statistics, 52, 280-286. McDonald, J.B. and Newey, W.K. (1988), Partially adaptive estimation of regression models via the generalized t distribution, Econometric Theory, 4, 428-457. Johnson, N. L., Kotz, S. and Balakrishnan, N. (1995), Continuous Univariate Distributions, volume 2, 2nd edition, Wiley: New York (1995, p.422) Mineo, A.M. and Ruggieri, M. (2005), A software tool for the Exponential Power distribution: the normalp package, Journal of Statistical Software, 12(4), 1-21. ... all before the paper referenced on Wiki. Aside from being 80 years out of date, the name used on Wiki 'a Generalised Normal' also seems inappropriate because there are an infinity of distributions that are generalisations of the Normal, and the name is, in any event, ambiguous to the literature. It also fails to acknowledge the original author.
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$ Short Answer The pdf you describe is most appropriately known as a Subbotin distribution ... see the paper in 1923 by Subbotin which has exactly the same functional form, with say $Y = X-\mu$. Subb
11,323
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$
For obvious reasons, you can get rid of μ and β so all that remains is $$\int_0^\infty \exp\{−x^p\}\text{d}x\stackrel{y=x^p}{=}\int_0^\infty \exp\{−y\}\left|\dfrac{\text{d}x}{\text{d}y}\right|\text{d}y\stackrel{x=y^{1/p}}{=}\int_0^\infty \exp\{−y\}\frac{1}{p}y^{\frac{1}{p}-1}\text{d}y=\Gamma(1/p)\frac{1}{p} $$ Hence $$\int_{-\infty}^\infty \exp\{−\beta^{-1}|x-\mu|^p\}\text{d}x=\dfrac{2\Gamma(1/p)}{p}\beta^{1/p}$$
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$
For obvious reasons, you can get rid of μ and β so all that remains is $$\int_0^\infty \exp\{−x^p\}\text{d}x\stackrel{y=x^p}{=}\int_0^\infty \exp\{−y\}\left|\dfrac{\text{d}x}{\text{d}y}\right|\text{d}
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$ For obvious reasons, you can get rid of μ and β so all that remains is $$\int_0^\infty \exp\{−x^p\}\text{d}x\stackrel{y=x^p}{=}\int_0^\infty \exp\{−y\}\left|\dfrac{\text{d}x}{\text{d}y}\right|\text{d}y\stackrel{x=y^{1/p}}{=}\int_0^\infty \exp\{−y\}\frac{1}{p}y^{\frac{1}{p}-1}\text{d}y=\Gamma(1/p)\frac{1}{p} $$ Hence $$\int_{-\infty}^\infty \exp\{−\beta^{-1}|x-\mu|^p\}\text{d}x=\dfrac{2\Gamma(1/p)}{p}\beta^{1/p}$$
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$ For obvious reasons, you can get rid of μ and β so all that remains is $$\int_0^\infty \exp\{−x^p\}\text{d}x\stackrel{y=x^p}{=}\int_0^\infty \exp\{−y\}\left|\dfrac{\text{d}x}{\text{d}y}\right|\text{d}
11,324
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$
According to Wikipedia, this is known as Generalized normal distribution (version 1 in the article), and the restriction $p\in [1,2]$ is not required but any positive value is fine. The reference given in Wikipedia is Saralees Nadarajah (2005) A generalized normal distribution, Journal of Applied Statistics, 32:7, 685-694, DOI: 10.1080/02664760500079464. This article mentions that the normalization constant is found by 'simple integration' - I presume following Xi'an's answer.
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$
According to Wikipedia, this is known as Generalized normal distribution (version 1 in the article), and the restriction $p\in [1,2]$ is not required but any positive value is fine. The reference gi
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$ According to Wikipedia, this is known as Generalized normal distribution (version 1 in the article), and the restriction $p\in [1,2]$ is not required but any positive value is fine. The reference given in Wikipedia is Saralees Nadarajah (2005) A generalized normal distribution, Journal of Applied Statistics, 32:7, 685-694, DOI: 10.1080/02664760500079464. This article mentions that the normalization constant is found by 'simple integration' - I presume following Xi'an's answer.
Does this distribution have a name? $f(x)\propto\exp(-|x-\mu|^p/\beta)$ According to Wikipedia, this is known as Generalized normal distribution (version 1 in the article), and the restriction $p\in [1,2]$ is not required but any positive value is fine. The reference gi
11,325
Distribution of ratio between two independent uniform random variables
The right logic is that with independent $X, Y \sim U(0,1)$, $Z=\frac YX$ and $Z^{-1} =\frac XY$ have the same distribution and so for $0 < z < 1$ \begin{align} P\left\{\frac YX \leq z\right\} &= P\left\{\frac XY \leq z\right\}\\ &= P\left\{\frac YX \geq \frac 1z \right\}\\ \left.\left.F_{Z}\right(z\right) &= 1 - F_{Z}\left(\frac 1z\right) \end{align} where the equation with CDFs uses the fact that $\frac YX$ is a continuous random variable and so $P\{Z \geq a\} = P\{Z > a\} = 1-F_Z(a)$. Hence the pdf of $Z$ satisfies $$f_Z(z) = z^{-2}f_Z(z^{-1}), \quad 0 < z < 1.$$ Thus $f_Z(\frac 12) = 4f_Z(2)$, and not $f_Z(\frac 12) = f_Z(2)$ as you thought it should be.
Distribution of ratio between two independent uniform random variables
The right logic is that with independent $X, Y \sim U(0,1)$, $Z=\frac YX$ and $Z^{-1} =\frac XY$ have the same distribution and so for $0 < z < 1$ \begin{align} P\left\{\frac YX \leq z\right\} &= P\l
Distribution of ratio between two independent uniform random variables The right logic is that with independent $X, Y \sim U(0,1)$, $Z=\frac YX$ and $Z^{-1} =\frac XY$ have the same distribution and so for $0 < z < 1$ \begin{align} P\left\{\frac YX \leq z\right\} &= P\left\{\frac XY \leq z\right\}\\ &= P\left\{\frac YX \geq \frac 1z \right\}\\ \left.\left.F_{Z}\right(z\right) &= 1 - F_{Z}\left(\frac 1z\right) \end{align} where the equation with CDFs uses the fact that $\frac YX$ is a continuous random variable and so $P\{Z \geq a\} = P\{Z > a\} = 1-F_Z(a)$. Hence the pdf of $Z$ satisfies $$f_Z(z) = z^{-2}f_Z(z^{-1}), \quad 0 < z < 1.$$ Thus $f_Z(\frac 12) = 4f_Z(2)$, and not $f_Z(\frac 12) = f_Z(2)$ as you thought it should be.
Distribution of ratio between two independent uniform random variables The right logic is that with independent $X, Y \sim U(0,1)$, $Z=\frac YX$ and $Z^{-1} =\frac XY$ have the same distribution and so for $0 < z < 1$ \begin{align} P\left\{\frac YX \leq z\right\} &= P\l
11,326
Distribution of ratio between two independent uniform random variables
This distribution is symmetric--if you look at it the right way. The symmetry you have (correctly) observed is that $Y/X$ and $X/Y = 1/(Y/X)$ must be identically distributed. When working with ratios and powers, you are really working within the multiplicative group of the positive real numbers. The analog of the location invariant measure $d\lambda=dx$ on the additive real numbers $\mathbb{R}$ is the scale invariant measure $d\mu = dx/x$ on the multiplicative group $\mathbb{R}^{*}$ of positive real numbers. It has these desirable properties: $d\mu$ is invariant under the transformation $x\to ax$ for any positive constant $a$: $$d\mu(ax) = \frac{d(ax)}{ax} = \frac{dx}{x} = d\mu.$$ $d\mu$ is covariant under the transformation $x\to x^b$ for nonzero numbers $b$: $$d\mu(x^b) = \frac{d(x^b)}{x^b} = \frac{b x^{b-1} dx}{x^b} = b\frac{dx}{x} = b\, d\mu.$$ $d\mu$ is transformed into $d\lambda$ via the exponential: $$d\mu(e^x) = \frac{de^x}{e^x} = \frac{e^x dx}{e^x} = dx = d\lambda.$$ Likewise, $d\lambda$ is transformed back to $d\mu$ via the logarithm. (3) establishes an isomorphism between the measured groups $(\mathbb{R}, +, d\lambda)$ and $(\mathbb{R}^{*}, *, d\mu)$. The reflection $x \to -x$ on the additive space corresponds to the inversion $x \to 1/x$ on the multiplicative space, because $e^{-x} = 1/e^x$. Let's apply these observations by writing the probability element of $Z=Y/X$ in terms of $d\mu$ (understanding implicitly that $z \gt 0$) rather than $d\lambda$: $$f_Z(z)\,dz = g_Z(z)\,d\mu = \frac{1}{2}\begin{cases} 1\,dz = z\, d\mu, & \text{if } 0 \le z \le 1 \\ \frac{1}{z^2}dz = \frac{1}{z}\, d\mu, & \text{if } z > 1. \end{cases}$$ That is, the PDF with respect to the invariant measure $d\mu$ is $g_Z(z)$, proportional to $z$ when $0\lt z \le 1$ and to $1/z$ when $1 \le z$, close to what you had hoped. This is not a mere one-off trick. Understanding the role of $d\mu$ makes many formulas look simpler and more natural. For instance, the probability element of the Gamma function with parameter $k$, $x^{k-1}e^x\,dx$ becomes $x^k e^x d\mu$. It's easier to work with $d\mu$ than with $d\lambda$ when transforming $x$ by rescaling, taking powers, or exponentiating. The idea of an invariant measure on a group is far more general, too, and has applications in that area of statistics where problems exhibit some invariance under groups of transformations (such as changes of units of measure, rotations in higher dimensions, and so on).
Distribution of ratio between two independent uniform random variables
This distribution is symmetric--if you look at it the right way. The symmetry you have (correctly) observed is that $Y/X$ and $X/Y = 1/(Y/X)$ must be identically distributed. When working with ratios
Distribution of ratio between two independent uniform random variables This distribution is symmetric--if you look at it the right way. The symmetry you have (correctly) observed is that $Y/X$ and $X/Y = 1/(Y/X)$ must be identically distributed. When working with ratios and powers, you are really working within the multiplicative group of the positive real numbers. The analog of the location invariant measure $d\lambda=dx$ on the additive real numbers $\mathbb{R}$ is the scale invariant measure $d\mu = dx/x$ on the multiplicative group $\mathbb{R}^{*}$ of positive real numbers. It has these desirable properties: $d\mu$ is invariant under the transformation $x\to ax$ for any positive constant $a$: $$d\mu(ax) = \frac{d(ax)}{ax} = \frac{dx}{x} = d\mu.$$ $d\mu$ is covariant under the transformation $x\to x^b$ for nonzero numbers $b$: $$d\mu(x^b) = \frac{d(x^b)}{x^b} = \frac{b x^{b-1} dx}{x^b} = b\frac{dx}{x} = b\, d\mu.$$ $d\mu$ is transformed into $d\lambda$ via the exponential: $$d\mu(e^x) = \frac{de^x}{e^x} = \frac{e^x dx}{e^x} = dx = d\lambda.$$ Likewise, $d\lambda$ is transformed back to $d\mu$ via the logarithm. (3) establishes an isomorphism between the measured groups $(\mathbb{R}, +, d\lambda)$ and $(\mathbb{R}^{*}, *, d\mu)$. The reflection $x \to -x$ on the additive space corresponds to the inversion $x \to 1/x$ on the multiplicative space, because $e^{-x} = 1/e^x$. Let's apply these observations by writing the probability element of $Z=Y/X$ in terms of $d\mu$ (understanding implicitly that $z \gt 0$) rather than $d\lambda$: $$f_Z(z)\,dz = g_Z(z)\,d\mu = \frac{1}{2}\begin{cases} 1\,dz = z\, d\mu, & \text{if } 0 \le z \le 1 \\ \frac{1}{z^2}dz = \frac{1}{z}\, d\mu, & \text{if } z > 1. \end{cases}$$ That is, the PDF with respect to the invariant measure $d\mu$ is $g_Z(z)$, proportional to $z$ when $0\lt z \le 1$ and to $1/z$ when $1 \le z$, close to what you had hoped. This is not a mere one-off trick. Understanding the role of $d\mu$ makes many formulas look simpler and more natural. For instance, the probability element of the Gamma function with parameter $k$, $x^{k-1}e^x\,dx$ becomes $x^k e^x d\mu$. It's easier to work with $d\mu$ than with $d\lambda$ when transforming $x$ by rescaling, taking powers, or exponentiating. The idea of an invariant measure on a group is far more general, too, and has applications in that area of statistics where problems exhibit some invariance under groups of transformations (such as changes of units of measure, rotations in higher dimensions, and so on).
Distribution of ratio between two independent uniform random variables This distribution is symmetric--if you look at it the right way. The symmetry you have (correctly) observed is that $Y/X$ and $X/Y = 1/(Y/X)$ must be identically distributed. When working with ratios
11,327
Distribution of ratio between two independent uniform random variables
Method 1: Let $X_1\sim U(0,1)$ and $X_2\sim U(0,1)$. Since $X_1$ and $X_2$ are independent, $$f_{X_1,X_2}(x_1,x_2)=f_{X_1}(x_1).f_{X_2}(x_2)=1.$$ Define $Y_1=\frac{X_1}{X_2}$ and $Y_2=X_2$. It means that $Y_1=u_1(X_1,X_2)$ and $Y_2=u_2(X_1,X_2)$ where $u_1(x_1,x_2)=\frac{x_1}{x_2}$ and $u_2(x_1,x_2)=x_2$. Now, let's find $X_1,X_2$ in terms of $Y_1,Y_2$. We get: $$X_1=Y_1Y_2 \mbox{ and } X_2=Y_2.$$ In other words, $X_1=v_1(Y_1,Y_2)$ and $X_2=v_2(Y_2)$ where $v_1(y_1,y_2)=y_1y_2$ and $v_2(y_1,y_2)=y_2$. Calculate the Jacobian and we have $$J= \det\left[\begin{matrix}\frac{\partial v_1}{\partial y_1} & \frac{\partial v_1}{\partial y_2} \\ \frac{\partial v_2}{\partial y_1} & \frac{\partial v_2}{\partial y_2} \end{matrix}\right] =\det\left[\begin{matrix}y_2 & y_1 \\ 0 & 1 \end{matrix}\right]=y_2. $$ So we have $$f_{Y_1,Y_2}(y_1,y_2)=f_{X_1,X_2}(v_1(y_1,y_1),v_2(y_1,y_2)).|J| = y_2.$$ Now, we can calculate the marginal pdf of $Y_1$. Note that the region $$\{(x_1,x_2)|0<x_1<1,0<x_2<1\}$$ maps to the region $$\{(y_1,y_2)|y_1>0,y_2<\min\{1,1/y_1\}\}.$$ So we have: $$f_{Y_1}(y_1)=\int f_{Y_1,Y_2}(y_1,y_2)dy_2=\left\{\begin{matrix} \int_{0}^{1}y_2dy_2 & 0<y_1<1\\ \int_{0}^{\frac{1}{y_1}}y_2dy_2 & y_1>1\end{matrix}\right. = \left\{\begin{matrix} \frac{1}{2} & 0<y_1<1 \\ \frac{1}{2y_1^2} & y_1>1.\end{matrix}\right.$$ Method 2: Let $X_1\sim U(0,1)$ and $X_2\sim U(0,1)$. Since $X_1$ and $X_2$ are independent, $$f_{X_1,X_2}(x_1,x_2)=f_{X_1}(x_1).f_{X_2}(x_2)=1.$$ Let $Z=\frac{X_2}{X_1}$. We have $$F(z)=P(Z\le z) = P(\frac{X_2}{X_1} \le z) = P(X_2\le zX_1).$$ Note that if $0<z<1$, then the slope of the line $X_2=zX_1$ is less than 1 and this line is in region 1 (below the line $X_2=X_1$), otherwise it will be in region 2 (above the line $X_2=X_1$) (See the picture). So we have $$ F(z)= P(X_2\le zX_1)=\left\{ \begin{matrix} \int_{0}^{1}\int_{0}^{zx_1} 1dx_2dx_1 & 0<z<1 \\ \int_{0}^{1/z}\int_{0}^{zx_1} 1dx_2dx_1+\int_{1/z}^{1}\int_{0}^{1} 1dx_2dx_1 & z>1 \end{matrix}\right.$$ $$ =\left\{ \begin{matrix} \frac{1}{2}z & 0<z<1 \\ 1-\frac{1}{2z} & z>1 \end{matrix}\right.$$ So, the pdf is $$ f(z)=\left\{ \begin{matrix} \frac{1}{2} & 0<z<1 \\ \frac{1}{2z^2} & z>1 \end{matrix}\right.$$
Distribution of ratio between two independent uniform random variables
Method 1: Let $X_1\sim U(0,1)$ and $X_2\sim U(0,1)$. Since $X_1$ and $X_2$ are independent, $$f_{X_1,X_2}(x_1,x_2)=f_{X_1}(x_1).f_{X_2}(x_2)=1.$$ Define $Y_1=\frac{X_1}{X_2}$ and $Y_2=X_2$. It means t
Distribution of ratio between two independent uniform random variables Method 1: Let $X_1\sim U(0,1)$ and $X_2\sim U(0,1)$. Since $X_1$ and $X_2$ are independent, $$f_{X_1,X_2}(x_1,x_2)=f_{X_1}(x_1).f_{X_2}(x_2)=1.$$ Define $Y_1=\frac{X_1}{X_2}$ and $Y_2=X_2$. It means that $Y_1=u_1(X_1,X_2)$ and $Y_2=u_2(X_1,X_2)$ where $u_1(x_1,x_2)=\frac{x_1}{x_2}$ and $u_2(x_1,x_2)=x_2$. Now, let's find $X_1,X_2$ in terms of $Y_1,Y_2$. We get: $$X_1=Y_1Y_2 \mbox{ and } X_2=Y_2.$$ In other words, $X_1=v_1(Y_1,Y_2)$ and $X_2=v_2(Y_2)$ where $v_1(y_1,y_2)=y_1y_2$ and $v_2(y_1,y_2)=y_2$. Calculate the Jacobian and we have $$J= \det\left[\begin{matrix}\frac{\partial v_1}{\partial y_1} & \frac{\partial v_1}{\partial y_2} \\ \frac{\partial v_2}{\partial y_1} & \frac{\partial v_2}{\partial y_2} \end{matrix}\right] =\det\left[\begin{matrix}y_2 & y_1 \\ 0 & 1 \end{matrix}\right]=y_2. $$ So we have $$f_{Y_1,Y_2}(y_1,y_2)=f_{X_1,X_2}(v_1(y_1,y_1),v_2(y_1,y_2)).|J| = y_2.$$ Now, we can calculate the marginal pdf of $Y_1$. Note that the region $$\{(x_1,x_2)|0<x_1<1,0<x_2<1\}$$ maps to the region $$\{(y_1,y_2)|y_1>0,y_2<\min\{1,1/y_1\}\}.$$ So we have: $$f_{Y_1}(y_1)=\int f_{Y_1,Y_2}(y_1,y_2)dy_2=\left\{\begin{matrix} \int_{0}^{1}y_2dy_2 & 0<y_1<1\\ \int_{0}^{\frac{1}{y_1}}y_2dy_2 & y_1>1\end{matrix}\right. = \left\{\begin{matrix} \frac{1}{2} & 0<y_1<1 \\ \frac{1}{2y_1^2} & y_1>1.\end{matrix}\right.$$ Method 2: Let $X_1\sim U(0,1)$ and $X_2\sim U(0,1)$. Since $X_1$ and $X_2$ are independent, $$f_{X_1,X_2}(x_1,x_2)=f_{X_1}(x_1).f_{X_2}(x_2)=1.$$ Let $Z=\frac{X_2}{X_1}$. We have $$F(z)=P(Z\le z) = P(\frac{X_2}{X_1} \le z) = P(X_2\le zX_1).$$ Note that if $0<z<1$, then the slope of the line $X_2=zX_1$ is less than 1 and this line is in region 1 (below the line $X_2=X_1$), otherwise it will be in region 2 (above the line $X_2=X_1$) (See the picture). So we have $$ F(z)= P(X_2\le zX_1)=\left\{ \begin{matrix} \int_{0}^{1}\int_{0}^{zx_1} 1dx_2dx_1 & 0<z<1 \\ \int_{0}^{1/z}\int_{0}^{zx_1} 1dx_2dx_1+\int_{1/z}^{1}\int_{0}^{1} 1dx_2dx_1 & z>1 \end{matrix}\right.$$ $$ =\left\{ \begin{matrix} \frac{1}{2}z & 0<z<1 \\ 1-\frac{1}{2z} & z>1 \end{matrix}\right.$$ So, the pdf is $$ f(z)=\left\{ \begin{matrix} \frac{1}{2} & 0<z<1 \\ \frac{1}{2z^2} & z>1 \end{matrix}\right.$$
Distribution of ratio between two independent uniform random variables Method 1: Let $X_1\sim U(0,1)$ and $X_2\sim U(0,1)$. Since $X_1$ and $X_2$ are independent, $$f_{X_1,X_2}(x_1,x_2)=f_{X_1}(x_1).f_{X_2}(x_2)=1.$$ Define $Y_1=\frac{X_1}{X_2}$ and $Y_2=X_2$. It means t
11,328
Distribution of ratio between two independent uniform random variables
If you think geometrically... In the $X$-$Y$ plane, curves of constant $Z = Y/X$ are lines through the origin. ($Y/X$ is the slope.) One can read off the value of $Z$ from a line through the origin by finding its intersection with the line $X=1$. (If you've ever studied projective space: here $X$ is the homogenizing variable, so looking at values on the slice $X=1$ is a relatively natural thing to do.) Consider a small interval of $Z$s, $(a,b)$. This interval can also be discussed on the line $X=1$ as the line segment from $(1,a)$ to $(1,b)$. The set of lines through the origin passing through this interval forms a solid triangle in the square $(X,Y) \in U = [0,1]\times[0,1]$, which is the region we're actually interested in. If $0 \leq a < b \leq 1$, then the area of the triangle is $\frac{1}{2}(1-0)(b-a)$, so keeping the length of the interval constant and sliding it up and down the line $X=1$ (but not past $0$ or $1$), the area is the same, so the probability of picking an $(X,Y)$ in the triangle is constant, so the probability of picking a $Z$ in the interval is constant. However, for $b>1$, the boundary of the region $U$ turns away from the line $X = 1$ and the triangle is truncated. If $1 \leq a < b$, the projections down lines through the origin from $(1,a)$ and $(1,b)$ to the upper boundary of $U$ are to the points $(1/a,1)$ and $(1/b,1)$. The resulting area of the triangle is $\frac{1}{2}(\frac{1}{a} - \frac{1}{b})(1-0)$. From this we see the area is not uniform and as we slide $(a,b)$ further and further to the right, the probability of selecting a point in the triangle decreases to zero. Then the same algebra demonstrated in other answers finishes the problem. In particular, returning to the OP's last question, $f_Z(1/2)$ corresponds to a line that reaches $X=1$, but $f_Z(2)$ does not, so the desired symmetry does not hold.
Distribution of ratio between two independent uniform random variables
If you think geometrically... In the $X$-$Y$ plane, curves of constant $Z = Y/X$ are lines through the origin. ($Y/X$ is the slope.) One can read off the value of $Z$ from a line through the origin
Distribution of ratio between two independent uniform random variables If you think geometrically... In the $X$-$Y$ plane, curves of constant $Z = Y/X$ are lines through the origin. ($Y/X$ is the slope.) One can read off the value of $Z$ from a line through the origin by finding its intersection with the line $X=1$. (If you've ever studied projective space: here $X$ is the homogenizing variable, so looking at values on the slice $X=1$ is a relatively natural thing to do.) Consider a small interval of $Z$s, $(a,b)$. This interval can also be discussed on the line $X=1$ as the line segment from $(1,a)$ to $(1,b)$. The set of lines through the origin passing through this interval forms a solid triangle in the square $(X,Y) \in U = [0,1]\times[0,1]$, which is the region we're actually interested in. If $0 \leq a < b \leq 1$, then the area of the triangle is $\frac{1}{2}(1-0)(b-a)$, so keeping the length of the interval constant and sliding it up and down the line $X=1$ (but not past $0$ or $1$), the area is the same, so the probability of picking an $(X,Y)$ in the triangle is constant, so the probability of picking a $Z$ in the interval is constant. However, for $b>1$, the boundary of the region $U$ turns away from the line $X = 1$ and the triangle is truncated. If $1 \leq a < b$, the projections down lines through the origin from $(1,a)$ and $(1,b)$ to the upper boundary of $U$ are to the points $(1/a,1)$ and $(1/b,1)$. The resulting area of the triangle is $\frac{1}{2}(\frac{1}{a} - \frac{1}{b})(1-0)$. From this we see the area is not uniform and as we slide $(a,b)$ further and further to the right, the probability of selecting a point in the triangle decreases to zero. Then the same algebra demonstrated in other answers finishes the problem. In particular, returning to the OP's last question, $f_Z(1/2)$ corresponds to a line that reaches $X=1$, but $f_Z(2)$ does not, so the desired symmetry does not hold.
Distribution of ratio between two independent uniform random variables If you think geometrically... In the $X$-$Y$ plane, curves of constant $Z = Y/X$ are lines through the origin. ($Y/X$ is the slope.) One can read off the value of $Z$ from a line through the origin
11,329
Distribution of ratio between two independent uniform random variables
Just for the record, my intuition was totally wrong. We are talking about density, not probability. The right logic is to check that $$ \int_1^k f_Z(z) dz = \int_{1/k}^1 f_Z(z) = \frac{1}{2}(1 - \frac{1}{k}) $$, and this is indeed the case.
Distribution of ratio between two independent uniform random variables
Just for the record, my intuition was totally wrong. We are talking about density, not probability. The right logic is to check that $$ \int_1^k f_Z(z) dz = \int_{1/k}^1 f_Z(z) = \frac{1}{2}(1 - \frac
Distribution of ratio between two independent uniform random variables Just for the record, my intuition was totally wrong. We are talking about density, not probability. The right logic is to check that $$ \int_1^k f_Z(z) dz = \int_{1/k}^1 f_Z(z) = \frac{1}{2}(1 - \frac{1}{k}) $$, and this is indeed the case.
Distribution of ratio between two independent uniform random variables Just for the record, my intuition was totally wrong. We are talking about density, not probability. The right logic is to check that $$ \int_1^k f_Z(z) dz = \int_{1/k}^1 f_Z(z) = \frac{1}{2}(1 - \frac
11,330
Distribution of ratio between two independent uniform random variables
Yea the link Distribution of a ratio of uniforms: What is wrong? provides CDF of $Z=Y/X$. The PDF here is just derivative of the CDF. So the formula is correct. I think your problem lies in the assumption that you think Z is "symmetric" around 1. However this is not true. Intuitively Z should be a skewed distribution, for example it is useful to think when Y is a fixed number between $(0,1)$ and X is a number close to 0, thus the ratio would be going to infinity. So the symmetry of distribution is not true. I hope this help a bit.
Distribution of ratio between two independent uniform random variables
Yea the link Distribution of a ratio of uniforms: What is wrong? provides CDF of $Z=Y/X$. The PDF here is just derivative of the CDF. So the formula is correct. I think your problem lies in the assum
Distribution of ratio between two independent uniform random variables Yea the link Distribution of a ratio of uniforms: What is wrong? provides CDF of $Z=Y/X$. The PDF here is just derivative of the CDF. So the formula is correct. I think your problem lies in the assumption that you think Z is "symmetric" around 1. However this is not true. Intuitively Z should be a skewed distribution, for example it is useful to think when Y is a fixed number between $(0,1)$ and X is a number close to 0, thus the ratio would be going to infinity. So the symmetry of distribution is not true. I hope this help a bit.
Distribution of ratio between two independent uniform random variables Yea the link Distribution of a ratio of uniforms: What is wrong? provides CDF of $Z=Y/X$. The PDF here is just derivative of the CDF. So the formula is correct. I think your problem lies in the assum
11,331
Difference between Random Forests and Decision tree
You are right that the two concepts are similar. As is implied by the names "Tree" and "Forest," a Random Forest is essentially a collection of Decision Trees. A decision tree is built on an entire dataset, using all the features/variables of interest, whereas a random forest randomly selects observations/rows and specific features/variables to build multiple decision trees from and then averages the results. After a large number of trees are built using this method, each tree "votes" or chooses the class, and the class receiving the most votes by a simple majority is the "winner" or predicted class. There are of course some more detailed differences, but this is the main conceptual difference.
Difference between Random Forests and Decision tree
You are right that the two concepts are similar. As is implied by the names "Tree" and "Forest," a Random Forest is essentially a collection of Decision Trees. A decision tree is built on an entire
Difference between Random Forests and Decision tree You are right that the two concepts are similar. As is implied by the names "Tree" and "Forest," a Random Forest is essentially a collection of Decision Trees. A decision tree is built on an entire dataset, using all the features/variables of interest, whereas a random forest randomly selects observations/rows and specific features/variables to build multiple decision trees from and then averages the results. After a large number of trees are built using this method, each tree "votes" or chooses the class, and the class receiving the most votes by a simple majority is the "winner" or predicted class. There are of course some more detailed differences, but this is the main conceptual difference.
Difference between Random Forests and Decision tree You are right that the two concepts are similar. As is implied by the names "Tree" and "Forest," a Random Forest is essentially a collection of Decision Trees. A decision tree is built on an entire
11,332
Difference between Random Forests and Decision tree
When using a decision tree model on a given training dataset the accuracy keeps improving with more and more splits. You can easily overfit the data and doesn't know when you have crossed the line unless you are using cross validation (on training data set). The advantage of a simple decision tree model is easy to interpret, you know what variable and what value of that variable is used to split the data and predict outcome. A random forest is like a black box and works as mentioned in above answer. It's a forest you can build and control. You can specify the number of trees you want in your forest(n_estimators) and also you can specify max num of features to be used in each tree. But you cannot control the randomness, you cannot control which feature is part of which tree in the forest, you cannot control which data point is part of which tree. Accuracy keeps increasing as you increase the number of trees, but becomes constant at certain point. Unlike decision tree, it won't create highly biased model and reduces the variance. When to use to decision tree: When you want your model to be simple and explainable When you want non parametric model When you don't want to worry about feature selection or regularization or worry about multi-collinearity. You can overfit the tree and build a model if you are sure of validation or test data set is going to be subset of training data set or almost overlapping instead of unexpected. When to use random forest : When you don't bother much about interpreting the model but want better accuracy. Random forest will reduce variance part of error rather than bias part, so on a given training data set decision tree may be more accurate than a random forest. But on an unexpected inference data set, Random forest always wins in terms of accuracy.
Difference between Random Forests and Decision tree
When using a decision tree model on a given training dataset the accuracy keeps improving with more and more splits. You can easily overfit the data and doesn't know when you have crossed the line unl
Difference between Random Forests and Decision tree When using a decision tree model on a given training dataset the accuracy keeps improving with more and more splits. You can easily overfit the data and doesn't know when you have crossed the line unless you are using cross validation (on training data set). The advantage of a simple decision tree model is easy to interpret, you know what variable and what value of that variable is used to split the data and predict outcome. A random forest is like a black box and works as mentioned in above answer. It's a forest you can build and control. You can specify the number of trees you want in your forest(n_estimators) and also you can specify max num of features to be used in each tree. But you cannot control the randomness, you cannot control which feature is part of which tree in the forest, you cannot control which data point is part of which tree. Accuracy keeps increasing as you increase the number of trees, but becomes constant at certain point. Unlike decision tree, it won't create highly biased model and reduces the variance. When to use to decision tree: When you want your model to be simple and explainable When you want non parametric model When you don't want to worry about feature selection or regularization or worry about multi-collinearity. You can overfit the tree and build a model if you are sure of validation or test data set is going to be subset of training data set or almost overlapping instead of unexpected. When to use random forest : When you don't bother much about interpreting the model but want better accuracy. Random forest will reduce variance part of error rather than bias part, so on a given training data set decision tree may be more accurate than a random forest. But on an unexpected inference data set, Random forest always wins in terms of accuracy.
Difference between Random Forests and Decision tree When using a decision tree model on a given training dataset the accuracy keeps improving with more and more splits. You can easily overfit the data and doesn't know when you have crossed the line unl
11,333
Difference between Random Forests and Decision tree
The random forest algorithm is a type of ensemble learning algorithm. This means that it uses multiple decision trees to make predictions. The advantage of using an ensemble algorithm is that it can reduce the variance in the predictions, making them more accurate. The random forest algorithm achieves this by averaging the predictions of the individual decision trees. The decision tree algorithm is a type of supervised learning algorithm. This means that it requires a training dataset in order to learn how to make predictions. The advantage of using a supervised learning algorithm is that it can learn complex patterns in the data. The disadvantage of using a supervised learning algorithm is that it takes longer to train than an unsupervised learning algorithm.
Difference between Random Forests and Decision tree
The random forest algorithm is a type of ensemble learning algorithm. This means that it uses multiple decision trees to make predictions. The advantage of using an ensemble algorithm is that it can r
Difference between Random Forests and Decision tree The random forest algorithm is a type of ensemble learning algorithm. This means that it uses multiple decision trees to make predictions. The advantage of using an ensemble algorithm is that it can reduce the variance in the predictions, making them more accurate. The random forest algorithm achieves this by averaging the predictions of the individual decision trees. The decision tree algorithm is a type of supervised learning algorithm. This means that it requires a training dataset in order to learn how to make predictions. The advantage of using a supervised learning algorithm is that it can learn complex patterns in the data. The disadvantage of using a supervised learning algorithm is that it takes longer to train than an unsupervised learning algorithm.
Difference between Random Forests and Decision tree The random forest algorithm is a type of ensemble learning algorithm. This means that it uses multiple decision trees to make predictions. The advantage of using an ensemble algorithm is that it can r
11,334
Evaluate definite interval of normal distribution
It depends on exactly what you are looking for. Below are some brief details and references. Much of the literature for approximations centers around the function $$ Q(x) = \int_x^\infty \frac{1}{\sqrt{2\pi}} e^{-\frac{u^2}{2}} \, \mathrm{d}u $$ for $x > 0$. This is because the function you provided can be decomposed as a simple difference of the function above (possibly adjusted by a constant). This function is referred to by many names, including "upper-tail of the normal distribution", "right normal integral", and "Gaussian $Q$-function", to name a few. You'll also see approximations to Mills' ratio, which is $$ R(x) = \frac{Q(x)}{\varphi(x)} $$ where $\varphi(x) = (2\pi)^{-1/2} e^{-x^2 / 2}$ is the Gaussian pdf. Here I list some references for various purposes that you might be interested in. Computational The de-facto standard for computing the $Q$-function or the related complementary error function is W. J. Cody, Rational Chebyshev Approximations for the Error Function, Math. Comp., 1969, pp. 631--637. Every (self-respecting) implementation uses this paper. (MATLAB, R, etc.) "Simple" Approximations Abramowitz and Stegun have one based on a polynomial expansion of a transformation of the input. Some people use it as a "high-precision" approximation. I don't like it for that purpose since it behaves badly around zero. For example, their approximation does not yield $\hat{Q}(0) = 1/2$, which I think is a big no-no. Sometimes bad things happen because of this. Borjesson and Sundberg give a simple approximation which works pretty well for most applications where one only requires a few digits of precision. The absolute relative error is never worse than 1%, which is quite good considering its simplicity. The basic approximation is $$ \hat{Q}(x) = \frac{1}{(1-a) x + a \sqrt{x^2 + b}} \varphi(x) $$ and their preferred choices of the constants are $a = 0.339$ and $b = 5.51$. That reference is P. O. Borjesson and C. E. Sundberg. Simple approximations of the error function Q(x) for communications applications. IEEE Trans. Commun., COM-27(3):639–643, March 1979. Here is a plot of its absolute relative error. The electrical-engineering literature is awash with various such approximations and seem to take an overly intense interest in them. Many of them are poor though or expand to very strange and convoluted expressions. You might also look at W. Bryc. A uniform approximation to the right normal integral. Applied Mathematics and Computation, 127(2-3):365–374, April 2002. Laplace's continued fraction Laplace has a beautiful continued fraction which yields successive upper and lower bounds for every value of $x > 0$. It is, in terms of Mills' ratio, $$ R(x) = \frac{1}{x+}\frac{1}{x+}\frac{2}{x+}\frac{3}{x+}\cdots , $$ where the notation I've used is fairly standard for a continued fraction, i.e., $1/(x+1/(x+2/(x+3/(x+\cdots))))$. This expression doesn't converge very fast for small $x$, though, and it diverges at $x = 0$. This continued fraction actually yields many of the "simple" bounds on $Q(x)$ that were "rediscovered" in the mid-to-late 1900s. It's easy to see that for a continued fraction in "standard" form (i.e., composed of positive integer coefficients), truncating the fraction at odd (even) terms gives an upper (lower) bound. Hence, Laplace tells us immediately that $$ \frac{x}{x^2 + 1} < R(x) < \frac{1}{x} \>, $$ both of which are bounds that were "rediscovered" in the mid-1900's. In terms of the $Q$-function, this is equivalent to $$ \frac{x}{x^2 + 1} \varphi(x) < Q(x) < \frac{1}{x} \varphi(x) . $$ An alternative proof of this using simple integration by parts can be found in S. Resnick, Adventures in Stochastic Processes, Birkhauser, 1992, in Chapter 6 (Brownian motion). The absolute relative error of these bounds is no worse than $x^{-2}$, as shown in this related answer. Notice, in particular, that the inequalities above immediately imply that $Q(x) \sim \varphi(x)/x$. This fact can be established using L'Hopital's rule as well. This also helps explain the choice of the functional form of the Borjesson-Sundberg approximation. Any choice of $a \in [0,1]$ maintains the asymptotic equivalence as $x \to \infty$. The parameter $b$ serves as a "continuity correction" near zero. Here is a plot of the $Q$-function and the two Laplace bounds. C-I. C. Lee has a paper from the early 1990's that does a "correction" for small values of $x$. See C-I. C. Lee. On Laplace continued fraction for the normal integral. Ann. Inst. Statist. Math., 44(1):107–120, March 1992. Durrett's Probability: Theory and Examples provides the classical upper and lower bounds on $Q(x)$ on pages 6–7 of the 3rd edition. They're meant for larger values of $x$ (say, $x > 3$) and are asymptotically tight. Hopefully this will get you started. If you have a more specific interest, I might be able to point you somewhere.
Evaluate definite interval of normal distribution
It depends on exactly what you are looking for. Below are some brief details and references. Much of the literature for approximations centers around the function $$ Q(x) = \int_x^\infty \frac{1}{\sqr
Evaluate definite interval of normal distribution It depends on exactly what you are looking for. Below are some brief details and references. Much of the literature for approximations centers around the function $$ Q(x) = \int_x^\infty \frac{1}{\sqrt{2\pi}} e^{-\frac{u^2}{2}} \, \mathrm{d}u $$ for $x > 0$. This is because the function you provided can be decomposed as a simple difference of the function above (possibly adjusted by a constant). This function is referred to by many names, including "upper-tail of the normal distribution", "right normal integral", and "Gaussian $Q$-function", to name a few. You'll also see approximations to Mills' ratio, which is $$ R(x) = \frac{Q(x)}{\varphi(x)} $$ where $\varphi(x) = (2\pi)^{-1/2} e^{-x^2 / 2}$ is the Gaussian pdf. Here I list some references for various purposes that you might be interested in. Computational The de-facto standard for computing the $Q$-function or the related complementary error function is W. J. Cody, Rational Chebyshev Approximations for the Error Function, Math. Comp., 1969, pp. 631--637. Every (self-respecting) implementation uses this paper. (MATLAB, R, etc.) "Simple" Approximations Abramowitz and Stegun have one based on a polynomial expansion of a transformation of the input. Some people use it as a "high-precision" approximation. I don't like it for that purpose since it behaves badly around zero. For example, their approximation does not yield $\hat{Q}(0) = 1/2$, which I think is a big no-no. Sometimes bad things happen because of this. Borjesson and Sundberg give a simple approximation which works pretty well for most applications where one only requires a few digits of precision. The absolute relative error is never worse than 1%, which is quite good considering its simplicity. The basic approximation is $$ \hat{Q}(x) = \frac{1}{(1-a) x + a \sqrt{x^2 + b}} \varphi(x) $$ and their preferred choices of the constants are $a = 0.339$ and $b = 5.51$. That reference is P. O. Borjesson and C. E. Sundberg. Simple approximations of the error function Q(x) for communications applications. IEEE Trans. Commun., COM-27(3):639–643, March 1979. Here is a plot of its absolute relative error. The electrical-engineering literature is awash with various such approximations and seem to take an overly intense interest in them. Many of them are poor though or expand to very strange and convoluted expressions. You might also look at W. Bryc. A uniform approximation to the right normal integral. Applied Mathematics and Computation, 127(2-3):365–374, April 2002. Laplace's continued fraction Laplace has a beautiful continued fraction which yields successive upper and lower bounds for every value of $x > 0$. It is, in terms of Mills' ratio, $$ R(x) = \frac{1}{x+}\frac{1}{x+}\frac{2}{x+}\frac{3}{x+}\cdots , $$ where the notation I've used is fairly standard for a continued fraction, i.e., $1/(x+1/(x+2/(x+3/(x+\cdots))))$. This expression doesn't converge very fast for small $x$, though, and it diverges at $x = 0$. This continued fraction actually yields many of the "simple" bounds on $Q(x)$ that were "rediscovered" in the mid-to-late 1900s. It's easy to see that for a continued fraction in "standard" form (i.e., composed of positive integer coefficients), truncating the fraction at odd (even) terms gives an upper (lower) bound. Hence, Laplace tells us immediately that $$ \frac{x}{x^2 + 1} < R(x) < \frac{1}{x} \>, $$ both of which are bounds that were "rediscovered" in the mid-1900's. In terms of the $Q$-function, this is equivalent to $$ \frac{x}{x^2 + 1} \varphi(x) < Q(x) < \frac{1}{x} \varphi(x) . $$ An alternative proof of this using simple integration by parts can be found in S. Resnick, Adventures in Stochastic Processes, Birkhauser, 1992, in Chapter 6 (Brownian motion). The absolute relative error of these bounds is no worse than $x^{-2}$, as shown in this related answer. Notice, in particular, that the inequalities above immediately imply that $Q(x) \sim \varphi(x)/x$. This fact can be established using L'Hopital's rule as well. This also helps explain the choice of the functional form of the Borjesson-Sundberg approximation. Any choice of $a \in [0,1]$ maintains the asymptotic equivalence as $x \to \infty$. The parameter $b$ serves as a "continuity correction" near zero. Here is a plot of the $Q$-function and the two Laplace bounds. C-I. C. Lee has a paper from the early 1990's that does a "correction" for small values of $x$. See C-I. C. Lee. On Laplace continued fraction for the normal integral. Ann. Inst. Statist. Math., 44(1):107–120, March 1992. Durrett's Probability: Theory and Examples provides the classical upper and lower bounds on $Q(x)$ on pages 6–7 of the 3rd edition. They're meant for larger values of $x$ (say, $x > 3$) and are asymptotically tight. Hopefully this will get you started. If you have a more specific interest, I might be able to point you somewhere.
Evaluate definite interval of normal distribution It depends on exactly what you are looking for. Below are some brief details and references. Much of the literature for approximations centers around the function $$ Q(x) = \int_x^\infty \frac{1}{\sqr
11,335
Evaluate definite interval of normal distribution
I suppose I'm too late the hero, but I wanted to comment on cardinal's post, and this comment became too big for its intended box. For this answer, I'm assuming $x >0$; appropriate reflection formulae can be used for negative $x$. I'm more used to dealing with the error function $\mathrm{erf}(x)$ myself, but I'll try to recast what I know in terms of Mills's ratio $R(x)$ (as defined in cardinal's answer). There are in fact alternative ways for computing the (complementary) error function apart from using Chebyshev approximations. Since the use of a Chebyshev approximation requires the storage of not a few coefficients, these methods might have an edge if array structures are a bit costly in your computing environment (you could inline the coefficients, but the resulting code would probably look like a baroque mess). For "small" $|x|$, Abramowitz and Stegun give a nicely behaved series (at least better behaved than the usual Maclaurin series): $$R(x)=\sqrt{\frac{\pi}{2}}\exp\left(\frac{x^2}{2}\right)-x\sum_{j=0}^\infty\frac{2^j j!}{(2j+1)!}x^{2j}$$ (adapted from formula 7.1.6) Note that the coefficients of $x^{2j}$ in the series $c_j=\frac{2^j j!}{(2j+1)!}$ can be computed by starting with $c_0=1$ and then using the recursion formula $c_{j+1}=\frac{c_j}{2j+3}$. This is convenient when implementing the series as a summation loop. cardinal gave the Laplacian continued fraction as a way to bound Mills's ratio for large $|x|$; what is not as well-known is that the continued fraction is also useful for numerical evaluation. Lentz, Thompson and Barnett derived an algorithm for numerically evaluating a continued fraction as an infinite product, which is more efficient than the usual approach of computing a continued fraction "backwards". Instead of displaying the general algorithm, I'll show how it specializes to the computation of Mills's ratio: $\displaystyle Y_0=x,\,C_0=Y_0,\,D_0=0$ $\text{repeat for }j=1,2,\dots$ $$D_j=\frac1{x+jD_{j-1}}$$ $$C_j=x+\frac{j}{C_{j-1}}$$ $$H_j=C_j D_j$$ $$Y_j=H_j Y_{j-1}$$ $\text{until }|H_j-1| < \text{tol}$ $\displaystyle R(x)=\frac1{Y_j}$ where $\text{tol}$ determines the accuracy. The CF is useful where the previously mentioned series starts to converge slowly; you will have to experiment with determining the appropriate "break point" to switch from the series to the CF in your computing environment. There is also the alternative of using an asymptotic series instead of the Laplacian CF, but my experience is that the Laplacian CF is good enough for most applications. Finally, if you don't need to compute the (complementary) error function very accurately (i.e., to only a few significant digits), there are compact approximations due to Serge Winitzki. Here is one of them: $$R(x)\approx \frac{\sqrt{2\pi}+x(\pi-2)}{2+x\sqrt{2\pi}+x^2(\pi-2)}$$ This approximation has a maximum relative error of $1.84\times 10^{-2}$ and becomes more accurate as $x$ increases.
Evaluate definite interval of normal distribution
I suppose I'm too late the hero, but I wanted to comment on cardinal's post, and this comment became too big for its intended box. For this answer, I'm assuming $x >0$; appropriate reflection formulae
Evaluate definite interval of normal distribution I suppose I'm too late the hero, but I wanted to comment on cardinal's post, and this comment became too big for its intended box. For this answer, I'm assuming $x >0$; appropriate reflection formulae can be used for negative $x$. I'm more used to dealing with the error function $\mathrm{erf}(x)$ myself, but I'll try to recast what I know in terms of Mills's ratio $R(x)$ (as defined in cardinal's answer). There are in fact alternative ways for computing the (complementary) error function apart from using Chebyshev approximations. Since the use of a Chebyshev approximation requires the storage of not a few coefficients, these methods might have an edge if array structures are a bit costly in your computing environment (you could inline the coefficients, but the resulting code would probably look like a baroque mess). For "small" $|x|$, Abramowitz and Stegun give a nicely behaved series (at least better behaved than the usual Maclaurin series): $$R(x)=\sqrt{\frac{\pi}{2}}\exp\left(\frac{x^2}{2}\right)-x\sum_{j=0}^\infty\frac{2^j j!}{(2j+1)!}x^{2j}$$ (adapted from formula 7.1.6) Note that the coefficients of $x^{2j}$ in the series $c_j=\frac{2^j j!}{(2j+1)!}$ can be computed by starting with $c_0=1$ and then using the recursion formula $c_{j+1}=\frac{c_j}{2j+3}$. This is convenient when implementing the series as a summation loop. cardinal gave the Laplacian continued fraction as a way to bound Mills's ratio for large $|x|$; what is not as well-known is that the continued fraction is also useful for numerical evaluation. Lentz, Thompson and Barnett derived an algorithm for numerically evaluating a continued fraction as an infinite product, which is more efficient than the usual approach of computing a continued fraction "backwards". Instead of displaying the general algorithm, I'll show how it specializes to the computation of Mills's ratio: $\displaystyle Y_0=x,\,C_0=Y_0,\,D_0=0$ $\text{repeat for }j=1,2,\dots$ $$D_j=\frac1{x+jD_{j-1}}$$ $$C_j=x+\frac{j}{C_{j-1}}$$ $$H_j=C_j D_j$$ $$Y_j=H_j Y_{j-1}$$ $\text{until }|H_j-1| < \text{tol}$ $\displaystyle R(x)=\frac1{Y_j}$ where $\text{tol}$ determines the accuracy. The CF is useful where the previously mentioned series starts to converge slowly; you will have to experiment with determining the appropriate "break point" to switch from the series to the CF in your computing environment. There is also the alternative of using an asymptotic series instead of the Laplacian CF, but my experience is that the Laplacian CF is good enough for most applications. Finally, if you don't need to compute the (complementary) error function very accurately (i.e., to only a few significant digits), there are compact approximations due to Serge Winitzki. Here is one of them: $$R(x)\approx \frac{\sqrt{2\pi}+x(\pi-2)}{2+x\sqrt{2\pi}+x^2(\pi-2)}$$ This approximation has a maximum relative error of $1.84\times 10^{-2}$ and becomes more accurate as $x$ increases.
Evaluate definite interval of normal distribution I suppose I'm too late the hero, but I wanted to comment on cardinal's post, and this comment became too big for its intended box. For this answer, I'm assuming $x >0$; appropriate reflection formulae
11,336
Evaluate definite interval of normal distribution
(This reply originally appeared in response to a similar question, subsequently closed as a duplicate. The O.P. only wanted "an" implementation of the Gaussian integral, not necessarily "state of the art." In his comments it became apparent that a relatively simple, short implementation would be preferred.) As comments point out, you need to integrate the PDF. There are many ways to perform the integral. Long ago, when computations were slow and expensive, David Hill worked out an approximation using simple arithmetic (rational functions and an exponentiation). It has double precision accuracy for typical arguments (between $-8.5$ and $+8.5$, approximately). In 1973 he published a Fortran version in Applied Statistics called ALNORM.F. Over the years I have ported this to various environments which did not have a Normal (Gaussian) integral or which had suspect ones (such as Excel). A MatLab version (with appropriate attributions) is available at http://people.sc.fsu.edu/~jburkardt/m_src/asa005/alnorm.m. A completely undocumented version of the original Fortran code appears on a "Koders Code Search" (sic) site. Many years ago I ported this to AWK. This version may be more congenial for the modern developer to port due to its C-like (rather than Fortran) syntax and some additional comments I inserted when developing and testing it, because I needed to enhance its accuracy. It appears below. For those without much experience porting scientific/math/stats code, some words of advice: one single typographical mistake can create serious errors that might not be easily detectable. (Trust me on this, I've made lots of them.) Always, always create a careful and exhaustive test. Because the normal integral/Gaussian integral/error function is available in so many tables and so much software, it's simple and fast to tabulate a huge number of values of your ported function and systematically compare (i.e., with the computer, not by eye) the values to correct ones. You can see such a test at the beginning of my code: it produces a table of values in -8.5:8.5 (by 0.1) which can be piped (via STDOUT) to another program for systematic checking. Another testing approach--for those with enough numerical analysis background to know how to estimate expected errors--would be to numerically differentiate the values and compare them to the PDF (which is readily computed). By the way: this code is only for the case with a mean of $0$ and unit standard deviation ("sigma"). But that's all one needs: to integrate from $-\infty$ to $x$ when the mean is $\mu$ and the SD is $\sigma$, just compute $z = (x-\mu)/\sigma$ and apply alnorm to it. Edit I tested a port of alnorm to Mathematica, which computes the values to arbitrary precision. To compare the results, here is a plot of the natural log of the ratios of upper tail values $1 - \Phi(z)$ with $z\ge 1$. (A positive relative error means alnorm is too large.) The values are always accurate to $4 \times 10^{-11}$ relative to the vanishingly small tail probabilities. You can see where the calculation switches to an asymptotic formula (at $z=16$) and it is evident that this formula becomes extremely accurate as $z$ increases. The plot stops at $z=\sqrt(2\times 708) \approx 37.6$ because here is where double-precision exponentiation begins underflowing. For example, alnorm[-6.0] returns $9.865\ 876\ 450\ 315E-10$ while the true value, equal to $\frac{1}{2}\text{erfc}(3\sqrt{2})$, is approximately $9.865\ 876\ 450\ 377E-10$, first differing in the twelfth decimal digit. NB As part of this edit, I changed UPPER_TAIL_IS_ZERO from 15. to 16. in the code: it makes the result a tiny bit more accurate for $Z$ between $15$ and $16$. (End of edit.) #----------------------------------------------------------------------# # ALNORM.AWK # Compute values of the cumulative normal probability function. # From G. Dallal's STAT-SAK (Fortran code). # Additional precision using asymptotic expression added 7/8/92. #----------------------------------------------------------------------# BEGIN { for (i=-85; i<=85; i++) { x = i/10 p = alnorm(x, 0) printf("%3.1f %12.10f\n", x, p) } exit } function alnorm(z,up, y,aln,w) { # # ALGORITHM AS 66 APPL. STATIST. (1973) VOL.22, NO.3: # Hill, I.D. (1973). Algorithm AS 66. The normal integral. # Appl. Statist.,22,424-427. # # Evaluates the tail area of the standard normal curve from # z to infinity if up, or from -infinity to z if not up. # # LOWER_TAIL_IS_ONE, UPPER_TAIL_IS_ZERO, and EXP_MIN_ARG # must be set to suit this computer and compiler. LOWER_TAIL_IS_ONE = 8.5 # I.e., alnorm(8.5,0) = .999999999999+ UPPER_TAIL_IS_ZERO = 16.0 # Changes to power series expression FORMULA_BREAK = 1.28 # Changes cont. fraction coefficients EXP_MIN_ARG = -708 # I.e., exp(-708) is essentially true 0 if (z < 0.0) { up = !up z = -z } if ((z <= LOWER_TAIL_IS_ONE) || (up && z <= UPPER_TAIL_IS_ZERO)) { y = 0.5 * z * z if (z > FORMULA_BREAK) { if (-y > EXP_MIN_ARG) { aln = .398942280385 * exp(-y) / \ (z - 3.8052E-8 + 1.00000615302 / \ (z + 3.98064794E-4 + 1.98615381364 / \ (z - 0.151679116635 + 5.29330324926 / \ (z + 4.8385912808 - 15.1508972451 / \ (z + 0.742380924027 + 30.789933034 / \ (z + 3.99019417011)))))) } else { aln = 0.0 } } else { aln = 0.5 - z * (0.398942280444 - 0.399903438504 * y / \ (y + 5.75885480458 - 29.8213557808 / \ (y + 2.62433121679 + 48.6959930692 / \ (y + 5.92885724438)))) } } else { if (up) { # 7/8/92 # Uses asymptotic expansion for exp(-z*z/2)/alnorm(z) # Agrees with continued fraction to 11 s.f. when z >= 15 # and coefficients through 706 are used. y = -0.5*z*z if (y > EXP_MIN_ARG) { w = -0.5/y # 1/z^2 aln = 0.3989422804014327*exp(y)/ \ (z*(1 + w*(1 + w*(-2 + w*(10 + w*(-74 + w*706)))))) # Next coefficients would be -8162, 110410 } else { aln = 0.0 } } else { aln = 0.0 } } return up ? aln : 1.0 - aln } ### end of file ###
Evaluate definite interval of normal distribution
(This reply originally appeared in response to a similar question, subsequently closed as a duplicate. The O.P. only wanted "an" implementation of the Gaussian integral, not necessarily "state of the
Evaluate definite interval of normal distribution (This reply originally appeared in response to a similar question, subsequently closed as a duplicate. The O.P. only wanted "an" implementation of the Gaussian integral, not necessarily "state of the art." In his comments it became apparent that a relatively simple, short implementation would be preferred.) As comments point out, you need to integrate the PDF. There are many ways to perform the integral. Long ago, when computations were slow and expensive, David Hill worked out an approximation using simple arithmetic (rational functions and an exponentiation). It has double precision accuracy for typical arguments (between $-8.5$ and $+8.5$, approximately). In 1973 he published a Fortran version in Applied Statistics called ALNORM.F. Over the years I have ported this to various environments which did not have a Normal (Gaussian) integral or which had suspect ones (such as Excel). A MatLab version (with appropriate attributions) is available at http://people.sc.fsu.edu/~jburkardt/m_src/asa005/alnorm.m. A completely undocumented version of the original Fortran code appears on a "Koders Code Search" (sic) site. Many years ago I ported this to AWK. This version may be more congenial for the modern developer to port due to its C-like (rather than Fortran) syntax and some additional comments I inserted when developing and testing it, because I needed to enhance its accuracy. It appears below. For those without much experience porting scientific/math/stats code, some words of advice: one single typographical mistake can create serious errors that might not be easily detectable. (Trust me on this, I've made lots of them.) Always, always create a careful and exhaustive test. Because the normal integral/Gaussian integral/error function is available in so many tables and so much software, it's simple and fast to tabulate a huge number of values of your ported function and systematically compare (i.e., with the computer, not by eye) the values to correct ones. You can see such a test at the beginning of my code: it produces a table of values in -8.5:8.5 (by 0.1) which can be piped (via STDOUT) to another program for systematic checking. Another testing approach--for those with enough numerical analysis background to know how to estimate expected errors--would be to numerically differentiate the values and compare them to the PDF (which is readily computed). By the way: this code is only for the case with a mean of $0$ and unit standard deviation ("sigma"). But that's all one needs: to integrate from $-\infty$ to $x$ when the mean is $\mu$ and the SD is $\sigma$, just compute $z = (x-\mu)/\sigma$ and apply alnorm to it. Edit I tested a port of alnorm to Mathematica, which computes the values to arbitrary precision. To compare the results, here is a plot of the natural log of the ratios of upper tail values $1 - \Phi(z)$ with $z\ge 1$. (A positive relative error means alnorm is too large.) The values are always accurate to $4 \times 10^{-11}$ relative to the vanishingly small tail probabilities. You can see where the calculation switches to an asymptotic formula (at $z=16$) and it is evident that this formula becomes extremely accurate as $z$ increases. The plot stops at $z=\sqrt(2\times 708) \approx 37.6$ because here is where double-precision exponentiation begins underflowing. For example, alnorm[-6.0] returns $9.865\ 876\ 450\ 315E-10$ while the true value, equal to $\frac{1}{2}\text{erfc}(3\sqrt{2})$, is approximately $9.865\ 876\ 450\ 377E-10$, first differing in the twelfth decimal digit. NB As part of this edit, I changed UPPER_TAIL_IS_ZERO from 15. to 16. in the code: it makes the result a tiny bit more accurate for $Z$ between $15$ and $16$. (End of edit.) #----------------------------------------------------------------------# # ALNORM.AWK # Compute values of the cumulative normal probability function. # From G. Dallal's STAT-SAK (Fortran code). # Additional precision using asymptotic expression added 7/8/92. #----------------------------------------------------------------------# BEGIN { for (i=-85; i<=85; i++) { x = i/10 p = alnorm(x, 0) printf("%3.1f %12.10f\n", x, p) } exit } function alnorm(z,up, y,aln,w) { # # ALGORITHM AS 66 APPL. STATIST. (1973) VOL.22, NO.3: # Hill, I.D. (1973). Algorithm AS 66. The normal integral. # Appl. Statist.,22,424-427. # # Evaluates the tail area of the standard normal curve from # z to infinity if up, or from -infinity to z if not up. # # LOWER_TAIL_IS_ONE, UPPER_TAIL_IS_ZERO, and EXP_MIN_ARG # must be set to suit this computer and compiler. LOWER_TAIL_IS_ONE = 8.5 # I.e., alnorm(8.5,0) = .999999999999+ UPPER_TAIL_IS_ZERO = 16.0 # Changes to power series expression FORMULA_BREAK = 1.28 # Changes cont. fraction coefficients EXP_MIN_ARG = -708 # I.e., exp(-708) is essentially true 0 if (z < 0.0) { up = !up z = -z } if ((z <= LOWER_TAIL_IS_ONE) || (up && z <= UPPER_TAIL_IS_ZERO)) { y = 0.5 * z * z if (z > FORMULA_BREAK) { if (-y > EXP_MIN_ARG) { aln = .398942280385 * exp(-y) / \ (z - 3.8052E-8 + 1.00000615302 / \ (z + 3.98064794E-4 + 1.98615381364 / \ (z - 0.151679116635 + 5.29330324926 / \ (z + 4.8385912808 - 15.1508972451 / \ (z + 0.742380924027 + 30.789933034 / \ (z + 3.99019417011)))))) } else { aln = 0.0 } } else { aln = 0.5 - z * (0.398942280444 - 0.399903438504 * y / \ (y + 5.75885480458 - 29.8213557808 / \ (y + 2.62433121679 + 48.6959930692 / \ (y + 5.92885724438)))) } } else { if (up) { # 7/8/92 # Uses asymptotic expansion for exp(-z*z/2)/alnorm(z) # Agrees with continued fraction to 11 s.f. when z >= 15 # and coefficients through 706 are used. y = -0.5*z*z if (y > EXP_MIN_ARG) { w = -0.5/y # 1/z^2 aln = 0.3989422804014327*exp(y)/ \ (z*(1 + w*(1 + w*(-2 + w*(10 + w*(-74 + w*706)))))) # Next coefficients would be -8162, 110410 } else { aln = 0.0 } } else { aln = 0.0 } } return up ? aln : 1.0 - aln } ### end of file ###
Evaluate definite interval of normal distribution (This reply originally appeared in response to a similar question, subsequently closed as a duplicate. The O.P. only wanted "an" implementation of the Gaussian integral, not necessarily "state of the
11,337
Distribution of the maximum of two correlated normal variables
According to Nadarajah and Kotz, 2008, Exact Distribution of the Max/Min of Two Gaussian Random Variables, the PDF of $X = \max(X_1, X_2)$ appears to be $$f(x) = 2 \cdot \phi(x) \cdot \Phi\left( \frac{1 - r}{\sqrt{1 - r^2}} x\right),$$ where $\phi$ is the PDF and $\Phi$ is the CDF of the standard normal distribution. $\hskip2in$
Distribution of the maximum of two correlated normal variables
According to Nadarajah and Kotz, 2008, Exact Distribution of the Max/Min of Two Gaussian Random Variables, the PDF of $X = \max(X_1, X_2)$ appears to be $$f(x) = 2 \cdot \phi(x) \cdot \Phi\left( \frac
Distribution of the maximum of two correlated normal variables According to Nadarajah and Kotz, 2008, Exact Distribution of the Max/Min of Two Gaussian Random Variables, the PDF of $X = \max(X_1, X_2)$ appears to be $$f(x) = 2 \cdot \phi(x) \cdot \Phi\left( \frac{1 - r}{\sqrt{1 - r^2}} x\right),$$ where $\phi$ is the PDF and $\Phi$ is the CDF of the standard normal distribution. $\hskip2in$
Distribution of the maximum of two correlated normal variables According to Nadarajah and Kotz, 2008, Exact Distribution of the Max/Min of Two Gaussian Random Variables, the PDF of $X = \max(X_1, X_2)$ appears to be $$f(x) = 2 \cdot \phi(x) \cdot \Phi\left( \frac
11,338
Distribution of the maximum of two correlated normal variables
Let $f_\rho$ be the bivariate Normal PDF for $(X,Y)$ with standard marginals and correlation $\rho$. The CDF of the maximum is, by definition, $$\Pr(\max(X, Y)\le z) = \Pr(X\le z,\ Y\le z) = \int_{-\infty}^z\int_{-\infty}^z f_\rho(x,y)dy dx.$$ The bivariate Normal PDF is symmetric (via reflection) around the diagonal. Thus, increasing $z$ to $z+dz$ adds two strips of equivalent probability to the original semi-infinite square: the infinitesimally thick upper one is $(-\infty, z]\times (z, z+dz]$ while its reflected counterpart, the right-hand strip, is $(z, z+dz]\times (-\infty, z]$. The probability density of the right-hand strip is the density of $X$ at $z$ times the total conditional probability that $Y$ is in the strip, $\Pr(Y\le z\,|\, X=z)$. The conditional distribution of $Y$ is always Normal, so to find this total conditional probability we only need the mean and variance. The conditional mean of $Y$ at $X$ is the regression prediction $\rho X$ and the conditional variance is the "unexplained" variance $\text{var}(Y) - \text{var}(\rho X) = 1-\rho^2$. Now that we know the conditional mean and variance, the conditional CDF of $Y$ given $X$ can be obtained by standardizing $Y$ and applying the standard Normal CDF $\Phi$: $$\Pr(Y \le y\,|\, X) = \Phi\left(\frac{y-\rho X}{\sqrt{1-\rho^2}}\right).$$ Evaluating this at $y=z$ and $X=z$ and multiplying by the density of $X$ at $z$ (a standard Normal pdf $\phi$) gives the probability density of the second (right-hand) strip $$\phi(z)\Phi\left(\frac{z-\rho z}{\sqrt{1-\rho^2}}\right) = \phi(z)\Phi\left(\frac{1-\rho}{\sqrt{1-\rho^2}}z\right).$$ Doubling this accounts for the equi-probable upper strip, giving the PDF of the maximum as $$\frac{d}{dz}\Pr(\max(X,Y)\le z) = \color{blue}{2}\color{black}{\phi(z)}\color{darkred}{\Phi\left(\frac{1-\rho}{\sqrt{1-\rho^2}}z\right)}.$$ Recapitulation I have colored the factors to signify their origins: $\color{blue}2$ for the two symmetrical strips; $\color{black}{\phi(z)}$ for the infinitesimal strip widths; and $\color{darkred}{\Phi\left(\cdots\right)}$ for the strip lengths. The argument of the latter, $\frac{1-\rho}{\sqrt{1-\rho^2}}z$, is just a standardized version of $Y=z$ conditional on $X=z$. Here are plots of this density for a range of values of $\rho.$ Two dotted black curves in this figure provide references for the extreme cases: For extremely positive $\rho,$ the density must approximate a Standard Normal distribution, because we are (to a good approximation) computing the larger of a standard normal variable $Z$ and a copy of itself. For extremely negative $\rho,$ the density must approximate a Standard Half-Normal distribution, because the maximum of $Z$ and $-Z$ is $|Z|.$ Edit 2022-06-22 The same method described here leads to the density of the maximum of any Binormal variable $(X,Y):$ you add the contributions from the vertical and horizontal strips; the tiny square where they overlap is negligible. On each strip there is a width factor given by a Normal density and a height factor given by a Normal distribution function. See https://stats.stackexchange.com/a/579392/919 for a statement of the result.
Distribution of the maximum of two correlated normal variables
Let $f_\rho$ be the bivariate Normal PDF for $(X,Y)$ with standard marginals and correlation $\rho$. The CDF of the maximum is, by definition, $$\Pr(\max(X, Y)\le z) = \Pr(X\le z,\ Y\le z) = \int_{-\
Distribution of the maximum of two correlated normal variables Let $f_\rho$ be the bivariate Normal PDF for $(X,Y)$ with standard marginals and correlation $\rho$. The CDF of the maximum is, by definition, $$\Pr(\max(X, Y)\le z) = \Pr(X\le z,\ Y\le z) = \int_{-\infty}^z\int_{-\infty}^z f_\rho(x,y)dy dx.$$ The bivariate Normal PDF is symmetric (via reflection) around the diagonal. Thus, increasing $z$ to $z+dz$ adds two strips of equivalent probability to the original semi-infinite square: the infinitesimally thick upper one is $(-\infty, z]\times (z, z+dz]$ while its reflected counterpart, the right-hand strip, is $(z, z+dz]\times (-\infty, z]$. The probability density of the right-hand strip is the density of $X$ at $z$ times the total conditional probability that $Y$ is in the strip, $\Pr(Y\le z\,|\, X=z)$. The conditional distribution of $Y$ is always Normal, so to find this total conditional probability we only need the mean and variance. The conditional mean of $Y$ at $X$ is the regression prediction $\rho X$ and the conditional variance is the "unexplained" variance $\text{var}(Y) - \text{var}(\rho X) = 1-\rho^2$. Now that we know the conditional mean and variance, the conditional CDF of $Y$ given $X$ can be obtained by standardizing $Y$ and applying the standard Normal CDF $\Phi$: $$\Pr(Y \le y\,|\, X) = \Phi\left(\frac{y-\rho X}{\sqrt{1-\rho^2}}\right).$$ Evaluating this at $y=z$ and $X=z$ and multiplying by the density of $X$ at $z$ (a standard Normal pdf $\phi$) gives the probability density of the second (right-hand) strip $$\phi(z)\Phi\left(\frac{z-\rho z}{\sqrt{1-\rho^2}}\right) = \phi(z)\Phi\left(\frac{1-\rho}{\sqrt{1-\rho^2}}z\right).$$ Doubling this accounts for the equi-probable upper strip, giving the PDF of the maximum as $$\frac{d}{dz}\Pr(\max(X,Y)\le z) = \color{blue}{2}\color{black}{\phi(z)}\color{darkred}{\Phi\left(\frac{1-\rho}{\sqrt{1-\rho^2}}z\right)}.$$ Recapitulation I have colored the factors to signify their origins: $\color{blue}2$ for the two symmetrical strips; $\color{black}{\phi(z)}$ for the infinitesimal strip widths; and $\color{darkred}{\Phi\left(\cdots\right)}$ for the strip lengths. The argument of the latter, $\frac{1-\rho}{\sqrt{1-\rho^2}}z$, is just a standardized version of $Y=z$ conditional on $X=z$. Here are plots of this density for a range of values of $\rho.$ Two dotted black curves in this figure provide references for the extreme cases: For extremely positive $\rho,$ the density must approximate a Standard Normal distribution, because we are (to a good approximation) computing the larger of a standard normal variable $Z$ and a copy of itself. For extremely negative $\rho,$ the density must approximate a Standard Half-Normal distribution, because the maximum of $Z$ and $-Z$ is $|Z|.$ Edit 2022-06-22 The same method described here leads to the density of the maximum of any Binormal variable $(X,Y):$ you add the contributions from the vertical and horizontal strips; the tiny square where they overlap is negligible. On each strip there is a width factor given by a Normal density and a height factor given by a Normal distribution function. See https://stats.stackexchange.com/a/579392/919 for a statement of the result.
Distribution of the maximum of two correlated normal variables Let $f_\rho$ be the bivariate Normal PDF for $(X,Y)$ with standard marginals and correlation $\rho$. The CDF of the maximum is, by definition, $$\Pr(\max(X, Y)\le z) = \Pr(X\le z,\ Y\le z) = \int_{-\
11,339
"Fully Bayesian" vs "Bayesian"
The terminology "fully Bayesian approach" is nothing but a way to indicate that one moves from a "partially" Bayesian approach to a "true" Bayesian approach, depending on the context. Or to distinguish a "pseudo-Bayesian" approach from a "strictly" Bayesian approach. For example one author writes: "Unlike the majority of other authors interested who typically used an Empirical Bayes approach for RVM, we adopt a fully Bayesian approach" beacuse the empirical Bayes approach is a "pseudo-Bayesian" approach. There are others pseudo-Bayesian approaches, such as the Bayesian-frequentist predictive distribution (a distribution whose quantiles match the bounds of the frequentist prediction intervals). In this page several R packages for Bayesian inference are presented. The MCMCglmm is presented as a "fully Bayesian approach" because the user has to choose the prior distribution, contrary to the other packages. Another possible meaning of "fully Bayesian" is when one performs a Bayesian inference derived from the Bayesian decision theory framework, that is, derived from a loss function, because Bayesian decision theory is a solid foundational framework for Bayesian inference.
"Fully Bayesian" vs "Bayesian"
The terminology "fully Bayesian approach" is nothing but a way to indicate that one moves from a "partially" Bayesian approach to a "true" Bayesian approach, depending on the context. Or to distinguis
"Fully Bayesian" vs "Bayesian" The terminology "fully Bayesian approach" is nothing but a way to indicate that one moves from a "partially" Bayesian approach to a "true" Bayesian approach, depending on the context. Or to distinguish a "pseudo-Bayesian" approach from a "strictly" Bayesian approach. For example one author writes: "Unlike the majority of other authors interested who typically used an Empirical Bayes approach for RVM, we adopt a fully Bayesian approach" beacuse the empirical Bayes approach is a "pseudo-Bayesian" approach. There are others pseudo-Bayesian approaches, such as the Bayesian-frequentist predictive distribution (a distribution whose quantiles match the bounds of the frequentist prediction intervals). In this page several R packages for Bayesian inference are presented. The MCMCglmm is presented as a "fully Bayesian approach" because the user has to choose the prior distribution, contrary to the other packages. Another possible meaning of "fully Bayesian" is when one performs a Bayesian inference derived from the Bayesian decision theory framework, that is, derived from a loss function, because Bayesian decision theory is a solid foundational framework for Bayesian inference.
"Fully Bayesian" vs "Bayesian" The terminology "fully Bayesian approach" is nothing but a way to indicate that one moves from a "partially" Bayesian approach to a "true" Bayesian approach, depending on the context. Or to distinguis
11,340
"Fully Bayesian" vs "Bayesian"
I think the terminology is used to distinguish between the Bayesian approach and the empirical Bayes approach. Full Bayes uses a specified prior whereas empirical Bayes allows the prior to be estimated through use of data.
"Fully Bayesian" vs "Bayesian"
I think the terminology is used to distinguish between the Bayesian approach and the empirical Bayes approach. Full Bayes uses a specified prior whereas empirical Bayes allows the prior to be estimat
"Fully Bayesian" vs "Bayesian" I think the terminology is used to distinguish between the Bayesian approach and the empirical Bayes approach. Full Bayes uses a specified prior whereas empirical Bayes allows the prior to be estimated through use of data.
"Fully Bayesian" vs "Bayesian" I think the terminology is used to distinguish between the Bayesian approach and the empirical Bayes approach. Full Bayes uses a specified prior whereas empirical Bayes allows the prior to be estimat
11,341
"Fully Bayesian" vs "Bayesian"
I would use "fully Bayesian" to mean that any nuissance parameters had been marginalised from the analysis, rather than optimised (e.g. MAP estimates). For example a Gaussian process model, with hyper-parameters tuned to maximise the marginal likelihood would be Bayesian, but only partially so, whereas if the hyper-parameters defining the covariance function were integrated out using a hyper-prior, that would be fully Bayesian.
"Fully Bayesian" vs "Bayesian"
I would use "fully Bayesian" to mean that any nuissance parameters had been marginalised from the analysis, rather than optimised (e.g. MAP estimates). For example a Gaussian process model, with hype
"Fully Bayesian" vs "Bayesian" I would use "fully Bayesian" to mean that any nuissance parameters had been marginalised from the analysis, rather than optimised (e.g. MAP estimates). For example a Gaussian process model, with hyper-parameters tuned to maximise the marginal likelihood would be Bayesian, but only partially so, whereas if the hyper-parameters defining the covariance function were integrated out using a hyper-prior, that would be fully Bayesian.
"Fully Bayesian" vs "Bayesian" I would use "fully Bayesian" to mean that any nuissance parameters had been marginalised from the analysis, rather than optimised (e.g. MAP estimates). For example a Gaussian process model, with hype
11,342
"Fully Bayesian" vs "Bayesian"
"Bayesian" really means "approximate Bayesian". "Fully Bayesian" also means "approximate Bayesian", but with less approximation. Edit: Clarification. The fully Bayesian approach would be, for a given model and data, to calculate the posterior probability using the Bayes rule $$ p(\theta \mid \text{Data}) \propto p(\text{Data} \mid \theta)p(\theta) \>.$$ Except for very simple models, this has too large computational complexity, and approximations are necessary. More accurate approximations, such as using MCMC with Gibbs sampling for all parameters $\theta$, are sometimes called "Fully Bayesian". Less accurate approximations, such as using point estimation for some parameters, cannot be called "Fully Bayesian". Some approximate inference methods are in-between, like Variational Bayes or Expectation Propagation, and they are sometimes (rarely) also called "Fully Bayesian".
"Fully Bayesian" vs "Bayesian"
"Bayesian" really means "approximate Bayesian". "Fully Bayesian" also means "approximate Bayesian", but with less approximation. Edit: Clarification. The fully Bayesian approach would be, for a given
"Fully Bayesian" vs "Bayesian" "Bayesian" really means "approximate Bayesian". "Fully Bayesian" also means "approximate Bayesian", but with less approximation. Edit: Clarification. The fully Bayesian approach would be, for a given model and data, to calculate the posterior probability using the Bayes rule $$ p(\theta \mid \text{Data}) \propto p(\text{Data} \mid \theta)p(\theta) \>.$$ Except for very simple models, this has too large computational complexity, and approximations are necessary. More accurate approximations, such as using MCMC with Gibbs sampling for all parameters $\theta$, are sometimes called "Fully Bayesian". Less accurate approximations, such as using point estimation for some parameters, cannot be called "Fully Bayesian". Some approximate inference methods are in-between, like Variational Bayes or Expectation Propagation, and they are sometimes (rarely) also called "Fully Bayesian".
"Fully Bayesian" vs "Bayesian" "Bayesian" really means "approximate Bayesian". "Fully Bayesian" also means "approximate Bayesian", but with less approximation. Edit: Clarification. The fully Bayesian approach would be, for a given
11,343
"Fully Bayesian" vs "Bayesian"
As a practical example: I do some Bayesian modeling using splines. A common problem with splines is knot selection. One popular possibility is to use a Reversible Jump Markov Chain Monte Carlo (RJMCMC) scheme where one proposes to add, delete, or move a knot during each iteration. The coefficients for the splines are the Least Square estimates. Free Knot Splines In my opinion this makes it only 'partially Bayesian' because for a 'fully Bayesian' approach priors would need to be placed on these coefficients (and new coefficients proposed during each iteration), but then the Least Squares estimates do not work for the RJMCMC scheme, and things become much more difficult.
"Fully Bayesian" vs "Bayesian"
As a practical example: I do some Bayesian modeling using splines. A common problem with splines is knot selection. One popular possibility is to use a Reversible Jump Markov Chain Monte Carlo (RJMC
"Fully Bayesian" vs "Bayesian" As a practical example: I do some Bayesian modeling using splines. A common problem with splines is knot selection. One popular possibility is to use a Reversible Jump Markov Chain Monte Carlo (RJMCMC) scheme where one proposes to add, delete, or move a knot during each iteration. The coefficients for the splines are the Least Square estimates. Free Knot Splines In my opinion this makes it only 'partially Bayesian' because for a 'fully Bayesian' approach priors would need to be placed on these coefficients (and new coefficients proposed during each iteration), but then the Least Squares estimates do not work for the RJMCMC scheme, and things become much more difficult.
"Fully Bayesian" vs "Bayesian" As a practical example: I do some Bayesian modeling using splines. A common problem with splines is knot selection. One popular possibility is to use a Reversible Jump Markov Chain Monte Carlo (RJMC
11,344
"Fully Bayesian" vs "Bayesian"
I would add a characterization that has not been mentioned so far. A fully Bayesian approach "fully" propagates the uncertainty in all the unknown quantities through the Bayes theorem. On the other hand, Pseudo-Bayes approaches such as empirical Bayes do not propagate all the uncertainties. For example, when estimating posterior predictive quantities, a fully Bayesian approach would make use of the posterior density of the unknown model parameters to obtain the predictive distribution for the target parameter. An EB approach would not account for the uncertainty in all the unknowns - for example, some of the hyper-parameters may be set to particular values, thus underestimating the overall uncertainty.
"Fully Bayesian" vs "Bayesian"
I would add a characterization that has not been mentioned so far. A fully Bayesian approach "fully" propagates the uncertainty in all the unknown quantities through the Bayes theorem. On the other
"Fully Bayesian" vs "Bayesian" I would add a characterization that has not been mentioned so far. A fully Bayesian approach "fully" propagates the uncertainty in all the unknown quantities through the Bayes theorem. On the other hand, Pseudo-Bayes approaches such as empirical Bayes do not propagate all the uncertainties. For example, when estimating posterior predictive quantities, a fully Bayesian approach would make use of the posterior density of the unknown model parameters to obtain the predictive distribution for the target parameter. An EB approach would not account for the uncertainty in all the unknowns - for example, some of the hyper-parameters may be set to particular values, thus underestimating the overall uncertainty.
"Fully Bayesian" vs "Bayesian" I would add a characterization that has not been mentioned so far. A fully Bayesian approach "fully" propagates the uncertainty in all the unknown quantities through the Bayes theorem. On the other
11,345
What's the purpose of autocorrelation?
Autocorrelation has several plain-language interpretations that signify in ways that non-autocorrelated processes and models do not: An autocorrelated variable has memory of its previous values. Such variables have behavior that depends on what went before. Memory may be long or short relative to the period of observation; memory may be infinite; memory may be negative (i.e. may oscillate). If your guiding theories say the past (of a variable) remains with us, then autocorrelation is an expression of that. (See, for example Boef, S. D. (2001). Modeling equilibrium relationships: Error correction models with strongly autoregressive data. Political Analysis, 9(1), 78–94, and also de Boef, S., & Keele, L. (2008). Taking Time Seriously. American Journal of Political Science, 52(1), 184–200.) An autocorrelated variable implies a dynamic system. The questions we ask and answer about the behavior of dynamic systems are different than those we ask about non-dynamic systems. For example, when causal effects enter a system, and how long effects from a perturbation at one point in time remain relevant are answered in the language of autocorrelated models. (See, for example, Levins, R. (1998). Dialectics and Systems Theory. Science & Society, 62(3), 375–399, but also the Pesaran citation below.) An autocorrelated variable implies a need for time series modeling (if not dynamic systems modeling also). Time series methodologies are predicated on autoregressive behaviors (and moving average, which is a modeling assumption about the time-dependent structure of errors) attempting to capture salient details of the data generating process, and stand in marked contrast to, for example, so-called "longitudinal models" which simply incorporate some measure of time as a variable in an otherwise non-dynamic model without autocorrelation. See, for example, Pesaran, M. H. (2015) Time Series and Panel Data in Econometrics, New York, NY: Oxford University Press. Caveat: I am using "autoregression" and "autoregressive" to imply any memory structure to a variable in general, regardless of short-term, long term, unit-root, explosive, etc. properties of that process.
What's the purpose of autocorrelation?
Autocorrelation has several plain-language interpretations that signify in ways that non-autocorrelated processes and models do not: An autocorrelated variable has memory of its previous values. Such
What's the purpose of autocorrelation? Autocorrelation has several plain-language interpretations that signify in ways that non-autocorrelated processes and models do not: An autocorrelated variable has memory of its previous values. Such variables have behavior that depends on what went before. Memory may be long or short relative to the period of observation; memory may be infinite; memory may be negative (i.e. may oscillate). If your guiding theories say the past (of a variable) remains with us, then autocorrelation is an expression of that. (See, for example Boef, S. D. (2001). Modeling equilibrium relationships: Error correction models with strongly autoregressive data. Political Analysis, 9(1), 78–94, and also de Boef, S., & Keele, L. (2008). Taking Time Seriously. American Journal of Political Science, 52(1), 184–200.) An autocorrelated variable implies a dynamic system. The questions we ask and answer about the behavior of dynamic systems are different than those we ask about non-dynamic systems. For example, when causal effects enter a system, and how long effects from a perturbation at one point in time remain relevant are answered in the language of autocorrelated models. (See, for example, Levins, R. (1998). Dialectics and Systems Theory. Science & Society, 62(3), 375–399, but also the Pesaran citation below.) An autocorrelated variable implies a need for time series modeling (if not dynamic systems modeling also). Time series methodologies are predicated on autoregressive behaviors (and moving average, which is a modeling assumption about the time-dependent structure of errors) attempting to capture salient details of the data generating process, and stand in marked contrast to, for example, so-called "longitudinal models" which simply incorporate some measure of time as a variable in an otherwise non-dynamic model without autocorrelation. See, for example, Pesaran, M. H. (2015) Time Series and Panel Data in Econometrics, New York, NY: Oxford University Press. Caveat: I am using "autoregression" and "autoregressive" to imply any memory structure to a variable in general, regardless of short-term, long term, unit-root, explosive, etc. properties of that process.
What's the purpose of autocorrelation? Autocorrelation has several plain-language interpretations that signify in ways that non-autocorrelated processes and models do not: An autocorrelated variable has memory of its previous values. Such
11,346
What's the purpose of autocorrelation?
An attempt at an answer. Autocorrelation is no different than any other relationship between predictors. It's just that the predictor and the dependent variable happen to be the same time series, just lagged. isn't every state in the universe dependent on the previous one? Yes indeed. Just as every object's state in the universe depends on every other object's, via all kinds of physical forces. The question just is whether the relationship is strong enough to be detectable, or strong enough to help us in predicting states. And the very same thing applies to autocorrelation. It's always there. The question is whether we need to model it, or whether modeling it just introduces additional uncertainty (the bias-variance trade-off), making us worse off than not modeling it. An example from my personal work: I forecast supermarket sales. My household's consumption of milk is fairly regular. If I haven't bought any milk in three or four days, chances are high I'll come in today or tomorrow to buy milk. If the supermarket wants to forecast my household's demand for milk, they should by all means take this autocorrelation into account. However, I am not the only customer in my supermarket. There are maybe another 2,000 households that buy their groceries there. Each one's milk consumption is again autocorrelated. But since everyone's rate of consumption is different, the autocorrelation at the aggregate is so much attenuated that it may not make sense to model it any more. It has disappeared into the general daily demand, i.e., the intercept. And since the supermarket doesn't care who it sells milk to, it will model aggregate demand, and probably not include autocorrelation. (Yes, there is intra-weekly seasonality. Which is a kind of autocorrelation, but it really depends on the day of the week, not on the demand on the same weekday one week earlier, so it's more a weekday effect than seasonal autocorrelation.)
What's the purpose of autocorrelation?
An attempt at an answer. Autocorrelation is no different than any other relationship between predictors. It's just that the predictor and the dependent variable happen to be the same time series, just
What's the purpose of autocorrelation? An attempt at an answer. Autocorrelation is no different than any other relationship between predictors. It's just that the predictor and the dependent variable happen to be the same time series, just lagged. isn't every state in the universe dependent on the previous one? Yes indeed. Just as every object's state in the universe depends on every other object's, via all kinds of physical forces. The question just is whether the relationship is strong enough to be detectable, or strong enough to help us in predicting states. And the very same thing applies to autocorrelation. It's always there. The question is whether we need to model it, or whether modeling it just introduces additional uncertainty (the bias-variance trade-off), making us worse off than not modeling it. An example from my personal work: I forecast supermarket sales. My household's consumption of milk is fairly regular. If I haven't bought any milk in three or four days, chances are high I'll come in today or tomorrow to buy milk. If the supermarket wants to forecast my household's demand for milk, they should by all means take this autocorrelation into account. However, I am not the only customer in my supermarket. There are maybe another 2,000 households that buy their groceries there. Each one's milk consumption is again autocorrelated. But since everyone's rate of consumption is different, the autocorrelation at the aggregate is so much attenuated that it may not make sense to model it any more. It has disappeared into the general daily demand, i.e., the intercept. And since the supermarket doesn't care who it sells milk to, it will model aggregate demand, and probably not include autocorrelation. (Yes, there is intra-weekly seasonality. Which is a kind of autocorrelation, but it really depends on the day of the week, not on the demand on the same weekday one week earlier, so it's more a weekday effect than seasonal autocorrelation.)
What's the purpose of autocorrelation? An attempt at an answer. Autocorrelation is no different than any other relationship between predictors. It's just that the predictor and the dependent variable happen to be the same time series, just
11,347
What's the purpose of autocorrelation?
First, I think you mean what is the purpose of evaluating autocorrelation and dealing with it. If you really mean the "purpose of autocorrelation" then that's philosophy, not statistics. Second, states of the universe are correlated with previous states but not every statistical problem deals with previous states of nature. Lots of studies are cross-sectional. Third, do we need to model it when it is there? Methods make assumptions. Most forms of regression assume no auto-correlation (that is, the errors are independent). If we violate this assumption, then our results could be wrong. How far wrong? One way to tell would be to do the usual regression and also some model that accounts for autocorrelation (e.g. multilevel models or time series methods) and see how different the results are. But, I think generally, accounting for auto-correlation will reduce noise and make the model more accurate.
What's the purpose of autocorrelation?
First, I think you mean what is the purpose of evaluating autocorrelation and dealing with it. If you really mean the "purpose of autocorrelation" then that's philosophy, not statistics. Second, state
What's the purpose of autocorrelation? First, I think you mean what is the purpose of evaluating autocorrelation and dealing with it. If you really mean the "purpose of autocorrelation" then that's philosophy, not statistics. Second, states of the universe are correlated with previous states but not every statistical problem deals with previous states of nature. Lots of studies are cross-sectional. Third, do we need to model it when it is there? Methods make assumptions. Most forms of regression assume no auto-correlation (that is, the errors are independent). If we violate this assumption, then our results could be wrong. How far wrong? One way to tell would be to do the usual regression and also some model that accounts for autocorrelation (e.g. multilevel models or time series methods) and see how different the results are. But, I think generally, accounting for auto-correlation will reduce noise and make the model more accurate.
What's the purpose of autocorrelation? First, I think you mean what is the purpose of evaluating autocorrelation and dealing with it. If you really mean the "purpose of autocorrelation" then that's philosophy, not statistics. Second, state
11,348
Is a high $R^2$ ever useless?
Yes. The criteria for evaluating a statistical model depend on the specific problem at hand and aren't some mechanical function of $R^2$ or statistical significance (though they matter). The relevant question is, "does the model help you understand the data?" Meaningless regressions with high $R^2$ The simplest way to get high $R^2$ is to do some equivalent of regressing right shoes on left shoes. Tell me the size of your right shoe, and I can predict the size of your left shoe with great accuracy. Huge $R^2$! What a great statistical model! Except it means diddly poo. You can get great $R^2$ by putting the same variable on the left and right hand side of a regression, but this huge $R^2$ regression would almost certainly be useless. There are other cases where including a variable on the right hand side is conceptually the wrong thing to do (even if it raises $R^2$). Let's say you're trying to estimate if some minority group is discriminated against and less likely to get a job. You shouldn't control for whether the company gave a call back after the job application because being less likely to respond to job applications of minorities may be the channel through which discrimination occurs! Adding the wrong control can render your regression meaningless. You can always increase $R^2$ by adding more regressors! I can keep adding regressors to the right hand side until I get whatever $R^2$ I like. To predict labor earnings, I could add education controls, age controls, quarter fixed effects, zip code fixed effects, occupation fixed effects, firm fixed effects, family fixed effects, pet fixed effects, hair length etc... at some point the controls cease to make sense but $R^2$ keeps going up. Adding everything as a regressor is known as a "kitchen sink" regression. You can get high $R^2$ but may massively overfit the data: your model perfectly predicts the sample used to estimate the model (has high $R^2$) but the estimated model fails horribly on new data. Same idea can show up in polynomial curve fitting. Give me random data, and I can probably get great $R^2$ by fitting a 200 degree polynomial. On new data though, the estimated polynomial would fail to work because of overfitting. Again, high $R^2$ for the estimated model but estimated model is useless. Point (3-4) is why we have adjusted $R^2$, which provides some penalty for adding more regressors, but adjusted $R^2$ can typically still be juiced up by overfitting the data. It also has the wonderfully nonsensical feature that it can go negative. I could also give examples where low $R^2$ is just fine (e.g. estimating betas in asset pricing models) but this post has already gotten quite long. To summarize, the overall question should be something like, "knowing what I know about the problem and about statistics, does this model help me understand/explain the data?" $R^2$ can be a tool to help answer this question, but it's not so simple as models with higher $R^2$ are always better.
Is a high $R^2$ ever useless?
Yes. The criteria for evaluating a statistical model depend on the specific problem at hand and aren't some mechanical function of $R^2$ or statistical significance (though they matter). The relevant
Is a high $R^2$ ever useless? Yes. The criteria for evaluating a statistical model depend on the specific problem at hand and aren't some mechanical function of $R^2$ or statistical significance (though they matter). The relevant question is, "does the model help you understand the data?" Meaningless regressions with high $R^2$ The simplest way to get high $R^2$ is to do some equivalent of regressing right shoes on left shoes. Tell me the size of your right shoe, and I can predict the size of your left shoe with great accuracy. Huge $R^2$! What a great statistical model! Except it means diddly poo. You can get great $R^2$ by putting the same variable on the left and right hand side of a regression, but this huge $R^2$ regression would almost certainly be useless. There are other cases where including a variable on the right hand side is conceptually the wrong thing to do (even if it raises $R^2$). Let's say you're trying to estimate if some minority group is discriminated against and less likely to get a job. You shouldn't control for whether the company gave a call back after the job application because being less likely to respond to job applications of minorities may be the channel through which discrimination occurs! Adding the wrong control can render your regression meaningless. You can always increase $R^2$ by adding more regressors! I can keep adding regressors to the right hand side until I get whatever $R^2$ I like. To predict labor earnings, I could add education controls, age controls, quarter fixed effects, zip code fixed effects, occupation fixed effects, firm fixed effects, family fixed effects, pet fixed effects, hair length etc... at some point the controls cease to make sense but $R^2$ keeps going up. Adding everything as a regressor is known as a "kitchen sink" regression. You can get high $R^2$ but may massively overfit the data: your model perfectly predicts the sample used to estimate the model (has high $R^2$) but the estimated model fails horribly on new data. Same idea can show up in polynomial curve fitting. Give me random data, and I can probably get great $R^2$ by fitting a 200 degree polynomial. On new data though, the estimated polynomial would fail to work because of overfitting. Again, high $R^2$ for the estimated model but estimated model is useless. Point (3-4) is why we have adjusted $R^2$, which provides some penalty for adding more regressors, but adjusted $R^2$ can typically still be juiced up by overfitting the data. It also has the wonderfully nonsensical feature that it can go negative. I could also give examples where low $R^2$ is just fine (e.g. estimating betas in asset pricing models) but this post has already gotten quite long. To summarize, the overall question should be something like, "knowing what I know about the problem and about statistics, does this model help me understand/explain the data?" $R^2$ can be a tool to help answer this question, but it's not so simple as models with higher $R^2$ are always better.
Is a high $R^2$ ever useless? Yes. The criteria for evaluating a statistical model depend on the specific problem at hand and aren't some mechanical function of $R^2$ or statistical significance (though they matter). The relevant
11,349
Is a high $R^2$ ever useless?
"Higher is better" is a bad rule of thumb for R-square. Don Morrison wrote some famous articles a few years back demonstrating that R-squares approaching zero could still both actionable and profitable, depending on the industry. For instance, in direct marketing predicting response to a magazine subscription mailing to 10 million households, R-squares in the low single digits can produce profitable campaigns (on an ROI basis) if the mailing is based on the top 2 or 3 deciles of response likelihood. Another sociologist (whose name escapes me) segmented R-squares by data type noting that wrt survey research, R-squares in the 10-20% range were the norm, whereas for business data, R-squares in the 40-60% range were to be expected. They went on to remark that R-squares of 80-90% or greater were probably in violation of fundamental regression assumptions. However, this author had no experience with marketing mix, time series data or models containing a full set of "causal" features (e.g., the classic 4 "Ps" of price, promotion, place and product) which can and will produce R-squares approaching 100%. That said, even sensible, benchmarking rules of thumb such as these aren't terribly helpful when dealing with the technically illiterate whose first question about a predictive model will always be, "What's the R-square?"
Is a high $R^2$ ever useless?
"Higher is better" is a bad rule of thumb for R-square. Don Morrison wrote some famous articles a few years back demonstrating that R-squares approaching zero could still both actionable and profitab
Is a high $R^2$ ever useless? "Higher is better" is a bad rule of thumb for R-square. Don Morrison wrote some famous articles a few years back demonstrating that R-squares approaching zero could still both actionable and profitable, depending on the industry. For instance, in direct marketing predicting response to a magazine subscription mailing to 10 million households, R-squares in the low single digits can produce profitable campaigns (on an ROI basis) if the mailing is based on the top 2 or 3 deciles of response likelihood. Another sociologist (whose name escapes me) segmented R-squares by data type noting that wrt survey research, R-squares in the 10-20% range were the norm, whereas for business data, R-squares in the 40-60% range were to be expected. They went on to remark that R-squares of 80-90% or greater were probably in violation of fundamental regression assumptions. However, this author had no experience with marketing mix, time series data or models containing a full set of "causal" features (e.g., the classic 4 "Ps" of price, promotion, place and product) which can and will produce R-squares approaching 100%. That said, even sensible, benchmarking rules of thumb such as these aren't terribly helpful when dealing with the technically illiterate whose first question about a predictive model will always be, "What's the R-square?"
Is a high $R^2$ ever useless? "Higher is better" is a bad rule of thumb for R-square. Don Morrison wrote some famous articles a few years back demonstrating that R-squares approaching zero could still both actionable and profitab
11,350
Is a high $R^2$ ever useless?
The other answers offer great theoretical explanations of the many ways R-squared values can be fixed/faked/misleading/etc.. Here is a hands-on demonstration that has always stuck with me, coded in r: y <- rnorm(10) x <- sapply(rep(10,8),rnorm) summary(lm(y~x)) This can provide R-squared values > 0.90. Add enough regressors and even random values can "predict" random values.
Is a high $R^2$ ever useless?
The other answers offer great theoretical explanations of the many ways R-squared values can be fixed/faked/misleading/etc.. Here is a hands-on demonstration that has always stuck with me, coded in r:
Is a high $R^2$ ever useless? The other answers offer great theoretical explanations of the many ways R-squared values can be fixed/faked/misleading/etc.. Here is a hands-on demonstration that has always stuck with me, coded in r: y <- rnorm(10) x <- sapply(rep(10,8),rnorm) summary(lm(y~x)) This can provide R-squared values > 0.90. Add enough regressors and even random values can "predict" random values.
Is a high $R^2$ ever useless? The other answers offer great theoretical explanations of the many ways R-squared values can be fixed/faked/misleading/etc.. Here is a hands-on demonstration that has always stuck with me, coded in r:
11,351
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution?
For the more restricted question Why is a biased standard deviation formula typically used? the simple answer Because the associated variance estimator is unbiased. There is no real mathematical/statistical justification. may be accurate in many cases. However, this is not necessarily always the case. There are at least two important aspects of these issues that should be understood. First, the sample variance $s^2$ is not just unbiased for Gaussian random variables. It is unbiased for any distribution with finite variance $\sigma^2$ (as discussed below, in my original answer). The question notes that $s$ is not unbiased for $\sigma$, and suggests an alternative which is unbiased for a Gaussian random variable. However it is important to note that unlike the variance, for the standard deviation it is not possible to have a "distribution free" unbiased estimator (*see note below). Second, as mentioned in the comment by whuber the fact that $s$ is biased does not impact the standard "t test". First note that, for a Gaussian variable $x$, if we estimate z-scores from a sample $\{x_i\}$ as $$z_i=\frac{x_i-\mu}{\sigma}\approx\frac{x_i-\bar{x}}{s}$$ then these will be biased. However the t statistic is usually used in the context of the sampling distribution of $\bar{x}$. In this case the z-score would be $$z_{\bar{x}}=\frac{\bar{x}-\mu}{\sigma_{\bar{x}}}\approx\frac{\bar{x}-\mu}{s/\sqrt{n}}=t$$ though we can compute neither $z$ nor $t$, as we do not know $\mu$. Nonetheless, if the $z_{\bar{x}}$ statistic would be normal, then the $t$ statistic will follow a Student-t distribution. This is not a large-$n$ approximation. The only assumption is that the $x$ samples are i.i.d. Gaussian. (Commonly the t-test is applied more broadly for possibly non-Gaussian $x$. This does rely on large-$n$, which by the central limit theorem ensures that $\bar{x}$ will still be Gaussian.) *Clarification on "distribution-free unbiased estimator" By "distribution free", I mean that the estimator cannot depend on any information about the population $x$ aside from the sample $\{x_1,\ldots,x_n\}$. By "unbiased" I mean that the expected error $\mathbb{E}[\hat{\theta}_n]-\theta$ is uniformly zero, independent of the sample size $n$. (As opposed to an estimator that is merely asymptotically unbiased, a.k.a. "consistent", for which the bias vanishes as $n\to\infty$.) In the comments this was given as a possible example of a "distribution-free unbiased estimator". Abstracting a bit, this estimator is of the form $\hat{\sigma}=f[s,n,\kappa_x]$, where $\kappa_x$ is the excess kurtosis of $x$. This estimator is not "distribution free", as $\kappa_x$ depends on the distribution of $x$. The estimator is said to satisfy $\mathbb{E}[\hat{\sigma}]-\sigma_x=\mathrm{O}[\frac{1}{n}]$, where $\sigma_x^2$ is the variance of $x$. Hence the estimator is consistent, but not (absolutely) "unbiased", as $\mathrm{O}[\frac{1}{n}]$ can be arbitrarily large for small $n$. Note: Below is my original "answer". From here on, the comments are about the standard "sample" mean and variance, which are "distribution-free" unbiased estimators (i.e. the population is not assumed to be Gaussian). This is not a complete answer, but rather a clarification on why the sample variance formula is commonly used. Given a random sample $\{x_1,\ldots,x_n\}$, so long as the variables have a common mean, the estimator $\bar{x}=\frac{1}{n}\sum_ix_i$ will be unbiased, i.e. $$\mathbb{E}[x_i]=\mu \implies \mathbb{E}[\bar{x}]=\mu$$ If the variables also have a common finite variance, and they are uncorrelated, then the estimator $s^2=\frac{1}{n-1}\sum_i(x_i-\bar{x})^2$ will also be unbiased, i.e. $$\mathbb{E}[x_ix_j]-\mu^2=\begin{cases}\sigma^2&i=j\\0&i\neq{j}\end{cases} \implies \mathbb{E}[s^2]=\sigma^2$$ Note that the unbiasedness of these estimators depends only on the above assumptions (and the linearity of expectation; the proof is just algebra). The result does not depend on any particular distribution, such as Gaussian. The variables $x_i$ do not have to have a common distribution, and they do not even have to be independent (i.e. the sample does not have to be i.i.d.). The "sample standard deviation" $s$ is not an unbiased estimator, $\mathbb{s}\neq\sigma$, but nonetheless it is commonly used. My guess is that this is simply because it is the square root of the unbiased sample variance. (With no more sophisticated justification.) In the case of an i.i.d. Gaussian sample, the maximum likelihood estimates (MLE) of the parameters are $\hat{\mu}_\mathrm{MLE}=\bar{x}$ and $(\hat{\sigma}^2)_\mathrm{MLE}=\frac{n-1}{n}s^2$, i.e. the variance divides by $n$ rather than $n^2$. Moreover, in the i.i.d. Gaussian case the standard deviation MLE is just the square root of the MLE variance. However these formulas, as well as the one hinted at in your question, depend on the Gaussian i.i.d. assumption. Update: Additional clarification on "biased" vs. "unbiased". Consider an $n$-element sample as above, $X=\{x_1,\ldots,x_n\}$, with sum-square-deviation $$\delta^2_n=\sum_i(x_i-\bar{x})^2$$ Given the assumptions outlined in the first part above, we necessarily have $$\mathbb{E}[\delta^2_n]=(n-1)\sigma^2$$ so the (Gaussian-)MLE estimator is biased $$\widehat{\sigma^2_n}=\tfrac{1}{n}\delta^2_n \implies \mathbb{E}[\widehat{\sigma^2_n}]=\tfrac{n-1}{n}\sigma^2 $$ while the "sample variance" estimator is unbiased $$s^2_n=\tfrac{1}{n-1}\delta^2_n \implies \mathbb{E}[s^2_n]=\sigma^2$$ Now it is true that $\widehat{\sigma^2_n}$ becomes less biased as the sample size $n$ increases. However $s^2_n$ has zero bias no matter the sample size (so long as $n>1$). For both estimators, the variance of their sampling distribution will be non-zero, and depend on $n$. As an example, the below Matlab code considers an experiment with $n=2$ samples from a standard-normal population $z$. To estimate the sampling distributions for $\bar{x},\widehat{\sigma^2},s^2$, the experiment is repeated $N=10^6$ times. (You can cut & paste the code here to try it out yourself.) % n=sample size, N=number of samples n=2; N=1e6; % generate standard-normal random #'s z=randn(n,N); % i.e. mu=0, sigma=1 % compute sample stats (Gaussian MLE) zbar=sum(z)/n; zvar_mle=sum((z-zbar).^2)/n; % compute ensemble stats (sampling-pdf means) zbar_avg=sum(zbar)/N, zvar_mle_avg=sum(zvar_mle)/N % compute unbiased variance zvar_avg=zvar_mle_avg*n/(n-1) Typical output is like zbar_avg = 1.4442e-04 zvar_mle_avg = 0.49988 zvar_avg = 0.99977 confirming that \begin{align} \mathbb{E}[\bar{z}]&\approx\overline{(\bar{z})}\approx\mu=0 \\ \mathbb{E}[s^2]&\approx\overline{(s^2)}\approx\sigma^2=1 \\ \mathbb{E}[\widehat{\sigma^2}]&\approx\overline{(\widehat{\sigma^2})}\approx\frac{n-1}{n}\sigma^2=\frac{1}{2} \end{align} Update 2: Note on fundamentally "algebraic" nature of unbiased-ness. In the above numerical demonstration, the code approximates the true expectation $\mathbb{E}[\,]$ using an ensemble average with $N=10^6$ replications of the experiment (i.e. each is a sample of size $n=2$). Even with this large number, the typical results quoted above are far from exact. To numerically demonstrate that the estimators are really unbiased, we can use a simple trick to approximate the $N\to\infty$ case: simply add the following line to the code % optional: "whiten" data (ensure exact ensemble stats) [U,S,V]=svd(z-mean(z,2),'econ'); z=sqrt(N)*U*V'; (placing after "generate standard-normal random #'s" and before "compute sample stats") With this simple change, even running the code with $N=10$ gives results like zbar_avg = 1.1102e-17 zvar_mle_avg = 0.50000 zvar_avg = 1.00000
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distrib
For the more restricted question Why is a biased standard deviation formula typically used? the simple answer Because the associated variance estimator is unbiased. There is no real mathematical/s
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution? For the more restricted question Why is a biased standard deviation formula typically used? the simple answer Because the associated variance estimator is unbiased. There is no real mathematical/statistical justification. may be accurate in many cases. However, this is not necessarily always the case. There are at least two important aspects of these issues that should be understood. First, the sample variance $s^2$ is not just unbiased for Gaussian random variables. It is unbiased for any distribution with finite variance $\sigma^2$ (as discussed below, in my original answer). The question notes that $s$ is not unbiased for $\sigma$, and suggests an alternative which is unbiased for a Gaussian random variable. However it is important to note that unlike the variance, for the standard deviation it is not possible to have a "distribution free" unbiased estimator (*see note below). Second, as mentioned in the comment by whuber the fact that $s$ is biased does not impact the standard "t test". First note that, for a Gaussian variable $x$, if we estimate z-scores from a sample $\{x_i\}$ as $$z_i=\frac{x_i-\mu}{\sigma}\approx\frac{x_i-\bar{x}}{s}$$ then these will be biased. However the t statistic is usually used in the context of the sampling distribution of $\bar{x}$. In this case the z-score would be $$z_{\bar{x}}=\frac{\bar{x}-\mu}{\sigma_{\bar{x}}}\approx\frac{\bar{x}-\mu}{s/\sqrt{n}}=t$$ though we can compute neither $z$ nor $t$, as we do not know $\mu$. Nonetheless, if the $z_{\bar{x}}$ statistic would be normal, then the $t$ statistic will follow a Student-t distribution. This is not a large-$n$ approximation. The only assumption is that the $x$ samples are i.i.d. Gaussian. (Commonly the t-test is applied more broadly for possibly non-Gaussian $x$. This does rely on large-$n$, which by the central limit theorem ensures that $\bar{x}$ will still be Gaussian.) *Clarification on "distribution-free unbiased estimator" By "distribution free", I mean that the estimator cannot depend on any information about the population $x$ aside from the sample $\{x_1,\ldots,x_n\}$. By "unbiased" I mean that the expected error $\mathbb{E}[\hat{\theta}_n]-\theta$ is uniformly zero, independent of the sample size $n$. (As opposed to an estimator that is merely asymptotically unbiased, a.k.a. "consistent", for which the bias vanishes as $n\to\infty$.) In the comments this was given as a possible example of a "distribution-free unbiased estimator". Abstracting a bit, this estimator is of the form $\hat{\sigma}=f[s,n,\kappa_x]$, where $\kappa_x$ is the excess kurtosis of $x$. This estimator is not "distribution free", as $\kappa_x$ depends on the distribution of $x$. The estimator is said to satisfy $\mathbb{E}[\hat{\sigma}]-\sigma_x=\mathrm{O}[\frac{1}{n}]$, where $\sigma_x^2$ is the variance of $x$. Hence the estimator is consistent, but not (absolutely) "unbiased", as $\mathrm{O}[\frac{1}{n}]$ can be arbitrarily large for small $n$. Note: Below is my original "answer". From here on, the comments are about the standard "sample" mean and variance, which are "distribution-free" unbiased estimators (i.e. the population is not assumed to be Gaussian). This is not a complete answer, but rather a clarification on why the sample variance formula is commonly used. Given a random sample $\{x_1,\ldots,x_n\}$, so long as the variables have a common mean, the estimator $\bar{x}=\frac{1}{n}\sum_ix_i$ will be unbiased, i.e. $$\mathbb{E}[x_i]=\mu \implies \mathbb{E}[\bar{x}]=\mu$$ If the variables also have a common finite variance, and they are uncorrelated, then the estimator $s^2=\frac{1}{n-1}\sum_i(x_i-\bar{x})^2$ will also be unbiased, i.e. $$\mathbb{E}[x_ix_j]-\mu^2=\begin{cases}\sigma^2&i=j\\0&i\neq{j}\end{cases} \implies \mathbb{E}[s^2]=\sigma^2$$ Note that the unbiasedness of these estimators depends only on the above assumptions (and the linearity of expectation; the proof is just algebra). The result does not depend on any particular distribution, such as Gaussian. The variables $x_i$ do not have to have a common distribution, and they do not even have to be independent (i.e. the sample does not have to be i.i.d.). The "sample standard deviation" $s$ is not an unbiased estimator, $\mathbb{s}\neq\sigma$, but nonetheless it is commonly used. My guess is that this is simply because it is the square root of the unbiased sample variance. (With no more sophisticated justification.) In the case of an i.i.d. Gaussian sample, the maximum likelihood estimates (MLE) of the parameters are $\hat{\mu}_\mathrm{MLE}=\bar{x}$ and $(\hat{\sigma}^2)_\mathrm{MLE}=\frac{n-1}{n}s^2$, i.e. the variance divides by $n$ rather than $n^2$. Moreover, in the i.i.d. Gaussian case the standard deviation MLE is just the square root of the MLE variance. However these formulas, as well as the one hinted at in your question, depend on the Gaussian i.i.d. assumption. Update: Additional clarification on "biased" vs. "unbiased". Consider an $n$-element sample as above, $X=\{x_1,\ldots,x_n\}$, with sum-square-deviation $$\delta^2_n=\sum_i(x_i-\bar{x})^2$$ Given the assumptions outlined in the first part above, we necessarily have $$\mathbb{E}[\delta^2_n]=(n-1)\sigma^2$$ so the (Gaussian-)MLE estimator is biased $$\widehat{\sigma^2_n}=\tfrac{1}{n}\delta^2_n \implies \mathbb{E}[\widehat{\sigma^2_n}]=\tfrac{n-1}{n}\sigma^2 $$ while the "sample variance" estimator is unbiased $$s^2_n=\tfrac{1}{n-1}\delta^2_n \implies \mathbb{E}[s^2_n]=\sigma^2$$ Now it is true that $\widehat{\sigma^2_n}$ becomes less biased as the sample size $n$ increases. However $s^2_n$ has zero bias no matter the sample size (so long as $n>1$). For both estimators, the variance of their sampling distribution will be non-zero, and depend on $n$. As an example, the below Matlab code considers an experiment with $n=2$ samples from a standard-normal population $z$. To estimate the sampling distributions for $\bar{x},\widehat{\sigma^2},s^2$, the experiment is repeated $N=10^6$ times. (You can cut & paste the code here to try it out yourself.) % n=sample size, N=number of samples n=2; N=1e6; % generate standard-normal random #'s z=randn(n,N); % i.e. mu=0, sigma=1 % compute sample stats (Gaussian MLE) zbar=sum(z)/n; zvar_mle=sum((z-zbar).^2)/n; % compute ensemble stats (sampling-pdf means) zbar_avg=sum(zbar)/N, zvar_mle_avg=sum(zvar_mle)/N % compute unbiased variance zvar_avg=zvar_mle_avg*n/(n-1) Typical output is like zbar_avg = 1.4442e-04 zvar_mle_avg = 0.49988 zvar_avg = 0.99977 confirming that \begin{align} \mathbb{E}[\bar{z}]&\approx\overline{(\bar{z})}\approx\mu=0 \\ \mathbb{E}[s^2]&\approx\overline{(s^2)}\approx\sigma^2=1 \\ \mathbb{E}[\widehat{\sigma^2}]&\approx\overline{(\widehat{\sigma^2})}\approx\frac{n-1}{n}\sigma^2=\frac{1}{2} \end{align} Update 2: Note on fundamentally "algebraic" nature of unbiased-ness. In the above numerical demonstration, the code approximates the true expectation $\mathbb{E}[\,]$ using an ensemble average with $N=10^6$ replications of the experiment (i.e. each is a sample of size $n=2$). Even with this large number, the typical results quoted above are far from exact. To numerically demonstrate that the estimators are really unbiased, we can use a simple trick to approximate the $N\to\infty$ case: simply add the following line to the code % optional: "whiten" data (ensure exact ensemble stats) [U,S,V]=svd(z-mean(z,2),'econ'); z=sqrt(N)*U*V'; (placing after "generate standard-normal random #'s" and before "compute sample stats") With this simple change, even running the code with $N=10$ gives results like zbar_avg = 1.1102e-17 zvar_mle_avg = 0.50000 zvar_avg = 1.00000
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distrib For the more restricted question Why is a biased standard deviation formula typically used? the simple answer Because the associated variance estimator is unbiased. There is no real mathematical/s
11,352
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution?
The sample standard deviation $S=\sqrt{\frac{\sum (X - \bar{X})^2}{n-1}}$ is complete and sufficient for $\sigma$ so the set of unbiased estimators of $\sigma^k$ given by $$ \frac{(n-1)^\frac{k}{2}}{2^\frac{k}{2}} \cdot \frac{\Gamma\left(\frac{n-1}{2}\right)}{\Gamma\left(\frac{n+k-1}{2}\right)} \cdot S^k = \frac{S^k}{c_k} $$ (See Why is sample standard deviation a biased estimator of $\sigma$?) are, by the Lehmann–Scheffé theorem, UMVUE. Consistent, though biased, estimators of $\sigma^k$ can also be formed as $$ \tilde{\sigma}^k_j= \left(\frac{S^j}{c_j}\right)^\frac{k}{j} $$ (the unbiased estimators being specified when $j=k$). The bias of each is given by $$\operatorname{E}\tilde{\sigma}^k_j - \sigma^k =\left( \frac{c_k}{c_j^\frac{k}{j}} -1 \right) \sigma^k$$ & its variance by $$\operatorname{Var}\tilde{\sigma}^{k}_j=\operatorname{E}\tilde{\sigma}^{2k}_j - \left(\operatorname{E}\tilde{\sigma}^k_j\right)^2=\frac{c_{2k}-c_k^2}{c_j^\frac{2k}{j}} \sigma^{2k}$$ For the two estimators of $\sigma$ you've considered, $\tilde{\sigma}^1_1=\frac{S}{c_1}$ & $\tilde{\sigma}^1_2=S$, the lack of bias of $\tilde{\sigma}_1$ is more than offset by its larger variance when compared to $\tilde{\sigma}_2$: $$\begin{align} \operatorname{E}\tilde{\sigma}_1 - \sigma &= 0 \\ \operatorname{E}\tilde{\sigma}_2 - \sigma &=(c_1 -1) \sigma \\ \operatorname{Var}\tilde{\sigma}_1 =\operatorname{E}\tilde{\sigma}^{2}_1 - \left(\operatorname{E}\tilde{\sigma}^1_1\right)^2 &=\frac{c_{2}-c_1^2}{c_1^2} \sigma^{2} = \left(\frac{1}{c_1^2}-1\right) \sigma^2 \\ \operatorname{Var}\tilde{\sigma}_2 =\operatorname{E}\tilde{\sigma}^{2}_1 - \left(\operatorname{E}\tilde{\sigma}_2\right)^2 &=\frac{c_{2}-c_1^2}{c_2} \sigma^{2}=(1-c_1^2)\sigma^2 \end{align}$$ (Note that $c_2=1$, as $S^2$ is already an unbiased estimator of $\sigma^2$.) The mean square error of $a_k S^k$ as an estimator of $\sigma^2$ is given by $$ \begin{align} (\operatorname{E} a_k S^k - \sigma^k)^2 + \operatorname{E} (a_k S^k)^2 - (\operatorname{E} a_k S^k)^2 &= [ (a_k c_k -1)^2 + a_k^2 c_{2k} - a_k^2 c_k^2 ] \sigma^{2k}\\ &= ( a_k^2 c_{2k} -2 a_k c_k + 1 ) \sigma^{2k} \end{align} $$ & therefore minimized when $$a_k = \frac{c_k}{c_{2k}}$$ , allowing the definition of another set of estimators of potential interest: $$ \hat{\sigma}^k_j= \left(\frac{c_j S^j}{c_{2j}}\right)^\frac{k}{j} $$ Curiously, $\hat{\sigma}^1_1=c_1S$, so the same constant that divides $S$ to remove bias multiplies $S$ to reduce MSE. Anyway, these are the uniformly minimum variance location-invariant & scale-equivariant estimators of $\sigma^k$ (you don't want your estimate to change at all if you measure in kelvins rather than degrees Celsius, & you want it to change by a factor of $\left(\frac{9}{5}\right)^k$ if you measure in Fahrenheit). None of the above has any bearing on the construction of hypothesis tests or confidence intervals (see e.g. Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant?). And $\tilde{\sigma}^k_j$ & $\hat{\sigma}^k_j$ exhaust neither estimators nor parameter scales of potential interest—consider the maximum-likelihood estimator† $\sqrt{\frac{n-1}{n}}S$, or the median-unbiased estimator $\sqrt{\frac{n-1}{\chi^2_{n-1}(0.5)}}S$; or the geometric standard deviation of a lognormal distribution $\mathrm{e}^\sigma$. It may be worth showing a few more-or-less popular estimates made from a small sample ($n=2$) together with the upper & lower bounds, $\sqrt{\frac{(n-1)s^2}{\chi^2_{n-1}(\alpha)}}$ & $\sqrt{\frac{(n-1)s^2}{\chi^2_{n-1}(1-\alpha)}}$, of the equal-tailed confidence interval having coverage $1-\alpha$: The span between the most divergent estimates is negligible in comparison with the width of any confidence interval having decent coverage. (The 95% C.I., for instance, is $(0.45s,31.9s)$.) There's no sense in being finicky about the properties of a point estimator unless you're prepared to be fairly explicit about what you want you want to use it for—most explicitly you can define a custom loss function for a particular application. A reason you might prefer an exactly (or almost) unbiased estimator is that you're going to use it in subsequent calculations during which you don't want bias to accumulate: your illustration of averaging biased estimates of standard deviation is a simple example of such (a more complex example might be using them as a response in a linear regression). In principle an all-encompassing model should obviate the need for unbiased estimates as an intermediate step, but might be considerably more tricky to specify & fit. † The value of $\sigma$ that makes the observed data most probable has an appeal as an estimate independent of consideration of its sampling distribution.
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distrib
The sample standard deviation $S=\sqrt{\frac{\sum (X - \bar{X})^2}{n-1}}$ is complete and sufficient for $\sigma$ so the set of unbiased estimators of $\sigma^k$ given by $$ \frac{(n-1)^\frac{k}{2}}{2
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution? The sample standard deviation $S=\sqrt{\frac{\sum (X - \bar{X})^2}{n-1}}$ is complete and sufficient for $\sigma$ so the set of unbiased estimators of $\sigma^k$ given by $$ \frac{(n-1)^\frac{k}{2}}{2^\frac{k}{2}} \cdot \frac{\Gamma\left(\frac{n-1}{2}\right)}{\Gamma\left(\frac{n+k-1}{2}\right)} \cdot S^k = \frac{S^k}{c_k} $$ (See Why is sample standard deviation a biased estimator of $\sigma$?) are, by the Lehmann–Scheffé theorem, UMVUE. Consistent, though biased, estimators of $\sigma^k$ can also be formed as $$ \tilde{\sigma}^k_j= \left(\frac{S^j}{c_j}\right)^\frac{k}{j} $$ (the unbiased estimators being specified when $j=k$). The bias of each is given by $$\operatorname{E}\tilde{\sigma}^k_j - \sigma^k =\left( \frac{c_k}{c_j^\frac{k}{j}} -1 \right) \sigma^k$$ & its variance by $$\operatorname{Var}\tilde{\sigma}^{k}_j=\operatorname{E}\tilde{\sigma}^{2k}_j - \left(\operatorname{E}\tilde{\sigma}^k_j\right)^2=\frac{c_{2k}-c_k^2}{c_j^\frac{2k}{j}} \sigma^{2k}$$ For the two estimators of $\sigma$ you've considered, $\tilde{\sigma}^1_1=\frac{S}{c_1}$ & $\tilde{\sigma}^1_2=S$, the lack of bias of $\tilde{\sigma}_1$ is more than offset by its larger variance when compared to $\tilde{\sigma}_2$: $$\begin{align} \operatorname{E}\tilde{\sigma}_1 - \sigma &= 0 \\ \operatorname{E}\tilde{\sigma}_2 - \sigma &=(c_1 -1) \sigma \\ \operatorname{Var}\tilde{\sigma}_1 =\operatorname{E}\tilde{\sigma}^{2}_1 - \left(\operatorname{E}\tilde{\sigma}^1_1\right)^2 &=\frac{c_{2}-c_1^2}{c_1^2} \sigma^{2} = \left(\frac{1}{c_1^2}-1\right) \sigma^2 \\ \operatorname{Var}\tilde{\sigma}_2 =\operatorname{E}\tilde{\sigma}^{2}_1 - \left(\operatorname{E}\tilde{\sigma}_2\right)^2 &=\frac{c_{2}-c_1^2}{c_2} \sigma^{2}=(1-c_1^2)\sigma^2 \end{align}$$ (Note that $c_2=1$, as $S^2$ is already an unbiased estimator of $\sigma^2$.) The mean square error of $a_k S^k$ as an estimator of $\sigma^2$ is given by $$ \begin{align} (\operatorname{E} a_k S^k - \sigma^k)^2 + \operatorname{E} (a_k S^k)^2 - (\operatorname{E} a_k S^k)^2 &= [ (a_k c_k -1)^2 + a_k^2 c_{2k} - a_k^2 c_k^2 ] \sigma^{2k}\\ &= ( a_k^2 c_{2k} -2 a_k c_k + 1 ) \sigma^{2k} \end{align} $$ & therefore minimized when $$a_k = \frac{c_k}{c_{2k}}$$ , allowing the definition of another set of estimators of potential interest: $$ \hat{\sigma}^k_j= \left(\frac{c_j S^j}{c_{2j}}\right)^\frac{k}{j} $$ Curiously, $\hat{\sigma}^1_1=c_1S$, so the same constant that divides $S$ to remove bias multiplies $S$ to reduce MSE. Anyway, these are the uniformly minimum variance location-invariant & scale-equivariant estimators of $\sigma^k$ (you don't want your estimate to change at all if you measure in kelvins rather than degrees Celsius, & you want it to change by a factor of $\left(\frac{9}{5}\right)^k$ if you measure in Fahrenheit). None of the above has any bearing on the construction of hypothesis tests or confidence intervals (see e.g. Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant?). And $\tilde{\sigma}^k_j$ & $\hat{\sigma}^k_j$ exhaust neither estimators nor parameter scales of potential interest—consider the maximum-likelihood estimator† $\sqrt{\frac{n-1}{n}}S$, or the median-unbiased estimator $\sqrt{\frac{n-1}{\chi^2_{n-1}(0.5)}}S$; or the geometric standard deviation of a lognormal distribution $\mathrm{e}^\sigma$. It may be worth showing a few more-or-less popular estimates made from a small sample ($n=2$) together with the upper & lower bounds, $\sqrt{\frac{(n-1)s^2}{\chi^2_{n-1}(\alpha)}}$ & $\sqrt{\frac{(n-1)s^2}{\chi^2_{n-1}(1-\alpha)}}$, of the equal-tailed confidence interval having coverage $1-\alpha$: The span between the most divergent estimates is negligible in comparison with the width of any confidence interval having decent coverage. (The 95% C.I., for instance, is $(0.45s,31.9s)$.) There's no sense in being finicky about the properties of a point estimator unless you're prepared to be fairly explicit about what you want you want to use it for—most explicitly you can define a custom loss function for a particular application. A reason you might prefer an exactly (or almost) unbiased estimator is that you're going to use it in subsequent calculations during which you don't want bias to accumulate: your illustration of averaging biased estimates of standard deviation is a simple example of such (a more complex example might be using them as a response in a linear regression). In principle an all-encompassing model should obviate the need for unbiased estimates as an intermediate step, but might be considerably more tricky to specify & fit. † The value of $\sigma$ that makes the observed data most probable has an appeal as an estimate independent of consideration of its sampling distribution.
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distrib The sample standard deviation $S=\sqrt{\frac{\sum (X - \bar{X})^2}{n-1}}$ is complete and sufficient for $\sigma$ so the set of unbiased estimators of $\sigma^k$ given by $$ \frac{(n-1)^\frac{k}{2}}{2
11,353
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution?
Q2: Would someone please explain to me why we are using SD anyway as it is clearly biased and misleading? This came up as an aside in comments, but I think it bears repeating because it's the crux of the answer: The sample variance formula is unbiased, and variances are additive. So if you expect to do any (affine) transformations, this is a serious statistical reason why you should insist on a "nice" variance estimator over a "nice" SD estimator. In an ideal world, they'd be equivalent. But that's not true in this universe. You have to choose one, so you might as well choose the one that lets you combine information down the road. Comparing two sample means? The variance of their difference is sum of their variances. Doing a linear contrast with several terms? Get its variance by taking a linear combination of their variances. Looking at regression line fits? Get their variance using the variance-covariance matrix of your estimated beta coefficients. Using F-tests, or t-tests, or t-based confidence intervals? The F-test calls for variances directly; and the t-test is exactly equivalent to the square root of an F-test. In each of these common scenarios, if you start with unbiased variances, you'll remain unbiased all the way (unless your final step converts to SDs for reporting). Meanwhile, if you'd started with unbiased SDs, neither your intermediate steps nor the final outcome would be unbiased anyway.
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distrib
Q2: Would someone please explain to me why we are using SD anyway as it is clearly biased and misleading? This came up as an aside in comments, but I think it bears repeating because it's the crux o
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution? Q2: Would someone please explain to me why we are using SD anyway as it is clearly biased and misleading? This came up as an aside in comments, but I think it bears repeating because it's the crux of the answer: The sample variance formula is unbiased, and variances are additive. So if you expect to do any (affine) transformations, this is a serious statistical reason why you should insist on a "nice" variance estimator over a "nice" SD estimator. In an ideal world, they'd be equivalent. But that's not true in this universe. You have to choose one, so you might as well choose the one that lets you combine information down the road. Comparing two sample means? The variance of their difference is sum of their variances. Doing a linear contrast with several terms? Get its variance by taking a linear combination of their variances. Looking at regression line fits? Get their variance using the variance-covariance matrix of your estimated beta coefficients. Using F-tests, or t-tests, or t-based confidence intervals? The F-test calls for variances directly; and the t-test is exactly equivalent to the square root of an F-test. In each of these common scenarios, if you start with unbiased variances, you'll remain unbiased all the way (unless your final step converts to SDs for reporting). Meanwhile, if you'd started with unbiased SDs, neither your intermediate steps nor the final outcome would be unbiased anyway.
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distrib Q2: Would someone please explain to me why we are using SD anyway as it is clearly biased and misleading? This came up as an aside in comments, but I think it bears repeating because it's the crux o
11,354
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution?
This post is in outline form. (1) Taking a square root is not an affine transformation (Credit @Scortchi.) (2) ${\rm var}(s) = {\rm E} (s^2) - {\rm E}(s)^2$, thus ${\rm E}(s) = \sqrt{{\rm E}(s^2) -{\rm var}(s)}\neq{\sqrt{\rm var(s)}}$ (3) $ {\rm var}(s)=\frac{\Sigma_{i=1}^{n}(x_i-\bar{x})^2}{n-1}$, whereas $\text{E}(s)\,=\,\,\frac{\Gamma\left(\frac{n-1}{2}\right)}{\Gamma\left(\frac{n}{2}\right)}\sqrt{\frac{\Sigma_{i=1}^{n}(x_i-\bar{x})^2}{2}}$$\neq\sqrt{\frac{\Sigma_{i=1}^{n}(x_i-\bar{x})^2}{n-1}}={\sqrt{\rm var(s)}}$ (4) Thus, we cannot substitute ${\sqrt{\rm var(s)}}$ for $\text{E}(s)$, for $n$ small, as square root is not affine. (5) ${\rm var}(s)$ and $\text{E}(s)$ are unbiased (Credit @GeoMatt22 and @Macro, respectively). (6) For non-normal distributions $\bar{x}$ is sometimes (a) undefined (e.g., Cauchy, Pareto with small $\alpha$) and (b) not UMVUE (e.g., Cauchy ($\rightarrow$ Student's-$t$ with $df=1$), Pareto, Uniform, beta). Even more commonly, variance may be undefined, e.g. Student's-$t$ with $1\leq df\leq2$. Then one can state that $\text{var}(s)$ is not UMVUE for the general case distribution. Thus, there is then no special onus to introducing an approximate small number correction for standard deviation, which likely has similar limitations to $\sqrt{\text{var}(s)}$, but is additionally less biased, $\hat\sigma = \sqrt{ \frac{1}{n - 1.5 - \tfrac14 \gamma_2} \sum_{i=1}^n (x_i - \bar{x})^2 }$ , where $\gamma_2$ is excess kurtosis. In a similar vein, when examining a normal squared distribution (a Chi-squared with $df=1$ transform), we might be tempted to take its square root and use the resulting normal distribution properties. That is, in general, the normal distribution can result from transformations of other distributions and it may be expedient to examine the properties of that normal distribution such that the limitation of small number correction to the normal case is not so severe a restriction as one might at first assume. For the normal distribution case: A1: By Lehmann-Scheffe theorem ${\rm var}(s)$ and $\text{E}(s)$ are UMVUE (Credit @Scortchi). A2: (Edited to adjust for comments below.) For $n\leq 25$, we should use $\text{E}(s)$ for standard deviation, standard error, confidence intervals of the mean and of the distribution, and optionally for z-statistics. For $t$-testing we would not use the unbiased estimator as $\frac{ \bar X - \mu} {\sqrt{\text{var}(n)/n}}$ itself is Student's-$t$ distributed with $n-1$ degrees of freedom (Credit @whuber and @GeoMatt22). For z-statistics, $\sigma$ is usually approximated using $n$ large for which $\text{E}(s)-\sqrt{\text{var}(n)}$ is small, but for which $\text{E}(s)$ appears to be more mathematically appropriate (Credit @whuber and @GeoMatt22).
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distrib
This post is in outline form. (1) Taking a square root is not an affine transformation (Credit @Scortchi.) (2) ${\rm var}(s) = {\rm E} (s^2) - {\rm E}(s)^2$, thus ${\rm E}(s) = \sqrt{{\rm E}(s^2) -{\
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution? This post is in outline form. (1) Taking a square root is not an affine transformation (Credit @Scortchi.) (2) ${\rm var}(s) = {\rm E} (s^2) - {\rm E}(s)^2$, thus ${\rm E}(s) = \sqrt{{\rm E}(s^2) -{\rm var}(s)}\neq{\sqrt{\rm var(s)}}$ (3) $ {\rm var}(s)=\frac{\Sigma_{i=1}^{n}(x_i-\bar{x})^2}{n-1}$, whereas $\text{E}(s)\,=\,\,\frac{\Gamma\left(\frac{n-1}{2}\right)}{\Gamma\left(\frac{n}{2}\right)}\sqrt{\frac{\Sigma_{i=1}^{n}(x_i-\bar{x})^2}{2}}$$\neq\sqrt{\frac{\Sigma_{i=1}^{n}(x_i-\bar{x})^2}{n-1}}={\sqrt{\rm var(s)}}$ (4) Thus, we cannot substitute ${\sqrt{\rm var(s)}}$ for $\text{E}(s)$, for $n$ small, as square root is not affine. (5) ${\rm var}(s)$ and $\text{E}(s)$ are unbiased (Credit @GeoMatt22 and @Macro, respectively). (6) For non-normal distributions $\bar{x}$ is sometimes (a) undefined (e.g., Cauchy, Pareto with small $\alpha$) and (b) not UMVUE (e.g., Cauchy ($\rightarrow$ Student's-$t$ with $df=1$), Pareto, Uniform, beta). Even more commonly, variance may be undefined, e.g. Student's-$t$ with $1\leq df\leq2$. Then one can state that $\text{var}(s)$ is not UMVUE for the general case distribution. Thus, there is then no special onus to introducing an approximate small number correction for standard deviation, which likely has similar limitations to $\sqrt{\text{var}(s)}$, but is additionally less biased, $\hat\sigma = \sqrt{ \frac{1}{n - 1.5 - \tfrac14 \gamma_2} \sum_{i=1}^n (x_i - \bar{x})^2 }$ , where $\gamma_2$ is excess kurtosis. In a similar vein, when examining a normal squared distribution (a Chi-squared with $df=1$ transform), we might be tempted to take its square root and use the resulting normal distribution properties. That is, in general, the normal distribution can result from transformations of other distributions and it may be expedient to examine the properties of that normal distribution such that the limitation of small number correction to the normal case is not so severe a restriction as one might at first assume. For the normal distribution case: A1: By Lehmann-Scheffe theorem ${\rm var}(s)$ and $\text{E}(s)$ are UMVUE (Credit @Scortchi). A2: (Edited to adjust for comments below.) For $n\leq 25$, we should use $\text{E}(s)$ for standard deviation, standard error, confidence intervals of the mean and of the distribution, and optionally for z-statistics. For $t$-testing we would not use the unbiased estimator as $\frac{ \bar X - \mu} {\sqrt{\text{var}(n)/n}}$ itself is Student's-$t$ distributed with $n-1$ degrees of freedom (Credit @whuber and @GeoMatt22). For z-statistics, $\sigma$ is usually approximated using $n$ large for which $\text{E}(s)-\sqrt{\text{var}(n)}$ is small, but for which $\text{E}(s)$ appears to be more mathematically appropriate (Credit @whuber and @GeoMatt22).
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distrib This post is in outline form. (1) Taking a square root is not an affine transformation (Credit @Scortchi.) (2) ${\rm var}(s) = {\rm E} (s^2) - {\rm E}(s)^2$, thus ${\rm E}(s) = \sqrt{{\rm E}(s^2) -{\
11,355
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution?
I want to add the Bayesian answer to this discussion. Just because your assumption is that the data is generated according to some normal with unknown mean and variance, that doesn't mean that you should summarize your data using a mean and a variance. This whole problem can be avoided if you draw the model, which will have a posterior predictive that is a three parameter noncentral scaled student's T distribution. The three parameters are the total of the samples, total of the squared samples, and the number of samples. (Or any bijective map of these.) Incidentally, I like civilstat's answer because it highlights our desire to combine information. The three sufficient statistics above are even better than the two given in the question (or by civilstat's answer). Two sets of these statistics can easily be combined, and they give the best posterior predictive given the assumption of normality.
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distrib
I want to add the Bayesian answer to this discussion. Just because your assumption is that the data is generated according to some normal with unknown mean and variance, that doesn't mean that you sh
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distribution? I want to add the Bayesian answer to this discussion. Just because your assumption is that the data is generated according to some normal with unknown mean and variance, that doesn't mean that you should summarize your data using a mean and a variance. This whole problem can be avoided if you draw the model, which will have a posterior predictive that is a three parameter noncentral scaled student's T distribution. The three parameters are the total of the samples, total of the squared samples, and the number of samples. (Or any bijective map of these.) Incidentally, I like civilstat's answer because it highlights our desire to combine information. The three sufficient statistics above are even better than the two given in the question (or by civilstat's answer). Two sets of these statistics can easily be combined, and they give the best posterior predictive given the assumption of normality.
Why are we using a biased and misleading standard deviation formula for $\sigma$ of a normal distrib I want to add the Bayesian answer to this discussion. Just because your assumption is that the data is generated according to some normal with unknown mean and variance, that doesn't mean that you sh
11,356
Good resource to understand ANOVA and ANCOVA?
The classics I think are Winer and Kirk, both cover essentially only ANOVA and ANCOVA. You can probably get used copys for cheap (e.g., I own a Winer second edition from 71 bought via AMAZON for less than 10$): Winer - Statistical Principles In Experimental Design Kirk - Experimental Design A more contemporary book is the one by Maxwell & Delaney. Besides ANOVA and ANCOVA it covers other methods, e.g., multivariate and multilevel: Maxwell & Delaney - Designing Experiments and Analyzing Data: A Model Comparison Perspective Perhaps it is the best to go with this last one. It is pretty good.
Good resource to understand ANOVA and ANCOVA?
The classics I think are Winer and Kirk, both cover essentially only ANOVA and ANCOVA. You can probably get used copys for cheap (e.g., I own a Winer second edition from 71 bought via AMAZON for less
Good resource to understand ANOVA and ANCOVA? The classics I think are Winer and Kirk, both cover essentially only ANOVA and ANCOVA. You can probably get used copys for cheap (e.g., I own a Winer second edition from 71 bought via AMAZON for less than 10$): Winer - Statistical Principles In Experimental Design Kirk - Experimental Design A more contemporary book is the one by Maxwell & Delaney. Besides ANOVA and ANCOVA it covers other methods, e.g., multivariate and multilevel: Maxwell & Delaney - Designing Experiments and Analyzing Data: A Model Comparison Perspective Perhaps it is the best to go with this last one. It is pretty good.
Good resource to understand ANOVA and ANCOVA? The classics I think are Winer and Kirk, both cover essentially only ANOVA and ANCOVA. You can probably get used copys for cheap (e.g., I own a Winer second edition from 71 bought via AMAZON for less
11,357
Good resource to understand ANOVA and ANCOVA?
So, in addition to this paper, Misunderstanding Analysis of Covariance, which enumerates common pitfalls when using ANCOVA, I would recommend starting with: Frank Harrell's homepage, especially his handout on Regression Modeling Strategies and Biostatistical Modeling John Fox's homepage includes great material on Linear Model Practical Regression and Anova using R This is mostly R-oriented material, but I feel you might better catch the idea if you start playing a little bit with these models on toy examples or real datasets (and R is great for that). As for a good book, I would recommend Design and Analysis of Experiments by Montgomery (now in its 7th ed.); ANCOVA is described in chapter 15. Plane Answers to Complex Questions by Christensen is an excellent book on the theory of linear model (ANCOVA in chapter 9); it assumes a good mathematical background. Any biostatistical textbook should cover both topics, but I like Biostatistical Analysis by Zar (ANCOVA in chapter 12), mainly because this was one of my first textbook. And finally, H. Baayen's textbook is very complete, Practical Data Analysis for the Language Sciences with R. Although it focus on linguistic data, it includes a very comprehensive treatment of the Linear Model and mixed-effects models.
Good resource to understand ANOVA and ANCOVA?
So, in addition to this paper, Misunderstanding Analysis of Covariance, which enumerates common pitfalls when using ANCOVA, I would recommend starting with: Frank Harrell's homepage, especially his h
Good resource to understand ANOVA and ANCOVA? So, in addition to this paper, Misunderstanding Analysis of Covariance, which enumerates common pitfalls when using ANCOVA, I would recommend starting with: Frank Harrell's homepage, especially his handout on Regression Modeling Strategies and Biostatistical Modeling John Fox's homepage includes great material on Linear Model Practical Regression and Anova using R This is mostly R-oriented material, but I feel you might better catch the idea if you start playing a little bit with these models on toy examples or real datasets (and R is great for that). As for a good book, I would recommend Design and Analysis of Experiments by Montgomery (now in its 7th ed.); ANCOVA is described in chapter 15. Plane Answers to Complex Questions by Christensen is an excellent book on the theory of linear model (ANCOVA in chapter 9); it assumes a good mathematical background. Any biostatistical textbook should cover both topics, but I like Biostatistical Analysis by Zar (ANCOVA in chapter 12), mainly because this was one of my first textbook. And finally, H. Baayen's textbook is very complete, Practical Data Analysis for the Language Sciences with R. Although it focus on linguistic data, it includes a very comprehensive treatment of the Linear Model and mixed-effects models.
Good resource to understand ANOVA and ANCOVA? So, in addition to this paper, Misunderstanding Analysis of Covariance, which enumerates common pitfalls when using ANCOVA, I would recommend starting with: Frank Harrell's homepage, especially his h
11,358
Good resource to understand ANOVA and ANCOVA?
Applied Linear Statistical Models by Neter, Kutner, Wasserman, and Nachtscheim, has a very exhaustive (and exhausting!) treatment of ANOVA and ANCOVA. It also covers power analysis, linear regression, multilinear regression, and introduces some MANOVA. It's a very long text, but does a very thorough job. I've linked you to the fourth edition. I doubt there's a huge difference over the fifth edition, and it's substantially cheaper.
Good resource to understand ANOVA and ANCOVA?
Applied Linear Statistical Models by Neter, Kutner, Wasserman, and Nachtscheim, has a very exhaustive (and exhausting!) treatment of ANOVA and ANCOVA. It also covers power analysis, linear regression,
Good resource to understand ANOVA and ANCOVA? Applied Linear Statistical Models by Neter, Kutner, Wasserman, and Nachtscheim, has a very exhaustive (and exhausting!) treatment of ANOVA and ANCOVA. It also covers power analysis, linear regression, multilinear regression, and introduces some MANOVA. It's a very long text, but does a very thorough job. I've linked you to the fourth edition. I doubt there's a huge difference over the fifth edition, and it's substantially cheaper.
Good resource to understand ANOVA and ANCOVA? Applied Linear Statistical Models by Neter, Kutner, Wasserman, and Nachtscheim, has a very exhaustive (and exhausting!) treatment of ANOVA and ANCOVA. It also covers power analysis, linear regression,
11,359
Good resource to understand ANOVA and ANCOVA?
Gelman has a good discussion paper on ANOVA Analysis of variance—why it is more important than ever
Good resource to understand ANOVA and ANCOVA?
Gelman has a good discussion paper on ANOVA Analysis of variance—why it is more important than ever
Good resource to understand ANOVA and ANCOVA? Gelman has a good discussion paper on ANOVA Analysis of variance—why it is more important than ever
Good resource to understand ANOVA and ANCOVA? Gelman has a good discussion paper on ANOVA Analysis of variance—why it is more important than ever
11,360
Good resource to understand ANOVA and ANCOVA?
In my line of work, I've found this one to be quite useful: Statistical Methods for Psychology (Howell, 2009)
Good resource to understand ANOVA and ANCOVA?
In my line of work, I've found this one to be quite useful: Statistical Methods for Psychology (Howell, 2009)
Good resource to understand ANOVA and ANCOVA? In my line of work, I've found this one to be quite useful: Statistical Methods for Psychology (Howell, 2009)
Good resource to understand ANOVA and ANCOVA? In my line of work, I've found this one to be quite useful: Statistical Methods for Psychology (Howell, 2009)
11,361
Good resource to understand ANOVA and ANCOVA?
The R book does a good job on that. You can see that it dedicates one chapter to each one of those methods (11 and 12). If you are new to R, this is a great book to start with.
Good resource to understand ANOVA and ANCOVA?
The R book does a good job on that. You can see that it dedicates one chapter to each one of those methods (11 and 12). If you are new to R, this is a great book to start with.
Good resource to understand ANOVA and ANCOVA? The R book does a good job on that. You can see that it dedicates one chapter to each one of those methods (11 and 12). If you are new to R, this is a great book to start with.
Good resource to understand ANOVA and ANCOVA? The R book does a good job on that. You can see that it dedicates one chapter to each one of those methods (11 and 12). If you are new to R, this is a great book to start with.
11,362
Why are second-order derivatives useful in convex optimization?
Here's a common framework for interpreting both gradient descent and Newton's method, which is maybe a useful way to think of the difference as a supplement to @Sycorax's answer. (BFGS approximates Newton's method; I won't talk about it in particular here.) We're minimizing the function $f$, but we don't know how to do that directly. So, instead, we take a local approximation at our current point $x$ and minimize that. Newton's method approximates the function using a second-order Taylor expansion: $$ f(y) \approx N_x(y) := f(x) + \nabla f(x)^T (y - x) + \tfrac12 (y - x)^T \, \nabla^2 f(x) \, (y - x) ,$$ where $\nabla f(x)$ denotes the gradient of $f$ at the point $x$ and $\nabla^2 f(x)$ the Hessian at $x$. It then steps to $\arg\min_y N_x(y)$ and repeats. Gradient descent, only having the gradient and not the Hessian, can't just make a first-order approximation and minimize that, since as @Hurkyl noted it has no minimum. Instead, we define a step size $t$ and step to $x - t \nabla f(x)$. But note that \begin{align} x - t \,\nabla f(x) &= \arg\max_y \left[f(x) + \nabla f(x)^T (y - x) + \tfrac{1}{2 t} \lVert y - x \rVert^2\right] \\&= \arg\max_y \left[f(x) + \nabla f(x)^T (y - x) + \tfrac12 (y-x)^T \tfrac{1}{t} I (y - x)\right] .\end{align} Thus gradient descent minimizes a function $$G_x(y) := f(x) + \nabla f(x)^T (y - x) + \tfrac12 (y-x)^T \tfrac{1}{t} I (y - x).$$ Thus gradient descent is kind of like using Newton's method, but instead of taking the second-order Taylor expansion, we pretend that the Hessian is $\tfrac1t I$. This $G$ is often a substantially worse approximation to $f$ than $N$, and hence gradient descent often takes much worse steps than Newton's method. This is counterbalanced, of course, by each step of gradient descent being so much cheaper to compute than each step of Newton's method. Which is better depends entirely on the nature of the problem, your computational resources, and your accuracy requirements. Looking at @Sycorax's example of minimizing a quadratic $$ f(x) = \tfrac12 x^T A x + d^T x + c $$ for a moment, it's worth noting that this perspective helps with understanding both methods. With Newton's method, we'll have $N = f$ so that it terminates with the exact answer (up to floating point accuracy issues) in a single step. Gradient descent, on the other hand, uses $$ G_x(y) = f(x) + (A x + d)^T y + \tfrac12 (x - y)^T \tfrac1t I (x-y) $$ whose tangent plane at $x$ is correct, but whose curvature is entirely wrong, and indeed throws away the important differences in different directions when the eigenvalues of $A$ vary substantially.
Why are second-order derivatives useful in convex optimization?
Here's a common framework for interpreting both gradient descent and Newton's method, which is maybe a useful way to think of the difference as a supplement to @Sycorax's answer. (BFGS approximates Ne
Why are second-order derivatives useful in convex optimization? Here's a common framework for interpreting both gradient descent and Newton's method, which is maybe a useful way to think of the difference as a supplement to @Sycorax's answer. (BFGS approximates Newton's method; I won't talk about it in particular here.) We're minimizing the function $f$, but we don't know how to do that directly. So, instead, we take a local approximation at our current point $x$ and minimize that. Newton's method approximates the function using a second-order Taylor expansion: $$ f(y) \approx N_x(y) := f(x) + \nabla f(x)^T (y - x) + \tfrac12 (y - x)^T \, \nabla^2 f(x) \, (y - x) ,$$ where $\nabla f(x)$ denotes the gradient of $f$ at the point $x$ and $\nabla^2 f(x)$ the Hessian at $x$. It then steps to $\arg\min_y N_x(y)$ and repeats. Gradient descent, only having the gradient and not the Hessian, can't just make a first-order approximation and minimize that, since as @Hurkyl noted it has no minimum. Instead, we define a step size $t$ and step to $x - t \nabla f(x)$. But note that \begin{align} x - t \,\nabla f(x) &= \arg\max_y \left[f(x) + \nabla f(x)^T (y - x) + \tfrac{1}{2 t} \lVert y - x \rVert^2\right] \\&= \arg\max_y \left[f(x) + \nabla f(x)^T (y - x) + \tfrac12 (y-x)^T \tfrac{1}{t} I (y - x)\right] .\end{align} Thus gradient descent minimizes a function $$G_x(y) := f(x) + \nabla f(x)^T (y - x) + \tfrac12 (y-x)^T \tfrac{1}{t} I (y - x).$$ Thus gradient descent is kind of like using Newton's method, but instead of taking the second-order Taylor expansion, we pretend that the Hessian is $\tfrac1t I$. This $G$ is often a substantially worse approximation to $f$ than $N$, and hence gradient descent often takes much worse steps than Newton's method. This is counterbalanced, of course, by each step of gradient descent being so much cheaper to compute than each step of Newton's method. Which is better depends entirely on the nature of the problem, your computational resources, and your accuracy requirements. Looking at @Sycorax's example of minimizing a quadratic $$ f(x) = \tfrac12 x^T A x + d^T x + c $$ for a moment, it's worth noting that this perspective helps with understanding both methods. With Newton's method, we'll have $N = f$ so that it terminates with the exact answer (up to floating point accuracy issues) in a single step. Gradient descent, on the other hand, uses $$ G_x(y) = f(x) + (A x + d)^T y + \tfrac12 (x - y)^T \tfrac1t I (x-y) $$ whose tangent plane at $x$ is correct, but whose curvature is entirely wrong, and indeed throws away the important differences in different directions when the eigenvalues of $A$ vary substantially.
Why are second-order derivatives useful in convex optimization? Here's a common framework for interpreting both gradient descent and Newton's method, which is maybe a useful way to think of the difference as a supplement to @Sycorax's answer. (BFGS approximates Ne
11,363
Why are second-order derivatives useful in convex optimization?
Essentially, the advantage of a second-derivative method like Newton's method is that it has the quality of quadratic termination. This means that it can minimize a quadratic function in a finite number of steps. A method like gradient descent depends heavily on the learning rate, which can cause optimization to either converge slowly because it's bouncing around the optimum, or to diverge entirely. Stable learning rates can be found... but involve computing the hessian. Even when using a stable learning rate, you can have problems like oscillation around the optimum, i.e. you won't always take a "direct" or "efficient" path towards the minimum. So it can take many iterations to terminate, even if you're relatively close to it. BFGS and Newton's method can converge more quickly even though the computational effort of each step is more expensive. To your request for examples: Suppose you have the objective function $$ F(x)=\frac{1}{2}x^TAx+d^Tx+c $$ The gradient is $$ \nabla F(x)=Ax+d $$ and putting it into the steepest descent form with constant learning rate $$ x_{k+1}= x_k-\alpha(Ax_k+d) = (I-\alpha A)x_k-\alpha d. $$ This will be stable if the magnitudes of the eigenvalues of $I-\alpha A$ are less than 1. We can use this property to show that a stable learning rate satisfies $$\alpha<\frac{2}{\lambda_{max}},$$ where $\lambda_{max}$ is the largest eigenvalue of $A$. Choosing a learning rate which is too large will overshoot the minimum, and the optimization will diverge. The steepest descent algorithm's convergence rate is limited by the largest eigenvalue and the routine will converge most quickly in the direction of its corresponding eigenvector. Likewise, it will converge most slowly in directions of the eigenvector of the smallest eigenvalue. When there is a large disparity between large and small eigenvalues for $A$, gradient descent will be slow. Any $A$ with this property will converge slowly using gradient descent. In the specific context of neural networks, the book Neural Network Design has quite a bit of information on numerical optimization methods. The above discussion is a condensation of section 9-7.
Why are second-order derivatives useful in convex optimization?
Essentially, the advantage of a second-derivative method like Newton's method is that it has the quality of quadratic termination. This means that it can minimize a quadratic function in a finite numb
Why are second-order derivatives useful in convex optimization? Essentially, the advantage of a second-derivative method like Newton's method is that it has the quality of quadratic termination. This means that it can minimize a quadratic function in a finite number of steps. A method like gradient descent depends heavily on the learning rate, which can cause optimization to either converge slowly because it's bouncing around the optimum, or to diverge entirely. Stable learning rates can be found... but involve computing the hessian. Even when using a stable learning rate, you can have problems like oscillation around the optimum, i.e. you won't always take a "direct" or "efficient" path towards the minimum. So it can take many iterations to terminate, even if you're relatively close to it. BFGS and Newton's method can converge more quickly even though the computational effort of each step is more expensive. To your request for examples: Suppose you have the objective function $$ F(x)=\frac{1}{2}x^TAx+d^Tx+c $$ The gradient is $$ \nabla F(x)=Ax+d $$ and putting it into the steepest descent form with constant learning rate $$ x_{k+1}= x_k-\alpha(Ax_k+d) = (I-\alpha A)x_k-\alpha d. $$ This will be stable if the magnitudes of the eigenvalues of $I-\alpha A$ are less than 1. We can use this property to show that a stable learning rate satisfies $$\alpha<\frac{2}{\lambda_{max}},$$ where $\lambda_{max}$ is the largest eigenvalue of $A$. Choosing a learning rate which is too large will overshoot the minimum, and the optimization will diverge. The steepest descent algorithm's convergence rate is limited by the largest eigenvalue and the routine will converge most quickly in the direction of its corresponding eigenvector. Likewise, it will converge most slowly in directions of the eigenvector of the smallest eigenvalue. When there is a large disparity between large and small eigenvalues for $A$, gradient descent will be slow. Any $A$ with this property will converge slowly using gradient descent. In the specific context of neural networks, the book Neural Network Design has quite a bit of information on numerical optimization methods. The above discussion is a condensation of section 9-7.
Why are second-order derivatives useful in convex optimization? Essentially, the advantage of a second-derivative method like Newton's method is that it has the quality of quadratic termination. This means that it can minimize a quadratic function in a finite numb
11,364
Why are second-order derivatives useful in convex optimization?
In convex optimization you are approximating the function as the second degree polynomial in one dimensional case: $$f(x)=c+\beta x + \alpha x^2$$ In this case the the second derivative $$\partial^2 f(x)/\partial x^2=2\alpha$$ If you know the derivatives, then it's easy to get the next guess for the optimum: $$\text{guess}=-\frac{\beta}{2\alpha}$$ The multivariate case is very similar, just use gradients for derivatives.
Why are second-order derivatives useful in convex optimization?
In convex optimization you are approximating the function as the second degree polynomial in one dimensional case: $$f(x)=c+\beta x + \alpha x^2$$ In this case the the second derivative $$\partial^2 f
Why are second-order derivatives useful in convex optimization? In convex optimization you are approximating the function as the second degree polynomial in one dimensional case: $$f(x)=c+\beta x + \alpha x^2$$ In this case the the second derivative $$\partial^2 f(x)/\partial x^2=2\alpha$$ If you know the derivatives, then it's easy to get the next guess for the optimum: $$\text{guess}=-\frac{\beta}{2\alpha}$$ The multivariate case is very similar, just use gradients for derivatives.
Why are second-order derivatives useful in convex optimization? In convex optimization you are approximating the function as the second degree polynomial in one dimensional case: $$f(x)=c+\beta x + \alpha x^2$$ In this case the the second derivative $$\partial^2 f
11,365
Why are second-order derivatives useful in convex optimization?
@Danica already gave a great technical answer. The no-maths explanation is that while the linear (order 1) approximation provides a “plane” that is tangential to a point on an error surface, the quadratic approximation (order 2) provides a surface that hugs the curvature of the error surface. The videos on this link do a great job of visualizing this concept. They display order 0, order 1 and order 2 approximations to the function surface, which just intuitively verifies what the other answers present mathematically. Also, a good blogpost on the topic (applied to neural networks) is here.
Why are second-order derivatives useful in convex optimization?
@Danica already gave a great technical answer. The no-maths explanation is that while the linear (order 1) approximation provides a “plane” that is tangential to a point on an error surface, the quadr
Why are second-order derivatives useful in convex optimization? @Danica already gave a great technical answer. The no-maths explanation is that while the linear (order 1) approximation provides a “plane” that is tangential to a point on an error surface, the quadratic approximation (order 2) provides a surface that hugs the curvature of the error surface. The videos on this link do a great job of visualizing this concept. They display order 0, order 1 and order 2 approximations to the function surface, which just intuitively verifies what the other answers present mathematically. Also, a good blogpost on the topic (applied to neural networks) is here.
Why are second-order derivatives useful in convex optimization? @Danica already gave a great technical answer. The no-maths explanation is that while the linear (order 1) approximation provides a “plane” that is tangential to a point on an error surface, the quadr
11,366
ACF and PACF Formula
Autocorrelations The correlation between two variables $y_1, y_2$ is defined as: $$ \rho = \frac{\hbox{E}\left[(y_1-\mu_1)(y_2-\mu_2)\right]}{\sigma_1 \sigma_2} = \frac{\hbox{Cov}(y_1, y_2)}{\sigma_1 \sigma_2} \,, $$ where E is the expectation operator, $\mu_1$ and $\mu_2$ are the means respectively for $y_1$ and $y_2$ and $\sigma_1, \sigma_2$ are their standard deviations. In the context of a single variable, i.e. auto-correlation, $y_1$ is the original series and $y_2$ is a lagged version of it. Upon the above definition, sample autocorrelations of order $k=0,1,2,...$ can be obtained by computing the following expression with the observed series $y_t$, $t=1,2,...,n$: $$ \rho(k) = \frac{\frac{1}{n-k}\sum_{t=k+1}^n (y_t - \bar{y})(y_{t-k} - \bar{y})}{ \sqrt{\frac{1}{n}\sum_{t=1}^n (y_t - \bar{y})^2}\sqrt{\frac{1}{n-k}\sum_{t=k+1}^n (y_{t-k} - \bar{y})^2}} \,, $$ where $\bar{y}$ is the sample mean of the data. Partial autocorrelations Partial autocorrelations measure the linear dependence of one variable after removing the effect of other variable(s) that affect to both variables. For example, the partial autocorrelation of order measures the effect (linear dependence) of $y_{t-2}$ on $y_t$ after removing the effect of $y_{t-1}$ on both $y_t$ and $y_{t-2}$. Each partial autocorrelation could be obtained as a series of regressions of the form: $$ \tilde{y}_t = \phi_{21} \tilde{y}_{t-1} + \phi_{22} \tilde{y}_{t-2} + e_t \,, $$ where $\tilde{y}_t$ is the original series minus the sample mean, $y_t - \bar{y}$. The estimate of $\phi_{22}$ will give the value of the partial autocorrelation of order 2. Extending the regression with $k$ additional lags, the estimate of the last term will give the partial autocorrelation of order $k$. An alternative way to compute the sample partial autocorrelations is by solving the following system for each order $k$: \begin{eqnarray} \left(\begin{array}{cccc} \rho(0) & \rho(1) & \cdots & \rho(k-1) \\ \rho(1) & \rho(0) & \cdots & \rho(k-2) \\ \vdots & \vdots & \vdots & \vdots \\ \rho(k-1) & \rho(k-2) & \cdots & \rho(0) \\ \end{array}\right) \left(\begin{array}{c} \phi_{k1} \\ \phi_{k2} \\ \vdots \\ \phi_{kk} \\ \end{array}\right) = \left(\begin{array}{c} \rho(1) \\ \rho(2) \\ \vdots \\ \rho(k) \\ \end{array}\right) \,, \end{eqnarray} where $\rho(\cdot)$ are the sample autocorrelations. This mapping between the sample autocorrelations and the partial autocorrelations is known as the Durbin-Levinson recursion. This approach is relatively easy to implement for illustration. For example, in the R software, we can obtain the partial autocorrelation of order 5 as follows: # sample data x <- diff(AirPassengers) # autocorrelations sacf <- acf(x, lag.max = 10, plot = FALSE)$acf[,,1] # solve the system of equations res1 <- solve(toeplitz(sacf[1:5]), sacf[2:6]) res1 # [1] 0.29992688 -0.18784728 -0.08468517 -0.22463189 0.01008379 # benchmark result res2 <- pacf(x, lag.max = 5, plot = FALSE)$acf[,,1] res2 # [1] 0.30285526 -0.21344644 -0.16044680 -0.22163003 0.01008379 all.equal(res1[5], res2[5]) # [1] TRUE Confidence bands Confidence bands can be computed as the value of the sample autocorrelations $\pm \frac{z_{1-\alpha/2}}{\sqrt{n}}$, where $z_{1-\alpha/2}$ is the quantile $1-\alpha/2$ in the Gaussian distribution, e.g. 1.96 for 95% confidence bands. Sometimes confidence bands that increase as the order increases are used. In this cases the bands can be defined as $\pm z_{1-\alpha/2}\sqrt{\frac{1}{n}\left(1 + 2\sum_{i=1}^k \rho(i)^2\right)}$.
ACF and PACF Formula
Autocorrelations The correlation between two variables $y_1, y_2$ is defined as: $$ \rho = \frac{\hbox{E}\left[(y_1-\mu_1)(y_2-\mu_2)\right]}{\sigma_1 \sigma_2} = \frac{\hbox{Cov}(y_1, y_2)}{\sigma_1
ACF and PACF Formula Autocorrelations The correlation between two variables $y_1, y_2$ is defined as: $$ \rho = \frac{\hbox{E}\left[(y_1-\mu_1)(y_2-\mu_2)\right]}{\sigma_1 \sigma_2} = \frac{\hbox{Cov}(y_1, y_2)}{\sigma_1 \sigma_2} \,, $$ where E is the expectation operator, $\mu_1$ and $\mu_2$ are the means respectively for $y_1$ and $y_2$ and $\sigma_1, \sigma_2$ are their standard deviations. In the context of a single variable, i.e. auto-correlation, $y_1$ is the original series and $y_2$ is a lagged version of it. Upon the above definition, sample autocorrelations of order $k=0,1,2,...$ can be obtained by computing the following expression with the observed series $y_t$, $t=1,2,...,n$: $$ \rho(k) = \frac{\frac{1}{n-k}\sum_{t=k+1}^n (y_t - \bar{y})(y_{t-k} - \bar{y})}{ \sqrt{\frac{1}{n}\sum_{t=1}^n (y_t - \bar{y})^2}\sqrt{\frac{1}{n-k}\sum_{t=k+1}^n (y_{t-k} - \bar{y})^2}} \,, $$ where $\bar{y}$ is the sample mean of the data. Partial autocorrelations Partial autocorrelations measure the linear dependence of one variable after removing the effect of other variable(s) that affect to both variables. For example, the partial autocorrelation of order measures the effect (linear dependence) of $y_{t-2}$ on $y_t$ after removing the effect of $y_{t-1}$ on both $y_t$ and $y_{t-2}$. Each partial autocorrelation could be obtained as a series of regressions of the form: $$ \tilde{y}_t = \phi_{21} \tilde{y}_{t-1} + \phi_{22} \tilde{y}_{t-2} + e_t \,, $$ where $\tilde{y}_t$ is the original series minus the sample mean, $y_t - \bar{y}$. The estimate of $\phi_{22}$ will give the value of the partial autocorrelation of order 2. Extending the regression with $k$ additional lags, the estimate of the last term will give the partial autocorrelation of order $k$. An alternative way to compute the sample partial autocorrelations is by solving the following system for each order $k$: \begin{eqnarray} \left(\begin{array}{cccc} \rho(0) & \rho(1) & \cdots & \rho(k-1) \\ \rho(1) & \rho(0) & \cdots & \rho(k-2) \\ \vdots & \vdots & \vdots & \vdots \\ \rho(k-1) & \rho(k-2) & \cdots & \rho(0) \\ \end{array}\right) \left(\begin{array}{c} \phi_{k1} \\ \phi_{k2} \\ \vdots \\ \phi_{kk} \\ \end{array}\right) = \left(\begin{array}{c} \rho(1) \\ \rho(2) \\ \vdots \\ \rho(k) \\ \end{array}\right) \,, \end{eqnarray} where $\rho(\cdot)$ are the sample autocorrelations. This mapping between the sample autocorrelations and the partial autocorrelations is known as the Durbin-Levinson recursion. This approach is relatively easy to implement for illustration. For example, in the R software, we can obtain the partial autocorrelation of order 5 as follows: # sample data x <- diff(AirPassengers) # autocorrelations sacf <- acf(x, lag.max = 10, plot = FALSE)$acf[,,1] # solve the system of equations res1 <- solve(toeplitz(sacf[1:5]), sacf[2:6]) res1 # [1] 0.29992688 -0.18784728 -0.08468517 -0.22463189 0.01008379 # benchmark result res2 <- pacf(x, lag.max = 5, plot = FALSE)$acf[,,1] res2 # [1] 0.30285526 -0.21344644 -0.16044680 -0.22163003 0.01008379 all.equal(res1[5], res2[5]) # [1] TRUE Confidence bands Confidence bands can be computed as the value of the sample autocorrelations $\pm \frac{z_{1-\alpha/2}}{\sqrt{n}}$, where $z_{1-\alpha/2}$ is the quantile $1-\alpha/2$ in the Gaussian distribution, e.g. 1.96 for 95% confidence bands. Sometimes confidence bands that increase as the order increases are used. In this cases the bands can be defined as $\pm z_{1-\alpha/2}\sqrt{\frac{1}{n}\left(1 + 2\sum_{i=1}^k \rho(i)^2\right)}$.
ACF and PACF Formula Autocorrelations The correlation between two variables $y_1, y_2$ is defined as: $$ \rho = \frac{\hbox{E}\left[(y_1-\mu_1)(y_2-\mu_2)\right]}{\sigma_1 \sigma_2} = \frac{\hbox{Cov}(y_1, y_2)}{\sigma_1
11,367
ACF and PACF Formula
"I want to create a code for plotting ACF and PACF from time-series data". Although the OP is a bit vague, it may possibly be more targeted to a "recipe"-style coding formulation than a linear algebra model formulation. The ACF is rather straightforward: we have a time series, and basically make multiple "copies" (as in "copy and paste") of it, understanding that each copy is going to be offset by one entry from the prior copy, because the initial data contains $t$ data points, while the previous time series length (which excludes the last data point) is only $t-1$. We can make virtually as many copies as there are rows. Each copy is correlated to the original, keeping in mind that we need identical lengths, and to this end, we'll have to keep on clipping the tail end of the initial data series to make them comparable. For instance, to correlate the initial data to $ts_{t-3}$ we'll need to get rid of the last $3$ data points of the original time series (the first $3$ chronologically). Example: We'll concoct a times series with a cyclical sine pattern superimposed on a trend line, and noise, and plot the R generated ACF. I got this example from an online post by Christoph Scherber, and just added the noise to it: x=seq(pi, 10 * pi, 0.1) y = 0.1 * x + sin(x) + rnorm(x) y = ts(y, start=1800) Ordinarily we would have to test the data for stationarity (or just look at the plot above), but we know there is a trend in it, so let's skip this part, and go directly to the de-trending step: model=lm(y ~ I(1801:2083)) st.y = y - predict(model) Now we are ready to takle this time series by first generating the ACF with the acf() function in R, and then comparing the results to the makeshift loop I put together: ACF = 0 # Starting an empty vector to capture the auto-correlations. ACF[1] = cor(st.y, st.y) # The first entry in the ACF is the correlation with itself (1). for(i in 1:30){ # Took 30 points to parallel the output of `acf()` lag = st.y[-c(1:i)] # Introducing lags in the stationary ts. clipped.y = st.y[1:length(lag)] # Compensating by reducing length of ts. ACF[i + 1] = cor(clipped.y, lag) # Storing each correlation. } acf(st.y) # Plotting the built-in function (left) plot(ACF, type="h", main="ACF Manual calculation"); abline(h = 0) # and my results (right). OK. That was successful. On to the PACF. Much more tricky to hack... The idea here is to again clone the initial ts a bunch of times, and then select multiple time points. However, instead of just correlating with the initial time series, we put together all the lags in-between, and perform a regression analysis, so that the variance explained by the previous time points can be excluded (controlled). For example, if we are focusing on the PACF ending at time $ts_{t-4}$, we keep $ts_t$, $ts_{t-1}$, $ts_{t-2}$ and $ts_{t-3}$, as well as $ts_{t-4}$, and we regress $ts_t \sim ts_{t-1} + ts_{t-2} + ts_{t-3}+ts_{t-4}$ through the origin and keeping only the coefficient for $ts_{t-4}$: PACF = 0 # Starting up an empty storage vector. for(j in 2:25){ # Picked up 25 lag points to parallel R `pacf()` output. cols = j rows = length(st.y) - j + 1 # To end up with equal length vectors we clip. lag = matrix(0, rows, j) # The storage matrix for different groups of lagged vectors. for(i in 1:cols){ lag[ ,i] = st.y[i : (i + rows - 1)] #Clipping progressively to get lagged ts's. } lag = as.data.frame(lag) fit = lm(lag$V1 ~ . - 1, data = lag) # Running an OLS for every group. PACF[j] = coef(fit)[j - 1] # Getting the slope for the last lagged ts. } And finally plotting again side-by-side, R-generated and manual calculations: That the idea is correct, beside probable computational issues, can be seen comparing PACF to pacf(st.y, plot = F). code here.
ACF and PACF Formula
"I want to create a code for plotting ACF and PACF from time-series data". Although the OP is a bit vague, it may possibly be more targeted to a "recipe"-style coding formulation than a linear alge
ACF and PACF Formula "I want to create a code for plotting ACF and PACF from time-series data". Although the OP is a bit vague, it may possibly be more targeted to a "recipe"-style coding formulation than a linear algebra model formulation. The ACF is rather straightforward: we have a time series, and basically make multiple "copies" (as in "copy and paste") of it, understanding that each copy is going to be offset by one entry from the prior copy, because the initial data contains $t$ data points, while the previous time series length (which excludes the last data point) is only $t-1$. We can make virtually as many copies as there are rows. Each copy is correlated to the original, keeping in mind that we need identical lengths, and to this end, we'll have to keep on clipping the tail end of the initial data series to make them comparable. For instance, to correlate the initial data to $ts_{t-3}$ we'll need to get rid of the last $3$ data points of the original time series (the first $3$ chronologically). Example: We'll concoct a times series with a cyclical sine pattern superimposed on a trend line, and noise, and plot the R generated ACF. I got this example from an online post by Christoph Scherber, and just added the noise to it: x=seq(pi, 10 * pi, 0.1) y = 0.1 * x + sin(x) + rnorm(x) y = ts(y, start=1800) Ordinarily we would have to test the data for stationarity (or just look at the plot above), but we know there is a trend in it, so let's skip this part, and go directly to the de-trending step: model=lm(y ~ I(1801:2083)) st.y = y - predict(model) Now we are ready to takle this time series by first generating the ACF with the acf() function in R, and then comparing the results to the makeshift loop I put together: ACF = 0 # Starting an empty vector to capture the auto-correlations. ACF[1] = cor(st.y, st.y) # The first entry in the ACF is the correlation with itself (1). for(i in 1:30){ # Took 30 points to parallel the output of `acf()` lag = st.y[-c(1:i)] # Introducing lags in the stationary ts. clipped.y = st.y[1:length(lag)] # Compensating by reducing length of ts. ACF[i + 1] = cor(clipped.y, lag) # Storing each correlation. } acf(st.y) # Plotting the built-in function (left) plot(ACF, type="h", main="ACF Manual calculation"); abline(h = 0) # and my results (right). OK. That was successful. On to the PACF. Much more tricky to hack... The idea here is to again clone the initial ts a bunch of times, and then select multiple time points. However, instead of just correlating with the initial time series, we put together all the lags in-between, and perform a regression analysis, so that the variance explained by the previous time points can be excluded (controlled). For example, if we are focusing on the PACF ending at time $ts_{t-4}$, we keep $ts_t$, $ts_{t-1}$, $ts_{t-2}$ and $ts_{t-3}$, as well as $ts_{t-4}$, and we regress $ts_t \sim ts_{t-1} + ts_{t-2} + ts_{t-3}+ts_{t-4}$ through the origin and keeping only the coefficient for $ts_{t-4}$: PACF = 0 # Starting up an empty storage vector. for(j in 2:25){ # Picked up 25 lag points to parallel R `pacf()` output. cols = j rows = length(st.y) - j + 1 # To end up with equal length vectors we clip. lag = matrix(0, rows, j) # The storage matrix for different groups of lagged vectors. for(i in 1:cols){ lag[ ,i] = st.y[i : (i + rows - 1)] #Clipping progressively to get lagged ts's. } lag = as.data.frame(lag) fit = lm(lag$V1 ~ . - 1, data = lag) # Running an OLS for every group. PACF[j] = coef(fit)[j - 1] # Getting the slope for the last lagged ts. } And finally plotting again side-by-side, R-generated and manual calculations: That the idea is correct, beside probable computational issues, can be seen comparing PACF to pacf(st.y, plot = F). code here.
ACF and PACF Formula "I want to create a code for plotting ACF and PACF from time-series data". Although the OP is a bit vague, it may possibly be more targeted to a "recipe"-style coding formulation than a linear alge
11,368
ACF and PACF Formula
Well, in the practise we found error (noise) which is represented by $ e_t $ the confidence bands help you to figure out if a level can be considerate as only noise (because about the 95% times will be into the bands).
ACF and PACF Formula
Well, in the practise we found error (noise) which is represented by $ e_t $ the confidence bands help you to figure out if a level can be considerate as only noise (because about the 95% times will b
ACF and PACF Formula Well, in the practise we found error (noise) which is represented by $ e_t $ the confidence bands help you to figure out if a level can be considerate as only noise (because about the 95% times will be into the bands).
ACF and PACF Formula Well, in the practise we found error (noise) which is represented by $ e_t $ the confidence bands help you to figure out if a level can be considerate as only noise (because about the 95% times will b
11,369
ACF and PACF Formula
Here is a python code to compute ACF: def shift(x,b): if ( b <= 0 ): return x d = np.array(x); d1 = d d1[b:] = d[:-b] d1[0:b] = 0 return d1 # One way of doing it using bare bones # - you divide by first to normalize - because corr(x,x) = 1 x = np.arange(0,10) xo = x - x.mean() cors = [ np.correlate(xo,shift(xo,i))[0] for i in range(len(x1)) ] print (cors/cors[0] ) #-- Here is another way - you divide by first to normalize cors = np.correlate(xo,xo,'full')[n-1:] cors/cors[0]
ACF and PACF Formula
Here is a python code to compute ACF: def shift(x,b): if ( b <= 0 ): return x d = np.array(x); d1 = d d1[b:] = d[:-b] d1[0:b] = 0 return d1 # One way of doing it using
ACF and PACF Formula Here is a python code to compute ACF: def shift(x,b): if ( b <= 0 ): return x d = np.array(x); d1 = d d1[b:] = d[:-b] d1[0:b] = 0 return d1 # One way of doing it using bare bones # - you divide by first to normalize - because corr(x,x) = 1 x = np.arange(0,10) xo = x - x.mean() cors = [ np.correlate(xo,shift(xo,i))[0] for i in range(len(x1)) ] print (cors/cors[0] ) #-- Here is another way - you divide by first to normalize cors = np.correlate(xo,xo,'full')[n-1:] cors/cors[0]
ACF and PACF Formula Here is a python code to compute ACF: def shift(x,b): if ( b <= 0 ): return x d = np.array(x); d1 = d d1[b:] = d[:-b] d1[0:b] = 0 return d1 # One way of doing it using
11,370
What makes the mean of some distributions undefined?
The mean of a distribution is defined in terms of an integral (I'll write it as if for a continuous distribution - as a Riemann integral, say - but the issue applies more generally; we can proceed to Stieltjes or Lebesgue integration to deal with these properly and all at once): $$E(X) = \int_{-\infty}^\infty x f(x)\, dx$$ But what does that mean? It's effectively a shorthand for $$\stackrel{\lim}{_{a\to\infty,b\to\infty}} \int_{-a}^b x\, f(x)\, dx$$ or $$\stackrel{\lim}{_{a\to\infty}} \int_{-a}^0 x f(x)\, dx \, +\, \stackrel{\lim}{_{b\to\infty}} \int_{0}^b x f(x)\, dx$$ (though you could break it anywhere not just at 0) The problem comes when the limits of those integrals are not finite. So for example, consider the standard Cauchy density, which is proportional to $\frac{1}{1+x^2}$ ... note that $$\stackrel{\lim}{_{b\to\infty}} \int_{0}^b \frac{x}{1+x^2}\, dx$$ let $u=1+x^2$, so $du=2x\,dx$ $$=\,\stackrel{\lim}{_{b\to\infty}}\frac12 \int_{1}^{1+b^2} \frac{1}{u}\, du$$ $$=\,\stackrel{\lim}{_{b\to\infty}} \frac{_1}{^2}\ln(u)\Bigg |_{1}^{1+b^2} $$ $$=\,\stackrel{\lim}{_{b\to\infty}} \frac{_1}{^2}\ln(1+b^2)$$ which isn't finite. The limit in the lower half is also not finite; the expectation is thereby undefined. Or if we had as our random variable the absolute value of a standard Cauchy, its entire expectation would be proportional to that limit we just looked at (i.e. $\stackrel{\lim}{_{b\to\infty}} \frac12\ln(1+b^2)$). On the other hand, some other densities do continue out "to infinity" but their integral does have a limit.
What makes the mean of some distributions undefined?
The mean of a distribution is defined in terms of an integral (I'll write it as if for a continuous distribution - as a Riemann integral, say - but the issue applies more generally; we can proceed to
What makes the mean of some distributions undefined? The mean of a distribution is defined in terms of an integral (I'll write it as if for a continuous distribution - as a Riemann integral, say - but the issue applies more generally; we can proceed to Stieltjes or Lebesgue integration to deal with these properly and all at once): $$E(X) = \int_{-\infty}^\infty x f(x)\, dx$$ But what does that mean? It's effectively a shorthand for $$\stackrel{\lim}{_{a\to\infty,b\to\infty}} \int_{-a}^b x\, f(x)\, dx$$ or $$\stackrel{\lim}{_{a\to\infty}} \int_{-a}^0 x f(x)\, dx \, +\, \stackrel{\lim}{_{b\to\infty}} \int_{0}^b x f(x)\, dx$$ (though you could break it anywhere not just at 0) The problem comes when the limits of those integrals are not finite. So for example, consider the standard Cauchy density, which is proportional to $\frac{1}{1+x^2}$ ... note that $$\stackrel{\lim}{_{b\to\infty}} \int_{0}^b \frac{x}{1+x^2}\, dx$$ let $u=1+x^2$, so $du=2x\,dx$ $$=\,\stackrel{\lim}{_{b\to\infty}}\frac12 \int_{1}^{1+b^2} \frac{1}{u}\, du$$ $$=\,\stackrel{\lim}{_{b\to\infty}} \frac{_1}{^2}\ln(u)\Bigg |_{1}^{1+b^2} $$ $$=\,\stackrel{\lim}{_{b\to\infty}} \frac{_1}{^2}\ln(1+b^2)$$ which isn't finite. The limit in the lower half is also not finite; the expectation is thereby undefined. Or if we had as our random variable the absolute value of a standard Cauchy, its entire expectation would be proportional to that limit we just looked at (i.e. $\stackrel{\lim}{_{b\to\infty}} \frac12\ln(1+b^2)$). On the other hand, some other densities do continue out "to infinity" but their integral does have a limit.
What makes the mean of some distributions undefined? The mean of a distribution is defined in terms of an integral (I'll write it as if for a continuous distribution - as a Riemann integral, say - but the issue applies more generally; we can proceed to
11,371
What makes the mean of some distributions undefined?
The other answers are good, but might not convince everyone, especially people who take one look at the Cauchy distribution (with $x_0 = 0$) and say it's still intuitively obvious that the mean should be zero. The reason the intuitive answer is not correct from the mathematical perspective is due to the Riemann rearrangement theorem (video). Effectively what you're doing when you're looking at a Cauchy and saying that the mean "should be zero" is that you're splitting down the "center" at zero, and then claiming the moments of the two sizes balance. Or in other words, you're implicitly doing an infinite sum with "half" the terms positive (the moments at each point to the right) and "half" the terms negative (the moments at each point to the left) and claiming it sums to zero. (For the technically minded: $\int_{0}^\infty f(x_0+r)r\, dr - \int_{0}^{\infty} f(x_0-r)r\, dr = 0$) The Riemann rearrangement theorem says that this type of infinite sum (one with both positive and negative terms) is only consistent if the two series (positive terms only and negative terms only) are each convergent when taken independently. If both sides (positive and negative) are divergent on their own, then you can come up with an order of summation of the terms such that it sums to any number. (Video above, starting at 6:50) So, yes, if you do the summation in a balanced manner from 0 out, the first moments from the Cauchy distribution cancel out. However, the (standard) definition of mean doesn't enforce this order of summation. You should be able to sum the moments in any order and have it be equally valid. Therefore, the mean of the Cauchy distribution is undefined - by judiciously choosing how you sum the moments, you can make them "balance" (or not) at practically any point. So to make the mean of a distribution defined, the two moment integrals need to each be independently convergent (finite) around the proposed mean (which, when you do the math, is really just another way of saying that the full integral ($\int_{-\infty}^\infty f(x)x\, dx$) needs to be convergent). If the tails are "fat" enough to make the moment for one side infinite, you're done. You can't balance it out with an infinite moment on the other side. I should mention that the "counter intuitive" behavior of things like the Cauchy distribution is entirely due to problems when thinking about infinity. Take the Cauchy distribution and chop off the tails - even arbitrarily far out, like at plus/minus the xkcd number - and (once re-normalized) you suddenly get something that's well behaved and has a defined mean. It's not the fat tails in-and-of-themselves that are an issue, it's how those tails behave as you approach infinity.
What makes the mean of some distributions undefined?
The other answers are good, but might not convince everyone, especially people who take one look at the Cauchy distribution (with $x_0 = 0$) and say it's still intuitively obvious that the mean shoul
What makes the mean of some distributions undefined? The other answers are good, but might not convince everyone, especially people who take one look at the Cauchy distribution (with $x_0 = 0$) and say it's still intuitively obvious that the mean should be zero. The reason the intuitive answer is not correct from the mathematical perspective is due to the Riemann rearrangement theorem (video). Effectively what you're doing when you're looking at a Cauchy and saying that the mean "should be zero" is that you're splitting down the "center" at zero, and then claiming the moments of the two sizes balance. Or in other words, you're implicitly doing an infinite sum with "half" the terms positive (the moments at each point to the right) and "half" the terms negative (the moments at each point to the left) and claiming it sums to zero. (For the technically minded: $\int_{0}^\infty f(x_0+r)r\, dr - \int_{0}^{\infty} f(x_0-r)r\, dr = 0$) The Riemann rearrangement theorem says that this type of infinite sum (one with both positive and negative terms) is only consistent if the two series (positive terms only and negative terms only) are each convergent when taken independently. If both sides (positive and negative) are divergent on their own, then you can come up with an order of summation of the terms such that it sums to any number. (Video above, starting at 6:50) So, yes, if you do the summation in a balanced manner from 0 out, the first moments from the Cauchy distribution cancel out. However, the (standard) definition of mean doesn't enforce this order of summation. You should be able to sum the moments in any order and have it be equally valid. Therefore, the mean of the Cauchy distribution is undefined - by judiciously choosing how you sum the moments, you can make them "balance" (or not) at practically any point. So to make the mean of a distribution defined, the two moment integrals need to each be independently convergent (finite) around the proposed mean (which, when you do the math, is really just another way of saying that the full integral ($\int_{-\infty}^\infty f(x)x\, dx$) needs to be convergent). If the tails are "fat" enough to make the moment for one side infinite, you're done. You can't balance it out with an infinite moment on the other side. I should mention that the "counter intuitive" behavior of things like the Cauchy distribution is entirely due to problems when thinking about infinity. Take the Cauchy distribution and chop off the tails - even arbitrarily far out, like at plus/minus the xkcd number - and (once re-normalized) you suddenly get something that's well behaved and has a defined mean. It's not the fat tails in-and-of-themselves that are an issue, it's how those tails behave as you approach infinity.
What makes the mean of some distributions undefined? The other answers are good, but might not convince everyone, especially people who take one look at the Cauchy distribution (with $x_0 = 0$) and say it's still intuitively obvious that the mean shoul
11,372
What makes the mean of some distributions undefined?
General Abrial and Glen_b had perfect answers. I just want to add a small demo to show you the mean of Cauchy distribution does not exist / does not converge. In following experiment, you will see, even you get a large sample and calcluate the empirical mean from the sample, the numbers are quite different from experiment to experiment. set.seed(0) par(mfrow=c(1,2)) experiments=rep(1e5,100) mean_list_cauchy=sapply(experiments, function(n) mean(rcauchy(n))) mean_list_normal=sapply(experiments, function(n) mean(rnorm(n))) plot(mean_list_cauchy,ylim=c(-10,10)) plot(mean_list_normal,ylim=c(-10,10)) You can observe that we have $100$ experiments, and in each experiment, we sample $1\times 10^5$ points from two distributions, with such a big sample size, the empirical mean across different experiments should be fairly close to true mean. The results shows Cauchy distribution does not have a converging mean, but normal distribution has. EDIT: As @mark999 mentioned in the chat, we should argue the two distributions used in the experiment has similar "variance" (the reason I use quote is because Cauchy distribution variance is also undefined.). Here is the justification: their PDF are similar. Note that, by looking at the PDF of Cauchy distribution, we would guess it is $0$, but from the experiments we can see, it does not exist. That is the point of the demo. curve(dnorm, -8,8) curve(dcauchy, -8,8)
What makes the mean of some distributions undefined?
General Abrial and Glen_b had perfect answers. I just want to add a small demo to show you the mean of Cauchy distribution does not exist / does not converge. In following experiment, you will see, e
What makes the mean of some distributions undefined? General Abrial and Glen_b had perfect answers. I just want to add a small demo to show you the mean of Cauchy distribution does not exist / does not converge. In following experiment, you will see, even you get a large sample and calcluate the empirical mean from the sample, the numbers are quite different from experiment to experiment. set.seed(0) par(mfrow=c(1,2)) experiments=rep(1e5,100) mean_list_cauchy=sapply(experiments, function(n) mean(rcauchy(n))) mean_list_normal=sapply(experiments, function(n) mean(rnorm(n))) plot(mean_list_cauchy,ylim=c(-10,10)) plot(mean_list_normal,ylim=c(-10,10)) You can observe that we have $100$ experiments, and in each experiment, we sample $1\times 10^5$ points from two distributions, with such a big sample size, the empirical mean across different experiments should be fairly close to true mean. The results shows Cauchy distribution does not have a converging mean, but normal distribution has. EDIT: As @mark999 mentioned in the chat, we should argue the two distributions used in the experiment has similar "variance" (the reason I use quote is because Cauchy distribution variance is also undefined.). Here is the justification: their PDF are similar. Note that, by looking at the PDF of Cauchy distribution, we would guess it is $0$, but from the experiments we can see, it does not exist. That is the point of the demo. curve(dnorm, -8,8) curve(dcauchy, -8,8)
What makes the mean of some distributions undefined? General Abrial and Glen_b had perfect answers. I just want to add a small demo to show you the mean of Cauchy distribution does not exist / does not converge. In following experiment, you will see, e
11,373
What makes the mean of some distributions undefined?
The Cauchy distribution is a disguised form of a very fundamental distribution, namely the uniform distribution on a circle. In formulas, the infinitesimal probability is $d\theta/2\pi$, where $\theta$ is the angle coordinate. The probability (or measure) of an arc $A\subset \mathbb S^1$ is $\mathtt{length}(A)/2\pi$. This is different from the uniform distribution $U(-\pi,\pi)$, though measures are indeed the same for arcs not containing $\pi$. For example, on the arc from $\pi-\varepsilon$ counter-clockwise to $-\pi+\varepsilon\ (=\pi+\varepsilon \mod 2\pi)$, the mean of the distribution on the circle is $\pi$. But the mean of the uniform distribution $U(-\pi,\pi)$ on the corresponding union of two disjoint intervals, each of length $\varepsilon/2\pi$, is zero. Since the distribution on the circle is rotationally symmetric, there cannot be a mean, median or mode on the circle. Similarly, higher moments, such as variance, cannot make sense. This distribution arises naturally in many contexts. For example, my current project involves microscope images of cancerous tissue. The very numerous objects in the image are not symmetric and a "direction" can be assigned to each. The obvious null hypothesis is that these directions are uniformly distributed. To disguise the simplicity, let $\mathbb S^1$ be the standard unit circle, and let $p=(0,1)\in\mathbb S^1$. We define $x$ as a function of $\theta$ by stereographical projection of the circle from $p$ onto the $x$-axis. The formula is $x=\tan(\theta/2)$. Differentiating, we find $d\theta/2 = dx/(1+x^2)$. The infinitesimal probability is therefore $\frac{d\theta}{\pi(1+x^2)}$, the usual form of the Cauchy distribution, and "Hey, presto!", simplicity becomes a headache, requiring treatment by the subtleties of integration theory. In $\mathbb S^1 \setminus \{p\}$, we can ignore the absence of $p$ (in other words, reinstate $p\in\mathbb S^1$) for any consideration such as mean or higher order moment, because the probability of $p$ (its measure) is zero. So therefore the non-existence of mean and of higher moments carries over to the real line. However, there is now a special point, namely $-p = (0,-1)$, which maps to $0\in\mathbb R$ under stereographic projection and this becomes the median and mode of the Cauchy distribution.
What makes the mean of some distributions undefined?
The Cauchy distribution is a disguised form of a very fundamental distribution, namely the uniform distribution on a circle. In formulas, the infinitesimal probability is $d\theta/2\pi$, where $\theta
What makes the mean of some distributions undefined? The Cauchy distribution is a disguised form of a very fundamental distribution, namely the uniform distribution on a circle. In formulas, the infinitesimal probability is $d\theta/2\pi$, where $\theta$ is the angle coordinate. The probability (or measure) of an arc $A\subset \mathbb S^1$ is $\mathtt{length}(A)/2\pi$. This is different from the uniform distribution $U(-\pi,\pi)$, though measures are indeed the same for arcs not containing $\pi$. For example, on the arc from $\pi-\varepsilon$ counter-clockwise to $-\pi+\varepsilon\ (=\pi+\varepsilon \mod 2\pi)$, the mean of the distribution on the circle is $\pi$. But the mean of the uniform distribution $U(-\pi,\pi)$ on the corresponding union of two disjoint intervals, each of length $\varepsilon/2\pi$, is zero. Since the distribution on the circle is rotationally symmetric, there cannot be a mean, median or mode on the circle. Similarly, higher moments, such as variance, cannot make sense. This distribution arises naturally in many contexts. For example, my current project involves microscope images of cancerous tissue. The very numerous objects in the image are not symmetric and a "direction" can be assigned to each. The obvious null hypothesis is that these directions are uniformly distributed. To disguise the simplicity, let $\mathbb S^1$ be the standard unit circle, and let $p=(0,1)\in\mathbb S^1$. We define $x$ as a function of $\theta$ by stereographical projection of the circle from $p$ onto the $x$-axis. The formula is $x=\tan(\theta/2)$. Differentiating, we find $d\theta/2 = dx/(1+x^2)$. The infinitesimal probability is therefore $\frac{d\theta}{\pi(1+x^2)}$, the usual form of the Cauchy distribution, and "Hey, presto!", simplicity becomes a headache, requiring treatment by the subtleties of integration theory. In $\mathbb S^1 \setminus \{p\}$, we can ignore the absence of $p$ (in other words, reinstate $p\in\mathbb S^1$) for any consideration such as mean or higher order moment, because the probability of $p$ (its measure) is zero. So therefore the non-existence of mean and of higher moments carries over to the real line. However, there is now a special point, namely $-p = (0,-1)$, which maps to $0\in\mathbb R$ under stereographic projection and this becomes the median and mode of the Cauchy distribution.
What makes the mean of some distributions undefined? The Cauchy distribution is a disguised form of a very fundamental distribution, namely the uniform distribution on a circle. In formulas, the infinitesimal probability is $d\theta/2\pi$, where $\theta
11,374
What makes the mean of some distributions undefined?
By definition of Lebesgue-Stieltjes integral, the mean exists if: $$\int \vert x\vert dF(x)<\infty.$$ https://en.wikipedia.org/wiki/Moment_(mathematics)#Significance_of_the_moments https://en.wikipedia.org/wiki/Lebesgue_integration
What makes the mean of some distributions undefined?
By definition of Lebesgue-Stieltjes integral, the mean exists if: $$\int \vert x\vert dF(x)<\infty.$$ https://en.wikipedia.org/wiki/Moment_(mathematics)#Significance_of_the_moments https://en.wikipedi
What makes the mean of some distributions undefined? By definition of Lebesgue-Stieltjes integral, the mean exists if: $$\int \vert x\vert dF(x)<\infty.$$ https://en.wikipedia.org/wiki/Moment_(mathematics)#Significance_of_the_moments https://en.wikipedia.org/wiki/Lebesgue_integration
What makes the mean of some distributions undefined? By definition of Lebesgue-Stieltjes integral, the mean exists if: $$\int \vert x\vert dF(x)<\infty.$$ https://en.wikipedia.org/wiki/Moment_(mathematics)#Significance_of_the_moments https://en.wikipedi
11,375
What makes the mean of some distributions undefined?
It helps to think about such questions from a more abstract point of view. When we are talking about random variables we implicitly assume the existence of probability space $(\Omega, \mathcal{F}, \mathbb{P})$. Then a random variable $X: \Omega \to \mathbb{R}$ is simply a measurable function in $(\mathbb{R}, \mathcal{B})$. $X$ induces a measure $\mu$ on the measurable space $(\mathbb{R}, \mathcal{B})$ called the pushforward measure defined by $\mu = \mathbb{P} \circ X^{-1}$. The pdf of $X$ exists if $\mu$ is absolutely continuous with respect to the Lebesgue measure on $(\mathbb{R}, \mathcal{B})$. The pdf of $X$ is a function $f : \mathbb{R} \to \mathbb{R}$ and its mean exists if $\mathbb{E}(X) < \infty$ where this expectation is the integral of $X$ with respect to $(\Omega, \mathcal{F}, \mathbb{P})$. Using the law of unconscious statistician we can write $$ \mathbb{E}(X) = \int_{\mathbb{R}} x f(x) dx $$ Check out the construction of Lebesgue integral for more details about when $\mathbb{E}(X) < \infty$.
What makes the mean of some distributions undefined?
It helps to think about such questions from a more abstract point of view. When we are talking about random variables we implicitly assume the existence of probability space $(\Omega, \mathcal{F}, \ma
What makes the mean of some distributions undefined? It helps to think about such questions from a more abstract point of view. When we are talking about random variables we implicitly assume the existence of probability space $(\Omega, \mathcal{F}, \mathbb{P})$. Then a random variable $X: \Omega \to \mathbb{R}$ is simply a measurable function in $(\mathbb{R}, \mathcal{B})$. $X$ induces a measure $\mu$ on the measurable space $(\mathbb{R}, \mathcal{B})$ called the pushforward measure defined by $\mu = \mathbb{P} \circ X^{-1}$. The pdf of $X$ exists if $\mu$ is absolutely continuous with respect to the Lebesgue measure on $(\mathbb{R}, \mathcal{B})$. The pdf of $X$ is a function $f : \mathbb{R} \to \mathbb{R}$ and its mean exists if $\mathbb{E}(X) < \infty$ where this expectation is the integral of $X$ with respect to $(\Omega, \mathcal{F}, \mathbb{P})$. Using the law of unconscious statistician we can write $$ \mathbb{E}(X) = \int_{\mathbb{R}} x f(x) dx $$ Check out the construction of Lebesgue integral for more details about when $\mathbb{E}(X) < \infty$.
What makes the mean of some distributions undefined? It helps to think about such questions from a more abstract point of view. When we are talking about random variables we implicitly assume the existence of probability space $(\Omega, \mathcal{F}, \ma
11,376
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) predict exact zeros?
Note that the predicted value in a GLM is a mean. For any distribution on non-negative values, to predict a mean of 0, its distribution would have to be entirely a spike at 0. However, with a log-link, you're never going to fit a mean of exactly zero (since that would require $\eta$ to go to $-\infty$). So your problem isn't a problem with the Tweedie, but far more general; you'd have exactly the same issue with the ordinary Poisson (whether zero-inflated or ordinary Poisson GLM) for example, or a binomial, a 0-1 inflated beta and indeed any other distribution on the non-negative real line. I thought the usefulness of the Tweedie distribution comes from its ability to predict exact zeros and the continuous part. Since predicting exact zeros isn't going to occur for any distribution over non-negative values with a log-link, your thinking on this must be mistaken. One of its attractions is that it can model exact zeros in the data, not that the mean predictions will be 0. [Of course a fitted distribution with nonzero mean can still have a probability of being exactly zero, even though the mean must exceed 0. A suitable prediction interval could well include 0, for example.] It matters not at all that the fitted distribution includes any substantial proportion of zeros - that doesn't make the fitted mean zero (except in the limit as you go to all zeros). Note that if you change your link function to say an identity link, it doesn't really solve your problem -- the mean of a non-negative random variable that's not all-zeros will be positive.
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) pred
Note that the predicted value in a GLM is a mean. For any distribution on non-negative values, to predict a mean of 0, its distribution would have to be entirely a spike at 0. However, with a log-link
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) predict exact zeros? Note that the predicted value in a GLM is a mean. For any distribution on non-negative values, to predict a mean of 0, its distribution would have to be entirely a spike at 0. However, with a log-link, you're never going to fit a mean of exactly zero (since that would require $\eta$ to go to $-\infty$). So your problem isn't a problem with the Tweedie, but far more general; you'd have exactly the same issue with the ordinary Poisson (whether zero-inflated or ordinary Poisson GLM) for example, or a binomial, a 0-1 inflated beta and indeed any other distribution on the non-negative real line. I thought the usefulness of the Tweedie distribution comes from its ability to predict exact zeros and the continuous part. Since predicting exact zeros isn't going to occur for any distribution over non-negative values with a log-link, your thinking on this must be mistaken. One of its attractions is that it can model exact zeros in the data, not that the mean predictions will be 0. [Of course a fitted distribution with nonzero mean can still have a probability of being exactly zero, even though the mean must exceed 0. A suitable prediction interval could well include 0, for example.] It matters not at all that the fitted distribution includes any substantial proportion of zeros - that doesn't make the fitted mean zero (except in the limit as you go to all zeros). Note that if you change your link function to say an identity link, it doesn't really solve your problem -- the mean of a non-negative random variable that's not all-zeros will be positive.
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) pred Note that the predicted value in a GLM is a mean. For any distribution on non-negative values, to predict a mean of 0, its distribution would have to be entirely a spike at 0. However, with a log-link
11,377
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) predict exact zeros?
Predicting the proportion of zeros I am the author of the statmod package and joint author of the tweedie package. Everything in your example is working correctly. The code is accounting correctly for any zeros that might be in the data. As Glen_b and Tim have explained, the predicted mean value will never be exactly zero, unless the probability of a zero is 100%. What might be of interest though is the predicted proportion of zeros, and this can easily be extracted from the model fit as I show below. Here is a more sensible working example. First simulate some data: > library(statmod) > library(tweedie) > x <- 1:100 > mutrue <- exp(-1+x/25) > summary(mutrue) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.3829 1.0306 2.7737 5.0287 7.4644 20.0855 > y <- rtweedie(100, mu=mutrue, phi=1, power=1.3) > summary(y) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.0000 0.8482 2.9249 4.7164 6.1522 24.3897 > sum(y==0) [1] 12 The data contains 12 zeros. Now fit a Tweedie glm: > fit <- glm(y ~ x, family=tweedie(var.power=1.3, link.power=0)) > summary(fit) Call: glm(formula = y ~ x, family = tweedie(var.power = 1.3, link.power = 0)) Deviance Residuals: Min 1Q Median 3Q Max -2.71253 -0.94685 -0.07556 0.69089 1.84013 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -0.816784 0.168764 -4.84 4.84e-06 *** x 0.036748 0.002275 16.15 < 2e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for Tweedie family taken to be 0.8578628) Null deviance: 363.26 on 99 degrees of freedom Residual deviance: 103.70 on 98 degrees of freedom AIC: NA Number of Fisher Scoring iterations: 4 Of course the regression on $x$ is highly significant. The estimated value of the dispersion $\phi$ is 0.85786. The predicted proportion of zeros for each value of $x$ can be computed from the following formula: > Phi <- 0.85786 > Mu <- fitted(fit) > Power <- 1.3 > Prob.Zero <- exp(-Mu^(2-Power) / Phi / (2-Power)) > Prob.Zero[1:5] 1 2 3 4 5 0.3811336 0.3716732 0.3622103 0.3527512 0.3433024 > Prob.Zero[96:100] 96 97 98 99 100 1.498569e-05 1.121936e-05 8.336499e-06 6.146648e-06 4.496188e-06 So the predicted proportion of zeros varies from 38.1% at the smallest mean values down to 4.5e-6 at the largest mean values. The formula for the probability of an exact zero can be found in Dunn & Smyth (2001) Tweedie Family Densities: Methods of Evaluation or Dunn & Smyth (2005) Series evaluation of Tweedie exponential dispersion model densities.
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) pred
Predicting the proportion of zeros I am the author of the statmod package and joint author of the tweedie package. Everything in your example is working correctly. The code is accounting correctly for
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) predict exact zeros? Predicting the proportion of zeros I am the author of the statmod package and joint author of the tweedie package. Everything in your example is working correctly. The code is accounting correctly for any zeros that might be in the data. As Glen_b and Tim have explained, the predicted mean value will never be exactly zero, unless the probability of a zero is 100%. What might be of interest though is the predicted proportion of zeros, and this can easily be extracted from the model fit as I show below. Here is a more sensible working example. First simulate some data: > library(statmod) > library(tweedie) > x <- 1:100 > mutrue <- exp(-1+x/25) > summary(mutrue) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.3829 1.0306 2.7737 5.0287 7.4644 20.0855 > y <- rtweedie(100, mu=mutrue, phi=1, power=1.3) > summary(y) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.0000 0.8482 2.9249 4.7164 6.1522 24.3897 > sum(y==0) [1] 12 The data contains 12 zeros. Now fit a Tweedie glm: > fit <- glm(y ~ x, family=tweedie(var.power=1.3, link.power=0)) > summary(fit) Call: glm(formula = y ~ x, family = tweedie(var.power = 1.3, link.power = 0)) Deviance Residuals: Min 1Q Median 3Q Max -2.71253 -0.94685 -0.07556 0.69089 1.84013 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -0.816784 0.168764 -4.84 4.84e-06 *** x 0.036748 0.002275 16.15 < 2e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for Tweedie family taken to be 0.8578628) Null deviance: 363.26 on 99 degrees of freedom Residual deviance: 103.70 on 98 degrees of freedom AIC: NA Number of Fisher Scoring iterations: 4 Of course the regression on $x$ is highly significant. The estimated value of the dispersion $\phi$ is 0.85786. The predicted proportion of zeros for each value of $x$ can be computed from the following formula: > Phi <- 0.85786 > Mu <- fitted(fit) > Power <- 1.3 > Prob.Zero <- exp(-Mu^(2-Power) / Phi / (2-Power)) > Prob.Zero[1:5] 1 2 3 4 5 0.3811336 0.3716732 0.3622103 0.3527512 0.3433024 > Prob.Zero[96:100] 96 97 98 99 100 1.498569e-05 1.121936e-05 8.336499e-06 6.146648e-06 4.496188e-06 So the predicted proportion of zeros varies from 38.1% at the smallest mean values down to 4.5e-6 at the largest mean values. The formula for the probability of an exact zero can be found in Dunn & Smyth (2001) Tweedie Family Densities: Methods of Evaluation or Dunn & Smyth (2005) Series evaluation of Tweedie exponential dispersion model densities.
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) pred Predicting the proportion of zeros I am the author of the statmod package and joint author of the tweedie package. Everything in your example is working correctly. The code is accounting correctly for
11,378
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) predict exact zeros?
This answer was merged from another thread asking about predictions zero-inflated regression model, but it also applies to the Tweedie GLM model. Regression-like models predict mean of some distribution (normal for linear regression, Bernoulli for logistic regression, Poisson for Poisson regression etc.). In the case of zero-inflated regression you predict mean of the zero inflated-something distribution (e.g. Poisson, binomial). When the probability density function of the non-inflated distribution is $f$, then probability density function of zero-inflated distribution is a mixture of point mass at zero and $f$: $$ f_\text{zeroinfl}(y) = \pi \,I_{\{0\}}(y) + (1-\pi)\, f(y) $$ where $I$ is an indicator function. Zero-inflated regression model predicts mean of $f_\text{zeroinfl}(y)$, i.e. $$ \mu_i = \pi \cdot 0 + (1-\pi)\, g^{-1}(x_i'\beta) $$ where $g^{-1}$ is an inverse of the link function. So since you are predicting the mean of this distribution, you won't see the excess zeros in your predictions since the zeros are not the mean of the distribution (while they shrink the mean towards zero), the same as linear regression does not predict the residuals. This is illustrated on the plot below, where values of random variable $Y$ are plotted against $X$, where $Y$ follows a zero-inflated Poisson distribution with mean conditional on $X$. The black points are the actual data that were used to fit the zero-inflated Poisson regression model, the red points are the predictions, and the blue points are means of $Y$ within the six arbitrary groups of $X$ values. As you can see, clearly the zero inflated Poisson regression model estimates $E(Y|X)$.
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) pred
This answer was merged from another thread asking about predictions zero-inflated regression model, but it also applies to the Tweedie GLM model. Regression-like models predict mean of some distributi
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) predict exact zeros? This answer was merged from another thread asking about predictions zero-inflated regression model, but it also applies to the Tweedie GLM model. Regression-like models predict mean of some distribution (normal for linear regression, Bernoulli for logistic regression, Poisson for Poisson regression etc.). In the case of zero-inflated regression you predict mean of the zero inflated-something distribution (e.g. Poisson, binomial). When the probability density function of the non-inflated distribution is $f$, then probability density function of zero-inflated distribution is a mixture of point mass at zero and $f$: $$ f_\text{zeroinfl}(y) = \pi \,I_{\{0\}}(y) + (1-\pi)\, f(y) $$ where $I$ is an indicator function. Zero-inflated regression model predicts mean of $f_\text{zeroinfl}(y)$, i.e. $$ \mu_i = \pi \cdot 0 + (1-\pi)\, g^{-1}(x_i'\beta) $$ where $g^{-1}$ is an inverse of the link function. So since you are predicting the mean of this distribution, you won't see the excess zeros in your predictions since the zeros are not the mean of the distribution (while they shrink the mean towards zero), the same as linear regression does not predict the residuals. This is illustrated on the plot below, where values of random variable $Y$ are plotted against $X$, where $Y$ follows a zero-inflated Poisson distribution with mean conditional on $X$. The black points are the actual data that were used to fit the zero-inflated Poisson regression model, the red points are the predictions, and the blue points are means of $Y$ within the six arbitrary groups of $X$ values. As you can see, clearly the zero inflated Poisson regression model estimates $E(Y|X)$.
Can a model for non-negative data with clumping at zeros (Tweedie GLM, zero-inflated GLM, etc.) pred This answer was merged from another thread asking about predictions zero-inflated regression model, but it also applies to the Tweedie GLM model. Regression-like models predict mean of some distributi
11,379
Cross validation and parameter tuning
Cross-validation gives a measure of out-of-sample accuracy by averaging over several random partitions of the data into training and test samples. It is often used for parameter tuning by doing cross-validation for several (or many) possible values of a parameter and choosing the parameter value that gives the lowest cross-validation average error. So the process itself doesn't give you a model or parameter estimates, but you can use it to help choose between alternatives.
Cross validation and parameter tuning
Cross-validation gives a measure of out-of-sample accuracy by averaging over several random partitions of the data into training and test samples. It is often used for parameter tuning by doing cross-
Cross validation and parameter tuning Cross-validation gives a measure of out-of-sample accuracy by averaging over several random partitions of the data into training and test samples. It is often used for parameter tuning by doing cross-validation for several (or many) possible values of a parameter and choosing the parameter value that gives the lowest cross-validation average error. So the process itself doesn't give you a model or parameter estimates, but you can use it to help choose between alternatives.
Cross validation and parameter tuning Cross-validation gives a measure of out-of-sample accuracy by averaging over several random partitions of the data into training and test samples. It is often used for parameter tuning by doing cross-
11,380
Cross validation and parameter tuning
To add to Jonathan's answer. However, if you use cross validation for parameter tuning, the out-samples in fact become part of your model. So you need another independent sample to correctly measure the final model's performance. Employed for measuring model performance, cross validation can measure more than just the average accuracy: A second thing you can measure with cross validation is the model stability with respect to changing training data: cross validation builds lots of "surrogate" models that are trained with slightly differing training sets. If the models are stable, all these surrogate models are equivalent, if training is unstable, the surrogate models vary a lot. You can quantify this "varies a lot" e.g. as variance of predictions of different surrogate models for the same sample (in iterated/repeated cross validation) or e.g. as variance of the surrogate models' parameters.
Cross validation and parameter tuning
To add to Jonathan's answer. However, if you use cross validation for parameter tuning, the out-samples in fact become part of your model. So you need another independent sample to correctly measure t
Cross validation and parameter tuning To add to Jonathan's answer. However, if you use cross validation for parameter tuning, the out-samples in fact become part of your model. So you need another independent sample to correctly measure the final model's performance. Employed for measuring model performance, cross validation can measure more than just the average accuracy: A second thing you can measure with cross validation is the model stability with respect to changing training data: cross validation builds lots of "surrogate" models that are trained with slightly differing training sets. If the models are stable, all these surrogate models are equivalent, if training is unstable, the surrogate models vary a lot. You can quantify this "varies a lot" e.g. as variance of predictions of different surrogate models for the same sample (in iterated/repeated cross validation) or e.g. as variance of the surrogate models' parameters.
Cross validation and parameter tuning To add to Jonathan's answer. However, if you use cross validation for parameter tuning, the out-samples in fact become part of your model. So you need another independent sample to correctly measure t
11,381
Cross validation and parameter tuning
To add to previous answers, we'll start from the beginning: There are few ways you can overfit your models to the training data, some are obvious, some less so. First, and the most important one is overfitting of the training parameters (weights) to the data (curve fitting parameters in logistic regression, network weights in neural network etc.). Then you would model the noise in the data - if you overfit you don't only capture the underlying generating function, but also randomness due to sample size and the fact that sample is not a perfect representation of the population. This overfitting can be to a certain extent mitigated by penalizing certain attributes (in general complexity) of the model. This can be done by stopping the training once the performance on the train sample is no longer significantly improving, by removing some neurons from a neural network (called dropout), by adding a term that explicitly penalizes complexity of the model (https://ieeexplore.ieee.org/document/614177/) etc.). However these regularization strategies are themselves parametrized (when do you stop?, how many neurons to remove? etc.). In addition most machine learning models have a number of hyper-parameters that need to be set before the training begins. And these hyper-parameters are tuned in the parameter tuning phase. That brings us to second, and more subtle type of overfitting: hyper-parameter overfitting. Cross-validation can be used to find "best" hyper-parameters, by repeatedly training your model from scratch on k-1 folds of the sample and testing on the last fold. So how is it done exactly? Depending on the search strategy (given by tenshi), you set hyper-parameters of the model and train your model k times, every time using different test fold. You "remember" the average performance of the model over all test folds and repeat the whole procedure for another set of hyper-parameters. Then you choose set of hyper-parameters that corresponds to the best performance during cross-validation. As you can see, the computation cost of this procedure heavily depends on the number of hyper-parameter sets that needs to be considered. That's why some strategies for choosing this set have been developed (here I'm going to generalize what tenshi said): Grid search: for each hyper-parameter you enumerate a finite number of possible values. Then the procedure is exhaustively done for all combinations of of enumerated hyper-parameters. Obviously, if you have continuous hyper-parameters, you cannot try them all. Randomized grid search: similar to normal grid search, but this time you do not try out all combinations exhaustively, but instead sample a fixed number of times for all possible values. Note that here it is possible to not just enumerate possible values for a hyper-parameter, but you can also provide a distribution to sample from. BayesianSearch - the combination of hyper-parameter values is chosen to maximize expected improvement of the score. For more: http://papers.nips.cc/paper/4522-practical-bayesian-optimization-of-machine-learning-algorithms.pdf. And a library that deals only with that: https://github.com/hyperopt/hyperopt . As it's not as easy to combine with sklearn as what tenshi recommended, use it only if you're not working with sklearn. Other ways for guided search in hyper-parameter space. From my experience they are rarely used, so I won't cover them here. However this is not the end of the story, as the hyper-parameters can (and will) also overfit the data. For most cases you can just live with it, but if you want to maximize the generalization power of your model, you might want to try and regularize the hyper-parameters as well. First, you can assess the performance on out-of-sample data a bit better by using nested grid search (details: http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html, discussion:Nested cross validation for model selection), or just use a validation set that is not used for hyper-parameter tuning. As for regularization in the hyper-parameter space, it's a more or less an open question. Some ideas include choosing not the best set of hyper-parameter values, but something closer to the middle; the reasoning goes as follows: best hyper-parameter values most likely overfit the data just because the perform better than the other of the train data, bad parameters are just bad, but the ones in the middle can possibly achieve better generalization than the best ones. Andrew Ng wrote a paper about it. Another option is limiting your search space (you're regularizing by introducing strong bias here - values outside of search space will never be selected obviously). Side remark: using accuracy as a performance metric is in most cases a very bad idea, look into f1 and f_beta scores - these metrics will in most cases better reflect what you're actually trying to optimize in binary classification problems. To summarize: cross-validation by itself is used to asses performance of the model on out-of-sample data, but can also be used to tune hyper-parameters in conjunction with one of the search strategies in hyper-parameters space. Finding good hyper-parameters allows to avoid or at least reduce overfitting, but keep in mind that hyper-parameters can also overfit the data.
Cross validation and parameter tuning
To add to previous answers, we'll start from the beginning: There are few ways you can overfit your models to the training data, some are obvious, some less so. First, and the most important one is ov
Cross validation and parameter tuning To add to previous answers, we'll start from the beginning: There are few ways you can overfit your models to the training data, some are obvious, some less so. First, and the most important one is overfitting of the training parameters (weights) to the data (curve fitting parameters in logistic regression, network weights in neural network etc.). Then you would model the noise in the data - if you overfit you don't only capture the underlying generating function, but also randomness due to sample size and the fact that sample is not a perfect representation of the population. This overfitting can be to a certain extent mitigated by penalizing certain attributes (in general complexity) of the model. This can be done by stopping the training once the performance on the train sample is no longer significantly improving, by removing some neurons from a neural network (called dropout), by adding a term that explicitly penalizes complexity of the model (https://ieeexplore.ieee.org/document/614177/) etc.). However these regularization strategies are themselves parametrized (when do you stop?, how many neurons to remove? etc.). In addition most machine learning models have a number of hyper-parameters that need to be set before the training begins. And these hyper-parameters are tuned in the parameter tuning phase. That brings us to second, and more subtle type of overfitting: hyper-parameter overfitting. Cross-validation can be used to find "best" hyper-parameters, by repeatedly training your model from scratch on k-1 folds of the sample and testing on the last fold. So how is it done exactly? Depending on the search strategy (given by tenshi), you set hyper-parameters of the model and train your model k times, every time using different test fold. You "remember" the average performance of the model over all test folds and repeat the whole procedure for another set of hyper-parameters. Then you choose set of hyper-parameters that corresponds to the best performance during cross-validation. As you can see, the computation cost of this procedure heavily depends on the number of hyper-parameter sets that needs to be considered. That's why some strategies for choosing this set have been developed (here I'm going to generalize what tenshi said): Grid search: for each hyper-parameter you enumerate a finite number of possible values. Then the procedure is exhaustively done for all combinations of of enumerated hyper-parameters. Obviously, if you have continuous hyper-parameters, you cannot try them all. Randomized grid search: similar to normal grid search, but this time you do not try out all combinations exhaustively, but instead sample a fixed number of times for all possible values. Note that here it is possible to not just enumerate possible values for a hyper-parameter, but you can also provide a distribution to sample from. BayesianSearch - the combination of hyper-parameter values is chosen to maximize expected improvement of the score. For more: http://papers.nips.cc/paper/4522-practical-bayesian-optimization-of-machine-learning-algorithms.pdf. And a library that deals only with that: https://github.com/hyperopt/hyperopt . As it's not as easy to combine with sklearn as what tenshi recommended, use it only if you're not working with sklearn. Other ways for guided search in hyper-parameter space. From my experience they are rarely used, so I won't cover them here. However this is not the end of the story, as the hyper-parameters can (and will) also overfit the data. For most cases you can just live with it, but if you want to maximize the generalization power of your model, you might want to try and regularize the hyper-parameters as well. First, you can assess the performance on out-of-sample data a bit better by using nested grid search (details: http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html, discussion:Nested cross validation for model selection), or just use a validation set that is not used for hyper-parameter tuning. As for regularization in the hyper-parameter space, it's a more or less an open question. Some ideas include choosing not the best set of hyper-parameter values, but something closer to the middle; the reasoning goes as follows: best hyper-parameter values most likely overfit the data just because the perform better than the other of the train data, bad parameters are just bad, but the ones in the middle can possibly achieve better generalization than the best ones. Andrew Ng wrote a paper about it. Another option is limiting your search space (you're regularizing by introducing strong bias here - values outside of search space will never be selected obviously). Side remark: using accuracy as a performance metric is in most cases a very bad idea, look into f1 and f_beta scores - these metrics will in most cases better reflect what you're actually trying to optimize in binary classification problems. To summarize: cross-validation by itself is used to asses performance of the model on out-of-sample data, but can also be used to tune hyper-parameters in conjunction with one of the search strategies in hyper-parameters space. Finding good hyper-parameters allows to avoid or at least reduce overfitting, but keep in mind that hyper-parameters can also overfit the data.
Cross validation and parameter tuning To add to previous answers, we'll start from the beginning: There are few ways you can overfit your models to the training data, some are obvious, some less so. First, and the most important one is ov
11,382
Cross validation and parameter tuning
If you are from scikit-learn background, this answer might be helpful. k-fold cross-validation is used to split the data into k partitions, the estimator is then trained on k-1 partitions and then tested on the kth partition. Like this, choosing which partition should be the kth partition, there are k possibilities. Therefore you get k results of all k possibilities of your estimator. these are computationally expensive methods, but if you are going to try different estimators you can try these three for doing the hyperparameter tuning along with CV: i. GridSearchCV - an exhaustive list of all possible P and C for the hyperparameters for all the estimators. In the end gives the best hyperparameters using the mean of that particular estimator CV's mean. ii. RandomizedSearchCV - Does not do all the P and C of hyperparameters, but on a randomized approach, gives the closest possible accurate estimator saving more on computation. iii. BayesSearchCV - Not part of scikit-learn but does Bayesian optimization for doing a randomized search and fit results. tl:dr: CV is just used to avoid high bias and high variance for you r estimator because of the data you are passing. Hope it was helpful.
Cross validation and parameter tuning
If you are from scikit-learn background, this answer might be helpful. k-fold cross-validation is used to split the data into k partitions, the estimator is then trained on k-1 partitions and then tes
Cross validation and parameter tuning If you are from scikit-learn background, this answer might be helpful. k-fold cross-validation is used to split the data into k partitions, the estimator is then trained on k-1 partitions and then tested on the kth partition. Like this, choosing which partition should be the kth partition, there are k possibilities. Therefore you get k results of all k possibilities of your estimator. these are computationally expensive methods, but if you are going to try different estimators you can try these three for doing the hyperparameter tuning along with CV: i. GridSearchCV - an exhaustive list of all possible P and C for the hyperparameters for all the estimators. In the end gives the best hyperparameters using the mean of that particular estimator CV's mean. ii. RandomizedSearchCV - Does not do all the P and C of hyperparameters, but on a randomized approach, gives the closest possible accurate estimator saving more on computation. iii. BayesSearchCV - Not part of scikit-learn but does Bayesian optimization for doing a randomized search and fit results. tl:dr: CV is just used to avoid high bias and high variance for you r estimator because of the data you are passing. Hope it was helpful.
Cross validation and parameter tuning If you are from scikit-learn background, this answer might be helpful. k-fold cross-validation is used to split the data into k partitions, the estimator is then trained on k-1 partitions and then tes
11,383
Cross validation and parameter tuning
Hyperparameters optimization or parameters tuning is used to find the best hyperparameters sklearn hyperparameters optimization that are parameters that are not directly learnt within estimators. They are passed as arguments to the constructor of the estimator classes. Typical examples include C, kernel and gamma for Support Vector Classifier, alpha for Lasso, etc. Model selection or model comparison model selection is to search the best model with high generalization ability (low generalization error) for your datasets. For large datasets, it usually divide datasets into two parts: training data and test data(it is similar to Kaggle competition). So, the training data is fitting by the model to learning the pattern, and test data is used to evaluate the model generalization ability. However, hyperparameters are very important to the model learning ability (like XGBoost). It needs to search the optimal hyperparameters combination. It is time to use K-fold cross validation to find the optimal hyperparameters(GridsearchCV, RandomSearchCV), beacause the one fold in cross validation can be used as validation data to evaluate the model in corresponding hyperparameters combination. Therefore, the training data is used to tune hyperparameters and fit the modle, the test data is used to calculate the generalization ability in the optimal hyperparameters combination and compare different models. for small datasets (the large datasets or small datasets refers to the size of samples from your study field), the training data and test data are not advisable. To calculate or compare the generalization ability of each model. It is recommanded to use k-fold cross validation which can compare the generalization ability in the whole datasets. However, the question is how to choose the optimal hyperparameters. The nested cross validation is to use. It is understood that the K-1 fold data is as training data and left fold is as test data. to find the optimal hyperparameters. the k-1 fold data (training data like 3.) is used to hyperparameters optimazition and left fold to compare the models. It is called nested cross validation. I think the result of K-fold cross validation can be stored with the predicted value and corresponding observed value in the .csv and then handle them for your task.
Cross validation and parameter tuning
Hyperparameters optimization or parameters tuning is used to find the best hyperparameters sklearn hyperparameters optimization that are parameters that are not directly learnt within estimators. They
Cross validation and parameter tuning Hyperparameters optimization or parameters tuning is used to find the best hyperparameters sklearn hyperparameters optimization that are parameters that are not directly learnt within estimators. They are passed as arguments to the constructor of the estimator classes. Typical examples include C, kernel and gamma for Support Vector Classifier, alpha for Lasso, etc. Model selection or model comparison model selection is to search the best model with high generalization ability (low generalization error) for your datasets. For large datasets, it usually divide datasets into two parts: training data and test data(it is similar to Kaggle competition). So, the training data is fitting by the model to learning the pattern, and test data is used to evaluate the model generalization ability. However, hyperparameters are very important to the model learning ability (like XGBoost). It needs to search the optimal hyperparameters combination. It is time to use K-fold cross validation to find the optimal hyperparameters(GridsearchCV, RandomSearchCV), beacause the one fold in cross validation can be used as validation data to evaluate the model in corresponding hyperparameters combination. Therefore, the training data is used to tune hyperparameters and fit the modle, the test data is used to calculate the generalization ability in the optimal hyperparameters combination and compare different models. for small datasets (the large datasets or small datasets refers to the size of samples from your study field), the training data and test data are not advisable. To calculate or compare the generalization ability of each model. It is recommanded to use k-fold cross validation which can compare the generalization ability in the whole datasets. However, the question is how to choose the optimal hyperparameters. The nested cross validation is to use. It is understood that the K-1 fold data is as training data and left fold is as test data. to find the optimal hyperparameters. the k-1 fold data (training data like 3.) is used to hyperparameters optimazition and left fold to compare the models. It is called nested cross validation. I think the result of K-fold cross validation can be stored with the predicted value and corresponding observed value in the .csv and then handle them for your task.
Cross validation and parameter tuning Hyperparameters optimization or parameters tuning is used to find the best hyperparameters sklearn hyperparameters optimization that are parameters that are not directly learnt within estimators. They
11,384
Appropriate normality tests for small samples
The fBasics package in R (part of Rmetrics) includes several normality tests, covering many of the popular frequentist tests -- Kolmogorov-Smirnov, Shapiro-Wilk, Jarque–Bera, and D'Agostino -- along with a wrapper for the normality tests in the nortest package -- Anderson–Darling, Cramer–von Mises, Lilliefors (Kolmogorov-Smirnov), Pearson chi–square, and Shapiro–Francia. The package documentation also provides all the important references. Here is a demo that shows how to use the tests from nortest. One approach, if you have the time, is to use more than one test and check for agreement. The tests vary in a number of ways, so it isn't entirely straightforward to choose "the best". What do other researchers in your field use? This can vary and it may be best to stick with the accepted methods so that others will accept your work. I frequently use the Jarque-Bera test, partly for that reason, and Anderson–Darling for comparison. You can look at "Comparison of Tests for Univariate Normality" (Seier 2002) and "A comparison of various tests of normality" (Yazici; Yolacan 2007) for a comparison and discussion of the issues. It's also trivial to test these methods for comparison in R, thanks to all the distribution functions. Here's a simple example with simulated data (I won't print out the results to save space), although a more full exposition would be required: library(fBasics); library(ggplot2) set.seed(1) # normal distribution x1 <- rnorm(1e+06) x1.samp <- sample(x1, 200) qplot(x1.samp, geom="histogram") jbTest(x1.samp) adTest(x1.samp) # cauchy distribution x2 <- rcauchy(1e+06) x2.samp <- sample(x2, 200) qplot(x2.samp, geom="histogram") jbTest(x2.samp) adTest(x2.samp) Once you have the results from the various tests over different distributions, you can compare which were the most effective. For instance, the p-value for the Jarque-Bera test above returned 0.276 for the normal distribution (accepting) and < 2.2e-16 for the cauchy (rejecting the null hypothesis).
Appropriate normality tests for small samples
The fBasics package in R (part of Rmetrics) includes several normality tests, covering many of the popular frequentist tests -- Kolmogorov-Smirnov, Shapiro-Wilk, Jarque–Bera, and D'Agostino -- along w
Appropriate normality tests for small samples The fBasics package in R (part of Rmetrics) includes several normality tests, covering many of the popular frequentist tests -- Kolmogorov-Smirnov, Shapiro-Wilk, Jarque–Bera, and D'Agostino -- along with a wrapper for the normality tests in the nortest package -- Anderson–Darling, Cramer–von Mises, Lilliefors (Kolmogorov-Smirnov), Pearson chi–square, and Shapiro–Francia. The package documentation also provides all the important references. Here is a demo that shows how to use the tests from nortest. One approach, if you have the time, is to use more than one test and check for agreement. The tests vary in a number of ways, so it isn't entirely straightforward to choose "the best". What do other researchers in your field use? This can vary and it may be best to stick with the accepted methods so that others will accept your work. I frequently use the Jarque-Bera test, partly for that reason, and Anderson–Darling for comparison. You can look at "Comparison of Tests for Univariate Normality" (Seier 2002) and "A comparison of various tests of normality" (Yazici; Yolacan 2007) for a comparison and discussion of the issues. It's also trivial to test these methods for comparison in R, thanks to all the distribution functions. Here's a simple example with simulated data (I won't print out the results to save space), although a more full exposition would be required: library(fBasics); library(ggplot2) set.seed(1) # normal distribution x1 <- rnorm(1e+06) x1.samp <- sample(x1, 200) qplot(x1.samp, geom="histogram") jbTest(x1.samp) adTest(x1.samp) # cauchy distribution x2 <- rcauchy(1e+06) x2.samp <- sample(x2, 200) qplot(x2.samp, geom="histogram") jbTest(x2.samp) adTest(x2.samp) Once you have the results from the various tests over different distributions, you can compare which were the most effective. For instance, the p-value for the Jarque-Bera test above returned 0.276 for the normal distribution (accepting) and < 2.2e-16 for the cauchy (rejecting the null hypothesis).
Appropriate normality tests for small samples The fBasics package in R (part of Rmetrics) includes several normality tests, covering many of the popular frequentist tests -- Kolmogorov-Smirnov, Shapiro-Wilk, Jarque–Bera, and D'Agostino -- along w
11,385
Appropriate normality tests for small samples
For normality, actual Shapiro-Wilk has good power in fairly small samples. The main competitor in studies that I have seen is the more general Anderson-Darling, which does fairly well, but I wouldn't say it was better. If you can clarify what alternatives interest you, possibly a better statistic would be more obvious. [edit: if you estimate parameters, the A-D test should be adjusted for that.] [I strongly recommend against considering Jarque-Bera in small samples (which probably better known as Bowman-Shenton in statistical circles - they studied the small sample distribution). The asymptotic joint distribution of skewness and kurtosis is nothing like the small-sample distribution - in the same way a banana doesn't look much like an orange. It also has very low power against some interesting alternatives - for example it has low power to pick up a symmetric bimodal distribution that has kurtosis close to that of a normal distribution.] Frequently people test goodness of fit for what turn out to be not-particularly-good reasons, or they're answering a question other than the one that they actually want to answer. For example, you almost certainly already know your data aren't really normal (not exactly), so there's no point in trying to answer a question you know the answer to - and the hypothesis test doesn't actually answer it anyway. Given you know you don't have exact normality already, your hypothesis test of normality is really giving you an answer to a question closer to "is my sample size large enough to pick up the amount of non-normality that I have", while the real question you're interested in answering is usually closer to "what is the impact of this non-normality on these other things I'm interested in?". The hypothesis test is measuring sample size, while the question you're interested in answering is not very dependent on sample size. There are times when testing of normality makes some sense, but those situations almost never occur with small samples. Why are you testing normality?
Appropriate normality tests for small samples
For normality, actual Shapiro-Wilk has good power in fairly small samples. The main competitor in studies that I have seen is the more general Anderson-Darling, which does fairly well, but I wouldn't
Appropriate normality tests for small samples For normality, actual Shapiro-Wilk has good power in fairly small samples. The main competitor in studies that I have seen is the more general Anderson-Darling, which does fairly well, but I wouldn't say it was better. If you can clarify what alternatives interest you, possibly a better statistic would be more obvious. [edit: if you estimate parameters, the A-D test should be adjusted for that.] [I strongly recommend against considering Jarque-Bera in small samples (which probably better known as Bowman-Shenton in statistical circles - they studied the small sample distribution). The asymptotic joint distribution of skewness and kurtosis is nothing like the small-sample distribution - in the same way a banana doesn't look much like an orange. It also has very low power against some interesting alternatives - for example it has low power to pick up a symmetric bimodal distribution that has kurtosis close to that of a normal distribution.] Frequently people test goodness of fit for what turn out to be not-particularly-good reasons, or they're answering a question other than the one that they actually want to answer. For example, you almost certainly already know your data aren't really normal (not exactly), so there's no point in trying to answer a question you know the answer to - and the hypothesis test doesn't actually answer it anyway. Given you know you don't have exact normality already, your hypothesis test of normality is really giving you an answer to a question closer to "is my sample size large enough to pick up the amount of non-normality that I have", while the real question you're interested in answering is usually closer to "what is the impact of this non-normality on these other things I'm interested in?". The hypothesis test is measuring sample size, while the question you're interested in answering is not very dependent on sample size. There are times when testing of normality makes some sense, but those situations almost never occur with small samples. Why are you testing normality?
Appropriate normality tests for small samples For normality, actual Shapiro-Wilk has good power in fairly small samples. The main competitor in studies that I have seen is the more general Anderson-Darling, which does fairly well, but I wouldn't
11,386
Appropriate normality tests for small samples
There is a whole Wikipedia category on normality tests including: the Anderson-Darling test, popular amongst statisticians; and the Jarque-Bera test, popular amongst econometricians. I think A-D is probably the best of them.
Appropriate normality tests for small samples
There is a whole Wikipedia category on normality tests including: the Anderson-Darling test, popular amongst statisticians; and the Jarque-Bera test, popular amongst econometricians. I think A-D is
Appropriate normality tests for small samples There is a whole Wikipedia category on normality tests including: the Anderson-Darling test, popular amongst statisticians; and the Jarque-Bera test, popular amongst econometricians. I think A-D is probably the best of them.
Appropriate normality tests for small samples There is a whole Wikipedia category on normality tests including: the Anderson-Darling test, popular amongst statisticians; and the Jarque-Bera test, popular amongst econometricians. I think A-D is
11,387
Appropriate normality tests for small samples
For completeness, econometricians also like the Kiefer and Salmon test from their 1983 paper in Economics Letters -- it sums 'normalized' expressions of skewness and kurtosis which is then chi-square distributed. I have an old C++ version I wrote during grad school I could translate into R. Edit: And here is recent paper by Bierens (re-)deriving Jarque-Bera and Kiefer-Salmon. Edit 2: I looked over the old code, and it seems that it really is the same test between Jarque-Bera and Kiefer-Salmon.
Appropriate normality tests for small samples
For completeness, econometricians also like the Kiefer and Salmon test from their 1983 paper in Economics Letters -- it sums 'normalized' expressions of skewness and kurtosis which is then chi-square
Appropriate normality tests for small samples For completeness, econometricians also like the Kiefer and Salmon test from their 1983 paper in Economics Letters -- it sums 'normalized' expressions of skewness and kurtosis which is then chi-square distributed. I have an old C++ version I wrote during grad school I could translate into R. Edit: And here is recent paper by Bierens (re-)deriving Jarque-Bera and Kiefer-Salmon. Edit 2: I looked over the old code, and it seems that it really is the same test between Jarque-Bera and Kiefer-Salmon.
Appropriate normality tests for small samples For completeness, econometricians also like the Kiefer and Salmon test from their 1983 paper in Economics Letters -- it sums 'normalized' expressions of skewness and kurtosis which is then chi-square
11,388
Appropriate normality tests for small samples
In fact the Kiefer Salmon test and the Jarque Bera test are critically different as shown in several places but most recently here -Moment Tests for Standardized Error Distributions: A Simple Robust Approach by Yi-Ting Chen. The Kiefer Salmon test by construction is robust in the face of ARCH type error structures unlike the standard Jarque Bera test. The paper by Yi-Ting Chen develops and discusses what I think are likely to be the best tests around at the moment.
Appropriate normality tests for small samples
In fact the Kiefer Salmon test and the Jarque Bera test are critically different as shown in several places but most recently here -Moment Tests for Standardized Error Distributions: A Simple Robust
Appropriate normality tests for small samples In fact the Kiefer Salmon test and the Jarque Bera test are critically different as shown in several places but most recently here -Moment Tests for Standardized Error Distributions: A Simple Robust Approach by Yi-Ting Chen. The Kiefer Salmon test by construction is robust in the face of ARCH type error structures unlike the standard Jarque Bera test. The paper by Yi-Ting Chen develops and discusses what I think are likely to be the best tests around at the moment.
Appropriate normality tests for small samples In fact the Kiefer Salmon test and the Jarque Bera test are critically different as shown in several places but most recently here -Moment Tests for Standardized Error Distributions: A Simple Robust
11,389
Appropriate normality tests for small samples
For sample sizes <30 subjects, Shapiro-Wilk is considered to have a robust power - Be careful, when adjusting the significance level of the test, since it may induce a type II error! [1]
Appropriate normality tests for small samples
For sample sizes <30 subjects, Shapiro-Wilk is considered to have a robust power - Be careful, when adjusting the significance level of the test, since it may induce a type II error! [1]
Appropriate normality tests for small samples For sample sizes <30 subjects, Shapiro-Wilk is considered to have a robust power - Be careful, when adjusting the significance level of the test, since it may induce a type II error! [1]
Appropriate normality tests for small samples For sample sizes <30 subjects, Shapiro-Wilk is considered to have a robust power - Be careful, when adjusting the significance level of the test, since it may induce a type II error! [1]
11,390
Appropriate normality tests for small samples
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. I read about the z-score intervals: For small samples (n < 50), if absolute z-scores for either skewness or kurtosis are larger than 1.96, which corresponds with an alpha level 0.05, then reject the null hypothesis and conclude the distribution of the sample is non-normal (Hae-Young Kim, 2013.)
Appropriate normality tests for small samples
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Appropriate normality tests for small samples Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. I read about the z-score intervals: For small samples (n < 50), if absolute z-scores for either skewness or kurtosis are larger than 1.96, which corresponds with an alpha level 0.05, then reject the null hypothesis and conclude the distribution of the sample is non-normal (Hae-Young Kim, 2013.)
Appropriate normality tests for small samples Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
11,391
Why use extreme value theory?
Disclaimer: At points in the following, this GROSSLY presumes that your data is normally distributed. If you are actually engineering anything then talk to a strong stats professional and let that person sign on the line saying what the level will be. Talk to five of them, or 25 of them. This answer is meant for a civil engineering student asking "why" not for an engineering professional asking "how". I think the question behind the question is "what is the extreme value distribution?". Yes it is some algebra - symbols. So what? right? Lets think about 1000 year floods. They are big. http://www.huffingtonpost.com/2013/09/20/1000-year-storm_n_3956897.html http://science.time.com/2013/09/17/the-science-behind-colorados-thousand-year-flood/ http://gizmodo.com/why-we-dont-design-our-cities-to-withstand-1-000-year-1325451888 When they happen, they are going to kill a lot of people. Lots of bridges are going down. You know what bridge isn't going down? I do. You don't ... yet. Question: Which bridge isn't going down in a 1000 year flood? Answer: The bridge designed to withstand it. The data you need to do it your way: So lets say you have 200 years of daily water data. Is the 1000 year flood in there? Not remotely. You have a sample of one tail of the distribution. You don't have the population. If you knew all of the history of floods then you would have the total population of data. Lets think about this. How many years of data do you need to have, how many samples, in order to have at least one value whose likelihood is 1 in 1000? In a perfect world, you would need at least 1000 samples. The real world is messy, so you need more. You start getting 50/50 odds at about 4000 samples. You start getting guaranteed to have more than 1 at around 20,000 samples. Sample doesn't mean "water one second vs. the next" but a measure for each unique source of variation - like year-to-year variation. One measure over one year, along with another measure over another year constitute two samples. If you don't have 4,000 years of good data then you likely don't have an example 1000 year flood in the data. The good thing is - you don't need that much data to get a good result. Here is how to get better results with less data: If you look at the annual maxima, you can fit the "extreme value distribution" to the 200 values of year-max-levels and you will have the distribution that contains the 1000 year flood-level. It will be the algebra, not the actual "how big is it". You can use the equation to determine how big the 1000 year flood will be. Then, given that volume of water - you can build your bridge to resist it. Don't shoot for the exact value, shoot for bigger, otherwise you are designing it to fail on the 1000 year flood. If you are bold, then you can use resampling to figure out how much beyond on the exact 1000 year value you need to build it to in order to have it resist. Here is why EV/GEV are the relevant analytic forms: The generalized extreme value distribution is about how much the max varies. The variation in the maximum behaves really different than variation in the mean. The normal distribution, via the central limit theorem, describes a lot of "central tendencies". Procedure: do the following 1000 times: i. pick 1000 numbers from the standard normal distribution ii. compute the max of that group of samples and store it now plot the distribution of the result #libraries library(ggplot2) #parameters and pre-declarations nrolls <- 1000 ntimes <- 10000 store <- vector(length=ntimes) #main loop for (i in 1:ntimes){ #get samples y <- rnorm(nrolls,mean=0,sd=1) #store max store[i] <- max(y) } #plot ggplot(data=data.frame(store), aes(store)) + geom_histogram(aes(y = ..density..), col="red", fill="green", alpha = .2) + geom_density(col=2) + labs(title="Histogram for Max") + labs(x="Max", y="Count") This is NOT the "standard normal distribution": The peak is at 3.2 but the max goes up toward 5.0. It has skew. It doesn't get below about 2.5. If you had actual data (the standard normal) and you just pick the tail, then you are uniformly randomly picking something along this curve. If you get lucky then you are toward the center and not the lower tail. Engineering is about the opposite of luck - it is about achieving consistently the desired results every time. "Random numbers are far too important to leave to chance" (see footnote), especially for an engineer. The analytic function family that best fits this data - the extreme value family of distributions. Sample fit: Let's say we have 200 random values of the year-maximum from the standard normal distribution, and we are going to pretend they are our 200 year history of maximum water levels (whatever that means). To get the distribution we would do the following: Sample the "store" variable (to make for short/easy code) fit to a generalized extreme value distribution find the mean of the distribution use bootstrapping to find the 95% CI upper limit in variation of the mean, so we can target our engineering for that. (code presumes the above have been run first) library(SpatialExtremes) #if it isn't here install it, it is the ev library y2 <- sample(store,size=200,replace=FALSE) #this is our data myfit <- gevmle(y2) This gives results: > gevmle(y2) loc scale shape 3.0965530 0.2957722 -0.1139021 These can be plugged into the generating function to create 20,000 samples y3 <- rgev(20000,loc=myfit[1],scale=myfit[2],shape=myfit[3]) Building to the following will give 50/50 odds of failing on any year: mean(y3) 3.23681 Here is the code to determine what the 1000 year "flood" level is: p1000 <- qgev(1-(1/1000),loc=myfit[1],scale=myfit[2],shape=myfit[3]) p1000 Building to this following should give you 50/50 odds of failing on the 1000 year flood. p1000 4.510931 To determine the 95% upper CI I used the following code: myloc <- 3.0965530 myscale <- 0.2957722 myshape <- -0.1139021 N <- 1000 m <- 200 p_1000 <- vector(length=N) yd <- vector(length=m) for (i in 1:N){ #generate samples yd <- rgev(m,loc=myloc,scale=myscale,shape=myshape) #compute fit fit_d <- gevmle(yd) #compute quantile p_1000[i] <- qgev(1-(1/1000),loc=fit_d[1],scale=fit_d[2],shape=fit_d[3]) } mytarget <- quantile(p_1000,probs=0.95) The result was: > mytarget 95% 4.812148 This means, that in order to resist the large majority of 1000 year floods, given that your data is immaculately normal (not likely), you must build for the ... > out <- pgev(4.812148,loc=fit_d[1],scale=fit_d[2],shape=fit_d[3]) > 1/(1-out) or the > 1/(1-out) shape 1077.829 ... 1078 year flood. Bottom lines: you have a sample of the data, not the actual total population. That means your quantiles are estimates, and could be off. Distributions like the generalized extreme value distribution are built to use the samples to determine the actual tails. They are much less badly off at estimating than using the sample values, even if you don't have enough samples for the classic approach. If you are robust the ceiling is high, but the result of that is - you don't fail. Best of luck PS: I have heard that some civil engineering designs target the 98.5th percentile. If we had computed the 98.5th percentile instead of the max, then we would have found a different curve with different parameters. I think it is meant to build to a 67 year storm. $$ 1/(1-0.985) \approx 67 $$ The approach there, imo, would be to find the distribution for 67 year storms, then to determine variation around the mean, and get the padding so that it is engineered to succeed on the 67th year storm instead of to fail in it. Given the previous point, on average every 67 years the civil folks should have to rebuild. So at the full cost of engineering and construction every 67 years, given the operational life of the civil structure (I don't know what that is), at some point it might be less expensive to engineer for a longer inter-storm period. A sustainable civil infrastructure is one designed to last at least one human lifespan without failure, right? PS: more fun - a youtube video (not mine) https://www.youtube.com/watch?v=EACkiMRT0pc Footnote: Coveyou, Robert R. "Random number generation is too important to be left to chance." Applied Probability and Monte Carlo Methods and modern aspects of dynamics. Studies in applied mathematics 3 (1969): 70-111.
Why use extreme value theory?
Disclaimer: At points in the following, this GROSSLY presumes that your data is normally distributed. If you are actually engineering anything then talk to a strong stats professional and let that pe
Why use extreme value theory? Disclaimer: At points in the following, this GROSSLY presumes that your data is normally distributed. If you are actually engineering anything then talk to a strong stats professional and let that person sign on the line saying what the level will be. Talk to five of them, or 25 of them. This answer is meant for a civil engineering student asking "why" not for an engineering professional asking "how". I think the question behind the question is "what is the extreme value distribution?". Yes it is some algebra - symbols. So what? right? Lets think about 1000 year floods. They are big. http://www.huffingtonpost.com/2013/09/20/1000-year-storm_n_3956897.html http://science.time.com/2013/09/17/the-science-behind-colorados-thousand-year-flood/ http://gizmodo.com/why-we-dont-design-our-cities-to-withstand-1-000-year-1325451888 When they happen, they are going to kill a lot of people. Lots of bridges are going down. You know what bridge isn't going down? I do. You don't ... yet. Question: Which bridge isn't going down in a 1000 year flood? Answer: The bridge designed to withstand it. The data you need to do it your way: So lets say you have 200 years of daily water data. Is the 1000 year flood in there? Not remotely. You have a sample of one tail of the distribution. You don't have the population. If you knew all of the history of floods then you would have the total population of data. Lets think about this. How many years of data do you need to have, how many samples, in order to have at least one value whose likelihood is 1 in 1000? In a perfect world, you would need at least 1000 samples. The real world is messy, so you need more. You start getting 50/50 odds at about 4000 samples. You start getting guaranteed to have more than 1 at around 20,000 samples. Sample doesn't mean "water one second vs. the next" but a measure for each unique source of variation - like year-to-year variation. One measure over one year, along with another measure over another year constitute two samples. If you don't have 4,000 years of good data then you likely don't have an example 1000 year flood in the data. The good thing is - you don't need that much data to get a good result. Here is how to get better results with less data: If you look at the annual maxima, you can fit the "extreme value distribution" to the 200 values of year-max-levels and you will have the distribution that contains the 1000 year flood-level. It will be the algebra, not the actual "how big is it". You can use the equation to determine how big the 1000 year flood will be. Then, given that volume of water - you can build your bridge to resist it. Don't shoot for the exact value, shoot for bigger, otherwise you are designing it to fail on the 1000 year flood. If you are bold, then you can use resampling to figure out how much beyond on the exact 1000 year value you need to build it to in order to have it resist. Here is why EV/GEV are the relevant analytic forms: The generalized extreme value distribution is about how much the max varies. The variation in the maximum behaves really different than variation in the mean. The normal distribution, via the central limit theorem, describes a lot of "central tendencies". Procedure: do the following 1000 times: i. pick 1000 numbers from the standard normal distribution ii. compute the max of that group of samples and store it now plot the distribution of the result #libraries library(ggplot2) #parameters and pre-declarations nrolls <- 1000 ntimes <- 10000 store <- vector(length=ntimes) #main loop for (i in 1:ntimes){ #get samples y <- rnorm(nrolls,mean=0,sd=1) #store max store[i] <- max(y) } #plot ggplot(data=data.frame(store), aes(store)) + geom_histogram(aes(y = ..density..), col="red", fill="green", alpha = .2) + geom_density(col=2) + labs(title="Histogram for Max") + labs(x="Max", y="Count") This is NOT the "standard normal distribution": The peak is at 3.2 but the max goes up toward 5.0. It has skew. It doesn't get below about 2.5. If you had actual data (the standard normal) and you just pick the tail, then you are uniformly randomly picking something along this curve. If you get lucky then you are toward the center and not the lower tail. Engineering is about the opposite of luck - it is about achieving consistently the desired results every time. "Random numbers are far too important to leave to chance" (see footnote), especially for an engineer. The analytic function family that best fits this data - the extreme value family of distributions. Sample fit: Let's say we have 200 random values of the year-maximum from the standard normal distribution, and we are going to pretend they are our 200 year history of maximum water levels (whatever that means). To get the distribution we would do the following: Sample the "store" variable (to make for short/easy code) fit to a generalized extreme value distribution find the mean of the distribution use bootstrapping to find the 95% CI upper limit in variation of the mean, so we can target our engineering for that. (code presumes the above have been run first) library(SpatialExtremes) #if it isn't here install it, it is the ev library y2 <- sample(store,size=200,replace=FALSE) #this is our data myfit <- gevmle(y2) This gives results: > gevmle(y2) loc scale shape 3.0965530 0.2957722 -0.1139021 These can be plugged into the generating function to create 20,000 samples y3 <- rgev(20000,loc=myfit[1],scale=myfit[2],shape=myfit[3]) Building to the following will give 50/50 odds of failing on any year: mean(y3) 3.23681 Here is the code to determine what the 1000 year "flood" level is: p1000 <- qgev(1-(1/1000),loc=myfit[1],scale=myfit[2],shape=myfit[3]) p1000 Building to this following should give you 50/50 odds of failing on the 1000 year flood. p1000 4.510931 To determine the 95% upper CI I used the following code: myloc <- 3.0965530 myscale <- 0.2957722 myshape <- -0.1139021 N <- 1000 m <- 200 p_1000 <- vector(length=N) yd <- vector(length=m) for (i in 1:N){ #generate samples yd <- rgev(m,loc=myloc,scale=myscale,shape=myshape) #compute fit fit_d <- gevmle(yd) #compute quantile p_1000[i] <- qgev(1-(1/1000),loc=fit_d[1],scale=fit_d[2],shape=fit_d[3]) } mytarget <- quantile(p_1000,probs=0.95) The result was: > mytarget 95% 4.812148 This means, that in order to resist the large majority of 1000 year floods, given that your data is immaculately normal (not likely), you must build for the ... > out <- pgev(4.812148,loc=fit_d[1],scale=fit_d[2],shape=fit_d[3]) > 1/(1-out) or the > 1/(1-out) shape 1077.829 ... 1078 year flood. Bottom lines: you have a sample of the data, not the actual total population. That means your quantiles are estimates, and could be off. Distributions like the generalized extreme value distribution are built to use the samples to determine the actual tails. They are much less badly off at estimating than using the sample values, even if you don't have enough samples for the classic approach. If you are robust the ceiling is high, but the result of that is - you don't fail. Best of luck PS: I have heard that some civil engineering designs target the 98.5th percentile. If we had computed the 98.5th percentile instead of the max, then we would have found a different curve with different parameters. I think it is meant to build to a 67 year storm. $$ 1/(1-0.985) \approx 67 $$ The approach there, imo, would be to find the distribution for 67 year storms, then to determine variation around the mean, and get the padding so that it is engineered to succeed on the 67th year storm instead of to fail in it. Given the previous point, on average every 67 years the civil folks should have to rebuild. So at the full cost of engineering and construction every 67 years, given the operational life of the civil structure (I don't know what that is), at some point it might be less expensive to engineer for a longer inter-storm period. A sustainable civil infrastructure is one designed to last at least one human lifespan without failure, right? PS: more fun - a youtube video (not mine) https://www.youtube.com/watch?v=EACkiMRT0pc Footnote: Coveyou, Robert R. "Random number generation is too important to be left to chance." Applied Probability and Monte Carlo Methods and modern aspects of dynamics. Studies in applied mathematics 3 (1969): 70-111.
Why use extreme value theory? Disclaimer: At points in the following, this GROSSLY presumes that your data is normally distributed. If you are actually engineering anything then talk to a strong stats professional and let that pe
11,392
Why use extreme value theory?
If you are only interested in a tail it makes a sense that you focus your data collection and analysis effort on the tail. It should be more efficient to do so. I emphasized the data collection because this aspect is often ignored when presenting an argument for EVT distributions. In fact, it could be infeasible to collect the relevant data to estimate what you call an overall distribution in some fields. I'll explain in more detail below. If you're looking at 1 in 1000 years flood like in @EngrStudent's example, then to build the normal distribution's body you need a lot data to fill it with observations. Potentially you need every flood that has occurred in past hundreds of years. Now stop for a second and think of what is exactly a flood? When my backyard is flooded after a heavy rain, is it a flood? Probably not, but where exactly is the line that delineates a flood from an event that is not a flood? This simple question highlights the issue with data collection. How can you make sure that we collect all the data on the body following the same standard for decades or maybe even centuries? It's practically impossible to collect the data on the body of the distribution of floods. Hence, it's not just a matter of efficiency of analysis, but a matter of feasibility of data collection: whether to model the whole distribution or just a tail? Naturally, with tails the data collection is much easier. If we define the high enough threshold for what is a huge flood, then we can have a greater chance that all or almost all such events are probably recorded in some way. It's hard to miss a devastating flood, and if there's any kind of civilization present there'll be some memory saved about the event. Thus it makes a sense to build the analytic tools that focus specifically on the tails given that the data collection is much more robust on extreme events rather than on non-extreme ones in many fields such as a reliability studies.
Why use extreme value theory?
If you are only interested in a tail it makes a sense that you focus your data collection and analysis effort on the tail. It should be more efficient to do so. I emphasized the data collection becaus
Why use extreme value theory? If you are only interested in a tail it makes a sense that you focus your data collection and analysis effort on the tail. It should be more efficient to do so. I emphasized the data collection because this aspect is often ignored when presenting an argument for EVT distributions. In fact, it could be infeasible to collect the relevant data to estimate what you call an overall distribution in some fields. I'll explain in more detail below. If you're looking at 1 in 1000 years flood like in @EngrStudent's example, then to build the normal distribution's body you need a lot data to fill it with observations. Potentially you need every flood that has occurred in past hundreds of years. Now stop for a second and think of what is exactly a flood? When my backyard is flooded after a heavy rain, is it a flood? Probably not, but where exactly is the line that delineates a flood from an event that is not a flood? This simple question highlights the issue with data collection. How can you make sure that we collect all the data on the body following the same standard for decades or maybe even centuries? It's practically impossible to collect the data on the body of the distribution of floods. Hence, it's not just a matter of efficiency of analysis, but a matter of feasibility of data collection: whether to model the whole distribution or just a tail? Naturally, with tails the data collection is much easier. If we define the high enough threshold for what is a huge flood, then we can have a greater chance that all or almost all such events are probably recorded in some way. It's hard to miss a devastating flood, and if there's any kind of civilization present there'll be some memory saved about the event. Thus it makes a sense to build the analytic tools that focus specifically on the tails given that the data collection is much more robust on extreme events rather than on non-extreme ones in many fields such as a reliability studies.
Why use extreme value theory? If you are only interested in a tail it makes a sense that you focus your data collection and analysis effort on the tail. It should be more efficient to do so. I emphasized the data collection becaus
11,393
Why use extreme value theory?
You use extreme value theory to extrapolate from the observed data. Often, the data you have simply isn't big enough to provide you with a sensible estimate of a tail probability. Taking @EngrStudent's example of a 1-in-1000 year event: that corresponds to finding the 99.9% quantile of a distribution. But if you only have 200 years of data, you can only compute empirical quantile estimates up to 99.5%. Extreme value theory lets you estimate the 99.9% quantile, by making various assumptions about the shape of your distribution in the tail: that it's smooth, that it decays with a certain pattern, and so on. You might be thinking that the difference between 99.5% and 99.9% is minor; it's only 0.4% after all. But that's a difference in probability, and when you're in the tail, it can translate into a huge difference in quantiles. Here's an illustration of what it looks like for a gamma distribution, which doesn't have a very long tail as these things go. The blue line corresponds to the 99.5% quantile, and the red line is the 99.9% quantile. While the difference between these is tiny on the vertical axis, the separation on the horizontal axis is substantial. The separation only gets bigger for truly long-tailed distributions; the gamma is actually a fairly innocuous case.
Why use extreme value theory?
You use extreme value theory to extrapolate from the observed data. Often, the data you have simply isn't big enough to provide you with a sensible estimate of a tail probability. Taking @EngrStudent'
Why use extreme value theory? You use extreme value theory to extrapolate from the observed data. Often, the data you have simply isn't big enough to provide you with a sensible estimate of a tail probability. Taking @EngrStudent's example of a 1-in-1000 year event: that corresponds to finding the 99.9% quantile of a distribution. But if you only have 200 years of data, you can only compute empirical quantile estimates up to 99.5%. Extreme value theory lets you estimate the 99.9% quantile, by making various assumptions about the shape of your distribution in the tail: that it's smooth, that it decays with a certain pattern, and so on. You might be thinking that the difference between 99.5% and 99.9% is minor; it's only 0.4% after all. But that's a difference in probability, and when you're in the tail, it can translate into a huge difference in quantiles. Here's an illustration of what it looks like for a gamma distribution, which doesn't have a very long tail as these things go. The blue line corresponds to the 99.5% quantile, and the red line is the 99.9% quantile. While the difference between these is tiny on the vertical axis, the separation on the horizontal axis is substantial. The separation only gets bigger for truly long-tailed distributions; the gamma is actually a fairly innocuous case.
Why use extreme value theory? You use extreme value theory to extrapolate from the observed data. Often, the data you have simply isn't big enough to provide you with a sensible estimate of a tail probability. Taking @EngrStudent'
11,394
Why use extreme value theory?
Usually, the distribution of the underlying data (e.g., Gaussian wind speeds) is for a single sample point. The 98th percentile will tell you that for any randomly selected point there is a 2% chance of the value being bigger than the 98th percentile. I'm not a civil engineer, but I'd imagine what you'd want to know is not the likelihood of the wind speed on any given day being above a certain number, but the distribution of the largest possible gust over, say, the course of the year. In that case, if the daily wind gust maximums are, say, exponentially distributed, then what you want is the distribution of the maximum wind gust over 365 days...this is what the extreme value distribution was meant to solve.
Why use extreme value theory?
Usually, the distribution of the underlying data (e.g., Gaussian wind speeds) is for a single sample point. The 98th percentile will tell you that for any randomly selected point there is a 2% chance
Why use extreme value theory? Usually, the distribution of the underlying data (e.g., Gaussian wind speeds) is for a single sample point. The 98th percentile will tell you that for any randomly selected point there is a 2% chance of the value being bigger than the 98th percentile. I'm not a civil engineer, but I'd imagine what you'd want to know is not the likelihood of the wind speed on any given day being above a certain number, but the distribution of the largest possible gust over, say, the course of the year. In that case, if the daily wind gust maximums are, say, exponentially distributed, then what you want is the distribution of the maximum wind gust over 365 days...this is what the extreme value distribution was meant to solve.
Why use extreme value theory? Usually, the distribution of the underlying data (e.g., Gaussian wind speeds) is for a single sample point. The 98th percentile will tell you that for any randomly selected point there is a 2% chance
11,395
Why use extreme value theory?
The use of the quantile makes the further calculation simpler. The civil engineers can substitute the value (wind speed, for instance) into their first-principle formulas and they obtain the behavior of the system for those extreme conditions that correspond to the 98.5% quantile. The use of the whole distribution could seem to provide more information, but would complicate the calculations. However, it could allow the use of advanced risk-management approaches that would optimally balance the costs related to (i) the construction and (ii) the risk of the failure.
Why use extreme value theory?
The use of the quantile makes the further calculation simpler. The civil engineers can substitute the value (wind speed, for instance) into their first-principle formulas and they obtain the behavior
Why use extreme value theory? The use of the quantile makes the further calculation simpler. The civil engineers can substitute the value (wind speed, for instance) into their first-principle formulas and they obtain the behavior of the system for those extreme conditions that correspond to the 98.5% quantile. The use of the whole distribution could seem to provide more information, but would complicate the calculations. However, it could allow the use of advanced risk-management approaches that would optimally balance the costs related to (i) the construction and (ii) the risk of the failure.
Why use extreme value theory? The use of the quantile makes the further calculation simpler. The civil engineers can substitute the value (wind speed, for instance) into their first-principle formulas and they obtain the behavior
11,396
How to find local peaks/valleys in a series of data?
The source of this code is obtained by typing its name at the R prompt. The output is function (x, thresh = 0) { pks <- which(diff(sign(diff(x, na.pad = FALSE)), na.pad = FALSE) < 0) + 2 if (!missing(thresh)) { pks[x[pks - 1] - x[pks] > thresh] } else pks } The test x[pks - 1] - x[pks] > thresh compares each peak value to the value immediately succeeding it in the series (not to the next trough in the series). It uses a (crude) estimate of the size of the slope of the function immediately after the peak and selects only those peaks where that slope exceeds thresh in size. In your case, only the first three peaks are sufficiently sharp to pass the test. You will detect all the peaks by using the default: > findPeaks(cc) [1] 3 22 41 59 78 96
How to find local peaks/valleys in a series of data?
The source of this code is obtained by typing its name at the R prompt. The output is function (x, thresh = 0) { pks <- which(diff(sign(diff(x, na.pad = FALSE)), na.pad = FALSE) < 0) + 2 if
How to find local peaks/valleys in a series of data? The source of this code is obtained by typing its name at the R prompt. The output is function (x, thresh = 0) { pks <- which(diff(sign(diff(x, na.pad = FALSE)), na.pad = FALSE) < 0) + 2 if (!missing(thresh)) { pks[x[pks - 1] - x[pks] > thresh] } else pks } The test x[pks - 1] - x[pks] > thresh compares each peak value to the value immediately succeeding it in the series (not to the next trough in the series). It uses a (crude) estimate of the size of the slope of the function immediately after the peak and selects only those peaks where that slope exceeds thresh in size. In your case, only the first three peaks are sufficiently sharp to pass the test. You will detect all the peaks by using the default: > findPeaks(cc) [1] 3 22 41 59 78 96
How to find local peaks/valleys in a series of data? The source of this code is obtained by typing its name at the R prompt. The output is function (x, thresh = 0) { pks <- which(diff(sign(diff(x, na.pad = FALSE)), na.pad = FALSE) < 0) + 2 if
11,397
How to find local peaks/valleys in a series of data?
I agree with whuber's response but just wanted to add that the "+2" portion of the code, which attempts to shift the index to match the newly found peak actually 'overshoots' and should be "+1". for instance in the example at hand we obtain: > findPeaks(cc) [1] 3 22 41 59 78 96 when we highlight these found peaks on a graph (bold red): we see that they are consistently 1 point away from the actual peak. consequenty pks[x[pks - 1] - x[pks] > thresh] should be pks[x[pks] - x[pks + 1] > thresh] or pks[x[pks] - x[pks - 1] > thresh] BIG UPDATE following my own quest to find an adequate peak finding function i wrote this: find_peaks <- function (x, m = 3){ shape <- diff(sign(diff(x, na.pad = FALSE))) pks <- sapply(which(shape < 0), FUN = function(i){ z <- i - m + 1 z <- ifelse(z > 0, z, 1) w <- i + m + 1 w <- ifelse(w < length(x), w, length(x)) if(all(x[c(z : i, (i + 2) : w)] <= x[i + 1])) return(i + 1) else return(numeric(0)) }) pks <- unlist(pks) pks } a 'peak' is defined as a local maxima with m points either side of it being smaller than it. hence, the bigger the parameter m, the more stringent is the peak funding procedure. so: find_peaks(cc, m = 1) [1] 2 21 40 58 77 95 the function can also be used to find local minima of any sequential vector x via find_peaks(-x). Note: i have now put the function on gitHub if anyone needs it: https://github.com/stas-g/findPeaks
How to find local peaks/valleys in a series of data?
I agree with whuber's response but just wanted to add that the "+2" portion of the code, which attempts to shift the index to match the newly found peak actually 'overshoots' and should be "+1". for i
How to find local peaks/valleys in a series of data? I agree with whuber's response but just wanted to add that the "+2" portion of the code, which attempts to shift the index to match the newly found peak actually 'overshoots' and should be "+1". for instance in the example at hand we obtain: > findPeaks(cc) [1] 3 22 41 59 78 96 when we highlight these found peaks on a graph (bold red): we see that they are consistently 1 point away from the actual peak. consequenty pks[x[pks - 1] - x[pks] > thresh] should be pks[x[pks] - x[pks + 1] > thresh] or pks[x[pks] - x[pks - 1] > thresh] BIG UPDATE following my own quest to find an adequate peak finding function i wrote this: find_peaks <- function (x, m = 3){ shape <- diff(sign(diff(x, na.pad = FALSE))) pks <- sapply(which(shape < 0), FUN = function(i){ z <- i - m + 1 z <- ifelse(z > 0, z, 1) w <- i + m + 1 w <- ifelse(w < length(x), w, length(x)) if(all(x[c(z : i, (i + 2) : w)] <= x[i + 1])) return(i + 1) else return(numeric(0)) }) pks <- unlist(pks) pks } a 'peak' is defined as a local maxima with m points either side of it being smaller than it. hence, the bigger the parameter m, the more stringent is the peak funding procedure. so: find_peaks(cc, m = 1) [1] 2 21 40 58 77 95 the function can also be used to find local minima of any sequential vector x via find_peaks(-x). Note: i have now put the function on gitHub if anyone needs it: https://github.com/stas-g/findPeaks
How to find local peaks/valleys in a series of data? I agree with whuber's response but just wanted to add that the "+2" portion of the code, which attempts to shift the index to match the newly found peak actually 'overshoots' and should be "+1". for i
11,398
How to find local peaks/valleys in a series of data?
Eek: Minor update. I had to change two lines of code, the bounds, (add a -1 and +1) to reach equivalency with Stas_G's function(it was finding a few too many 'extra peaks' in real data-sets). Apologies for anyone lead very minorly astray by my original post. I have been using Stas_g's find peaks algorithm for quite some time now. It was beneficial to me for one of my later projects due to its simplicity. I however, needed to use it millions of times for a computation so I rewrote it in Rcpp(See Rcpp package). It is roughly 6x faster then the R version in simple tests. If anyone is interested I have added the code below. Hopefully I help someone, Cheers! Some minor caveats. This function returns peak indices in reverse order of the R code. It requires a inhouse C++ Sign function, which I included. It has not been completely optimized but any further performance gains aren't expected. //This function returns the sign of a given real valued double. // [[Rcpp::export]] double signDblCPP (double x){ double ret = 0; if(x > 0){ret = 1;} if(x < 0){ret = -1;} return(ret); } //Tested to be 6x faster(37 us vs 207 us). This operation is done from 200x per layer //Original R function by Stas_G // [[Rcpp::export]] NumericVector findPeaksCPP( NumericVector vY, int m = 3) { int sze = vY.size(); int i = 0;//generic iterator int q = 0;//second generic iterator int lb = 0;//left bound int rb = 0;//right bound bool isGreatest = true;//flag to state whether current index is greatest known value NumericVector ret(1); int pksFound = 0; for(i = 0; i < (sze-2); ++i){ //Find all regions with negative laplacian between neighbors //following expression is identical to diff(sign(diff(xV, na.pad = FALSE))) if(signDblCPP( vY(i + 2) - vY( i + 1 ) ) - signDblCPP( vY( i + 1 ) - vY( i ) ) < 0){ //Now assess all regions with negative laplacian between neighbors... lb = i - m - 1;// define left bound of vector if(lb < 0){lb = 0;}//ensure our neighbor comparison is bounded by vector length rb = i + m + 1;// define right bound of vector if(rb >= (sze-2)){rb = (sze-3);}//ensure our neighbor comparison is bounded by vector length //Scan through loop and ensure that the neighbors are smaller in magnitude for(q = lb; q < rb; ++q){ if(vY(q) > vY(i+1)){ isGreatest = false; } } //We have found a peak by our criterion if(isGreatest){ if(pksFound > 0){//Check vector size. ret.insert( 0, double(i + 2) ); }else{ ret(0) = double(i + 2); } pksFound = pksFound + 1; }else{ // we did not find a peak, reset location is peak max flag. isGreatest = true; }//End if found peak }//End if laplace condition }//End loop return(ret); }//End Fn
How to find local peaks/valleys in a series of data?
Eek: Minor update. I had to change two lines of code, the bounds, (add a -1 and +1) to reach equivalency with Stas_G's function(it was finding a few too many 'extra peaks' in real data-sets). Apologie
How to find local peaks/valleys in a series of data? Eek: Minor update. I had to change two lines of code, the bounds, (add a -1 and +1) to reach equivalency with Stas_G's function(it was finding a few too many 'extra peaks' in real data-sets). Apologies for anyone lead very minorly astray by my original post. I have been using Stas_g's find peaks algorithm for quite some time now. It was beneficial to me for one of my later projects due to its simplicity. I however, needed to use it millions of times for a computation so I rewrote it in Rcpp(See Rcpp package). It is roughly 6x faster then the R version in simple tests. If anyone is interested I have added the code below. Hopefully I help someone, Cheers! Some minor caveats. This function returns peak indices in reverse order of the R code. It requires a inhouse C++ Sign function, which I included. It has not been completely optimized but any further performance gains aren't expected. //This function returns the sign of a given real valued double. // [[Rcpp::export]] double signDblCPP (double x){ double ret = 0; if(x > 0){ret = 1;} if(x < 0){ret = -1;} return(ret); } //Tested to be 6x faster(37 us vs 207 us). This operation is done from 200x per layer //Original R function by Stas_G // [[Rcpp::export]] NumericVector findPeaksCPP( NumericVector vY, int m = 3) { int sze = vY.size(); int i = 0;//generic iterator int q = 0;//second generic iterator int lb = 0;//left bound int rb = 0;//right bound bool isGreatest = true;//flag to state whether current index is greatest known value NumericVector ret(1); int pksFound = 0; for(i = 0; i < (sze-2); ++i){ //Find all regions with negative laplacian between neighbors //following expression is identical to diff(sign(diff(xV, na.pad = FALSE))) if(signDblCPP( vY(i + 2) - vY( i + 1 ) ) - signDblCPP( vY( i + 1 ) - vY( i ) ) < 0){ //Now assess all regions with negative laplacian between neighbors... lb = i - m - 1;// define left bound of vector if(lb < 0){lb = 0;}//ensure our neighbor comparison is bounded by vector length rb = i + m + 1;// define right bound of vector if(rb >= (sze-2)){rb = (sze-3);}//ensure our neighbor comparison is bounded by vector length //Scan through loop and ensure that the neighbors are smaller in magnitude for(q = lb; q < rb; ++q){ if(vY(q) > vY(i+1)){ isGreatest = false; } } //We have found a peak by our criterion if(isGreatest){ if(pksFound > 0){//Check vector size. ret.insert( 0, double(i + 2) ); }else{ ret(0) = double(i + 2); } pksFound = pksFound + 1; }else{ // we did not find a peak, reset location is peak max flag. isGreatest = true; }//End if found peak }//End if laplace condition }//End loop return(ret); }//End Fn
How to find local peaks/valleys in a series of data? Eek: Minor update. I had to change two lines of code, the bounds, (add a -1 and +1) to reach equivalency with Stas_G's function(it was finding a few too many 'extra peaks' in real data-sets). Apologie
11,399
How to find local peaks/valleys in a series of data?
Firstly: The algorithm also falsely calls a drop to the right of a flat plateau since sign(diff(x, na.pad = FALSE)) will be 0 then -1 so that its diff will also be -1. A simple fix is to ensure that the sign-diff preceding the negative entry is not zero but positive: n <- length(x) dx.1 <- sign(diff(x, na.pad = FALSE)) pks <- which(diff(dx.1, na.pad = FALSE) < 0 & dx.1[-(n-1)] > 0) + 1 Second: The algorithm gives very local results, e.g. an 'up' followed by a 'down' in any run of three consecutive terms in the sequence. If one is interested instead in local maxima of a noised continuous function, then -- there are probably other better things out there, but this is my cheap and immediate solution identify the peaks first using running average of 3 consecutive points to smooth the data ever so slightly. Also employ the above mentioned control against flat then drop-off. filter these candidates by comparing, for a loess-smoothed version, the average inside a window centered at each peak with the average of local terms outside. "myfindPeaks" <- function (x, thresh=0.05, span=0.25, lspan=0.05, noisey=TRUE) { n <- length(x) y <- x mu.y.loc <- y if(noisey) { mu.y.loc <- (x[1:(n-2)] + x[2:(n-1)] + x[3:n])/3 mu.y.loc <- c(mu.y.loc[1], mu.y.loc, mu.y.loc[n-2]) } y.loess <- loess(x~I(1:n), span=span) y <- y.loess[[2]] sig.y <- var(y.loess$resid, na.rm=TRUE)^0.5 DX.1 <- sign(diff(mu.y.loc, na.pad = FALSE)) pks <- which(diff(DX.1, na.pad = FALSE) < 0 & DX.1[-(n-1)] > 0) + 1 out <- pks if(noisey) { n.w <- floor(lspan*n/2) out <- NULL for(pk in pks) { inner <- (pk-n.w):(pk+n.w) outer <- c((pk-2*n.w):(pk-n.w),(pk+2*n.w):(pk+n.w)) mu.y.outer <- mean(y[outer]) if(!is.na(mu.y.outer)) if (mean(y[inner])-mu.y.outer > thresh*sig.y) out <- c(out, pk) } } out }
How to find local peaks/valleys in a series of data?
Firstly: The algorithm also falsely calls a drop to the right of a flat plateau since sign(diff(x, na.pad = FALSE)) will be 0 then -1 so that its diff will also be -1. A simple fix is to ensure tha
How to find local peaks/valleys in a series of data? Firstly: The algorithm also falsely calls a drop to the right of a flat plateau since sign(diff(x, na.pad = FALSE)) will be 0 then -1 so that its diff will also be -1. A simple fix is to ensure that the sign-diff preceding the negative entry is not zero but positive: n <- length(x) dx.1 <- sign(diff(x, na.pad = FALSE)) pks <- which(diff(dx.1, na.pad = FALSE) < 0 & dx.1[-(n-1)] > 0) + 1 Second: The algorithm gives very local results, e.g. an 'up' followed by a 'down' in any run of three consecutive terms in the sequence. If one is interested instead in local maxima of a noised continuous function, then -- there are probably other better things out there, but this is my cheap and immediate solution identify the peaks first using running average of 3 consecutive points to smooth the data ever so slightly. Also employ the above mentioned control against flat then drop-off. filter these candidates by comparing, for a loess-smoothed version, the average inside a window centered at each peak with the average of local terms outside. "myfindPeaks" <- function (x, thresh=0.05, span=0.25, lspan=0.05, noisey=TRUE) { n <- length(x) y <- x mu.y.loc <- y if(noisey) { mu.y.loc <- (x[1:(n-2)] + x[2:(n-1)] + x[3:n])/3 mu.y.loc <- c(mu.y.loc[1], mu.y.loc, mu.y.loc[n-2]) } y.loess <- loess(x~I(1:n), span=span) y <- y.loess[[2]] sig.y <- var(y.loess$resid, na.rm=TRUE)^0.5 DX.1 <- sign(diff(mu.y.loc, na.pad = FALSE)) pks <- which(diff(DX.1, na.pad = FALSE) < 0 & DX.1[-(n-1)] > 0) + 1 out <- pks if(noisey) { n.w <- floor(lspan*n/2) out <- NULL for(pk in pks) { inner <- (pk-n.w):(pk+n.w) outer <- c((pk-2*n.w):(pk-n.w),(pk+2*n.w):(pk+n.w)) mu.y.outer <- mean(y[outer]) if(!is.na(mu.y.outer)) if (mean(y[inner])-mu.y.outer > thresh*sig.y) out <- c(out, pk) } } out }
How to find local peaks/valleys in a series of data? Firstly: The algorithm also falsely calls a drop to the right of a flat plateau since sign(diff(x, na.pad = FALSE)) will be 0 then -1 so that its diff will also be -1. A simple fix is to ensure tha
11,400
How to find local peaks/valleys in a series of data?
It's true the function also identifies the end of plateaux, but I think there is another easier fix: Since the first diff of a real peak will result in '1' then '-1', the second diff would be '-2', and we can check directly pks <- which(diff(sign(diff(x, na.pad = FALSE)), na.pad = FALSE) < 1) + 1
How to find local peaks/valleys in a series of data?
It's true the function also identifies the end of plateaux, but I think there is another easier fix: Since the first diff of a real peak will result in '1' then '-1', the second diff would be '-2', a
How to find local peaks/valleys in a series of data? It's true the function also identifies the end of plateaux, but I think there is another easier fix: Since the first diff of a real peak will result in '1' then '-1', the second diff would be '-2', and we can check directly pks <- which(diff(sign(diff(x, na.pad = FALSE)), na.pad = FALSE) < 1) + 1
How to find local peaks/valleys in a series of data? It's true the function also identifies the end of plateaux, but I think there is another easier fix: Since the first diff of a real peak will result in '1' then '-1', the second diff would be '-2', a