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
25,101
What exactly is the Box-Jenkins method for ARIMA processes?
Box and Jenkins themselves didn't use AIC. Their book came out in 1970 based on methodology developed previously, while Akaike's papers on AIC came (not long) after the book was published. Their methodology is outlined in their book [1], but what's today included under the mantle of "Box-Jenkins" is a bit broader and varies from person to person. Box and Jenkins themselves give a simple flowchart on model identification which might be regarded as a useful summary of the process they used to identify models. (I'd suggest looking at the book if you can - most decent university libraries should have a copy.) They incorporated stages of model identification, estimation and diagnostic checking/validation (including a return to the first stage if the model is inadequate), and then once an adequate model is identified, the model may be forecasted. The wikipedia page here gives an outline of the sort of thing that's involved, but it contains a number of things that have been added in to what people tend to so since the book came out. Indeed, numerous documents that describe Box-Jenkins methodology these days would include the use of AIC or similar quantities. See also the discussion here. More recent books (e.g. see the above wikipedia page) give a more 'modern' version of the general approach. In the end, if you want to find out what Box-Jenkins methodology really "is", I would say "start with their book". Failing that, a number of more recent treatments of ARIMA models cover broadly similar methodology -- try any number of reasonably decent time series books that cover ARIMA models. [1]: Box, George; Jenkins, Gwilym (1970), Time series analysis: Forecasting and control San Francisco: Holden-Day
What exactly is the Box-Jenkins method for ARIMA processes?
Box and Jenkins themselves didn't use AIC. Their book came out in 1970 based on methodology developed previously, while Akaike's papers on AIC came (not long) after the book was published. Their metho
What exactly is the Box-Jenkins method for ARIMA processes? Box and Jenkins themselves didn't use AIC. Their book came out in 1970 based on methodology developed previously, while Akaike's papers on AIC came (not long) after the book was published. Their methodology is outlined in their book [1], but what's today included under the mantle of "Box-Jenkins" is a bit broader and varies from person to person. Box and Jenkins themselves give a simple flowchart on model identification which might be regarded as a useful summary of the process they used to identify models. (I'd suggest looking at the book if you can - most decent university libraries should have a copy.) They incorporated stages of model identification, estimation and diagnostic checking/validation (including a return to the first stage if the model is inadequate), and then once an adequate model is identified, the model may be forecasted. The wikipedia page here gives an outline of the sort of thing that's involved, but it contains a number of things that have been added in to what people tend to so since the book came out. Indeed, numerous documents that describe Box-Jenkins methodology these days would include the use of AIC or similar quantities. See also the discussion here. More recent books (e.g. see the above wikipedia page) give a more 'modern' version of the general approach. In the end, if you want to find out what Box-Jenkins methodology really "is", I would say "start with their book". Failing that, a number of more recent treatments of ARIMA models cover broadly similar methodology -- try any number of reasonably decent time series books that cover ARIMA models. [1]: Box, George; Jenkins, Gwilym (1970), Time series analysis: Forecasting and control San Francisco: Holden-Day
What exactly is the Box-Jenkins method for ARIMA processes? Box and Jenkins themselves didn't use AIC. Their book came out in 1970 based on methodology developed previously, while Akaike's papers on AIC came (not long) after the book was published. Their metho
25,102
What exactly is the Box-Jenkins method for ARIMA processes?
The Box-Jenkins methodology is a strategy or procedure that can be used to build an ARIMA model. The methodology is outlined in the book Time Series Analysis: Forecasting and Control by George E. P. Box and Gwilym M. Jenkins, originally published in 1970 - more recent editions exist. By opening up SAS, calling proc ARIMA, and supply numbers for p, d, and q, you have merely estimated an ARIMA model. Doing this blindly, that is, by not using any particular recognized methodology to identify the ARIMA model itself, is a bit like playing with matches - the dangers of software! If you keep repeating this process - estimating lots and lots of ARIMA models - you will eventually be able to select a model with the lowest Akaike Information criterion (from the set of models that you have estimated). In this context, a more systematic approach would be to use an algorithm based on comparing AIC values for a variety of different models to automatically select an ARIMA model for you, such as the one provided by the forecast package in R - the relevant function name is auto.arima(). In any event, the procedure you outlined involved selecting an ARIMA model based on minimizing some information criterion (in this case, AIC, but there are other measures). This is one particular methodology, but it's not the Box-Jenkins methodology; an alternative. The Box-Jenkins methodology comprises five stages (although sometimes said to involve just three stages): Checking for stationarity or non-stationarity and transforming the data, if necessary; Identification of a suitable ARMA model; Estimation of the parameters of the chosen model; Diagnostic checking of model adequacy; and Forecasting, or repetition of steps two to five. Notably, it is an iterative process that involves the model builder exercising some judgement - and this is one aspect of the methodology that has been considered a shortcoming. The judgemental part comes into play particularly when interpreting two tools; namely, the (estimated) autocorrelation function (ACF) and partial autocorrelation function (PACF). If you'd like to become a practitioner of the Box-Jenkins methodology, I'd recommended consulting the original text (you'd be surprised what modern textbooks omit!) alongside whatever modern variations you can find. Alan Pankratz has a couple of excellent textbooks, which I'd highly recommend, too; for example, Forecasting with Univariate Box-Jenkins Models: Concepts and Cases. Experience suggests to me that the term "Box-Jenkins methodology" is used in a loose manner because I've heard some people use it to simply refer to building ARIMA models in general - and not to the actual process involved in building an ARIMA model - while others use it to refer to a modified version of what was published in 1970. As @Glen_b has pointed out, "there are numerous documents that describe the Box-Jenkins methodology these days that would include the use of AIC or similar quantities". Q: Are you supposed to use Box-Jenkins methodology to come up with initial estimates of p,d,q? As already mentioned, there are different model selection strategies so the answer is no it's not necessarily the case that you need to employ the Box-Jenkins methodology, but you could if you wanted to. Q: Did SAS use it internally somehow? Highly unlikely unless that software offers a quite sophisticated function! Consult the official SAS documentation for details of what the software does or is capable of doing. If it was R, you could look at the source code, but I doubt that's an option with SAS.
What exactly is the Box-Jenkins method for ARIMA processes?
The Box-Jenkins methodology is a strategy or procedure that can be used to build an ARIMA model. The methodology is outlined in the book Time Series Analysis: Forecasting and Control by George E. P. B
What exactly is the Box-Jenkins method for ARIMA processes? The Box-Jenkins methodology is a strategy or procedure that can be used to build an ARIMA model. The methodology is outlined in the book Time Series Analysis: Forecasting and Control by George E. P. Box and Gwilym M. Jenkins, originally published in 1970 - more recent editions exist. By opening up SAS, calling proc ARIMA, and supply numbers for p, d, and q, you have merely estimated an ARIMA model. Doing this blindly, that is, by not using any particular recognized methodology to identify the ARIMA model itself, is a bit like playing with matches - the dangers of software! If you keep repeating this process - estimating lots and lots of ARIMA models - you will eventually be able to select a model with the lowest Akaike Information criterion (from the set of models that you have estimated). In this context, a more systematic approach would be to use an algorithm based on comparing AIC values for a variety of different models to automatically select an ARIMA model for you, such as the one provided by the forecast package in R - the relevant function name is auto.arima(). In any event, the procedure you outlined involved selecting an ARIMA model based on minimizing some information criterion (in this case, AIC, but there are other measures). This is one particular methodology, but it's not the Box-Jenkins methodology; an alternative. The Box-Jenkins methodology comprises five stages (although sometimes said to involve just three stages): Checking for stationarity or non-stationarity and transforming the data, if necessary; Identification of a suitable ARMA model; Estimation of the parameters of the chosen model; Diagnostic checking of model adequacy; and Forecasting, or repetition of steps two to five. Notably, it is an iterative process that involves the model builder exercising some judgement - and this is one aspect of the methodology that has been considered a shortcoming. The judgemental part comes into play particularly when interpreting two tools; namely, the (estimated) autocorrelation function (ACF) and partial autocorrelation function (PACF). If you'd like to become a practitioner of the Box-Jenkins methodology, I'd recommended consulting the original text (you'd be surprised what modern textbooks omit!) alongside whatever modern variations you can find. Alan Pankratz has a couple of excellent textbooks, which I'd highly recommend, too; for example, Forecasting with Univariate Box-Jenkins Models: Concepts and Cases. Experience suggests to me that the term "Box-Jenkins methodology" is used in a loose manner because I've heard some people use it to simply refer to building ARIMA models in general - and not to the actual process involved in building an ARIMA model - while others use it to refer to a modified version of what was published in 1970. As @Glen_b has pointed out, "there are numerous documents that describe the Box-Jenkins methodology these days that would include the use of AIC or similar quantities". Q: Are you supposed to use Box-Jenkins methodology to come up with initial estimates of p,d,q? As already mentioned, there are different model selection strategies so the answer is no it's not necessarily the case that you need to employ the Box-Jenkins methodology, but you could if you wanted to. Q: Did SAS use it internally somehow? Highly unlikely unless that software offers a quite sophisticated function! Consult the official SAS documentation for details of what the software does or is capable of doing. If it was R, you could look at the source code, but I doubt that's an option with SAS.
What exactly is the Box-Jenkins method for ARIMA processes? The Box-Jenkins methodology is a strategy or procedure that can be used to build an ARIMA model. The methodology is outlined in the book Time Series Analysis: Forecasting and Control by George E. P. B
25,103
Expectation of a squared Gamma
The expectation of the square of any random variable is its variance plus its expectation squared, as $\mathbb{D}^2(X)=\mathbb{E}([X-\mathbb{E}(X)]^2)=\mathbb{E}(X^2)-[\mathbb{E}(X)]^2 \Rightarrow \mathbb{E}(X^2) = \mathbb{D}^2(X)+[\mathbb{E}(X)]^2$. The expectation of the $\Gamma$-distribution parametrized as above is $\alpha/\beta$ (like you mentioned), the variance is $\alpha/\beta^2$, hence, the expectation of its square is $(\alpha/\beta)^2+\alpha/\beta^2$. That is: you are right.
Expectation of a squared Gamma
The expectation of the square of any random variable is its variance plus its expectation squared, as $\mathbb{D}^2(X)=\mathbb{E}([X-\mathbb{E}(X)]^2)=\mathbb{E}(X^2)-[\mathbb{E}(X)]^2 \Rightarrow \ma
Expectation of a squared Gamma The expectation of the square of any random variable is its variance plus its expectation squared, as $\mathbb{D}^2(X)=\mathbb{E}([X-\mathbb{E}(X)]^2)=\mathbb{E}(X^2)-[\mathbb{E}(X)]^2 \Rightarrow \mathbb{E}(X^2) = \mathbb{D}^2(X)+[\mathbb{E}(X)]^2$. The expectation of the $\Gamma$-distribution parametrized as above is $\alpha/\beta$ (like you mentioned), the variance is $\alpha/\beta^2$, hence, the expectation of its square is $(\alpha/\beta)^2+\alpha/\beta^2$. That is: you are right.
Expectation of a squared Gamma The expectation of the square of any random variable is its variance plus its expectation squared, as $\mathbb{D}^2(X)=\mathbb{E}([X-\mathbb{E}(X)]^2)=\mathbb{E}(X^2)-[\mathbb{E}(X)]^2 \Rightarrow \ma
25,104
Expectation of a squared Gamma
For the sake of completeness, I will directly compute the raw moments from the density. First, under a shape/rate parametrization, the gamma distribution has density $$f_X(x) = \frac{\beta^\alpha x^{\alpha-1} e^{-\beta x}}{\Gamma(\alpha)}, \quad x > 0.$$ We will take for granted that for any choice of parameters $\alpha, \beta > 0$, we have $$\int_{x=0}^\infty f_X(x) \, dx = 1,$$ although this result is easily derived from the identity $$\int_{z=0}^\infty x^{z-1} e^{-z} \, dz = \Gamma(z).$$ Then it follows that for a positive integer $k$, $$\begin{align*} \mathrm{E}[X^k] &= \int_{x=0}^\infty x^k f_X(x) \, dx \\ &= \frac{1}{\Gamma(\alpha)} \int_{x=0}^\infty \beta^\alpha x^{\alpha+k-1} e^{-\beta x} \, dx \\ &= \frac{\Gamma(\alpha+k)}{\beta^k \Gamma(\alpha)} \int_{x=0}^\infty \frac{\beta^{\alpha+k} x^{\alpha+k-1} e^{-\beta x}}{\Gamma(\alpha+k)} \, dx \\ &= \frac{\Gamma(\alpha+k)}{\beta^k \Gamma(\alpha)}, \end{align*}$$ where in the penultimate step we observe that the integral equals $1$ because it is the integral of a gamma density with parameters $\alpha+k$ and $\beta$. For $k = 2$, we immediately obtain $\mathrm{E}[X^2] = \frac{\Gamma(\alpha+2)}{\beta^2 \Gamma(\alpha)} = \frac{(\alpha+1)\alpha}{\beta^2}.$ Another approach is via the moment generating function: $$\begin{align*} M_X(t) = \mathrm{E}[e^{tX}] &= \int_{x=0}^\infty \frac{\beta^\alpha x^{\alpha-1} e^{-\beta x + tx}}{\Gamma(\alpha)} \, dx \\ &= \frac{\beta^\alpha}{(\beta-t)^\alpha} \int_{x=0}^\infty \frac{(\beta-t)^\alpha x^{\alpha-1} e^{-(\beta-t)x}}{\Gamma(\alpha)} \, dx \\ &= \biggl(\frac{\beta}{\beta-t}\biggr)^{\!\alpha}, \quad t < \beta, \end{align*}$$ where the condition on $t$ is required for the integral to converge. We may rewrite this as $$M_X(t) = (1 - t/\beta)^{-\alpha},$$ and it follows that $$\mathrm{E}[X^k] = \left[ \frac{d^k M_X(t)}{dt^k} \right]_{t=0} = \left[(1-t/\beta)^{-\alpha-k}\right]_{t=0} \prod_{j=0}^{k-1} \frac{\alpha+j}{\beta} = \frac{\Gamma(\alpha+k)}{\beta^k \Gamma(\alpha)}.$$
Expectation of a squared Gamma
For the sake of completeness, I will directly compute the raw moments from the density. First, under a shape/rate parametrization, the gamma distribution has density $$f_X(x) = \frac{\beta^\alpha x^{
Expectation of a squared Gamma For the sake of completeness, I will directly compute the raw moments from the density. First, under a shape/rate parametrization, the gamma distribution has density $$f_X(x) = \frac{\beta^\alpha x^{\alpha-1} e^{-\beta x}}{\Gamma(\alpha)}, \quad x > 0.$$ We will take for granted that for any choice of parameters $\alpha, \beta > 0$, we have $$\int_{x=0}^\infty f_X(x) \, dx = 1,$$ although this result is easily derived from the identity $$\int_{z=0}^\infty x^{z-1} e^{-z} \, dz = \Gamma(z).$$ Then it follows that for a positive integer $k$, $$\begin{align*} \mathrm{E}[X^k] &= \int_{x=0}^\infty x^k f_X(x) \, dx \\ &= \frac{1}{\Gamma(\alpha)} \int_{x=0}^\infty \beta^\alpha x^{\alpha+k-1} e^{-\beta x} \, dx \\ &= \frac{\Gamma(\alpha+k)}{\beta^k \Gamma(\alpha)} \int_{x=0}^\infty \frac{\beta^{\alpha+k} x^{\alpha+k-1} e^{-\beta x}}{\Gamma(\alpha+k)} \, dx \\ &= \frac{\Gamma(\alpha+k)}{\beta^k \Gamma(\alpha)}, \end{align*}$$ where in the penultimate step we observe that the integral equals $1$ because it is the integral of a gamma density with parameters $\alpha+k$ and $\beta$. For $k = 2$, we immediately obtain $\mathrm{E}[X^2] = \frac{\Gamma(\alpha+2)}{\beta^2 \Gamma(\alpha)} = \frac{(\alpha+1)\alpha}{\beta^2}.$ Another approach is via the moment generating function: $$\begin{align*} M_X(t) = \mathrm{E}[e^{tX}] &= \int_{x=0}^\infty \frac{\beta^\alpha x^{\alpha-1} e^{-\beta x + tx}}{\Gamma(\alpha)} \, dx \\ &= \frac{\beta^\alpha}{(\beta-t)^\alpha} \int_{x=0}^\infty \frac{(\beta-t)^\alpha x^{\alpha-1} e^{-(\beta-t)x}}{\Gamma(\alpha)} \, dx \\ &= \biggl(\frac{\beta}{\beta-t}\biggr)^{\!\alpha}, \quad t < \beta, \end{align*}$$ where the condition on $t$ is required for the integral to converge. We may rewrite this as $$M_X(t) = (1 - t/\beta)^{-\alpha},$$ and it follows that $$\mathrm{E}[X^k] = \left[ \frac{d^k M_X(t)}{dt^k} \right]_{t=0} = \left[(1-t/\beta)^{-\alpha-k}\right]_{t=0} \prod_{j=0}^{k-1} \frac{\alpha+j}{\beta} = \frac{\Gamma(\alpha+k)}{\beta^k \Gamma(\alpha)}.$$
Expectation of a squared Gamma For the sake of completeness, I will directly compute the raw moments from the density. First, under a shape/rate parametrization, the gamma distribution has density $$f_X(x) = \frac{\beta^\alpha x^{
25,105
Which bootstrapped regression model should I choose?
Bootstrapping is a resampling method to estimate the sampling distribution of your regression coefficients and therefore calculate the standard errors/confidence intervals of your regression coefficients. This post has a nice explanation. For a discussion of how many replications you need, see this post. The nonparametric bootstrap resamples repeatedly and randomly draws your observations with replacement (i.e. some observations are drawn only once, others multiple times and some never at all), then calculates the logistic regression and stores the coefficients. This is repeated $n$ times. So you'll end up with 10'000 different regression coefficients. These 10'000 coefficients can then be used to calculate their confidence itnervals. As a pseudo-random number generator is used, you could just set the seed to an arbitrary number to ensure that you have exactly the same results each time (see example below). To really have stable estimates, I would suggest more than 1000 replications, maybe 10'000. You could run the bootstrap several times and see if the estimates change much whether you do 1000 or 10'000 replications. In plain english: you should take replications until you reach convergence. If your bootstrap estimates vary between your estimates and the observed, single model, this could indicate that the observed model does not appropriately reflect the structure of your sample. The function boot in R, for example, puts out the "bias" which is the difference between the regression coefficients of your single model and the mean of the bootstrap samples. When performing the bootstrap, you are not interested in a single bootstrap sample, but in the distribution of statistics (e.g. regression coefficients) over the, say, 10'000 bootstrap samples. I'd say 10'000 is better than 1000. With modern Computers, this shouldn't pose a problem. In the example below, it took my PC around 45 seconds to draw 10'000 samples. This varies with your sample size of course. The bigger your sample size, the higher the number of iterations should be to ensure that every observation is taken into account. What do you mean "the results vary each time"? Recall that in every bootstrap step, the observations are newly drawn with replacement. Therefore, you're likely to end up with slightly different regression coefficients because your observations differ. But as I've said: you are not really interested in the result of a single bootstrap sample. When your number of replications is high enough, the bootstrap should yield very similar confidence intervals and point estimates every time. Here is an example in R: library(boot) mydata <- read.csv("http://www.ats.ucla.edu/stat/data/binary.csv") head(mydata) mydata$rank <- factor(mydata$rank) my.mod <- glm(admit ~ gre + gpa + rank, data = mydata, family = "binomial") summary(my.mod) Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) -3.989979 1.139951 -3.500 0.000465 *** gre 0.002264 0.001094 2.070 0.038465 * gpa 0.804038 0.331819 2.423 0.015388 * rank2 -0.675443 0.316490 -2.134 0.032829 * rank3 -1.340204 0.345306 -3.881 0.000104 *** rank4 -1.551464 0.417832 -3.713 0.000205 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # Set up the non-parametric bootstrap logit.bootstrap <- function(data, indices) { d <- data[indices, ] fit <- glm(admit ~ gre + gpa + rank, data = d, family = "binomial") return(coef(fit)) } set.seed(12345) # seed for the RNG to ensure that you get exactly the same results as here logit.boot <- boot(data=mydata, statistic=logit.bootstrap, R=10000) # 10'000 samples logit.boot Bootstrap Statistics : original bias std. error t1* -3.989979073 -7.217244e-02 1.165573039 t2* 0.002264426 4.054579e-05 0.001146039 t3* 0.804037549 1.440693e-02 0.354361032 t4* -0.675442928 -8.845389e-03 0.329099277 t5* -1.340203916 -1.977054e-02 0.359502576 t6* -1.551463677 -4.720579e-02 0.444998099 # Calculate confidence intervals (Bias corrected ="bca") for each coefficient boot.ci(logit.boot, type="bca", index=1) # intercept 95% (-6.292, -1.738 ) boot.ci(logit.boot, type="bca", index=2) # gre 95% ( 0.0000, 0.0045 ) boot.ci(logit.boot, type="bca", index=3) # gpa 95% ( 0.1017, 1.4932 ) boot.ci(logit.boot, type="bca", index=4) # rank2 95% (-1.3170, -0.0369 ) boot.ci(logit.boot, type="bca", index=5) # rank3 95% (-2.040, -0.629 ) boot.ci(logit.boot, type="bca", index=6) # rank4 95% (-2.425, -0.698 ) The bootstrap-ouput displays the original regression coefficients ("original") and their bias, which is the difference between the original coefficients and the bootstrapped ones. It also gives the standard errors. Note that they are bit larger than the original standard errors. From the confidence intervals, the bias-corrected ("bca") are usually preferred. It gives the confidence intervals on the original scale. For confidence intervals for the odds ratios, just exponentiate the confidence limits.
Which bootstrapped regression model should I choose?
Bootstrapping is a resampling method to estimate the sampling distribution of your regression coefficients and therefore calculate the standard errors/confidence intervals of your regression coefficie
Which bootstrapped regression model should I choose? Bootstrapping is a resampling method to estimate the sampling distribution of your regression coefficients and therefore calculate the standard errors/confidence intervals of your regression coefficients. This post has a nice explanation. For a discussion of how many replications you need, see this post. The nonparametric bootstrap resamples repeatedly and randomly draws your observations with replacement (i.e. some observations are drawn only once, others multiple times and some never at all), then calculates the logistic regression and stores the coefficients. This is repeated $n$ times. So you'll end up with 10'000 different regression coefficients. These 10'000 coefficients can then be used to calculate their confidence itnervals. As a pseudo-random number generator is used, you could just set the seed to an arbitrary number to ensure that you have exactly the same results each time (see example below). To really have stable estimates, I would suggest more than 1000 replications, maybe 10'000. You could run the bootstrap several times and see if the estimates change much whether you do 1000 or 10'000 replications. In plain english: you should take replications until you reach convergence. If your bootstrap estimates vary between your estimates and the observed, single model, this could indicate that the observed model does not appropriately reflect the structure of your sample. The function boot in R, for example, puts out the "bias" which is the difference between the regression coefficients of your single model and the mean of the bootstrap samples. When performing the bootstrap, you are not interested in a single bootstrap sample, but in the distribution of statistics (e.g. regression coefficients) over the, say, 10'000 bootstrap samples. I'd say 10'000 is better than 1000. With modern Computers, this shouldn't pose a problem. In the example below, it took my PC around 45 seconds to draw 10'000 samples. This varies with your sample size of course. The bigger your sample size, the higher the number of iterations should be to ensure that every observation is taken into account. What do you mean "the results vary each time"? Recall that in every bootstrap step, the observations are newly drawn with replacement. Therefore, you're likely to end up with slightly different regression coefficients because your observations differ. But as I've said: you are not really interested in the result of a single bootstrap sample. When your number of replications is high enough, the bootstrap should yield very similar confidence intervals and point estimates every time. Here is an example in R: library(boot) mydata <- read.csv("http://www.ats.ucla.edu/stat/data/binary.csv") head(mydata) mydata$rank <- factor(mydata$rank) my.mod <- glm(admit ~ gre + gpa + rank, data = mydata, family = "binomial") summary(my.mod) Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) -3.989979 1.139951 -3.500 0.000465 *** gre 0.002264 0.001094 2.070 0.038465 * gpa 0.804038 0.331819 2.423 0.015388 * rank2 -0.675443 0.316490 -2.134 0.032829 * rank3 -1.340204 0.345306 -3.881 0.000104 *** rank4 -1.551464 0.417832 -3.713 0.000205 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # Set up the non-parametric bootstrap logit.bootstrap <- function(data, indices) { d <- data[indices, ] fit <- glm(admit ~ gre + gpa + rank, data = d, family = "binomial") return(coef(fit)) } set.seed(12345) # seed for the RNG to ensure that you get exactly the same results as here logit.boot <- boot(data=mydata, statistic=logit.bootstrap, R=10000) # 10'000 samples logit.boot Bootstrap Statistics : original bias std. error t1* -3.989979073 -7.217244e-02 1.165573039 t2* 0.002264426 4.054579e-05 0.001146039 t3* 0.804037549 1.440693e-02 0.354361032 t4* -0.675442928 -8.845389e-03 0.329099277 t5* -1.340203916 -1.977054e-02 0.359502576 t6* -1.551463677 -4.720579e-02 0.444998099 # Calculate confidence intervals (Bias corrected ="bca") for each coefficient boot.ci(logit.boot, type="bca", index=1) # intercept 95% (-6.292, -1.738 ) boot.ci(logit.boot, type="bca", index=2) # gre 95% ( 0.0000, 0.0045 ) boot.ci(logit.boot, type="bca", index=3) # gpa 95% ( 0.1017, 1.4932 ) boot.ci(logit.boot, type="bca", index=4) # rank2 95% (-1.3170, -0.0369 ) boot.ci(logit.boot, type="bca", index=5) # rank3 95% (-2.040, -0.629 ) boot.ci(logit.boot, type="bca", index=6) # rank4 95% (-2.425, -0.698 ) The bootstrap-ouput displays the original regression coefficients ("original") and their bias, which is the difference between the original coefficients and the bootstrapped ones. It also gives the standard errors. Note that they are bit larger than the original standard errors. From the confidence intervals, the bias-corrected ("bca") are usually preferred. It gives the confidence intervals on the original scale. For confidence intervals for the odds ratios, just exponentiate the confidence limits.
Which bootstrapped regression model should I choose? Bootstrapping is a resampling method to estimate the sampling distribution of your regression coefficients and therefore calculate the standard errors/confidence intervals of your regression coefficie
25,106
Zero-inflated count models in R: what is the real advantage?
I think this is a poorly chosen data set for exploring the advantages of zero inflated models, because, as you note, there isn't that much zero inflation. plot(fitted(fm_pois), fitted(fm_zinb)) shows that the predicted values are almost identical. In data sets with more zero-inflation, the ZI models give different (and usually better fitting) results than Poisson. Another way to compare the fit of the models is to compare the size of residuals: boxplot(abs(resid(fm_pois) - resid(fm_zinb))) shows that, even here, the residuals from the Poisson are smaller than those from the ZINB. If you have some idea of a magnitude of the residual that is really problematic, you can see what proportion of the residuals in each model are above that. E.g. if being off by more than 1 was unacceptable sum(abs(resid(fm_pois) > 1)) sum(abs(resid(fm_zinb) > 1)) shows the latter is a bit better - 20 fewer large residuals. Then the question is whether the added complexity of the models is worth it to you.
Zero-inflated count models in R: what is the real advantage?
I think this is a poorly chosen data set for exploring the advantages of zero inflated models, because, as you note, there isn't that much zero inflation. plot(fitted(fm_pois), fitted(fm_zinb)) show
Zero-inflated count models in R: what is the real advantage? I think this is a poorly chosen data set for exploring the advantages of zero inflated models, because, as you note, there isn't that much zero inflation. plot(fitted(fm_pois), fitted(fm_zinb)) shows that the predicted values are almost identical. In data sets with more zero-inflation, the ZI models give different (and usually better fitting) results than Poisson. Another way to compare the fit of the models is to compare the size of residuals: boxplot(abs(resid(fm_pois) - resid(fm_zinb))) shows that, even here, the residuals from the Poisson are smaller than those from the ZINB. If you have some idea of a magnitude of the residual that is really problematic, you can see what proportion of the residuals in each model are above that. E.g. if being off by more than 1 was unacceptable sum(abs(resid(fm_pois) > 1)) sum(abs(resid(fm_zinb) > 1)) shows the latter is a bit better - 20 fewer large residuals. Then the question is whether the added complexity of the models is worth it to you.
Zero-inflated count models in R: what is the real advantage? I think this is a poorly chosen data set for exploring the advantages of zero inflated models, because, as you note, there isn't that much zero inflation. plot(fitted(fm_pois), fitted(fm_zinb)) show
25,107
Zero-inflated count models in R: what is the real advantage?
The fitted values will show less dispersion than the observed values because of random variation. You're not making a meaningful comparison. To take a simple case, if your data were just $X_i\sim\mathrm{Pois(\mu)}$ you wouldn't compare a histogram of $x_i$ against a histogram of the fitted value $\hat{\mu}$ - the same for all $i$ ! Though it would be reasonable to simulate values of $x^*_i$ from $X^*_i\sim\mathrm{Pois(\hat{\mu})}$ & compare histograms of $x_i^*$ & $x_i$.
Zero-inflated count models in R: what is the real advantage?
The fitted values will show less dispersion than the observed values because of random variation. You're not making a meaningful comparison. To take a simple case, if your data were just $X_i\sim\math
Zero-inflated count models in R: what is the real advantage? The fitted values will show less dispersion than the observed values because of random variation. You're not making a meaningful comparison. To take a simple case, if your data were just $X_i\sim\mathrm{Pois(\mu)}$ you wouldn't compare a histogram of $x_i$ against a histogram of the fitted value $\hat{\mu}$ - the same for all $i$ ! Though it would be reasonable to simulate values of $x^*_i$ from $X^*_i\sim\mathrm{Pois(\hat{\mu})}$ & compare histograms of $x_i^*$ & $x_i$.
Zero-inflated count models in R: what is the real advantage? The fitted values will show less dispersion than the observed values because of random variation. You're not making a meaningful comparison. To take a simple case, if your data were just $X_i\sim\math
25,108
Classes of distributions closed under maximum
It seems to me that proposing extreme value distributions really answers a different question. I will demonstrate that by addressing this question directly and showing it leads to distributions that are not among the extreme value types. Let's consider this from first principles. It is immediate, from the axioms of probability and definition of the CDF, that the distribution of the maximum of two independent random variables with CDFs $F_1$ and $F_2$ has $F_1 F_2$ for its CDF. Suppose a class of distributions $\Omega = \{F_{\theta}\}$ exists that is closed under pairwise maximum; that is, $$F_\theta \in \Omega, \ F_\phi \in \Omega \text{ implies } F_\theta F_\phi \in \Omega.$$ It is convenient to take logarithms, extending (as in Rudin's advanced analysis texts) the real numbers to include $-\infty$ as the log of $0$. Logs of CDFs of random variables essentially supported on $[0,\infty)$ are (i) mononotically nonincreasing, (ii) equal to $-\infty$ on $(-\infty,0)$, (iii) have right limits of $0$, and (iv) are cadlag. From this point of view, $\Omega$ must be a convex subset of a cone within the space of cadlag functions on $\mathbb{R}$. For it to be finitely parameterized, that cone must generate a finite-dimensional vector subspace. That still leaves a lot of possibilities. Some of these possibilities are well known. Consider, for example, the CDF of a uniform variable on $[0,1]$. Its CDF equals $0$ on $(-\infty,0]$, $x$ when $0 \le x \le 1$, and $1$ on $[1,\infty)$. The cone it generates is the set of CDFs of the form $$F_\theta(x) = \exp(\theta \log(x)) = x^\theta,\quad 0 \lt x \lt 1$$ parameterized by $\theta \gt 0$. Clearly the maximum of any two independent random variables with distributions in this family has a distribution also in this family (their parameters simply add). We may, if we wish, restrict to a convex subset of the form $\{F_\theta | \theta \ge \theta_0\}$ and still have a maximum-closed family. Notice, please, that no member of this family is an extreme-value distribution. This formulation includes discrete distributions (which obviously are not among the three types of extreme value distributions). For instance, consider the distributions supported on the natural numbers $0, 1, 2, \ldots, k, \ldots$ for which the probabilities are given by $${\Pr}_\theta(k) = \theta^{1/(k+1)} - \theta^{1/k}$$ (taking $\theta^{1/k}=0$ when $k=0$), parameterized by $0 \lt \theta \lt 1$. By construction, the CDF $F_\theta(k) = \theta^{1/(k+1)}$, whence it follows $$F_\theta(k) F_\phi(k) = \theta^{1/(k+1)}\phi^{1/(k+1)} = (\theta\phi)^{1/(k+1)},$$ and because the assumptions imply $0 \lt \theta\phi \lt 1$, this shows the family is closed under pairwise maxima. I hope that this analysis and these two examples show that, contrary to an opinion expressed in a comment, the approach of starting with a finite number of well-chosen CDFs and closing them with respect to the pairwise maximum (that is, forming their cones in an appropriate related vector space) not only is constructive but yields interesting and potentially useful classes of distributions.
Classes of distributions closed under maximum
It seems to me that proposing extreme value distributions really answers a different question. I will demonstrate that by addressing this question directly and showing it leads to distributions that
Classes of distributions closed under maximum It seems to me that proposing extreme value distributions really answers a different question. I will demonstrate that by addressing this question directly and showing it leads to distributions that are not among the extreme value types. Let's consider this from first principles. It is immediate, from the axioms of probability and definition of the CDF, that the distribution of the maximum of two independent random variables with CDFs $F_1$ and $F_2$ has $F_1 F_2$ for its CDF. Suppose a class of distributions $\Omega = \{F_{\theta}\}$ exists that is closed under pairwise maximum; that is, $$F_\theta \in \Omega, \ F_\phi \in \Omega \text{ implies } F_\theta F_\phi \in \Omega.$$ It is convenient to take logarithms, extending (as in Rudin's advanced analysis texts) the real numbers to include $-\infty$ as the log of $0$. Logs of CDFs of random variables essentially supported on $[0,\infty)$ are (i) mononotically nonincreasing, (ii) equal to $-\infty$ on $(-\infty,0)$, (iii) have right limits of $0$, and (iv) are cadlag. From this point of view, $\Omega$ must be a convex subset of a cone within the space of cadlag functions on $\mathbb{R}$. For it to be finitely parameterized, that cone must generate a finite-dimensional vector subspace. That still leaves a lot of possibilities. Some of these possibilities are well known. Consider, for example, the CDF of a uniform variable on $[0,1]$. Its CDF equals $0$ on $(-\infty,0]$, $x$ when $0 \le x \le 1$, and $1$ on $[1,\infty)$. The cone it generates is the set of CDFs of the form $$F_\theta(x) = \exp(\theta \log(x)) = x^\theta,\quad 0 \lt x \lt 1$$ parameterized by $\theta \gt 0$. Clearly the maximum of any two independent random variables with distributions in this family has a distribution also in this family (their parameters simply add). We may, if we wish, restrict to a convex subset of the form $\{F_\theta | \theta \ge \theta_0\}$ and still have a maximum-closed family. Notice, please, that no member of this family is an extreme-value distribution. This formulation includes discrete distributions (which obviously are not among the three types of extreme value distributions). For instance, consider the distributions supported on the natural numbers $0, 1, 2, \ldots, k, \ldots$ for which the probabilities are given by $${\Pr}_\theta(k) = \theta^{1/(k+1)} - \theta^{1/k}$$ (taking $\theta^{1/k}=0$ when $k=0$), parameterized by $0 \lt \theta \lt 1$. By construction, the CDF $F_\theta(k) = \theta^{1/(k+1)}$, whence it follows $$F_\theta(k) F_\phi(k) = \theta^{1/(k+1)}\phi^{1/(k+1)} = (\theta\phi)^{1/(k+1)},$$ and because the assumptions imply $0 \lt \theta\phi \lt 1$, this shows the family is closed under pairwise maxima. I hope that this analysis and these two examples show that, contrary to an opinion expressed in a comment, the approach of starting with a finite number of well-chosen CDFs and closing them with respect to the pairwise maximum (that is, forming their cones in an appropriate related vector space) not only is constructive but yields interesting and potentially useful classes of distributions.
Classes of distributions closed under maximum It seems to me that proposing extreme value distributions really answers a different question. I will demonstrate that by addressing this question directly and showing it leads to distributions that
25,109
Classes of distributions closed under maximum
Note: This answer assumes the variables are identically distributed, not just distributed according to the same class. Those would be the extreme value distributions. There are three of them, as they are usually presented, corresponding to three sets of conditions on the underlying distribution for which the limiting distribution of the maximum is being found. They are closed under finding the maximum, which is what you want. More-or-less copying from an old version of Methods of Statistical Analysis for Reliability and Life Data (Mann, Schafer, Singpurwalla), Type I: $F_{X(n)}(x) = \exp\left\{-\exp \left[-\frac{x-\gamma}{\alpha}\right] \right\},\space -\infty < x < \infty, \space \alpha > 0$ Type II: $F_{X(n)}(x) = \exp\left\{-\left(\frac{x-\gamma}{\alpha}\right)^{-\beta}\right\}, \space x \geq \gamma, \space \alpha,\beta > 0$ Type III: $F_{X(n)}(x) = \exp\left\{-\left[-\left(\frac{x-\gamma}{\alpha}\right)^\beta\right]\right\}. \space x \leq \gamma, \space \alpha,\beta > 0$ Edit: Read the comments, which extend this answer to make a greatly improved and more complete answer to this question!
Classes of distributions closed under maximum
Note: This answer assumes the variables are identically distributed, not just distributed according to the same class. Those would be the extreme value distributions. There are three of them, as they
Classes of distributions closed under maximum Note: This answer assumes the variables are identically distributed, not just distributed according to the same class. Those would be the extreme value distributions. There are three of them, as they are usually presented, corresponding to three sets of conditions on the underlying distribution for which the limiting distribution of the maximum is being found. They are closed under finding the maximum, which is what you want. More-or-less copying from an old version of Methods of Statistical Analysis for Reliability and Life Data (Mann, Schafer, Singpurwalla), Type I: $F_{X(n)}(x) = \exp\left\{-\exp \left[-\frac{x-\gamma}{\alpha}\right] \right\},\space -\infty < x < \infty, \space \alpha > 0$ Type II: $F_{X(n)}(x) = \exp\left\{-\left(\frac{x-\gamma}{\alpha}\right)^{-\beta}\right\}, \space x \geq \gamma, \space \alpha,\beta > 0$ Type III: $F_{X(n)}(x) = \exp\left\{-\left[-\left(\frac{x-\gamma}{\alpha}\right)^\beta\right]\right\}. \space x \leq \gamma, \space \alpha,\beta > 0$ Edit: Read the comments, which extend this answer to make a greatly improved and more complete answer to this question!
Classes of distributions closed under maximum Note: This answer assumes the variables are identically distributed, not just distributed according to the same class. Those would be the extreme value distributions. There are three of them, as they
25,110
Classes of distributions closed under maximum
jbowman beat me to the answer. A explanation for why they work is that Gnedenko's Theorem states that if $X_1,\dotsc,X_n$ is a sequence of $n$ independent identically distributed random variables $M_n=\max(X_1, X_2,\dotsc,X_n)$ under certain conditions on the tail of the distribution converges to 1 of the three type that jbowman listed in his answer. Now since any type I, type II or type III distribution can be expressed as the limit of the max of an iid sequence then if $G_1$ is say type I and is the limit distribution of $M_n=\max(X_1, X_2,\dotsc,X_n)$ as $n$ tends to infinity and $G_2$ is also type I and is the limit of $N_n=\max(Y_1,Y_2,dotsc,Y_n)$ then say $V_n=\max(M_n,N_n)$ and $G_3$ is the distribution of the limit as $n$ approaches infinity for $V_n$ then $G_3$ will be type I and be the distribution for the maximum of a rv with distribution $G_1$ and another with distribution $G_2$ and hence type I is closed under maximization. The same argument works for type II and type III.
Classes of distributions closed under maximum
jbowman beat me to the answer. A explanation for why they work is that Gnedenko's Theorem states that if $X_1,\dotsc,X_n$ is a sequence of $n$ independent identically distributed random variables $M_
Classes of distributions closed under maximum jbowman beat me to the answer. A explanation for why they work is that Gnedenko's Theorem states that if $X_1,\dotsc,X_n$ is a sequence of $n$ independent identically distributed random variables $M_n=\max(X_1, X_2,\dotsc,X_n)$ under certain conditions on the tail of the distribution converges to 1 of the three type that jbowman listed in his answer. Now since any type I, type II or type III distribution can be expressed as the limit of the max of an iid sequence then if $G_1$ is say type I and is the limit distribution of $M_n=\max(X_1, X_2,\dotsc,X_n)$ as $n$ tends to infinity and $G_2$ is also type I and is the limit of $N_n=\max(Y_1,Y_2,dotsc,Y_n)$ then say $V_n=\max(M_n,N_n)$ and $G_3$ is the distribution of the limit as $n$ approaches infinity for $V_n$ then $G_3$ will be type I and be the distribution for the maximum of a rv with distribution $G_1$ and another with distribution $G_2$ and hence type I is closed under maximization. The same argument works for type II and type III.
Classes of distributions closed under maximum jbowman beat me to the answer. A explanation for why they work is that Gnedenko's Theorem states that if $X_1,\dotsc,X_n$ is a sequence of $n$ independent identically distributed random variables $M_
25,111
How to fit a regression like $y=\lfloor ax+b \rfloor$ in R?
You could fit the model you state using the nls (non-linear least squares) function in R, but as you said that will violate many of the assumptions and still probably will not make much sense (you are saying the predicted outcome is random around a step function, not integer values around a smoothly increasing relationship). The more common way to fit count data is using Poisson regression using the glm function in R, the first example on the help page is a Poisson regression, though if you are not that familiar with statistics it would be best to consult with a statistician to make sure that you are doing things correctly. If the value of 8 is an absolute maximum (impossible to ever see a higher count, not just that is what you saw) then you might consider proportional odds logistic regression, there are a couple of tools to do this in packages for R, but you really should get a statistician involved if you want to do this.
How to fit a regression like $y=\lfloor ax+b \rfloor$ in R?
You could fit the model you state using the nls (non-linear least squares) function in R, but as you said that will violate many of the assumptions and still probably will not make much sense (you are
How to fit a regression like $y=\lfloor ax+b \rfloor$ in R? You could fit the model you state using the nls (non-linear least squares) function in R, but as you said that will violate many of the assumptions and still probably will not make much sense (you are saying the predicted outcome is random around a step function, not integer values around a smoothly increasing relationship). The more common way to fit count data is using Poisson regression using the glm function in R, the first example on the help page is a Poisson regression, though if you are not that familiar with statistics it would be best to consult with a statistician to make sure that you are doing things correctly. If the value of 8 is an absolute maximum (impossible to ever see a higher count, not just that is what you saw) then you might consider proportional odds logistic regression, there are a couple of tools to do this in packages for R, but you really should get a statistician involved if you want to do this.
How to fit a regression like $y=\lfloor ax+b \rfloor$ in R? You could fit the model you state using the nls (non-linear least squares) function in R, but as you said that will violate many of the assumptions and still probably will not make much sense (you are
25,112
How to fit a regression like $y=\lfloor ax+b \rfloor$ in R?
$\def\lf{\lfloor}\def\rf{\rfloor}\def\pnorm{\mathrm{pnorm}}$It is plain that Greg’s suggestion is the first thing to try: Poisson regression is the natural model in many many concrete situations. However the model you’re suggesting can occur for example when you observe rounded data: $$ Y_i = \lf ax_i + b + \epsilon_i \rf,$$ with iid normal errors $\epsilon_i$. I think this is interesting to have a look on what can be done with it. I denote by $F$ the cdf of the standard normal variable. If $\epsilon \sim \mathcal N(0,\sigma^2)$, then $$\begin{align*} \mathbb P\left(\lf ax + b + \epsilon \rf = k\right) &= F\left({k-b+1-ax\over \sigma}\right) - F\left({k-b-ax\over \sigma}\right)\\ &= \pnorm(k+1-ax-b,sd=\sigma) - \pnorm(k-ax-b,sd=\sigma),\end{align*}$$ using familiar computer notations. You observe data points $(x_i,y_i)$. The log likelihood is given by $$\ell(a,b,\sigma) = \sum_i \log\left( F\left({y_i-b+1-ax_i\over \sigma}\right) - F\left({y_i-b-ax_i\over \sigma}\right) \right).$$ This is not identical to least squares. You can try to maximize this with a numerical method. Here is an illustration in R: log_lik <- function(a,b,s,x,y) sum(log(pnorm(y+1-a*x-b, sd=s) - pnorm(y-a*x-b, sd=s))); x <- 0:20 y <- floor(x+3+rnorm(length(x), sd=3)) plot(x,y, pch=19) optim(c(1,1,1), function(p) -log_lik(p[1], p[2], p[3], x, y)) -> r abline(r$par[2], r$par[1], lty=2, col="red") t <- seq(0,20,by=0.01) lines(t, floor( r$par[1]*t+r$par[2]), col="green") lm(y~x) -> r1 abline(r1, lty=2, col="blue"); In red and blue, the lines $ax+b$ found by numerical maximization of this likelihood, and least squares, respectively. The green staircase is $\lf ax +b\rf$ for $a,b$ found from the max likelihood... this suggest that you could use least squares, up to a translation of $b$ by 0.5, and get roughly the same result; or, that least squares fit well the model $$ Y_i = [ a x_i + b +\epsilon_i], $$ where $[x] = \lf x + 0.5 \rf$ is the nearest integer. Rounded data are so often met that I am sure this is known and had been studied extensively...
How to fit a regression like $y=\lfloor ax+b \rfloor$ in R?
$\def\lf{\lfloor}\def\rf{\rfloor}\def\pnorm{\mathrm{pnorm}}$It is plain that Greg’s suggestion is the first thing to try: Poisson regression is the natural model in many many concrete situations. Howe
How to fit a regression like $y=\lfloor ax+b \rfloor$ in R? $\def\lf{\lfloor}\def\rf{\rfloor}\def\pnorm{\mathrm{pnorm}}$It is plain that Greg’s suggestion is the first thing to try: Poisson regression is the natural model in many many concrete situations. However the model you’re suggesting can occur for example when you observe rounded data: $$ Y_i = \lf ax_i + b + \epsilon_i \rf,$$ with iid normal errors $\epsilon_i$. I think this is interesting to have a look on what can be done with it. I denote by $F$ the cdf of the standard normal variable. If $\epsilon \sim \mathcal N(0,\sigma^2)$, then $$\begin{align*} \mathbb P\left(\lf ax + b + \epsilon \rf = k\right) &= F\left({k-b+1-ax\over \sigma}\right) - F\left({k-b-ax\over \sigma}\right)\\ &= \pnorm(k+1-ax-b,sd=\sigma) - \pnorm(k-ax-b,sd=\sigma),\end{align*}$$ using familiar computer notations. You observe data points $(x_i,y_i)$. The log likelihood is given by $$\ell(a,b,\sigma) = \sum_i \log\left( F\left({y_i-b+1-ax_i\over \sigma}\right) - F\left({y_i-b-ax_i\over \sigma}\right) \right).$$ This is not identical to least squares. You can try to maximize this with a numerical method. Here is an illustration in R: log_lik <- function(a,b,s,x,y) sum(log(pnorm(y+1-a*x-b, sd=s) - pnorm(y-a*x-b, sd=s))); x <- 0:20 y <- floor(x+3+rnorm(length(x), sd=3)) plot(x,y, pch=19) optim(c(1,1,1), function(p) -log_lik(p[1], p[2], p[3], x, y)) -> r abline(r$par[2], r$par[1], lty=2, col="red") t <- seq(0,20,by=0.01) lines(t, floor( r$par[1]*t+r$par[2]), col="green") lm(y~x) -> r1 abline(r1, lty=2, col="blue"); In red and blue, the lines $ax+b$ found by numerical maximization of this likelihood, and least squares, respectively. The green staircase is $\lf ax +b\rf$ for $a,b$ found from the max likelihood... this suggest that you could use least squares, up to a translation of $b$ by 0.5, and get roughly the same result; or, that least squares fit well the model $$ Y_i = [ a x_i + b +\epsilon_i], $$ where $[x] = \lf x + 0.5 \rf$ is the nearest integer. Rounded data are so often met that I am sure this is known and had been studied extensively...
How to fit a regression like $y=\lfloor ax+b \rfloor$ in R? $\def\lf{\lfloor}\def\rf{\rfloor}\def\pnorm{\mathrm{pnorm}}$It is plain that Greg’s suggestion is the first thing to try: Poisson regression is the natural model in many many concrete situations. Howe
25,113
How to compare two datasets with Q-Q plot using ggplot2?
The easiest thing to do is just look at how qqplot works. So in R type: R> qqplot function (x, y, plot.it = TRUE, xlab = deparse(substitute(x)), ylab = deparse(substitute(y)), ...) { sx <- sort(x) sy <- sort(y) lenx <- length(sx) leny <- length(sy) if (leny < lenx) sx <- approx(1L:lenx, sx, n = leny)$y if (leny > lenx) sy <- approx(1L:leny, sy, n = lenx)$y if (plot.it) plot(sx, sy, xlab = xlab, ylab = ylab, ...) invisible(list(x = sx, y = sy)) } <environment: namespace:stats> So to generate the plot we just have to get sx and sy, i.e: x <- rnorm(10);y <- rnorm(20) sx <- sort(x); sy <- sort(y) lenx <- length(sx) leny <- length(sy) if (leny < lenx)sx <- approx(1L:lenx, sx, n = leny)$y if (leny > lenx)sy <- approx(1L:leny, sy, n = lenx)$y require(ggplot2) g = ggplot() + geom_point(aes(x=sx, y=sy)) g
How to compare two datasets with Q-Q plot using ggplot2?
The easiest thing to do is just look at how qqplot works. So in R type: R> qqplot function (x, y, plot.it = TRUE, xlab = deparse(substitute(x)), ylab = deparse(substitute(y)), ...) { sx <- s
How to compare two datasets with Q-Q plot using ggplot2? The easiest thing to do is just look at how qqplot works. So in R type: R> qqplot function (x, y, plot.it = TRUE, xlab = deparse(substitute(x)), ylab = deparse(substitute(y)), ...) { sx <- sort(x) sy <- sort(y) lenx <- length(sx) leny <- length(sy) if (leny < lenx) sx <- approx(1L:lenx, sx, n = leny)$y if (leny > lenx) sy <- approx(1L:leny, sy, n = lenx)$y if (plot.it) plot(sx, sy, xlab = xlab, ylab = ylab, ...) invisible(list(x = sx, y = sy)) } <environment: namespace:stats> So to generate the plot we just have to get sx and sy, i.e: x <- rnorm(10);y <- rnorm(20) sx <- sort(x); sy <- sort(y) lenx <- length(sx) leny <- length(sy) if (leny < lenx)sx <- approx(1L:lenx, sx, n = leny)$y if (leny > lenx)sy <- approx(1L:leny, sy, n = lenx)$y require(ggplot2) g = ggplot() + geom_point(aes(x=sx, y=sy)) g
How to compare two datasets with Q-Q plot using ggplot2? The easiest thing to do is just look at how qqplot works. So in R type: R> qqplot function (x, y, plot.it = TRUE, xlab = deparse(substitute(x)), ylab = deparse(substitute(y)), ...) { sx <- s
25,114
How to compare two datasets with Q-Q plot using ggplot2?
I use this when I also want a normal line. ggplot(data, aes(sample = data$column1)) + stat_qq(color="firebrick2", alpha=1) + geom_abline(intercept = mean(data$column1), slope = sd(data$column1))
How to compare two datasets with Q-Q plot using ggplot2?
I use this when I also want a normal line. ggplot(data, aes(sample = data$column1)) + stat_qq(color="firebrick2", alpha=1) + geom_abline(intercept = mean(data$column1), slope = sd(data$column1))
How to compare two datasets with Q-Q plot using ggplot2? I use this when I also want a normal line. ggplot(data, aes(sample = data$column1)) + stat_qq(color="firebrick2", alpha=1) + geom_abline(intercept = mean(data$column1), slope = sd(data$column1))
How to compare two datasets with Q-Q plot using ggplot2? I use this when I also want a normal line. ggplot(data, aes(sample = data$column1)) + stat_qq(color="firebrick2", alpha=1) + geom_abline(intercept = mean(data$column1), slope = sd(data$column1))
25,115
How to compare two datasets with Q-Q plot using ggplot2?
If your original need is just to control the aspect ratio, here's one way to do that: x <- rnorm(1000) y <- rnorm(1500, 2) myqq <- function(x, y, ...) { rg <- range(x, y, na.rm=T) qqplot(x, y, xlim=rg, ylim=rg, ...) } myqq(x, y)
How to compare two datasets with Q-Q plot using ggplot2?
If your original need is just to control the aspect ratio, here's one way to do that: x <- rnorm(1000) y <- rnorm(1500, 2) myqq <- function(x, y, ...) { rg <- range(x, y, na.rm=T) qqplot(x, y, xl
How to compare two datasets with Q-Q plot using ggplot2? If your original need is just to control the aspect ratio, here's one way to do that: x <- rnorm(1000) y <- rnorm(1500, 2) myqq <- function(x, y, ...) { rg <- range(x, y, na.rm=T) qqplot(x, y, xlim=rg, ylim=rg, ...) } myqq(x, y)
How to compare two datasets with Q-Q plot using ggplot2? If your original need is just to control the aspect ratio, here's one way to do that: x <- rnorm(1000) y <- rnorm(1500, 2) myqq <- function(x, y, ...) { rg <- range(x, y, na.rm=T) qqplot(x, y, xl
25,116
Labeling boxplots in R
I think you will find this produces something like your hand-drawn diagram. data <- c(0.4, 0.7, 0.75, 0.82, 0.9) endaxis <- c(0, 1) # endpoints of axis datamm <- c(min(data), max(data)) boxplot(data, horizontal = TRUE, range = 0, ylim = endaxis, axes = FALSE, col = "grey", add = FALSE) arrows(endaxis, 1, datamm, 1, code = 1, angle = 90, length = 0.1) valuelabels <- c(endaxis[1], round(fivenum(data)[2], digits = 2) , round(fivenum(data)[4], digits = 2), endaxis[2] ) text(x = valuelabels, y = c(1.05, 1.25, 1.25, 1.05), labels = valuelabels) There are probably better ways of doing it. You may need to adapt it to fit your ROC plot, including changing add = FALSE
Labeling boxplots in R
I think you will find this produces something like your hand-drawn diagram. data <- c(0.4, 0.7, 0.75, 0.82, 0.9) endaxis <- c(0, 1) # endpoints of axis datamm <- c(min(data), max(data)) boxplot
Labeling boxplots in R I think you will find this produces something like your hand-drawn diagram. data <- c(0.4, 0.7, 0.75, 0.82, 0.9) endaxis <- c(0, 1) # endpoints of axis datamm <- c(min(data), max(data)) boxplot(data, horizontal = TRUE, range = 0, ylim = endaxis, axes = FALSE, col = "grey", add = FALSE) arrows(endaxis, 1, datamm, 1, code = 1, angle = 90, length = 0.1) valuelabels <- c(endaxis[1], round(fivenum(data)[2], digits = 2) , round(fivenum(data)[4], digits = 2), endaxis[2] ) text(x = valuelabels, y = c(1.05, 1.25, 1.25, 1.05), labels = valuelabels) There are probably better ways of doing it. You may need to adapt it to fit your ROC plot, including changing add = FALSE
Labeling boxplots in R I think you will find this produces something like your hand-drawn diagram. data <- c(0.4, 0.7, 0.75, 0.82, 0.9) endaxis <- c(0, 1) # endpoints of axis datamm <- c(min(data), max(data)) boxplot
25,117
Labeling boxplots in R
Try something like this for a standalone version: bxp <- boxplot(rnorm(100), horizontal=TRUE, axes=FALSE) mtext(c("Min","Max"), side=3, at=bxp$stats[c(1,5)], line=-3) Note that you can get some information when calling boxplot, in particular the "five numbers". If you want it to be superimposed onto another graphic, use add=T but replace mtext by text; you will need to set a $y$ value (which depend on the way you plot the other graphic). A more complete example was given by John Maindonald (code should be on his website):
Labeling boxplots in R
Try something like this for a standalone version: bxp <- boxplot(rnorm(100), horizontal=TRUE, axes=FALSE) mtext(c("Min","Max"), side=3, at=bxp$stats[c(1,5)], line=-3) Note that you can get some infor
Labeling boxplots in R Try something like this for a standalone version: bxp <- boxplot(rnorm(100), horizontal=TRUE, axes=FALSE) mtext(c("Min","Max"), side=3, at=bxp$stats[c(1,5)], line=-3) Note that you can get some information when calling boxplot, in particular the "five numbers". If you want it to be superimposed onto another graphic, use add=T but replace mtext by text; you will need to set a $y$ value (which depend on the way you plot the other graphic). A more complete example was given by John Maindonald (code should be on his website):
Labeling boxplots in R Try something like this for a standalone version: bxp <- boxplot(rnorm(100), horizontal=TRUE, axes=FALSE) mtext(c("Min","Max"), side=3, at=bxp$stats[c(1,5)], line=-3) Note that you can get some infor
25,118
Labeling boxplots in R
Fully customizable ggplot2 boxplot... #bootstrap data <- data.frame(value=rnorm(100,mean = 0.5, sd = 0.2),group=0) #processing metaData <- ddply(data,~group,summarise, mean=mean(data$value), sd=sd(data$value), min=min(data$value), max=max(data$value), median=median(data$value), Q1=0,Q3=0 ) bps <- boxplot.stats(data$value,coef=1.5) metaData$min <- bps$stats[1] #lower wisker metaData$max <- bps$stats[5] #upper wisker metaData$Q1 <- bps$stats[2] # 1st Quartile metaData$Q3 <- bps$stats[4] # 3rd Quartile #adding outliers out <- data.frame() #initialising storage for outliers if(length(bps$out) > 0){ for(n in 1:length(bps$out)){ pt <-data.frame(value=bps$out[n],group=0) out<-rbind(out,pt) } } #adding labels labels <-data.frame(value=metaData$max, label="Upper bound") labels <-rbind(labels,data.frame(value=metaData$min, label="Lower bound")) labels <-rbind(labels,data.frame(value=metaData$median, label="Median")) labels <-rbind(labels,data.frame(value=metaData$Q1, label="First quartile")) labels <-rbind(labels,data.frame(value=metaData$Q3, label="Third quartile")) #drawing library(ggplot2) p <- ggplot(metaData,aes(x=group,y=mean)) p <- p + geom_segment(aes(x=c(0.1,0,0.1),y=c(0,0,1),xend=c(0,0,-0.1),yend=c(0,1,1))) p <- p + geom_text(aes(y=c(0,1),label=c(0,1),x=0.2)) p <- p + geom_errorbar(aes(ymin=min,ymax=max),linetype = 1,width = 0.5) #main range p <- p + geom_linerange(aes(ymin=min,ymax=max),linetype = 1,width = 0, color="white")# white line range p <- p + geom_linerange(aes(ymin=min,ymax=max),linetype = 2) #main range dotted p <- p + geom_crossbar(aes(y=median,,ymin=Q1,ymax=Q3),linetype = 1,fill='white') #box if(length(out) >0) p <- p + geom_point(data=out,aes(x=group,y=value),shape=4) # drawning outliers if any p <- p + scale_x_discrete(breaks=c(0)) p <- p + scale_y_continuous(name= "Value") p <- p + geom_text(data=labels,aes(x=0.5,y=value,label=round(value,2)),colour="black",angle=0,hjust=0.5, vjust=0.5,size=3) p <- p + opts(panel.background = theme_rect(fill = "white",colour = NA)) p <- p + opts(panel.grid.minor = theme_blank(), panel.grid.major = theme_blank()) p <- p + opts(axis.title.x=theme_blank()) p <- p + opts(axis.text.x = theme_blank()) p <- p + opts(axis.title.y=theme_blank()) p <- p + opts(axis.text.y = theme_blank()) p + coord_flip() Result: ...code maybe a bit ugly but works the right way.
Labeling boxplots in R
Fully customizable ggplot2 boxplot... #bootstrap data <- data.frame(value=rnorm(100,mean = 0.5, sd = 0.2),group=0) #processing metaData <- ddply(data,~group,summarise, mean=mean(data$value
Labeling boxplots in R Fully customizable ggplot2 boxplot... #bootstrap data <- data.frame(value=rnorm(100,mean = 0.5, sd = 0.2),group=0) #processing metaData <- ddply(data,~group,summarise, mean=mean(data$value), sd=sd(data$value), min=min(data$value), max=max(data$value), median=median(data$value), Q1=0,Q3=0 ) bps <- boxplot.stats(data$value,coef=1.5) metaData$min <- bps$stats[1] #lower wisker metaData$max <- bps$stats[5] #upper wisker metaData$Q1 <- bps$stats[2] # 1st Quartile metaData$Q3 <- bps$stats[4] # 3rd Quartile #adding outliers out <- data.frame() #initialising storage for outliers if(length(bps$out) > 0){ for(n in 1:length(bps$out)){ pt <-data.frame(value=bps$out[n],group=0) out<-rbind(out,pt) } } #adding labels labels <-data.frame(value=metaData$max, label="Upper bound") labels <-rbind(labels,data.frame(value=metaData$min, label="Lower bound")) labels <-rbind(labels,data.frame(value=metaData$median, label="Median")) labels <-rbind(labels,data.frame(value=metaData$Q1, label="First quartile")) labels <-rbind(labels,data.frame(value=metaData$Q3, label="Third quartile")) #drawing library(ggplot2) p <- ggplot(metaData,aes(x=group,y=mean)) p <- p + geom_segment(aes(x=c(0.1,0,0.1),y=c(0,0,1),xend=c(0,0,-0.1),yend=c(0,1,1))) p <- p + geom_text(aes(y=c(0,1),label=c(0,1),x=0.2)) p <- p + geom_errorbar(aes(ymin=min,ymax=max),linetype = 1,width = 0.5) #main range p <- p + geom_linerange(aes(ymin=min,ymax=max),linetype = 1,width = 0, color="white")# white line range p <- p + geom_linerange(aes(ymin=min,ymax=max),linetype = 2) #main range dotted p <- p + geom_crossbar(aes(y=median,,ymin=Q1,ymax=Q3),linetype = 1,fill='white') #box if(length(out) >0) p <- p + geom_point(data=out,aes(x=group,y=value),shape=4) # drawning outliers if any p <- p + scale_x_discrete(breaks=c(0)) p <- p + scale_y_continuous(name= "Value") p <- p + geom_text(data=labels,aes(x=0.5,y=value,label=round(value,2)),colour="black",angle=0,hjust=0.5, vjust=0.5,size=3) p <- p + opts(panel.background = theme_rect(fill = "white",colour = NA)) p <- p + opts(panel.grid.minor = theme_blank(), panel.grid.major = theme_blank()) p <- p + opts(axis.title.x=theme_blank()) p <- p + opts(axis.text.x = theme_blank()) p <- p + opts(axis.title.y=theme_blank()) p <- p + opts(axis.text.y = theme_blank()) p + coord_flip() Result: ...code maybe a bit ugly but works the right way.
Labeling boxplots in R Fully customizable ggplot2 boxplot... #bootstrap data <- data.frame(value=rnorm(100,mean = 0.5, sd = 0.2),group=0) #processing metaData <- ddply(data,~group,summarise, mean=mean(data$value
25,119
Labeling boxplots in R
Here is mine implementation of your solutions. I've decided not to map the mean value, there is not to much space left. Also the line from 0 to 1 seems odd. Thank's a lot everyone. data <- read.table("roc_average.txt") bxp <- boxplot(data, horizontal = TRUE, range = 0, axes = FALSE, col = "grey", add = TRUE, at = 0.2, varwidth=FALSE, boxwex=0.3) valuelabels <- c(round(fivenum(data)[2], digits = 2), round(fivenum(data)[4], digits = 2)) text(x = valuelabels, y = c(0.35, 0.35), labels = valuelabels, font = 2) mtext(c(min(round(data, digits = 2)),max(round(data, digits = 2))), side=1, at=bxp$stats[c(1,5)], line=-3, font = 2)
Labeling boxplots in R
Here is mine implementation of your solutions. I've decided not to map the mean value, there is not to much space left. Also the line from 0 to 1 seems odd. Thank's a lot everyone. data <- read.table(
Labeling boxplots in R Here is mine implementation of your solutions. I've decided not to map the mean value, there is not to much space left. Also the line from 0 to 1 seems odd. Thank's a lot everyone. data <- read.table("roc_average.txt") bxp <- boxplot(data, horizontal = TRUE, range = 0, axes = FALSE, col = "grey", add = TRUE, at = 0.2, varwidth=FALSE, boxwex=0.3) valuelabels <- c(round(fivenum(data)[2], digits = 2), round(fivenum(data)[4], digits = 2)) text(x = valuelabels, y = c(0.35, 0.35), labels = valuelabels, font = 2) mtext(c(min(round(data, digits = 2)),max(round(data, digits = 2))), side=1, at=bxp$stats[c(1,5)], line=-3, font = 2)
Labeling boxplots in R Here is mine implementation of your solutions. I've decided not to map the mean value, there is not to much space left. Also the line from 0 to 1 seems odd. Thank's a lot everyone. data <- read.table(
25,120
nls() singular gradient matrix at initial parameter estimates error
There are some things we can do. These are generally useful to know for any kind of optimization problem and are not limited to the nls function in R. The first is to parameterize the model to make it everywhere differentiable in its coefficients and automatically constrain the parameters to reasonable ranges. These steps make it harder for the algorithm to have numerical problems or wander into forbidden territory. One way (of many possibilities) is to write $x$ as an exponential (making it positive), $y$ as a square (ditto), and $z$ -- which in the Richards paper is close to $1$ -- in the form $1 + \cos(t)$ for some angle $t.$ The second is to find a good set of starting values. I discovered one set by experimenting with a fit by eye, shown as the dotted curve in the plot below. The third is to prevent nls from exiting, so even if it fails to find a solution, you can inspect the solution. The fourth is to use suitable weights. I speculate that higher heights ought to be fit with larger error and so use weights proportional to height. This makes little difference here, but can sometimes be helpful and more statistically appropriate. This procedure finds the solution plotted in red. You can see it follows the data closely and is slightly better than the initial eyeball fit. The fitted values (in terms of the original parameters) are $x = 134571,$ $y = 0.000118,$ and $z = 0.926.$ The problem is evident: these data trend almost linearly, which is not enough to determine all three parameters in the model. Given that the model forces the curve through the origin, a linear trend uses just one parameter, making the other two parameters superfluous. To verify this, analyze the correlation matrix of the estimates. In this case the eigenvectors are approximately $2.96,$ $0.039,$ and $10^{-8}.$ The last two are essentially zero compared to the first. The corresponding eigenvectors correspond roughly to (a) a contrast between $x$ and the other parameters (increases in $x$ are almost perfectly offset by decreases in $y$ and $z$), (b) the $z$ parameter, and (c) the $x$ and $y$ parameters, in that order. This tells us the model is confident about a particular combination of $x,$ $y,$ and $z$ (which determines the slope for small ages) but can glean essentially no specific information about $z$ or $y$ from these data, apart from a tiny hint of curvature suggested by the fact the second eigenvalue is not truly zero. Thus, a least squares fit ought to work about as well. Using fit <- lm(height ~ 0 + age) I found a slope of $22.89.$ Plotting this line (through the origin) gives a curve barely distinguishable from the red curve above, so I haven't shown it. Here is the R code showing the details. # # The model. # f <- function(age, beta) { x <- beta["x"] y <- beta["y"] z <- beta["z"] exp(x) * (1 - exp(-y^2 * age))^(1 + sin(z)) } # # The data. # age <- scan(text = "0 3 6 17 29 47 57 63 72") height <- scan(text = "37 70 199 464 736 1008 1280 1462 1643") plot(age, height) # # Draw an eyeball fit. # These parameters correspond to an exponential curve (z == 0) that over the # range of ages in the data hardly departs from linearity (age * y is always # tiny). Only `x` has to be estimated; it determines the slope, which is # easy to gauge from the plots. # s <- c(x = 9, y = sqrt(1/300), z = 0) curve(f(x, s), add = TRUE, lwd = 2, col = gray(0.3), lty = 3) # # Polish this fit. # The `control` object shows how to specify some of the most useful aspects # of the search. # obj <- nls(height ~ exp(x) * (1 - exp(-y^2 * age))^(1 + sin(z)), start = s, weights = height, control = list(minFactor = 2^(-16), maxiter = 1e4, warnOnly = TRUE)) # # Plot the fit. # b <- coefficients(obj) curve(f(x, b), add = TRUE, lwd = 2, col = hsv(0.02, 1, 0.85)) # # Report the estimates in terms of the original parameterization. # c(x = exp(b["x"]), y = b["y"]^2, z = 1 + sin(b["z"])) # # Analyze the correlations among the estimates. # V <- vcov(obj) v <- sqrt(diag(V)) V <- t(V/v)/v eigen(V) # Alternatively, `eigen(cov2cor(vcov(obj)))` # # Look at a simpler alternative model. # fit <- lm(height ~ 0 + age) abline(fit, col = "Blue")
nls() singular gradient matrix at initial parameter estimates error
There are some things we can do. These are generally useful to know for any kind of optimization problem and are not limited to the nls function in R. The first is to parameterize the model to make i
nls() singular gradient matrix at initial parameter estimates error There are some things we can do. These are generally useful to know for any kind of optimization problem and are not limited to the nls function in R. The first is to parameterize the model to make it everywhere differentiable in its coefficients and automatically constrain the parameters to reasonable ranges. These steps make it harder for the algorithm to have numerical problems or wander into forbidden territory. One way (of many possibilities) is to write $x$ as an exponential (making it positive), $y$ as a square (ditto), and $z$ -- which in the Richards paper is close to $1$ -- in the form $1 + \cos(t)$ for some angle $t.$ The second is to find a good set of starting values. I discovered one set by experimenting with a fit by eye, shown as the dotted curve in the plot below. The third is to prevent nls from exiting, so even if it fails to find a solution, you can inspect the solution. The fourth is to use suitable weights. I speculate that higher heights ought to be fit with larger error and so use weights proportional to height. This makes little difference here, but can sometimes be helpful and more statistically appropriate. This procedure finds the solution plotted in red. You can see it follows the data closely and is slightly better than the initial eyeball fit. The fitted values (in terms of the original parameters) are $x = 134571,$ $y = 0.000118,$ and $z = 0.926.$ The problem is evident: these data trend almost linearly, which is not enough to determine all three parameters in the model. Given that the model forces the curve through the origin, a linear trend uses just one parameter, making the other two parameters superfluous. To verify this, analyze the correlation matrix of the estimates. In this case the eigenvectors are approximately $2.96,$ $0.039,$ and $10^{-8}.$ The last two are essentially zero compared to the first. The corresponding eigenvectors correspond roughly to (a) a contrast between $x$ and the other parameters (increases in $x$ are almost perfectly offset by decreases in $y$ and $z$), (b) the $z$ parameter, and (c) the $x$ and $y$ parameters, in that order. This tells us the model is confident about a particular combination of $x,$ $y,$ and $z$ (which determines the slope for small ages) but can glean essentially no specific information about $z$ or $y$ from these data, apart from a tiny hint of curvature suggested by the fact the second eigenvalue is not truly zero. Thus, a least squares fit ought to work about as well. Using fit <- lm(height ~ 0 + age) I found a slope of $22.89.$ Plotting this line (through the origin) gives a curve barely distinguishable from the red curve above, so I haven't shown it. Here is the R code showing the details. # # The model. # f <- function(age, beta) { x <- beta["x"] y <- beta["y"] z <- beta["z"] exp(x) * (1 - exp(-y^2 * age))^(1 + sin(z)) } # # The data. # age <- scan(text = "0 3 6 17 29 47 57 63 72") height <- scan(text = "37 70 199 464 736 1008 1280 1462 1643") plot(age, height) # # Draw an eyeball fit. # These parameters correspond to an exponential curve (z == 0) that over the # range of ages in the data hardly departs from linearity (age * y is always # tiny). Only `x` has to be estimated; it determines the slope, which is # easy to gauge from the plots. # s <- c(x = 9, y = sqrt(1/300), z = 0) curve(f(x, s), add = TRUE, lwd = 2, col = gray(0.3), lty = 3) # # Polish this fit. # The `control` object shows how to specify some of the most useful aspects # of the search. # obj <- nls(height ~ exp(x) * (1 - exp(-y^2 * age))^(1 + sin(z)), start = s, weights = height, control = list(minFactor = 2^(-16), maxiter = 1e4, warnOnly = TRUE)) # # Plot the fit. # b <- coefficients(obj) curve(f(x, b), add = TRUE, lwd = 2, col = hsv(0.02, 1, 0.85)) # # Report the estimates in terms of the original parameterization. # c(x = exp(b["x"]), y = b["y"]^2, z = 1 + sin(b["z"])) # # Analyze the correlations among the estimates. # V <- vcov(obj) v <- sqrt(diag(V)) V <- t(V/v)/v eigen(V) # Alternatively, `eigen(cov2cor(vcov(obj)))` # # Look at a simpler alternative model. # fit <- lm(height ~ 0 + age) abline(fit, col = "Blue")
nls() singular gradient matrix at initial parameter estimates error There are some things we can do. These are generally useful to know for any kind of optimization problem and are not limited to the nls function in R. The first is to parameterize the model to make i
25,121
nls() singular gradient matrix at initial parameter estimates error
The problem seems to be in convergence of the z parameter so fix it at each of a sequence of values and optimize on the others for each and then take the result with the lowest residual sum of squares. We use the plinear algorithm of nls which does not require starting values for the parameters that enter linearly -- x enters linearly so its starting value can be omitted. Since we are fixing z and since x enters linearly we only have to specify a starting value for y. To use plinear the right hand side should be a column that multiplies x but x itself is not specified (in a similar way to lm). age <- c(0, 3, 6, 17, 29, 47, 57, 63, 72) height <- c(37, 70, 199, 464, 736, 1008, 1280, 1462, 1643) fo <- "height ~ cbind(x = (1 - exp(-y * age))^z)" zseq <- seq(0, 2, 0.01) sse <- sapply(zseq, function(z) { res <- try(nls(fo, start = list(y = 1), algorithm = "plinear")) if (inherits(res, "try-error")) NA else deviance(res) }) z <- zseq[which.min(sse)] z # z value which minimizes the SSE ## [1] 1 fm <- nls(fo, start = list(y = 1), algorithm = "plinear") fm giving Nonlinear regression model model: height ~ cbind(x = (1 - exp(-y * age))^z) data: parent.frame() y .lin.x 3.384e-03 7.468e+03 residual sum-of-squares: 18004 Number of iterations to convergence: 9 Achieved convergence tolerance: 1.103e-06 Plotting the solution plot(height ~ age) lines(fitted(fm) ~ age) (continued after chart) Note that a simple linear regression actually gives a better fit (lower residual sum of squares) and has fewer parameters (2 vs 3). fm.lin <- lm(height ~ age) deviance(fm.lin) ## [1] 13546.89 deviance(fm) ## [1] 18003.86 The following is just to show that the deviance function in R is equivalent to taking the residual sum of squares for both nls and lm. sum(resid(fm.lin)^2) ## [1] 13546.89 sum(resid(fm)^2) ## [1] 18003.86
nls() singular gradient matrix at initial parameter estimates error
The problem seems to be in convergence of the z parameter so fix it at each of a sequence of values and optimize on the others for each and then take the result with the lowest residual sum of squares
nls() singular gradient matrix at initial parameter estimates error The problem seems to be in convergence of the z parameter so fix it at each of a sequence of values and optimize on the others for each and then take the result with the lowest residual sum of squares. We use the plinear algorithm of nls which does not require starting values for the parameters that enter linearly -- x enters linearly so its starting value can be omitted. Since we are fixing z and since x enters linearly we only have to specify a starting value for y. To use plinear the right hand side should be a column that multiplies x but x itself is not specified (in a similar way to lm). age <- c(0, 3, 6, 17, 29, 47, 57, 63, 72) height <- c(37, 70, 199, 464, 736, 1008, 1280, 1462, 1643) fo <- "height ~ cbind(x = (1 - exp(-y * age))^z)" zseq <- seq(0, 2, 0.01) sse <- sapply(zseq, function(z) { res <- try(nls(fo, start = list(y = 1), algorithm = "plinear")) if (inherits(res, "try-error")) NA else deviance(res) }) z <- zseq[which.min(sse)] z # z value which minimizes the SSE ## [1] 1 fm <- nls(fo, start = list(y = 1), algorithm = "plinear") fm giving Nonlinear regression model model: height ~ cbind(x = (1 - exp(-y * age))^z) data: parent.frame() y .lin.x 3.384e-03 7.468e+03 residual sum-of-squares: 18004 Number of iterations to convergence: 9 Achieved convergence tolerance: 1.103e-06 Plotting the solution plot(height ~ age) lines(fitted(fm) ~ age) (continued after chart) Note that a simple linear regression actually gives a better fit (lower residual sum of squares) and has fewer parameters (2 vs 3). fm.lin <- lm(height ~ age) deviance(fm.lin) ## [1] 13546.89 deviance(fm) ## [1] 18003.86 The following is just to show that the deviance function in R is equivalent to taking the residual sum of squares for both nls and lm. sum(resid(fm.lin)^2) ## [1] 13546.89 sum(resid(fm)^2) ## [1] 18003.86
nls() singular gradient matrix at initial parameter estimates error The problem seems to be in convergence of the z parameter so fix it at each of a sequence of values and optimize on the others for each and then take the result with the lowest residual sum of squares
25,122
nls() singular gradient matrix at initial parameter estimates error
Minor point: Don't try to recreate the exponential function in your code The excellent answer by whuber shows how you can use the data to choose better starting values for your iteration and how you can constrain the search space appropriately. This is something you should usually do when fitting nonlinear models using an iterative method. One other minor thing I notice in your code is that you define your own constant e and then take powers of this in later steps to yield your own exponential function. That is unecessary and it introduces additional rounding error. Instead of trying to create the exponential function yourself, use the exp function built into the program. (You will see that whuber has done this in his own code.)
nls() singular gradient matrix at initial parameter estimates error
Minor point: Don't try to recreate the exponential function in your code The excellent answer by whuber shows how you can use the data to choose better starting values for your iteration and how you
nls() singular gradient matrix at initial parameter estimates error Minor point: Don't try to recreate the exponential function in your code The excellent answer by whuber shows how you can use the data to choose better starting values for your iteration and how you can constrain the search space appropriately. This is something you should usually do when fitting nonlinear models using an iterative method. One other minor thing I notice in your code is that you define your own constant e and then take powers of this in later steps to yield your own exponential function. That is unecessary and it introduces additional rounding error. Instead of trying to create the exponential function yourself, use the exp function built into the program. (You will see that whuber has done this in his own code.)
nls() singular gradient matrix at initial parameter estimates error Minor point: Don't try to recreate the exponential function in your code The excellent answer by whuber shows how you can use the data to choose better starting values for your iteration and how you
25,123
Can I compare p-values?
You won't be able to tell which effect is larger simply by looking at p values. You haven't said how many people of each sex were in each group, but let's assume they are evenly split for now. Let the outcome be $y=0$ for not cured, and $y=1$ for cured. The data are then y Group Sex n 1 0 Group A Female 460 2 0 Group A Male 430 3 0 Group B Female 450 4 0 Group B Male 445 5 1 Group A Female 40 6 1 Group A Male 70 7 1 Group B Female 50 8 1 Group B Male 55 Let's model the risk of being cured using $$ \log \left( \dfrac{p}{1-p} \right) = \beta_0 + \beta_1x_1 + \beta_2 x_2 + \beta_3x_1x_2 $$ Here: $\beta_0$ is the reference category (females from group A). $\beta_1$ is the effect of being in group B $\beta_2$ is the effect of being male $\beta_3$ is the interaction of group B and being male. Hence, the risk of being cured on the logit scale from group A is $$\log \left( \dfrac{p}{1-p} \right) = \beta_0 + \beta_2$$ and the risk of being cured on the logit scale from group B is $$\log \left( \dfrac{p}{1-p} \right) = \beta_0 + \beta_1 + \beta_2 + \beta_3$$ The difference in risks is the quantity $\beta_1 + \beta_3$. Our null is that $\beta_1 + \beta_3 = 0$ versus the alternative that $\beta_1 + \beta_3 \neq 0$. Using R to perform the computations... # Fit a logistic regression to the data mod<-glm(y ~ Group*Sex, data = model_data, family=binomial(), weights = n) # Extract the covariance matrix for the coefficients Sigma = vcov(model) # Compute the standard error of the estimate using the covariance matrix x = c(0, 1, 0, 1) b = sum(coef(mod) %*% x) se_b = x %*% Sigma %*% x # Test statistic z = b/sqrt(se_b) >>> -1.43 The test statistic is $z = -1.43$ yielding a p value of about 0.15. We would fail to reject the null hypothesis that males have different risks of being cured across populations. EDIT: There may be a simpler way of testing this. The stated hypothesis is really about homogeneity of odds ratios between strata, here stratified by population. We can do this using Cochran's test of homogeneity. I'll work with log odds ratios because they are slightly simpler algebraically. Let $\hat{\theta}_k$ be the log odds ratio in the $k^{th}$ strata. Let $\hat{\theta}$ be the estimate of the marginal odds ratio (pooling strata). Asymptotically, $$\widehat{\theta}_{k}-\theta \stackrel{d}{\approx} N\left(0, \sigma_{\widehat{\theta}_{k}}^{2}\right)$$ Let $\tau_k = \sigma^{-2}_{\hat{\theta}_k}$ be the estimated precision of the log odds ratio. A test statistic for homogeneity of odds ratios is $$X_{H, C}^{2}=\sum_{k} \widehat{\tau}_{k}\left(\widehat{\theta}_{k}-\hat{\theta}\right)^{2}$$ Where $X^2_{H, C} \sim \chi^2_{K-1}$. When I compute this test statistic, I get $X^2_{H, C} = 3.136$ which yields a p value of 0.076, again failing to reject the null. For more, see section 4.6.2 of this book.
Can I compare p-values?
You won't be able to tell which effect is larger simply by looking at p values. You haven't said how many people of each sex were in each group, but let's assume they are evenly split for now. Let the
Can I compare p-values? You won't be able to tell which effect is larger simply by looking at p values. You haven't said how many people of each sex were in each group, but let's assume they are evenly split for now. Let the outcome be $y=0$ for not cured, and $y=1$ for cured. The data are then y Group Sex n 1 0 Group A Female 460 2 0 Group A Male 430 3 0 Group B Female 450 4 0 Group B Male 445 5 1 Group A Female 40 6 1 Group A Male 70 7 1 Group B Female 50 8 1 Group B Male 55 Let's model the risk of being cured using $$ \log \left( \dfrac{p}{1-p} \right) = \beta_0 + \beta_1x_1 + \beta_2 x_2 + \beta_3x_1x_2 $$ Here: $\beta_0$ is the reference category (females from group A). $\beta_1$ is the effect of being in group B $\beta_2$ is the effect of being male $\beta_3$ is the interaction of group B and being male. Hence, the risk of being cured on the logit scale from group A is $$\log \left( \dfrac{p}{1-p} \right) = \beta_0 + \beta_2$$ and the risk of being cured on the logit scale from group B is $$\log \left( \dfrac{p}{1-p} \right) = \beta_0 + \beta_1 + \beta_2 + \beta_3$$ The difference in risks is the quantity $\beta_1 + \beta_3$. Our null is that $\beta_1 + \beta_3 = 0$ versus the alternative that $\beta_1 + \beta_3 \neq 0$. Using R to perform the computations... # Fit a logistic regression to the data mod<-glm(y ~ Group*Sex, data = model_data, family=binomial(), weights = n) # Extract the covariance matrix for the coefficients Sigma = vcov(model) # Compute the standard error of the estimate using the covariance matrix x = c(0, 1, 0, 1) b = sum(coef(mod) %*% x) se_b = x %*% Sigma %*% x # Test statistic z = b/sqrt(se_b) >>> -1.43 The test statistic is $z = -1.43$ yielding a p value of about 0.15. We would fail to reject the null hypothesis that males have different risks of being cured across populations. EDIT: There may be a simpler way of testing this. The stated hypothesis is really about homogeneity of odds ratios between strata, here stratified by population. We can do this using Cochran's test of homogeneity. I'll work with log odds ratios because they are slightly simpler algebraically. Let $\hat{\theta}_k$ be the log odds ratio in the $k^{th}$ strata. Let $\hat{\theta}$ be the estimate of the marginal odds ratio (pooling strata). Asymptotically, $$\widehat{\theta}_{k}-\theta \stackrel{d}{\approx} N\left(0, \sigma_{\widehat{\theta}_{k}}^{2}\right)$$ Let $\tau_k = \sigma^{-2}_{\hat{\theta}_k}$ be the estimated precision of the log odds ratio. A test statistic for homogeneity of odds ratios is $$X_{H, C}^{2}=\sum_{k} \widehat{\tau}_{k}\left(\widehat{\theta}_{k}-\hat{\theta}\right)^{2}$$ Where $X^2_{H, C} \sim \chi^2_{K-1}$. When I compute this test statistic, I get $X^2_{H, C} = 3.136$ which yields a p value of 0.076, again failing to reject the null. For more, see section 4.6.2 of this book.
Can I compare p-values? You won't be able to tell which effect is larger simply by looking at p values. You haven't said how many people of each sex were in each group, but let's assume they are evenly split for now. Let the
25,124
Can I compare p-values?
Not an elaborated answer since we have already one, but a bit more focus on this part of the question: Now I see that p1 is smaller than p2, is there anything I can say regarding which vaccine is more effective on male patients? "The p-value is s the probability of obtaining test results at least as extreme as the results actually observed, under the assumption that the null hypothesis is correct". It is calculated from your sample and used to make inference about the larger population. It is associated to a specific null hypothesis.... and therefore make it complicated to be compared, as such, with another p-value. Comparing significant with non significant p-value In the example you provided (and assuming that male and female are equally distributed), the null hypothesis of the second test (vaccine B) cannot be rejected (p2-value = 0.606 for 2-sample test for equality of proportions)... So, a comparison of p-values will be even more than hazardous (if it had made sense), since it is not even significant. The p-value tells only a little part of the story Another illustration, the p-value of your first test (vaccine A) is p1-value = 0.0024 (2-sample test for equality of proportions) for 70 male patients and 40 female patients. However, you get a similar p-value of 0.0025 for 399 cured males and 358 cured females. So, you get the same (or similar) p-value as your initial test for vaccine A, but the overall efficiency of the vaccine is much more important (covering 70% - 80 % of the patients). In such tests, the p-value does not tell you the story of each vaccine and hide their overall efficiency... which can lead to incorrect conclusions. Below is an illustration of all possible pairs male/female (where vaccine A is more efficient on males) for a very similar p-value as your first test (vaccine A): In other words, we get similar p-values if vaccine A cures 14 males and 2 females or if it cures 498 males and 486 females. Finally, it has to tell a story that you can trust, which means that proper analysis must be carried out. Unfortunately, p-values do not tell much about the quality of the analysis: attractive p-values can actually hide poor analyses. So, there is no other choice than stating a "new" null hypothesis that both vaccines A and B are more effective on male patients than female, as described by @Demetri. I take advantage of this also to highlight the interesting link (direct access) mentioned by @StephanKolassa in comments (since comments are not always read): "The Difference Between “Significant” and “Not Significant” is not Itself Statistically Significant" - Gelman & Stern (2006).
Can I compare p-values?
Not an elaborated answer since we have already one, but a bit more focus on this part of the question: Now I see that p1 is smaller than p2, is there anything I can say regarding which vaccine is mor
Can I compare p-values? Not an elaborated answer since we have already one, but a bit more focus on this part of the question: Now I see that p1 is smaller than p2, is there anything I can say regarding which vaccine is more effective on male patients? "The p-value is s the probability of obtaining test results at least as extreme as the results actually observed, under the assumption that the null hypothesis is correct". It is calculated from your sample and used to make inference about the larger population. It is associated to a specific null hypothesis.... and therefore make it complicated to be compared, as such, with another p-value. Comparing significant with non significant p-value In the example you provided (and assuming that male and female are equally distributed), the null hypothesis of the second test (vaccine B) cannot be rejected (p2-value = 0.606 for 2-sample test for equality of proportions)... So, a comparison of p-values will be even more than hazardous (if it had made sense), since it is not even significant. The p-value tells only a little part of the story Another illustration, the p-value of your first test (vaccine A) is p1-value = 0.0024 (2-sample test for equality of proportions) for 70 male patients and 40 female patients. However, you get a similar p-value of 0.0025 for 399 cured males and 358 cured females. So, you get the same (or similar) p-value as your initial test for vaccine A, but the overall efficiency of the vaccine is much more important (covering 70% - 80 % of the patients). In such tests, the p-value does not tell you the story of each vaccine and hide their overall efficiency... which can lead to incorrect conclusions. Below is an illustration of all possible pairs male/female (where vaccine A is more efficient on males) for a very similar p-value as your first test (vaccine A): In other words, we get similar p-values if vaccine A cures 14 males and 2 females or if it cures 498 males and 486 females. Finally, it has to tell a story that you can trust, which means that proper analysis must be carried out. Unfortunately, p-values do not tell much about the quality of the analysis: attractive p-values can actually hide poor analyses. So, there is no other choice than stating a "new" null hypothesis that both vaccines A and B are more effective on male patients than female, as described by @Demetri. I take advantage of this also to highlight the interesting link (direct access) mentioned by @StephanKolassa in comments (since comments are not always read): "The Difference Between “Significant” and “Not Significant” is not Itself Statistically Significant" - Gelman & Stern (2006).
Can I compare p-values? Not an elaborated answer since we have already one, but a bit more focus on this part of the question: Now I see that p1 is smaller than p2, is there anything I can say regarding which vaccine is mor
25,125
Can I compare p-values?
Since effect size is one factor going into p-values, there are cases where p-values tell you something useful about effect sizes, but just looking at effect sizes directly is always more useful. You have the further issue that your p-values are from testing the hypothesis of the vaccine being more effective on males than females, rather than directly testing effectiveness on males. This means that your p-values are differing not only from the variable you care about (effectiveness on males) but also on one you don't (effectiveness on females). This makes the p-values even closer to useless. There would be little reason to not simply do hypothesis testing based on a binomial or Gaussian hypothesis of the data. If for some reason you were only given the p-values and did not have access to the raw data, the best course of action would probably be to simply refrain from trying to draw conclusions. As as a purely medical, rather than statistical note, generally vaccines are used to prevent infection rather than cure them (although I suppose there are cases where they can do the latter).
Can I compare p-values?
Since effect size is one factor going into p-values, there are cases where p-values tell you something useful about effect sizes, but just looking at effect sizes directly is always more useful. You h
Can I compare p-values? Since effect size is one factor going into p-values, there are cases where p-values tell you something useful about effect sizes, but just looking at effect sizes directly is always more useful. You have the further issue that your p-values are from testing the hypothesis of the vaccine being more effective on males than females, rather than directly testing effectiveness on males. This means that your p-values are differing not only from the variable you care about (effectiveness on males) but also on one you don't (effectiveness on females). This makes the p-values even closer to useless. There would be little reason to not simply do hypothesis testing based on a binomial or Gaussian hypothesis of the data. If for some reason you were only given the p-values and did not have access to the raw data, the best course of action would probably be to simply refrain from trying to draw conclusions. As as a purely medical, rather than statistical note, generally vaccines are used to prevent infection rather than cure them (although I suppose there are cases where they can do the latter).
Can I compare p-values? Since effect size is one factor going into p-values, there are cases where p-values tell you something useful about effect sizes, but just looking at effect sizes directly is always more useful. You h
25,126
Dimension reduction using space filling curve to avoid "Curse of dimensionality"?
I think your intuition is right; moving from $\mathbb{R}^n$ to an affine parameter along a space-filling curve will discard information about what points are close to one another in the high-dimensional space. Points in the same neighborhood can be separated by arbitrarily large distances along the curve. Consider, as an example, a problem where your prediction targets lie in a compact region in $\mathbb{R}^n$. Your machine learning task is to find a way to characterize that region. In the space-filling curve representation, the curve likely dips in and out of that region for an infinite number of ranges of the affine parameter $\lambda$. Finding these segments of the curve is not only much harder than finding the boundaries of the region in $\mathbb{R}^n$, it is likely impossible because you probably have arbitrary large $\lambda$ that lie in the region. Your generalization error will be terrible, since any new case that lies along a segment of the curve you haven't explored yet will generate a missed prediction, even if it differs imperceptibly from a training point in the $\mathbb{R}^n$ representation. Dimension reduction does have a place in machine learning, but the trick is to discard dimensions that are not providing useful information for your prediction problem. Just forcing everything into one dimension using a construct like a space-filling curve doesn't accomplish that.
Dimension reduction using space filling curve to avoid "Curse of dimensionality"?
I think your intuition is right; moving from $\mathbb{R}^n$ to an affine parameter along a space-filling curve will discard information about what points are close to one another in the high-dimension
Dimension reduction using space filling curve to avoid "Curse of dimensionality"? I think your intuition is right; moving from $\mathbb{R}^n$ to an affine parameter along a space-filling curve will discard information about what points are close to one another in the high-dimensional space. Points in the same neighborhood can be separated by arbitrarily large distances along the curve. Consider, as an example, a problem where your prediction targets lie in a compact region in $\mathbb{R}^n$. Your machine learning task is to find a way to characterize that region. In the space-filling curve representation, the curve likely dips in and out of that region for an infinite number of ranges of the affine parameter $\lambda$. Finding these segments of the curve is not only much harder than finding the boundaries of the region in $\mathbb{R}^n$, it is likely impossible because you probably have arbitrary large $\lambda$ that lie in the region. Your generalization error will be terrible, since any new case that lies along a segment of the curve you haven't explored yet will generate a missed prediction, even if it differs imperceptibly from a training point in the $\mathbb{R}^n$ representation. Dimension reduction does have a place in machine learning, but the trick is to discard dimensions that are not providing useful information for your prediction problem. Just forcing everything into one dimension using a construct like a space-filling curve doesn't accomplish that.
Dimension reduction using space filling curve to avoid "Curse of dimensionality"? I think your intuition is right; moving from $\mathbb{R}^n$ to an affine parameter along a space-filling curve will discard information about what points are close to one another in the high-dimension
25,127
Dimension reduction using space filling curve to avoid "Curse of dimensionality"?
The problem of the curse of dimensionality is caused by the amount of data needed, in the worst case, to adequately represent the underlying distribution goes up exponentially in the number of features/attributes. Unfortunately using a space-filling curve to reduce the number of dimensions will not eliminate the curse of dimensionality. Consider a Gaussian distribution in a d-dimensional space, which could be described by a mean vector and a covariance matrix. This is a nice smooth and "simple" distribution. Now consider where the areas of high density would lie on the space-filling curve. Instead of one contiguous smooth distributions, there would now be exponentially (in the dimension of the original space) many bumps of high data density along the "string". We would still need exponentially large amounts of data to specify where along the "string" those bumps should be, and how high and how wide they would be. So sadly this approach is highly unlikely to work.
Dimension reduction using space filling curve to avoid "Curse of dimensionality"?
The problem of the curse of dimensionality is caused by the amount of data needed, in the worst case, to adequately represent the underlying distribution goes up exponentially in the number of feature
Dimension reduction using space filling curve to avoid "Curse of dimensionality"? The problem of the curse of dimensionality is caused by the amount of data needed, in the worst case, to adequately represent the underlying distribution goes up exponentially in the number of features/attributes. Unfortunately using a space-filling curve to reduce the number of dimensions will not eliminate the curse of dimensionality. Consider a Gaussian distribution in a d-dimensional space, which could be described by a mean vector and a covariance matrix. This is a nice smooth and "simple" distribution. Now consider where the areas of high density would lie on the space-filling curve. Instead of one contiguous smooth distributions, there would now be exponentially (in the dimension of the original space) many bumps of high data density along the "string". We would still need exponentially large amounts of data to specify where along the "string" those bumps should be, and how high and how wide they would be. So sadly this approach is highly unlikely to work.
Dimension reduction using space filling curve to avoid "Curse of dimensionality"? The problem of the curse of dimensionality is caused by the amount of data needed, in the worst case, to adequately represent the underlying distribution goes up exponentially in the number of feature
25,128
Dimension reduction using space filling curve to avoid "Curse of dimensionality"?
If you transform the data by some dimensional reduction then you will be affecting the distance metrics that you will be using implicitly in the higher dimensional training. Try creating a 3d nearness metric from a 2d image - it's all distorted (see Fr Ted: "small, far away"). If you believe that all the N dimensions are useful, you could simply 'clump' the data based on clump size (a nearest neighbours metric over a reduced dimension, or a scaling matrix (eigenvalue/vectors), and either train each clump independently, or train against the clumps, depending on how the split happens/occurs/forced. I.e. something along the lines of the RVM/IVM approaches What is the difference between Informative (IVM) and Relevance (RVM) vector machines
Dimension reduction using space filling curve to avoid "Curse of dimensionality"?
If you transform the data by some dimensional reduction then you will be affecting the distance metrics that you will be using implicitly in the higher dimensional training. Try creating a 3d nearness
Dimension reduction using space filling curve to avoid "Curse of dimensionality"? If you transform the data by some dimensional reduction then you will be affecting the distance metrics that you will be using implicitly in the higher dimensional training. Try creating a 3d nearness metric from a 2d image - it's all distorted (see Fr Ted: "small, far away"). If you believe that all the N dimensions are useful, you could simply 'clump' the data based on clump size (a nearest neighbours metric over a reduced dimension, or a scaling matrix (eigenvalue/vectors), and either train each clump independently, or train against the clumps, depending on how the split happens/occurs/forced. I.e. something along the lines of the RVM/IVM approaches What is the difference between Informative (IVM) and Relevance (RVM) vector machines
Dimension reduction using space filling curve to avoid "Curse of dimensionality"? If you transform the data by some dimensional reduction then you will be affecting the distance metrics that you will be using implicitly in the higher dimensional training. Try creating a 3d nearness
25,129
Dimension reduction using space filling curve to avoid "Curse of dimensionality"?
This approach does work, to a degree, in low-dimensional $\mathbb{R}^n$ spaces, certainly in $\mathbb{R}^2$ and $\mathbb{R}^3$. A $k$-d tree is basically a data structure for ordering points along a space-filling curve. The common reason why/when tree-based techniques work is because they turn a decision among $\mathcal{O}(m)$ choices into a sequence of $\mathcal{O}(\log m)$ decisions among $\mathcal{O}(n)$ choices. That's useful as long as $n\ll m$, but it becomes utterly counterproductive when $n$ is similar or bigger than $m$. Oftentimes, the spaces for which the curse of dimensionality applies are not just high-dimensional, but conceptually infinite-dimensional, which makes a direct space-filling approach hopeless. Nevertheless, I wouldn't say it's completely futile to work in that direction, because even in such problems the data is in reality often confined to a finite-, perhaps even low-dimensional submanifold, and subdividing only that manifold in $k$-d fashion might well have its merits. The real problem is finding that manifold in the first place; that's what dimensionality reduction is all about.
Dimension reduction using space filling curve to avoid "Curse of dimensionality"?
This approach does work, to a degree, in low-dimensional $\mathbb{R}^n$ spaces, certainly in $\mathbb{R}^2$ and $\mathbb{R}^3$. A $k$-d tree is basically a data structure for ordering points along a s
Dimension reduction using space filling curve to avoid "Curse of dimensionality"? This approach does work, to a degree, in low-dimensional $\mathbb{R}^n$ spaces, certainly in $\mathbb{R}^2$ and $\mathbb{R}^3$. A $k$-d tree is basically a data structure for ordering points along a space-filling curve. The common reason why/when tree-based techniques work is because they turn a decision among $\mathcal{O}(m)$ choices into a sequence of $\mathcal{O}(\log m)$ decisions among $\mathcal{O}(n)$ choices. That's useful as long as $n\ll m$, but it becomes utterly counterproductive when $n$ is similar or bigger than $m$. Oftentimes, the spaces for which the curse of dimensionality applies are not just high-dimensional, but conceptually infinite-dimensional, which makes a direct space-filling approach hopeless. Nevertheless, I wouldn't say it's completely futile to work in that direction, because even in such problems the data is in reality often confined to a finite-, perhaps even low-dimensional submanifold, and subdividing only that manifold in $k$-d fashion might well have its merits. The real problem is finding that manifold in the first place; that's what dimensionality reduction is all about.
Dimension reduction using space filling curve to avoid "Curse of dimensionality"? This approach does work, to a degree, in low-dimensional $\mathbb{R}^n$ spaces, certainly in $\mathbb{R}^2$ and $\mathbb{R}^3$. A $k$-d tree is basically a data structure for ordering points along a s
25,130
Die 100 rolls no face appearing more than 20 times
This is a generalization of the famous Birthday Problem: given $n=100$ individuals who have random, uniformly distributed "birthdays" among a set of $d=6$ possibilities, what is the chance that no birthday is shared by more than $m=20$ individuals? An exact calculation yields the answer $0.267\,747\,907\,805\,267$ (to double precision). I will sketch the theory and provide the code for general $n, m, d.$ The code's asymptotic timing is $O(n^2\log(d))$ which makes it suitable for very large numbers of birthdays $d$ and provides reasonable performance until $n$ is in the thousands. At that point, the Poisson approximation discussed at Extending the birthday paradox to more than 2 people ought to work well in most cases. Explanation of the solution The probability generating function (pgf) for the outcomes of $n$ independent rolls of a $d$-sided die is $$d^{-n}f_n(x_1,x_2,\ldots,x_d) = d^{-n}(x_1+x_2+ \cdots + x_d)^n.$$ The coefficient of $x_1^{e_1}x_2^{e_2}\cdots x_d^{e_d}$ in the expansion of this multinomial gives the number of ways in which face $i$ can appear exactly $e_i$ times, $i=1, 2, \ldots, d.$ Limiting our interest to no more than $m$ appearances by any face is tantamount to evaluating $f_n$ modulo the ideal $\mathcal I$ generated by $x_1^{m+1}, x_2^{m+1}, \ldots, x_d^{m+1}.$ To perform this evaluation, use the Binomial Theorem recursively to obtain $$\eqalign{ f_n(x_1, \ldots, x_d) &= ((x_1+\cdots+x_r) + (x_{r+1}+x_{r+2} + \cdots + x_{2r}))^n \\ &= \sum_{k=0}^n \binom{n}{k} (x_1+\cdots+x_r)^k (x_{r+1}+\cdots+x_{2r})^{n-k} \\ &= \sum_{k=0}^n \binom{n}{k} f_k(x_1, \ldots, x_r) f_{n-k}(x_{r+1}, \ldots, x_{2r}) }$$ when $d=2r$ is even. Writing $f_n^{(d)} = f_n(1,1,\ldots, 1)$ ($d$ terms), we have $$f_n^{(2r)} = \sum_{k=0}^n \binom{n}{k} f_k^{(r)} f_{n-k}^{(r)}.\tag{a}$$ When $d=2r+1$ is odd, use an analogous decomposition $$\eqalign{ f_n(x_1, \ldots, x_d) &= ((x_1+\cdots+x_{2r}) + x_{2r+1})^n \\ &= \sum_{k=0}^n \binom{n}{k} f_k(x_1, \ldots, x_{2r}) f_{n-k}(x_{2r+1}), }$$ giving $$f_n^{(2r+1)} = \sum_{k=0}^n \binom{n}{k} f_k^{(2r)} f_{n-k}^{(1)}.\tag{b}$$ In both cases, we may also reduce everything modulo $\mathcal I$, which is easily carried out beginning with $$f_n(x_j) \cong \left\{ \matrix{x^n & n \le m \\ 0 & n \gt m} \right. \mod \mathcal{I},$$ providing the starting values for the recursion, $$f_n^{(1)} = \left\{ \matrix{1 & n \le m \\ 0 & n \gt m} \right.$$ What makes this efficient is that by splitting the $d$ variables into two equal-sized groups of $r$ variables each and setting all variable values to $1,$ we only have to evaluate everything once for one group and then combine the results. This requires computing up to $n+1$ terms, each of them needing $O(n)$ calculation for the combination. We don't even need a 2D array to store the $f_n^{(r)}$, because when computing $f_n^{(d)},$ only $f_n^{(r)}$ and $f_n^{(1)}$ are required. The total number of steps is one less than the number of digits in the binary expansion of $d$ (which counts the splits into equal groups in formula $(a)$) plus the number of ones in the expansion (which counts all of the times an odd value is encountered, requiring the application of formula $(b)$). That's still just $O(\log(d))$ steps. In R on a decade-old workstation the work was done in 0.007 seconds. The code is listed at the end of this post. It uses logarithms of the probabilities, rather than the probabilities themselves, to avoid possible overflows or accumulating too much underflow. This makes it possible to remove the $d^{-n}$ factor in the solution so we may compute the counts that underlie the probabilities. Note that this procedure results in computing the whole sequence of probabilities $f_0, f_1, \ldots, f_n$ at once, which easily enables us to study how the chances change with $n$. Applications The distribution in the generalized Birthday Problem is computed by the function tmultinom.full. The only challenge lies in finding an upper bound for the number of people who must be present before the chance of an $m+1$-collision becomes too great. The following code does this by brute force, starting with small $n$ and doubling it until it's large enough. The whole calculation therefore takes $O(n^2\log(n)\log(d))$ time where $n$ is the solution. The entire distribution of probabilities for numbers of people up through $n$ is computed. # # The birthday problem: find the number of people where the chance of # a collision of `m+1` birthdays first exceeds `alpha`. # birthday <- function(m=1, d=365, alpha=0.50) { n <- 8 while((p <- tmultinom.full(n, m, d))[n] > alpha) n <- n * 2 return(p) } As an example, the minimum number of people needed in a crowd to make it more likely than not that at least eight of them share a birthday is $798$, as found by the calculation birthday(7). It takes just a couple of seconds. Here is a plot of part of the output: A special version of this problem is addressed at Extending the birthday paradox to more than 2 people, which concerns the case of a $365$-sided die that is rolled a very large number of times. Code # Compute the chance that in `n` independent rolls of a `d`-sided die, # no side appears more than `m` times. # tmultinom <- function(n, m, d, count=FALSE) tmultinom.full(n, m, d, count)[n+1] # # Compute the chances that in 0, 1, 2, ..., `n` independent rolls of a # `d`-sided die, no side appears more than `m` times. # tmultinom.full <- function(n, m, d, count=FALSE) { if (n < 0) return(numeric(0)) one <- rep(1.0, n+1); names(one) <- 0:n if (d <= 0 || m >= n) return(one) if(count) log.p <- 0 else log.p <- -log(d) f <- function(n, m, d) { # The recursive solution if (d==1) return(one) # Base case r <- floor(d/2) x <- double(f(n, m, r), m) # Combine two equal values if (2*r < d) x <- combine(x, one, m) # Treat odd `d` return(x) } one <- c(log.p*(0:m), rep(-Inf, n-m)) # Reduction modulo x^(m+1) double <- function(x, m) combine(x, x, m) combine <- function(x, y, m) { # The Binomial Theorem z <- sapply(1:length(x), function(n) { # Need all powers 0..n z <- x[1:n] + lchoose(n-1, 1:n-1) + y[n:1] z.max <- max(z) log(sum(exp(z - z.max), na.rm=TRUE)) + z.max }) return(z) } x <- exp(f(n, m, d)); names(x) <- 0:n return(x) } The answer is obtained with print(tmultinom(100,20,6), digits=15) 0.267747907805267
Die 100 rolls no face appearing more than 20 times
This is a generalization of the famous Birthday Problem: given $n=100$ individuals who have random, uniformly distributed "birthdays" among a set of $d=6$ possibilities, what is the chance that no bir
Die 100 rolls no face appearing more than 20 times This is a generalization of the famous Birthday Problem: given $n=100$ individuals who have random, uniformly distributed "birthdays" among a set of $d=6$ possibilities, what is the chance that no birthday is shared by more than $m=20$ individuals? An exact calculation yields the answer $0.267\,747\,907\,805\,267$ (to double precision). I will sketch the theory and provide the code for general $n, m, d.$ The code's asymptotic timing is $O(n^2\log(d))$ which makes it suitable for very large numbers of birthdays $d$ and provides reasonable performance until $n$ is in the thousands. At that point, the Poisson approximation discussed at Extending the birthday paradox to more than 2 people ought to work well in most cases. Explanation of the solution The probability generating function (pgf) for the outcomes of $n$ independent rolls of a $d$-sided die is $$d^{-n}f_n(x_1,x_2,\ldots,x_d) = d^{-n}(x_1+x_2+ \cdots + x_d)^n.$$ The coefficient of $x_1^{e_1}x_2^{e_2}\cdots x_d^{e_d}$ in the expansion of this multinomial gives the number of ways in which face $i$ can appear exactly $e_i$ times, $i=1, 2, \ldots, d.$ Limiting our interest to no more than $m$ appearances by any face is tantamount to evaluating $f_n$ modulo the ideal $\mathcal I$ generated by $x_1^{m+1}, x_2^{m+1}, \ldots, x_d^{m+1}.$ To perform this evaluation, use the Binomial Theorem recursively to obtain $$\eqalign{ f_n(x_1, \ldots, x_d) &= ((x_1+\cdots+x_r) + (x_{r+1}+x_{r+2} + \cdots + x_{2r}))^n \\ &= \sum_{k=0}^n \binom{n}{k} (x_1+\cdots+x_r)^k (x_{r+1}+\cdots+x_{2r})^{n-k} \\ &= \sum_{k=0}^n \binom{n}{k} f_k(x_1, \ldots, x_r) f_{n-k}(x_{r+1}, \ldots, x_{2r}) }$$ when $d=2r$ is even. Writing $f_n^{(d)} = f_n(1,1,\ldots, 1)$ ($d$ terms), we have $$f_n^{(2r)} = \sum_{k=0}^n \binom{n}{k} f_k^{(r)} f_{n-k}^{(r)}.\tag{a}$$ When $d=2r+1$ is odd, use an analogous decomposition $$\eqalign{ f_n(x_1, \ldots, x_d) &= ((x_1+\cdots+x_{2r}) + x_{2r+1})^n \\ &= \sum_{k=0}^n \binom{n}{k} f_k(x_1, \ldots, x_{2r}) f_{n-k}(x_{2r+1}), }$$ giving $$f_n^{(2r+1)} = \sum_{k=0}^n \binom{n}{k} f_k^{(2r)} f_{n-k}^{(1)}.\tag{b}$$ In both cases, we may also reduce everything modulo $\mathcal I$, which is easily carried out beginning with $$f_n(x_j) \cong \left\{ \matrix{x^n & n \le m \\ 0 & n \gt m} \right. \mod \mathcal{I},$$ providing the starting values for the recursion, $$f_n^{(1)} = \left\{ \matrix{1 & n \le m \\ 0 & n \gt m} \right.$$ What makes this efficient is that by splitting the $d$ variables into two equal-sized groups of $r$ variables each and setting all variable values to $1,$ we only have to evaluate everything once for one group and then combine the results. This requires computing up to $n+1$ terms, each of them needing $O(n)$ calculation for the combination. We don't even need a 2D array to store the $f_n^{(r)}$, because when computing $f_n^{(d)},$ only $f_n^{(r)}$ and $f_n^{(1)}$ are required. The total number of steps is one less than the number of digits in the binary expansion of $d$ (which counts the splits into equal groups in formula $(a)$) plus the number of ones in the expansion (which counts all of the times an odd value is encountered, requiring the application of formula $(b)$). That's still just $O(\log(d))$ steps. In R on a decade-old workstation the work was done in 0.007 seconds. The code is listed at the end of this post. It uses logarithms of the probabilities, rather than the probabilities themselves, to avoid possible overflows or accumulating too much underflow. This makes it possible to remove the $d^{-n}$ factor in the solution so we may compute the counts that underlie the probabilities. Note that this procedure results in computing the whole sequence of probabilities $f_0, f_1, \ldots, f_n$ at once, which easily enables us to study how the chances change with $n$. Applications The distribution in the generalized Birthday Problem is computed by the function tmultinom.full. The only challenge lies in finding an upper bound for the number of people who must be present before the chance of an $m+1$-collision becomes too great. The following code does this by brute force, starting with small $n$ and doubling it until it's large enough. The whole calculation therefore takes $O(n^2\log(n)\log(d))$ time where $n$ is the solution. The entire distribution of probabilities for numbers of people up through $n$ is computed. # # The birthday problem: find the number of people where the chance of # a collision of `m+1` birthdays first exceeds `alpha`. # birthday <- function(m=1, d=365, alpha=0.50) { n <- 8 while((p <- tmultinom.full(n, m, d))[n] > alpha) n <- n * 2 return(p) } As an example, the minimum number of people needed in a crowd to make it more likely than not that at least eight of them share a birthday is $798$, as found by the calculation birthday(7). It takes just a couple of seconds. Here is a plot of part of the output: A special version of this problem is addressed at Extending the birthday paradox to more than 2 people, which concerns the case of a $365$-sided die that is rolled a very large number of times. Code # Compute the chance that in `n` independent rolls of a `d`-sided die, # no side appears more than `m` times. # tmultinom <- function(n, m, d, count=FALSE) tmultinom.full(n, m, d, count)[n+1] # # Compute the chances that in 0, 1, 2, ..., `n` independent rolls of a # `d`-sided die, no side appears more than `m` times. # tmultinom.full <- function(n, m, d, count=FALSE) { if (n < 0) return(numeric(0)) one <- rep(1.0, n+1); names(one) <- 0:n if (d <= 0 || m >= n) return(one) if(count) log.p <- 0 else log.p <- -log(d) f <- function(n, m, d) { # The recursive solution if (d==1) return(one) # Base case r <- floor(d/2) x <- double(f(n, m, r), m) # Combine two equal values if (2*r < d) x <- combine(x, one, m) # Treat odd `d` return(x) } one <- c(log.p*(0:m), rep(-Inf, n-m)) # Reduction modulo x^(m+1) double <- function(x, m) combine(x, x, m) combine <- function(x, y, m) { # The Binomial Theorem z <- sapply(1:length(x), function(n) { # Need all powers 0..n z <- x[1:n] + lchoose(n-1, 1:n-1) + y[n:1] z.max <- max(z) log(sum(exp(z - z.max), na.rm=TRUE)) + z.max }) return(z) } x <- exp(f(n, m, d)); names(x) <- 0:n return(x) } The answer is obtained with print(tmultinom(100,20,6), digits=15) 0.267747907805267
Die 100 rolls no face appearing more than 20 times This is a generalization of the famous Birthday Problem: given $n=100$ individuals who have random, uniformly distributed "birthdays" among a set of $d=6$ possibilities, what is the chance that no bir
25,131
Die 100 rolls no face appearing more than 20 times
Random sampling method I ran this code in R replicating 100 die throws for a million times: y <- replicate(1000000, all(table(sample(1:6, size = 100, replace = TRUE)) <=20)) The output of the code inside the replicate function is true if all the faces appear less than or equal to 20 times. y is a vector with 1 million values of true or false. The total no. of true values in y divided by 1 million should be approximately equal to the probability you desire. In my case it was 266872/1000000, suggesting a probability of around 26.6%
Die 100 rolls no face appearing more than 20 times
Random sampling method I ran this code in R replicating 100 die throws for a million times: y <- replicate(1000000, all(table(sample(1:6, size = 100, replace = TRUE)) <=20)) The output of the code ins
Die 100 rolls no face appearing more than 20 times Random sampling method I ran this code in R replicating 100 die throws for a million times: y <- replicate(1000000, all(table(sample(1:6, size = 100, replace = TRUE)) <=20)) The output of the code inside the replicate function is true if all the faces appear less than or equal to 20 times. y is a vector with 1 million values of true or false. The total no. of true values in y divided by 1 million should be approximately equal to the probability you desire. In my case it was 266872/1000000, suggesting a probability of around 26.6%
Die 100 rolls no face appearing more than 20 times Random sampling method I ran this code in R replicating 100 die throws for a million times: y <- replicate(1000000, all(table(sample(1:6, size = 100, replace = TRUE)) <=20)) The output of the code ins
25,132
Die 100 rolls no face appearing more than 20 times
Brute force calculation This code takes a few seconds on my laptop total = 0 pb <- txtProgressBar(min = 0, max = 20^2, style = 3) for (i in 0:20) { for (j in 0:20) { for (k in 0:20) { for (l in 0:20) { for (m in 0:20) { n = 100-sum(i,j,k,l,m) if (n<=20) { total = total+dmultinom(c(i,j,k,l,m,n),100,prob=rep(1/6,6)) } } } } setTxtProgressBar(pb, i*20+j) # update progression bar } } total output: 0.2677479 But still it might be interesting to find a more direct method in case you wish to do lots of these calculations or use higher values, or just for the sake of getting a more elegant method. At least this computation gives a simplistically calculated, but valid, number to check other (more complicated) methods.
Die 100 rolls no face appearing more than 20 times
Brute force calculation This code takes a few seconds on my laptop total = 0 pb <- txtProgressBar(min = 0, max = 20^2, style = 3) for (i in 0:20) { for (j in 0:20) { for (k in 0:20) { for
Die 100 rolls no face appearing more than 20 times Brute force calculation This code takes a few seconds on my laptop total = 0 pb <- txtProgressBar(min = 0, max = 20^2, style = 3) for (i in 0:20) { for (j in 0:20) { for (k in 0:20) { for (l in 0:20) { for (m in 0:20) { n = 100-sum(i,j,k,l,m) if (n<=20) { total = total+dmultinom(c(i,j,k,l,m,n),100,prob=rep(1/6,6)) } } } } setTxtProgressBar(pb, i*20+j) # update progression bar } } total output: 0.2677479 But still it might be interesting to find a more direct method in case you wish to do lots of these calculations or use higher values, or just for the sake of getting a more elegant method. At least this computation gives a simplistically calculated, but valid, number to check other (more complicated) methods.
Die 100 rolls no face appearing more than 20 times Brute force calculation This code takes a few seconds on my laptop total = 0 pb <- txtProgressBar(min = 0, max = 20^2, style = 3) for (i in 0:20) { for (j in 0:20) { for (k in 0:20) { for
25,133
QQ Plot Reference Line not 45°
Should it be a 45 degree line? It depends! A QQ plot is the parametric curve defined by: \begin{align*} x &= F^{-1}(p)\\ y &= G^{-1}(p) \end{align*} for $p \in [0, 1]$. Where $F^{-1}$ and $G^{-1}$ are inverse CDF functions. If $F = G$ then $x(p)=y(p)$ and it would be on a 45 degree line. Another case... Let $\Phi^{-1}(p)$ be the standard normal inverse CDF. Let $F^{-1}(p) = \Phi^{-1}(p)$ Let $G^{-1}(p) = \sigma \Phi^{-1}(p) + \mu$ That is $G$ is the inverse CDF for a normally distributed random variable with mean $\mu$ and standard deviation $\sigma$ while $F$ is the inverse CDF for a standard normal variable (i.e. mean 0, standard deviation 1). Then we see: $$y(p) = \sigma \Phi^{-1}(p) + \mu = \sigma x(p) + \mu$$ That is, the plot is a line $y = \sigma x + \mu$ What's going on in your case? From the Matlab documentation for qqplot Superimposed on the plot is a line joining the first and third quartiles of each distribution (this is a robust linear fit of the order statistics of the two samples). This line is extrapolated out to the ends of the sample to help evaluate the linearity of the data. So even if you standardized your data, the red line MATLAB plots wouldn't be a 45 degree line if the 1st and 3rd quartiles didn't match the normal distribution.
QQ Plot Reference Line not 45°
Should it be a 45 degree line? It depends! A QQ plot is the parametric curve defined by: \begin{align*} x &= F^{-1}(p)\\ y &= G^{-1}(p) \end{align*} for $p \in [0, 1]$. Where $F^{-1}$ and $G^{-1}$ are
QQ Plot Reference Line not 45° Should it be a 45 degree line? It depends! A QQ plot is the parametric curve defined by: \begin{align*} x &= F^{-1}(p)\\ y &= G^{-1}(p) \end{align*} for $p \in [0, 1]$. Where $F^{-1}$ and $G^{-1}$ are inverse CDF functions. If $F = G$ then $x(p)=y(p)$ and it would be on a 45 degree line. Another case... Let $\Phi^{-1}(p)$ be the standard normal inverse CDF. Let $F^{-1}(p) = \Phi^{-1}(p)$ Let $G^{-1}(p) = \sigma \Phi^{-1}(p) + \mu$ That is $G$ is the inverse CDF for a normally distributed random variable with mean $\mu$ and standard deviation $\sigma$ while $F$ is the inverse CDF for a standard normal variable (i.e. mean 0, standard deviation 1). Then we see: $$y(p) = \sigma \Phi^{-1}(p) + \mu = \sigma x(p) + \mu$$ That is, the plot is a line $y = \sigma x + \mu$ What's going on in your case? From the Matlab documentation for qqplot Superimposed on the plot is a line joining the first and third quartiles of each distribution (this is a robust linear fit of the order statistics of the two samples). This line is extrapolated out to the ends of the sample to help evaluate the linearity of the data. So even if you standardized your data, the red line MATLAB plots wouldn't be a 45 degree line if the 1st and 3rd quartiles didn't match the normal distribution.
QQ Plot Reference Line not 45° Should it be a 45 degree line? It depends! A QQ plot is the parametric curve defined by: \begin{align*} x &= F^{-1}(p)\\ y &= G^{-1}(p) \end{align*} for $p \in [0, 1]$. Where $F^{-1}$ and $G^{-1}$ are
25,134
QQ Plot Reference Line not 45°
How the line is determined varies from package to package but one common way is to join the lower-quartile point $(x,y)=(-0.6745,Q_1)$ to the upper-quartile point $(0.6745,Q_3)$. Looking at the Matlab help for qqplot, that's actually what it says Matlab does. The sample distribution is peaked and heavy-tailed in a manner that makes its quartiles closer together than they are for a normal with the same standard deviation, which makes the slope nearer to 0.7 than to 1.
QQ Plot Reference Line not 45°
How the line is determined varies from package to package but one common way is to join the lower-quartile point $(x,y)=(-0.6745,Q_1)$ to the upper-quartile point $(0.6745,Q_3)$. Looking at the Matla
QQ Plot Reference Line not 45° How the line is determined varies from package to package but one common way is to join the lower-quartile point $(x,y)=(-0.6745,Q_1)$ to the upper-quartile point $(0.6745,Q_3)$. Looking at the Matlab help for qqplot, that's actually what it says Matlab does. The sample distribution is peaked and heavy-tailed in a manner that makes its quartiles closer together than they are for a normal with the same standard deviation, which makes the slope nearer to 0.7 than to 1.
QQ Plot Reference Line not 45° How the line is determined varies from package to package but one common way is to join the lower-quartile point $(x,y)=(-0.6745,Q_1)$ to the upper-quartile point $(0.6745,Q_3)$. Looking at the Matla
25,135
PCA vs. random projection
PCA maintains the best possible projection. Some reasons you would use random projections are: With very high dimensions, if speed is an issue, then consider that on a matrix of size $n \times k$, PCA takes $O(k^2 \times n+k^3)$ time, whereas a random projection takes $O(nkd)$, where you're projecting on a subspace of size $d$. With a sparse matrix its even faster. The data may well be low-dimensional, but not in a linear subspace. PCA assumes this. Random projection are also quite fast for reducing the dimension of a mixture of Gaussians. If the data is very large, you don't need to hold it in memory for a random projections, whereas for PCA you do. In general PCA works well on relatively low dimensional data.
PCA vs. random projection
PCA maintains the best possible projection. Some reasons you would use random projections are: With very high dimensions, if speed is an issue, then consider that on a matrix of size $n \times k$, PC
PCA vs. random projection PCA maintains the best possible projection. Some reasons you would use random projections are: With very high dimensions, if speed is an issue, then consider that on a matrix of size $n \times k$, PCA takes $O(k^2 \times n+k^3)$ time, whereas a random projection takes $O(nkd)$, where you're projecting on a subspace of size $d$. With a sparse matrix its even faster. The data may well be low-dimensional, but not in a linear subspace. PCA assumes this. Random projection are also quite fast for reducing the dimension of a mixture of Gaussians. If the data is very large, you don't need to hold it in memory for a random projections, whereas for PCA you do. In general PCA works well on relatively low dimensional data.
PCA vs. random projection PCA maintains the best possible projection. Some reasons you would use random projections are: With very high dimensions, if speed is an issue, then consider that on a matrix of size $n \times k$, PC
25,136
PCA vs. random projection
I would add another reason which is valid for an online setting: PCA might give you the best projection for some initial training data but it might become arbitrarily worse as time goes by and new data arrives with an "evolved" distribution. Random projections gives you a kind of probabilistic warranty against that situation. Of course, eventually k might become too low if d is increasing over time but, anyway, in this scenario of continuously learning from large streams of data, I believe random projections are a sensible and efficient approach.
PCA vs. random projection
I would add another reason which is valid for an online setting: PCA might give you the best projection for some initial training data but it might become arbitrarily worse as time goes by and new dat
PCA vs. random projection I would add another reason which is valid for an online setting: PCA might give you the best projection for some initial training data but it might become arbitrarily worse as time goes by and new data arrives with an "evolved" distribution. Random projections gives you a kind of probabilistic warranty against that situation. Of course, eventually k might become too low if d is increasing over time but, anyway, in this scenario of continuously learning from large streams of data, I believe random projections are a sensible and efficient approach.
PCA vs. random projection I would add another reason which is valid for an online setting: PCA might give you the best projection for some initial training data but it might become arbitrarily worse as time goes by and new dat
25,137
PCA vs. random projection
If one only wants to approximate pairwise Euclidean distance between points (which may be useful for downstream computation like t-SNE) but the dimensionality makes computing the pairwise Euclidean distance prohibitively expensive, the Johnson-Lindenstrauss lemma makes random projections more suitable than PCA. For $n$ points in $d$ dimensions projection to $\frac{log(n)}{\epsilon^2}$ preserves the Euclidean distance between points to $1\pm \epsilon$ with high probability. I don’t know of any similar guarantees from PCA.
PCA vs. random projection
If one only wants to approximate pairwise Euclidean distance between points (which may be useful for downstream computation like t-SNE) but the dimensionality makes computing the pairwise Euclidean di
PCA vs. random projection If one only wants to approximate pairwise Euclidean distance between points (which may be useful for downstream computation like t-SNE) but the dimensionality makes computing the pairwise Euclidean distance prohibitively expensive, the Johnson-Lindenstrauss lemma makes random projections more suitable than PCA. For $n$ points in $d$ dimensions projection to $\frac{log(n)}{\epsilon^2}$ preserves the Euclidean distance between points to $1\pm \epsilon$ with high probability. I don’t know of any similar guarantees from PCA.
PCA vs. random projection If one only wants to approximate pairwise Euclidean distance between points (which may be useful for downstream computation like t-SNE) but the dimensionality makes computing the pairwise Euclidean di
25,138
Can standardized $\beta$ coefficients in linear regression be used to estimate the $R^2$?
The geometric interpretation of ordinary least squares regression provides the requisite insight. Most of what we need to know can be seen in the case of two regressors $x_1$ and $x_2$ with response $y$. The standardized coefficients, or "betas," arise when all three vectors are standardized to a common length (which we may take to be unity). Thus, $x_1$ and $x_2$ are unit vectors in a plane $E^2$--they are located on the unit circle--and $y$ is a unit vector in a three dimensional Euclidean space $E^3$ containing that plane. The fitted value $\hat y$ is the orthogonal (perpendicular) projection of $y$ onto $E^2$. Because $R^2$ simply is the squared length of $\hat y$, we needn't even visualize all three dimensions: all the information we need can be drawn in that plane. Orthogonal regressors The nicest situation is when the regressors are orthogonal, as in the first figure. In this and the rest of the figures I will consistently draw the unit disk in white and the regressors as black arrows. $x_1$ will always point directly to the right. The thick red arrows depict the components of $\hat y$ in the $x_1$ and $x_2$ directions: that is, $\beta_1 x_1$ and $\beta_2 x_2$. The length of $\hat y$ is the radius of the gray circle on which it lies--but remember that $R^2$ is the square of that length. The Pythagorean Theorem asserts $$R^2 = |\hat y|^2 = |\beta_1 x_1|^2 + |\beta_2 x_2|^2 = \beta_1^2(1)+\beta_2^2(1) = \beta_1^2 + \beta_2^2.$$ Because the Pythagorean Theorem holds in any number of dimensions, this reasoning generalizes to any number of regressors, yielding our first result: When the regressors are orthogonal, $R^2$ equals the sum of the squares of the betas. An immediate corollary is that when there is just one regressor--univariate regression--$R^2$ is the square of the standardized slope. Correlated Negatively correlated regressors meet at angles greater than a right angle. It is visually apparent in this image that the sum of squares of the betas is strictly greater than $R^2$. This can be proven algebraically using the Law of Cosines or by working with matrix solution of the Normal Equations. By making the two regressors almost parallel, we can position $\hat y$ near the origin (for an $R^2$ near $0$) while it continues to have large components in the $x_1$ and $x_2$ direction. Thus, there is no limit to how small $R^2$ might be. Let's memorialize this obvious result, our second generality: When regressors are correlated, $R^2$ may be arbitrarily smaller than the sum of squares of the betas. However, this is not a universal relation, as the next figure demonstrates. Now $R^2$ strictly exceeds the sum of squares of the betas. By drawing the two regressors close together and keeping $\hat y$ between them, we may make the betas both approach $1/2$, even when $R^2$ is close to $1$. Further analysis may require some algebra: I take that up below. I leave it to your imagination to construct similar examples with positively correlated regressors, which thereby meet at acute angles. Notice that these conclusions are incomplete: there are limits to how much less $R^2$ may be compared to the sum of squares of the betas. In particular, by examining the possibilities carefully, you may conclude (for a regression with two regressors) that When the regressors are positively correlated and the betas have a common sign, or when the regressors are negatively correlated and the betas have different signs, $R^2$ must be at least as large as the sum of the squares of the betas. Algebraic results Generally, let the regressors be (column vectors) $x_1, x_2, \ldots, x_p$ and the response be $y$. Standardization means (a) each is orthogonal to the vector $(1,1,\ldots,1)^\prime$ and (b) they have unit lengths: $$|x_i|^2 = |y|^2 = 1.$$ Assemble the column vectors $x_i$ into an $n\times p$ matrix $X$. The rules of matrix multiplication imply that $$\Sigma = X^\prime X$$ is the correlation matrix of the $x_i$. The betas are given by the Normal Equations, $$\beta = (X^\prime X)^{-1} X^\prime y = \Sigma^{-1} (X^\prime y).$$ Moreover, by definition, the fit is $$\hat y = X \beta = X (\Sigma ^{-1} X^\prime y).$$ Its squared length gives $R^2$ by definition: $$R^2 = |\hat y|^2 = \hat y^\prime \hat y = (X\beta)^\prime (X\beta) = \beta^\prime (X^\prime X)\beta = \beta^\prime \Sigma\beta. $$ The geometric analysis suggested we look for inequalities relating $R^2$ and the sum of squares of the betas, $$\sum_{i=1}^p \beta_i^2 = \beta^\prime \beta.$$ The $L_2$ norm of any matrix $A$ is given by the sum of squares of its coefficients (basically treating the matrix as a vector of $p^2$ components in a Euclidean space), $$|A|_2^2 = \sum_{i,j} a_{ij}^2 = \operatorname{tr}(A^\prime A) = \operatorname{tr}(AA^\prime).$$ The Cauchy-Schwarz Inequality implies $$R^2 = \operatorname{tr}(R^2) = \operatorname{tr}(\beta^\prime \Sigma \beta) = \operatorname{tr}(\Sigma \beta \beta^\prime) \le |\Sigma|_2 | \beta\beta^\prime|_2 = |\Sigma|_2 \beta^\prime \beta.$$ Since squared correlation coefficients cannot exceed $1$ and there are just $p^2$ of them in the $p\times p$ matrix $\Sigma$, $|\Sigma|_2$ cannot exceed $\sqrt{1\times p^2} = p$. Therefore $$R^2 \le p\, \beta^\prime \beta.$$ The inequality is attained, for instance, when all the $x_i$ are perfectly positively correlated. There is an upper limit on how large $R^2$ may be. Its average value per regressor, $R^2/p$, cannot exceed the sum of squares of the standardized coefficients. Conclusions What may we conclude in general? Evidently, information about the correlation structure of the regressors as well as the signs of the betas could be used either to bound the possible values of $R^2$ or even to compute it exactly. Absent that full information, little can be said beyond the obvious fact that when the regressors are linearly independent, a single nonzero beta implies $\hat y$ is nonzero, demonstrating $R^2$ is nonzero. One thing we can definitely conclude from the output in the question is that the data are correlated: because the sum of squares of the betas, equal to $1.1301$, exceeds the maximum possible value of $R^2$ (namely $1$), there must be some correlation. Another thing is that since the largest beta (in size) is $-0.83$, whose square is $0.69$--far exceeding the reported $R^2$ of $0.20$--we may conclude that some of the regressors must be negatively correlated. (In fact, $\text{VO}_{2\,\text{max}}$ is likely strongly negatively correlated with age, weight, and fat in any sample that covers a wide range of values of the latter.) If there were only two regressors, we could deduce a great deal more about $R^2$ from knowledge of high regressor correlations and inspection of the betas, because this would enable us to draw an accurate sketch of how $x_1$, $x_2$, and $\hat y$ must be situated. Unfortunately, the additional regressors in this six-variable problem complicate things considerably. In analyzing any two of the variables, we have to "take out" or "control for" the other four regressors (the "covariates"). In so doing, we shorten all of $x_1$, $x_2$, and $y$ by unknown amounts (depending on how all three of those are related to the covariates), leaving us knowing almost nothing about the actual sizes of the vectors we are working with.
Can standardized $\beta$ coefficients in linear regression be used to estimate the $R^2$?
The geometric interpretation of ordinary least squares regression provides the requisite insight. Most of what we need to know can be seen in the case of two regressors $x_1$ and $x_2$ with response $
Can standardized $\beta$ coefficients in linear regression be used to estimate the $R^2$? The geometric interpretation of ordinary least squares regression provides the requisite insight. Most of what we need to know can be seen in the case of two regressors $x_1$ and $x_2$ with response $y$. The standardized coefficients, or "betas," arise when all three vectors are standardized to a common length (which we may take to be unity). Thus, $x_1$ and $x_2$ are unit vectors in a plane $E^2$--they are located on the unit circle--and $y$ is a unit vector in a three dimensional Euclidean space $E^3$ containing that plane. The fitted value $\hat y$ is the orthogonal (perpendicular) projection of $y$ onto $E^2$. Because $R^2$ simply is the squared length of $\hat y$, we needn't even visualize all three dimensions: all the information we need can be drawn in that plane. Orthogonal regressors The nicest situation is when the regressors are orthogonal, as in the first figure. In this and the rest of the figures I will consistently draw the unit disk in white and the regressors as black arrows. $x_1$ will always point directly to the right. The thick red arrows depict the components of $\hat y$ in the $x_1$ and $x_2$ directions: that is, $\beta_1 x_1$ and $\beta_2 x_2$. The length of $\hat y$ is the radius of the gray circle on which it lies--but remember that $R^2$ is the square of that length. The Pythagorean Theorem asserts $$R^2 = |\hat y|^2 = |\beta_1 x_1|^2 + |\beta_2 x_2|^2 = \beta_1^2(1)+\beta_2^2(1) = \beta_1^2 + \beta_2^2.$$ Because the Pythagorean Theorem holds in any number of dimensions, this reasoning generalizes to any number of regressors, yielding our first result: When the regressors are orthogonal, $R^2$ equals the sum of the squares of the betas. An immediate corollary is that when there is just one regressor--univariate regression--$R^2$ is the square of the standardized slope. Correlated Negatively correlated regressors meet at angles greater than a right angle. It is visually apparent in this image that the sum of squares of the betas is strictly greater than $R^2$. This can be proven algebraically using the Law of Cosines or by working with matrix solution of the Normal Equations. By making the two regressors almost parallel, we can position $\hat y$ near the origin (for an $R^2$ near $0$) while it continues to have large components in the $x_1$ and $x_2$ direction. Thus, there is no limit to how small $R^2$ might be. Let's memorialize this obvious result, our second generality: When regressors are correlated, $R^2$ may be arbitrarily smaller than the sum of squares of the betas. However, this is not a universal relation, as the next figure demonstrates. Now $R^2$ strictly exceeds the sum of squares of the betas. By drawing the two regressors close together and keeping $\hat y$ between them, we may make the betas both approach $1/2$, even when $R^2$ is close to $1$. Further analysis may require some algebra: I take that up below. I leave it to your imagination to construct similar examples with positively correlated regressors, which thereby meet at acute angles. Notice that these conclusions are incomplete: there are limits to how much less $R^2$ may be compared to the sum of squares of the betas. In particular, by examining the possibilities carefully, you may conclude (for a regression with two regressors) that When the regressors are positively correlated and the betas have a common sign, or when the regressors are negatively correlated and the betas have different signs, $R^2$ must be at least as large as the sum of the squares of the betas. Algebraic results Generally, let the regressors be (column vectors) $x_1, x_2, \ldots, x_p$ and the response be $y$. Standardization means (a) each is orthogonal to the vector $(1,1,\ldots,1)^\prime$ and (b) they have unit lengths: $$|x_i|^2 = |y|^2 = 1.$$ Assemble the column vectors $x_i$ into an $n\times p$ matrix $X$. The rules of matrix multiplication imply that $$\Sigma = X^\prime X$$ is the correlation matrix of the $x_i$. The betas are given by the Normal Equations, $$\beta = (X^\prime X)^{-1} X^\prime y = \Sigma^{-1} (X^\prime y).$$ Moreover, by definition, the fit is $$\hat y = X \beta = X (\Sigma ^{-1} X^\prime y).$$ Its squared length gives $R^2$ by definition: $$R^2 = |\hat y|^2 = \hat y^\prime \hat y = (X\beta)^\prime (X\beta) = \beta^\prime (X^\prime X)\beta = \beta^\prime \Sigma\beta. $$ The geometric analysis suggested we look for inequalities relating $R^2$ and the sum of squares of the betas, $$\sum_{i=1}^p \beta_i^2 = \beta^\prime \beta.$$ The $L_2$ norm of any matrix $A$ is given by the sum of squares of its coefficients (basically treating the matrix as a vector of $p^2$ components in a Euclidean space), $$|A|_2^2 = \sum_{i,j} a_{ij}^2 = \operatorname{tr}(A^\prime A) = \operatorname{tr}(AA^\prime).$$ The Cauchy-Schwarz Inequality implies $$R^2 = \operatorname{tr}(R^2) = \operatorname{tr}(\beta^\prime \Sigma \beta) = \operatorname{tr}(\Sigma \beta \beta^\prime) \le |\Sigma|_2 | \beta\beta^\prime|_2 = |\Sigma|_2 \beta^\prime \beta.$$ Since squared correlation coefficients cannot exceed $1$ and there are just $p^2$ of them in the $p\times p$ matrix $\Sigma$, $|\Sigma|_2$ cannot exceed $\sqrt{1\times p^2} = p$. Therefore $$R^2 \le p\, \beta^\prime \beta.$$ The inequality is attained, for instance, when all the $x_i$ are perfectly positively correlated. There is an upper limit on how large $R^2$ may be. Its average value per regressor, $R^2/p$, cannot exceed the sum of squares of the standardized coefficients. Conclusions What may we conclude in general? Evidently, information about the correlation structure of the regressors as well as the signs of the betas could be used either to bound the possible values of $R^2$ or even to compute it exactly. Absent that full information, little can be said beyond the obvious fact that when the regressors are linearly independent, a single nonzero beta implies $\hat y$ is nonzero, demonstrating $R^2$ is nonzero. One thing we can definitely conclude from the output in the question is that the data are correlated: because the sum of squares of the betas, equal to $1.1301$, exceeds the maximum possible value of $R^2$ (namely $1$), there must be some correlation. Another thing is that since the largest beta (in size) is $-0.83$, whose square is $0.69$--far exceeding the reported $R^2$ of $0.20$--we may conclude that some of the regressors must be negatively correlated. (In fact, $\text{VO}_{2\,\text{max}}$ is likely strongly negatively correlated with age, weight, and fat in any sample that covers a wide range of values of the latter.) If there were only two regressors, we could deduce a great deal more about $R^2$ from knowledge of high regressor correlations and inspection of the betas, because this would enable us to draw an accurate sketch of how $x_1$, $x_2$, and $\hat y$ must be situated. Unfortunately, the additional regressors in this six-variable problem complicate things considerably. In analyzing any two of the variables, we have to "take out" or "control for" the other four regressors (the "covariates"). In so doing, we shorten all of $x_1$, $x_2$, and $y$ by unknown amounts (depending on how all three of those are related to the covariates), leaving us knowing almost nothing about the actual sizes of the vectors we are working with.
Can standardized $\beta$ coefficients in linear regression be used to estimate the $R^2$? The geometric interpretation of ordinary least squares regression provides the requisite insight. Most of what we need to know can be seen in the case of two regressors $x_1$ and $x_2$ with response $
25,139
Is it possible to train neural network to draw picture in a certain style?
There is a relevant paper: LA Gatus, AS Ecker, M Bethge, 2015, A Neural Algorithm of Artistic Style. Quoting from the abstract, Here we introduce an artificial system based on a Deep Neural Network that creates artistic images of high perceptual quality. The system uses neural representations to separate and recombine content and style of arbitrary images, providing a neural algorithm for the creation of artistic images. Here is Figure 2 from this paper: There is also a very popular open-source implementation based on torch here which is quite easy to use. See the link for more examples. Keep in mind, that the computations are heavy and therefore the processing of single images is the scope of this work. Edit: after checking your mentioned DeepArt project, it seems it is using the same techniques. I'm not sure why this is not what you want, because the concept of style-transfer is as general as it gets.
Is it possible to train neural network to draw picture in a certain style?
There is a relevant paper: LA Gatus, AS Ecker, M Bethge, 2015, A Neural Algorithm of Artistic Style. Quoting from the abstract, Here we introduce an artificial system based on a Deep Neural Network t
Is it possible to train neural network to draw picture in a certain style? There is a relevant paper: LA Gatus, AS Ecker, M Bethge, 2015, A Neural Algorithm of Artistic Style. Quoting from the abstract, Here we introduce an artificial system based on a Deep Neural Network that creates artistic images of high perceptual quality. The system uses neural representations to separate and recombine content and style of arbitrary images, providing a neural algorithm for the creation of artistic images. Here is Figure 2 from this paper: There is also a very popular open-source implementation based on torch here which is quite easy to use. See the link for more examples. Keep in mind, that the computations are heavy and therefore the processing of single images is the scope of this work. Edit: after checking your mentioned DeepArt project, it seems it is using the same techniques. I'm not sure why this is not what you want, because the concept of style-transfer is as general as it gets.
Is it possible to train neural network to draw picture in a certain style? There is a relevant paper: LA Gatus, AS Ecker, M Bethge, 2015, A Neural Algorithm of Artistic Style. Quoting from the abstract, Here we introduce an artificial system based on a Deep Neural Network t
25,140
Is it possible to train neural network to draw picture in a certain style?
This is a pretty difficult problem to solve. You can see some examples here on how a cartoon style, e.g. from the Simpson's has been applied to an image. A cartoon image generally doesn't have the structure that gives this artsy effect. The easiest way to try to apply this in some way would be to have a face-tracker, and then try to align two faces, e.g. a cartoon face and a human face, and then apply this. That might get you somewhere, but it might also look weird. You might then annotate landmarks in the images to help further and do a non-rigid registration before this. This is still somewhat a shitmix solution, but the closest I can think of that could work for faces. Edit: The comment by @TannerSwett adds something to this, it is potential to go onto some artists webpages and try to find their illustrations and try to learn "their" style. I still do not think that will satisfactory or yield enough data, but that would be an interesting thing to test. There is no generally available solution right now, but I think that are definitely some people working on this, and we will see better results soon. I think that maybe the way to go is not the artistic neural network approach. Maybe it is better to have a network that can classify objects in an image and then learn the correspondences between the objects and their cartoon counterparts, then blend the results in some meaningful way.
Is it possible to train neural network to draw picture in a certain style?
This is a pretty difficult problem to solve. You can see some examples here on how a cartoon style, e.g. from the Simpson's has been applied to an image. A cartoon image generally doesn't have the st
Is it possible to train neural network to draw picture in a certain style? This is a pretty difficult problem to solve. You can see some examples here on how a cartoon style, e.g. from the Simpson's has been applied to an image. A cartoon image generally doesn't have the structure that gives this artsy effect. The easiest way to try to apply this in some way would be to have a face-tracker, and then try to align two faces, e.g. a cartoon face and a human face, and then apply this. That might get you somewhere, but it might also look weird. You might then annotate landmarks in the images to help further and do a non-rigid registration before this. This is still somewhat a shitmix solution, but the closest I can think of that could work for faces. Edit: The comment by @TannerSwett adds something to this, it is potential to go onto some artists webpages and try to find their illustrations and try to learn "their" style. I still do not think that will satisfactory or yield enough data, but that would be an interesting thing to test. There is no generally available solution right now, but I think that are definitely some people working on this, and we will see better results soon. I think that maybe the way to go is not the artistic neural network approach. Maybe it is better to have a network that can classify objects in an image and then learn the correspondences between the objects and their cartoon counterparts, then blend the results in some meaningful way.
Is it possible to train neural network to draw picture in a certain style? This is a pretty difficult problem to solve. You can see some examples here on how a cartoon style, e.g. from the Simpson's has been applied to an image. A cartoon image generally doesn't have the st
25,141
Is it possible to train neural network to draw picture in a certain style?
It shouldn't be too complicated to do. Haven't read the article mentioned, here's my recipe: Variational Auto Encoders Online demo with morphing faces: http://vdumoulin.github.io/morphing_faces/online_demo.html and https://jmetzen.github.io/2015-11-27/vae.html for teh codez. Basically, this gives you a way to parametrize the 'style' in your case, for example let's say how wide or fuzzy should the brush stroke be. Stuff that depends on the particular style you are trying to emulate. In the example above different 'morphed' or 'imagined' faces are a function of the parameters in the latent space. In the image below that would be what you get by changing stuff at the 'code' level. Here's the basic idea: original image left, stylised version of the same image on the right: Now, in theory, if you would train such a model on a normal image and a stylised image as a target and add convolutions, you should be able to learn the kernel filters that correspond to the type of "brush strokes" that the artist uses. Of course, that means that you need to have a few examples of images in both original and stylized versions. Such a dataset would be nice to donate to the community - if you end up doing this I'd be very keen to see this sort of work. Good luck! The wiki article on auto encoders would be a good starting point: https://en.wikipedia.org/wiki/Autoencoder
Is it possible to train neural network to draw picture in a certain style?
It shouldn't be too complicated to do. Haven't read the article mentioned, here's my recipe: Variational Auto Encoders Online demo with morphing faces: http://vdumoulin.github.io/morphing_faces/on
Is it possible to train neural network to draw picture in a certain style? It shouldn't be too complicated to do. Haven't read the article mentioned, here's my recipe: Variational Auto Encoders Online demo with morphing faces: http://vdumoulin.github.io/morphing_faces/online_demo.html and https://jmetzen.github.io/2015-11-27/vae.html for teh codez. Basically, this gives you a way to parametrize the 'style' in your case, for example let's say how wide or fuzzy should the brush stroke be. Stuff that depends on the particular style you are trying to emulate. In the example above different 'morphed' or 'imagined' faces are a function of the parameters in the latent space. In the image below that would be what you get by changing stuff at the 'code' level. Here's the basic idea: original image left, stylised version of the same image on the right: Now, in theory, if you would train such a model on a normal image and a stylised image as a target and add convolutions, you should be able to learn the kernel filters that correspond to the type of "brush strokes" that the artist uses. Of course, that means that you need to have a few examples of images in both original and stylized versions. Such a dataset would be nice to donate to the community - if you end up doing this I'd be very keen to see this sort of work. Good luck! The wiki article on auto encoders would be a good starting point: https://en.wikipedia.org/wiki/Autoencoder
Is it possible to train neural network to draw picture in a certain style? It shouldn't be too complicated to do. Haven't read the article mentioned, here's my recipe: Variational Auto Encoders Online demo with morphing faces: http://vdumoulin.github.io/morphing_faces/on
25,142
Will larger correlation coefficient values result in greater slopes between x and y?
The answer is "not necessarily" — how correlated the variables are dictates how "noisy" the scatter plot is, but not how steep. In fact, the correlation and regression slope are telling you two quite different things. The slope estimates how many units $y$ increases, on average, per one unit increase in $x$. The correlation measures the strength and direction of that linear relationship (how closely the points fit to a line, and whether the trend is increasing or decreasing) on a scale between $-1$ and $1$, but which does not depend on the units of measurement of the $x$ and $y$ axes. Clearly you can have a steeper line which has a worse linear fit, for example in the following diagram. Note we can scale our $x$ and $y$ axes up or down by some scale factor (which is equivalent to a change in the units of measurement: for instance, switching from metres to centimetres makes the numerical values recorded 100 times larger) and this doesn't change the correlation. It will, however, change the slope. For example, consider the data set $\{(0,0), (1,2), (2,4), (3,6)\}$. Clearly the line of best fit will be $y=2x$ and the correlation will be $r=+1$ (there is a perfect linear fit, and the line is sloping upwards). Now consider the data set $\{(0,0), (1,200), (2,400), (3,600)\}$, where we have scaled up the $y$ values by a factor of $100$; this is equivalent to switching $y$ from being measured in metres to being measured in centimetres. The correlation is still $+1$ but the equation of the line of best fit is now $y=200x$, with a much steeper slope of $200$. Evidently we can have the same correlation but a different slope. Moreover, if we now introduce some "noise" (random error) to the second data set, we might end up with $\{(0,0.21), (1,199.57), (2,400.28), (3,600.09)\}$. This slightly changes the fitted regression line, but not much: the new equation is $y = 200.035x - 0.015$, with a slope of $200.035$. This is still a much steeper line than the original $y=2x$. And yet this time, the regression line is not a perfect fit, so the correlation is below one ($r=0.9999992$). So we have found a line with higher slope but lower correlation, which shows that slope and correlation do not always go hand in hand. Considering the effect of adding some random noise, and of rescaling the axes, is quite instructive in general when trying to understand regression. Moreover, suppose you did have two data sets, where the first has higher (let's keep it positive) correlation and slope than the second; $r_1 > r_2 > 0$ and $b_1 > b_2 > 0$. It will always be possible to find some scale factor $k$ that we can multiply the $y$ values of the second data set by, such that after rescaling the new data set has a steeper slope than the first data set. We just pick any $k > b_1/b_2$. The new data set has slope $b_3 = k b_2 > b_1$ but its correlation is unchanged from before the scaling, $r_3 = r_2 < r_1$. So from any pair of data sets that does obey "greater correlation with greater slope", we can transform the data sets into a pair where the set with greater correlation has a lower slope. Okay, so what do the correlation and slope have to do with each other? The (least-squares regression) slope and the (Pearson product-moment) correlation always have the same sign. The parenthetical remarks are to point out that regression slopes calculated some other way (e.g. least absolute deviations regression), and other types of correlation coefficient (for example Spearman's rank), need not obey the same relationship. The correlation and slope will be identical if the $x$ and $y$ variables have been standardised (rescaled to have unit standard deviation). (NB this doesn't apply to standardised slopes in multiple regression, when we introduce several predictor variables.) If we held the standard deviations of $x$ and $y$ constant, then it is true that "higher correlation means higher slope". Now, all three of these facts can be deduced (check you can prove each of them!) from the following formula: $$\text{slope} = \frac{\text{SD of y}}{\text{SD of x}} \cdot \text{correlation}$$ This might help you understand why the rescaling approach I used before changes the slope even though the correlation remains the same: rescaling $y$ by some factor will also scale its standard deviation. So for instance, doubling $y$ will double the slope. Now, what do you think will happen if we rescale $x$ instead? R code for plot set.seed(1234567) x1<-c(1,3,5,7,9) x2 <- c(2,4,6,8,10) y1 <- 3*x1 + rnorm(5,0,1) y2 <- 10 + 6*x2 + rnorm(5,0,10) plot(x2,y2, col="red", pch=16, xlim=c(0,10), ylim=c(0,80), xlab="x", ylab="y") points(x1,y1, col="blue", pch=16) abline(lm(y1~x1), col="blue") abline(lm(y2~x2), col="red") text(2,40,paste("Correlation =",round(cor(x2,y2), digits = 3))) text(6,5,paste("Correlation =",round(cor(x1,y1), digits = 3))) text(2,45,paste("Slope =",round(coef(summary(lm(y2~x2)))["x2", "Estimate"], digits = 3))) text(6,10,paste("Slope =",round(coef(summary(lm(y1~x1)))["x1", "Estimate"], digits = 3)))
Will larger correlation coefficient values result in greater slopes between x and y?
The answer is "not necessarily" — how correlated the variables are dictates how "noisy" the scatter plot is, but not how steep. In fact, the correlation and regression slope are telling you two quite
Will larger correlation coefficient values result in greater slopes between x and y? The answer is "not necessarily" — how correlated the variables are dictates how "noisy" the scatter plot is, but not how steep. In fact, the correlation and regression slope are telling you two quite different things. The slope estimates how many units $y$ increases, on average, per one unit increase in $x$. The correlation measures the strength and direction of that linear relationship (how closely the points fit to a line, and whether the trend is increasing or decreasing) on a scale between $-1$ and $1$, but which does not depend on the units of measurement of the $x$ and $y$ axes. Clearly you can have a steeper line which has a worse linear fit, for example in the following diagram. Note we can scale our $x$ and $y$ axes up or down by some scale factor (which is equivalent to a change in the units of measurement: for instance, switching from metres to centimetres makes the numerical values recorded 100 times larger) and this doesn't change the correlation. It will, however, change the slope. For example, consider the data set $\{(0,0), (1,2), (2,4), (3,6)\}$. Clearly the line of best fit will be $y=2x$ and the correlation will be $r=+1$ (there is a perfect linear fit, and the line is sloping upwards). Now consider the data set $\{(0,0), (1,200), (2,400), (3,600)\}$, where we have scaled up the $y$ values by a factor of $100$; this is equivalent to switching $y$ from being measured in metres to being measured in centimetres. The correlation is still $+1$ but the equation of the line of best fit is now $y=200x$, with a much steeper slope of $200$. Evidently we can have the same correlation but a different slope. Moreover, if we now introduce some "noise" (random error) to the second data set, we might end up with $\{(0,0.21), (1,199.57), (2,400.28), (3,600.09)\}$. This slightly changes the fitted regression line, but not much: the new equation is $y = 200.035x - 0.015$, with a slope of $200.035$. This is still a much steeper line than the original $y=2x$. And yet this time, the regression line is not a perfect fit, so the correlation is below one ($r=0.9999992$). So we have found a line with higher slope but lower correlation, which shows that slope and correlation do not always go hand in hand. Considering the effect of adding some random noise, and of rescaling the axes, is quite instructive in general when trying to understand regression. Moreover, suppose you did have two data sets, where the first has higher (let's keep it positive) correlation and slope than the second; $r_1 > r_2 > 0$ and $b_1 > b_2 > 0$. It will always be possible to find some scale factor $k$ that we can multiply the $y$ values of the second data set by, such that after rescaling the new data set has a steeper slope than the first data set. We just pick any $k > b_1/b_2$. The new data set has slope $b_3 = k b_2 > b_1$ but its correlation is unchanged from before the scaling, $r_3 = r_2 < r_1$. So from any pair of data sets that does obey "greater correlation with greater slope", we can transform the data sets into a pair where the set with greater correlation has a lower slope. Okay, so what do the correlation and slope have to do with each other? The (least-squares regression) slope and the (Pearson product-moment) correlation always have the same sign. The parenthetical remarks are to point out that regression slopes calculated some other way (e.g. least absolute deviations regression), and other types of correlation coefficient (for example Spearman's rank), need not obey the same relationship. The correlation and slope will be identical if the $x$ and $y$ variables have been standardised (rescaled to have unit standard deviation). (NB this doesn't apply to standardised slopes in multiple regression, when we introduce several predictor variables.) If we held the standard deviations of $x$ and $y$ constant, then it is true that "higher correlation means higher slope". Now, all three of these facts can be deduced (check you can prove each of them!) from the following formula: $$\text{slope} = \frac{\text{SD of y}}{\text{SD of x}} \cdot \text{correlation}$$ This might help you understand why the rescaling approach I used before changes the slope even though the correlation remains the same: rescaling $y$ by some factor will also scale its standard deviation. So for instance, doubling $y$ will double the slope. Now, what do you think will happen if we rescale $x$ instead? R code for plot set.seed(1234567) x1<-c(1,3,5,7,9) x2 <- c(2,4,6,8,10) y1 <- 3*x1 + rnorm(5,0,1) y2 <- 10 + 6*x2 + rnorm(5,0,10) plot(x2,y2, col="red", pch=16, xlim=c(0,10), ylim=c(0,80), xlab="x", ylab="y") points(x1,y1, col="blue", pch=16) abline(lm(y1~x1), col="blue") abline(lm(y2~x2), col="red") text(2,40,paste("Correlation =",round(cor(x2,y2), digits = 3))) text(6,5,paste("Correlation =",round(cor(x1,y1), digits = 3))) text(2,45,paste("Slope =",round(coef(summary(lm(y2~x2)))["x2", "Estimate"], digits = 3))) text(6,10,paste("Slope =",round(coef(summary(lm(y1~x1)))["x1", "Estimate"], digits = 3)))
Will larger correlation coefficient values result in greater slopes between x and y? The answer is "not necessarily" — how correlated the variables are dictates how "noisy" the scatter plot is, but not how steep. In fact, the correlation and regression slope are telling you two quite
25,143
Randomisation of non-random sample
Randomization in a non-random sample can still show an effect is not reasonably explained by random variation. For example imagine we have a population with two unrecognized subgroups (with somewhat different characteristics*) of roughly equal size, but your sample is non-random, giving an 80/20 split. Let's imagine 2 treatment groups of equal size. Randomization (at least with decent sample sizes) will tend to give close to that 80/20 split in each group, so that treatment effects are due to the treatment, rather than unequal allocation of the heterogeneous groups to the treatments. * leading to different baseline means, say The problem comes when you want to extend the inference to some target population other than what your sample is representative of (the self-selectors); this requires assumptions/an argument for which you may have no evidence (such as assuming that say the treatment differences will be consistent for all subsets of the population). For a similar situation, imagine testing a hypertension drug only on men, compared to a standard treatment and placebo. Assume the men are properly randomized to treatment group. A treatment effect will be real in the sense that it really does describe an effect in men. The difficulty will come when trying to extend that inference to women. So if they're properly conducted and randomized apart from the recruitment, an observed significant effect will be what it seems, but it will apply to what you actually sampled, not necessarily what your desired target was -- crossing the gap between the two may require careful argument; such argument is often absent. When I was a student it was quite common for psychology experiments to be conducted on psychology students, who were expected to volunteer for a certain number of hours of such experiments (this may still be the case but I don't have regular contact with psychologists who do experiments any more). With randomization to treatment, the inferences may have been valid (depending on what was done) but would apply to the local population of self-selected psychology undergraduates (in that they generally choose which experiments to sign up for), who are very far from a random sample of the broader population.
Randomisation of non-random sample
Randomization in a non-random sample can still show an effect is not reasonably explained by random variation. For example imagine we have a population with two unrecognized subgroups (with somewhat d
Randomisation of non-random sample Randomization in a non-random sample can still show an effect is not reasonably explained by random variation. For example imagine we have a population with two unrecognized subgroups (with somewhat different characteristics*) of roughly equal size, but your sample is non-random, giving an 80/20 split. Let's imagine 2 treatment groups of equal size. Randomization (at least with decent sample sizes) will tend to give close to that 80/20 split in each group, so that treatment effects are due to the treatment, rather than unequal allocation of the heterogeneous groups to the treatments. * leading to different baseline means, say The problem comes when you want to extend the inference to some target population other than what your sample is representative of (the self-selectors); this requires assumptions/an argument for which you may have no evidence (such as assuming that say the treatment differences will be consistent for all subsets of the population). For a similar situation, imagine testing a hypertension drug only on men, compared to a standard treatment and placebo. Assume the men are properly randomized to treatment group. A treatment effect will be real in the sense that it really does describe an effect in men. The difficulty will come when trying to extend that inference to women. So if they're properly conducted and randomized apart from the recruitment, an observed significant effect will be what it seems, but it will apply to what you actually sampled, not necessarily what your desired target was -- crossing the gap between the two may require careful argument; such argument is often absent. When I was a student it was quite common for psychology experiments to be conducted on psychology students, who were expected to volunteer for a certain number of hours of such experiments (this may still be the case but I don't have regular contact with psychologists who do experiments any more). With randomization to treatment, the inferences may have been valid (depending on what was done) but would apply to the local population of self-selected psychology undergraduates (in that they generally choose which experiments to sign up for), who are very far from a random sample of the broader population.
Randomisation of non-random sample Randomization in a non-random sample can still show an effect is not reasonably explained by random variation. For example imagine we have a population with two unrecognized subgroups (with somewhat d
25,144
Randomisation of non-random sample
Because is it known that randomisation solve the self-selection problem, I was wondering if randomisation of a non-random sample actually changed anything. In short, no. Think of it this way: you have an urn with 100 black balls and 100 white balls. You sample 90 black balls and 10 white balls from it. Sampling randomly from this subsample will not allow you unbiased inference on the urn itself. And also, what should we make of all these psychological experiments based on heavily self-selected sample ? People agree that non-random sampling is a problem. But how much of a problem is also a question of your "theory" of the mechanism you're interested in. If your hypothesis deals with a mechanism that should basically be the same for all humans (i.e. experiencing a freezing sensation when dipped in icy water), then non-random selection doesn't matter that much. Unfortunately, that's often not the things we're interested in.
Randomisation of non-random sample
Because is it known that randomisation solve the self-selection problem, I was wondering if randomisation of a non-random sample actually changed anything. In short, no. Think of it this way: you hav
Randomisation of non-random sample Because is it known that randomisation solve the self-selection problem, I was wondering if randomisation of a non-random sample actually changed anything. In short, no. Think of it this way: you have an urn with 100 black balls and 100 white balls. You sample 90 black balls and 10 white balls from it. Sampling randomly from this subsample will not allow you unbiased inference on the urn itself. And also, what should we make of all these psychological experiments based on heavily self-selected sample ? People agree that non-random sampling is a problem. But how much of a problem is also a question of your "theory" of the mechanism you're interested in. If your hypothesis deals with a mechanism that should basically be the same for all humans (i.e. experiencing a freezing sensation when dipped in icy water), then non-random selection doesn't matter that much. Unfortunately, that's often not the things we're interested in.
Randomisation of non-random sample Because is it known that randomisation solve the self-selection problem, I was wondering if randomisation of a non-random sample actually changed anything. In short, no. Think of it this way: you hav
25,145
Randomisation of non-random sample
There is a technique designed to deal with the issues you mention known as Bootstrapping. Bootstrapping is an approach where you generate new synthetic samples by drawing from your actual sample pool with replacement. You then do statistics on each of those synthetic sample pools, and compare the statistics between sets. This has a strong advantage of allowing you to use a great many additional tools in your statistics because these synthetic samples come from a known distribution. You can then determine how good your estimators are at handling these synthetic cases. If you find that the estimators for all of your synthetic samples converge nicely onto the same result, the assumptions of bootstrapping allow you to infer that your estimators, when applied to the full sample, provide good estimates for the unknown population. If, on the other hand, you find your estimators yield very different results from synthetic sample set to synthetic sample set, you should infer that your estimators, when applied to the full sample, may not provide a very good estimate for the unknown population. This bootstrapping approach can be used to validate whether the randomization of your non-random sample is sufficient. It can't prove it, of course, but it has been used as a tool to enhance credibility by double checking your assumption that your random sampling is sufficiently random.
Randomisation of non-random sample
There is a technique designed to deal with the issues you mention known as Bootstrapping. Bootstrapping is an approach where you generate new synthetic samples by drawing from your actual sample pool
Randomisation of non-random sample There is a technique designed to deal with the issues you mention known as Bootstrapping. Bootstrapping is an approach where you generate new synthetic samples by drawing from your actual sample pool with replacement. You then do statistics on each of those synthetic sample pools, and compare the statistics between sets. This has a strong advantage of allowing you to use a great many additional tools in your statistics because these synthetic samples come from a known distribution. You can then determine how good your estimators are at handling these synthetic cases. If you find that the estimators for all of your synthetic samples converge nicely onto the same result, the assumptions of bootstrapping allow you to infer that your estimators, when applied to the full sample, provide good estimates for the unknown population. If, on the other hand, you find your estimators yield very different results from synthetic sample set to synthetic sample set, you should infer that your estimators, when applied to the full sample, may not provide a very good estimate for the unknown population. This bootstrapping approach can be used to validate whether the randomization of your non-random sample is sufficient. It can't prove it, of course, but it has been used as a tool to enhance credibility by double checking your assumption that your random sampling is sufficiently random.
Randomisation of non-random sample There is a technique designed to deal with the issues you mention known as Bootstrapping. Bootstrapping is an approach where you generate new synthetic samples by drawing from your actual sample pool
25,146
Meaning of Surrogate Split
Surrogate splits are referenced elsewhere on this site, but I don't find an explanation for what they are. E.g.: how does rpart handle missing values in predictors? How do decision tree learning algorithms deal with missing values (under the hood) I use the documentation to rpart and these lecture notes to give an example of a surrogate split. I construct an example using rpart in R: tmp_df <- data.frame(Y = as.factor(c(1, 1, 1, 1, 1, 0, 0, 0, 0, 0)), weight = 10:1, height = c(10:7, 5, 6, 4:1)) tmp_df$weight[3] <- NA This generates the following data frame: Y weight height 1 1 10 10 2 1 9 9 3 1 8 8 4 1 7 7 5 1 6 5 6 0 5 6 7 0 NA 4 8 0 3 3 9 0 2 2 10 0 1 1 It is clear through the intent of the construction that the cutpoint weight > 5.5 gives a perfect split for the categorical response Y if the weight variable has no missing values. Now, an algorithm that ignores missing values will just discard row 7, and still obtain a split equivalent to weight > 5.5. The package rpart does not do this, it instead computes a surrogate split on the height variable, height > 3.5. The idea behind this is as follows: Weight is obviously the best variable to split on. However, when Weight is missing, a split using Height is a good approximation to the split otherwise obtained using Weight. Let's fit two models to demonstrate this, first, tm_0, a normal tree model with no surrogates, and tm a tree model using the default surrogate behaviour in rpart: tm_0 <- rpart(Y ~ weight + height, data = tmp_df, control = rpart.control(minsplit = 1, minbucket=1, cp=0, maxdepth = 1, usesurrogate = 0)) tm <- rpart(Y ~ weight + height, data = tmp_df, control = rpart.control(minsplit =1, minbucket=1, cp=0, maxdepth = 1)) We see that the splits are as I describe, from summary(tm): Primary splits: weight < 5.5 to the left, improve=4.444444, (1 missing) height < 4.5 to the left, improve=3.333333, (0 missing) Surrogate splits: height < 3.5 to the left, agree=0.889, adj=0.75, (1 split) Now, compare the predictions from these two models using the following new data: tmp_new_df <- data.frame(weight = c(rep(NA_real_, 4), 3:6), height = rep(3:6, 2)) > tmp_new_df weight height 1 NA 3 2 NA 4 3 NA 5 4 NA 6 5 3 3 6 4 4 7 5 5 8 6 6 Contrast predict(tm_0, newdata = tmp_new_df) (first column is probability of being in class 0): 0 1 1 0.5 0.5 2 0.5 0.5 3 0.5 0.5 4 0.5 0.5 5 1.0 0.0 6 1.0 0.0 7 1.0 0.0 8 0.0 1.0 to predict(tm, newdata = tmp_new_df): 0 1 1 1.0000000 0.0000000 2 0.1666667 0.8333333 3 0.1666667 0.8333333 4 0.1666667 0.8333333 5 1.0000000 0.0000000 6 1.0000000 0.0000000 7 1.0000000 0.0000000 8 0.1666667 0.8333333 In the first four rows, since weight has missing values, the decision tree tm_0 is unable to make a prediction using the split on weight, so returns the class membership ratio at the root node. In contrast, the tree tm using surrogate splits is able to use the height variable to give a more accurate prediction for these rows. However, note the difference in the latter four rows. The tree with surrogate splits is unable to give a 'perfect' prediction due to how observations with missing values in the predictors are aggregated in the terminal nodes. (See the documentation to rpart for more details).
Meaning of Surrogate Split
Surrogate splits are referenced elsewhere on this site, but I don't find an explanation for what they are. E.g.: how does rpart handle missing values in predictors? How do decision tree learning algor
Meaning of Surrogate Split Surrogate splits are referenced elsewhere on this site, but I don't find an explanation for what they are. E.g.: how does rpart handle missing values in predictors? How do decision tree learning algorithms deal with missing values (under the hood) I use the documentation to rpart and these lecture notes to give an example of a surrogate split. I construct an example using rpart in R: tmp_df <- data.frame(Y = as.factor(c(1, 1, 1, 1, 1, 0, 0, 0, 0, 0)), weight = 10:1, height = c(10:7, 5, 6, 4:1)) tmp_df$weight[3] <- NA This generates the following data frame: Y weight height 1 1 10 10 2 1 9 9 3 1 8 8 4 1 7 7 5 1 6 5 6 0 5 6 7 0 NA 4 8 0 3 3 9 0 2 2 10 0 1 1 It is clear through the intent of the construction that the cutpoint weight > 5.5 gives a perfect split for the categorical response Y if the weight variable has no missing values. Now, an algorithm that ignores missing values will just discard row 7, and still obtain a split equivalent to weight > 5.5. The package rpart does not do this, it instead computes a surrogate split on the height variable, height > 3.5. The idea behind this is as follows: Weight is obviously the best variable to split on. However, when Weight is missing, a split using Height is a good approximation to the split otherwise obtained using Weight. Let's fit two models to demonstrate this, first, tm_0, a normal tree model with no surrogates, and tm a tree model using the default surrogate behaviour in rpart: tm_0 <- rpart(Y ~ weight + height, data = tmp_df, control = rpart.control(minsplit = 1, minbucket=1, cp=0, maxdepth = 1, usesurrogate = 0)) tm <- rpart(Y ~ weight + height, data = tmp_df, control = rpart.control(minsplit =1, minbucket=1, cp=0, maxdepth = 1)) We see that the splits are as I describe, from summary(tm): Primary splits: weight < 5.5 to the left, improve=4.444444, (1 missing) height < 4.5 to the left, improve=3.333333, (0 missing) Surrogate splits: height < 3.5 to the left, agree=0.889, adj=0.75, (1 split) Now, compare the predictions from these two models using the following new data: tmp_new_df <- data.frame(weight = c(rep(NA_real_, 4), 3:6), height = rep(3:6, 2)) > tmp_new_df weight height 1 NA 3 2 NA 4 3 NA 5 4 NA 6 5 3 3 6 4 4 7 5 5 8 6 6 Contrast predict(tm_0, newdata = tmp_new_df) (first column is probability of being in class 0): 0 1 1 0.5 0.5 2 0.5 0.5 3 0.5 0.5 4 0.5 0.5 5 1.0 0.0 6 1.0 0.0 7 1.0 0.0 8 0.0 1.0 to predict(tm, newdata = tmp_new_df): 0 1 1 1.0000000 0.0000000 2 0.1666667 0.8333333 3 0.1666667 0.8333333 4 0.1666667 0.8333333 5 1.0000000 0.0000000 6 1.0000000 0.0000000 7 1.0000000 0.0000000 8 0.1666667 0.8333333 In the first four rows, since weight has missing values, the decision tree tm_0 is unable to make a prediction using the split on weight, so returns the class membership ratio at the root node. In contrast, the tree tm using surrogate splits is able to use the height variable to give a more accurate prediction for these rows. However, note the difference in the latter four rows. The tree with surrogate splits is unable to give a 'perfect' prediction due to how observations with missing values in the predictors are aggregated in the terminal nodes. (See the documentation to rpart for more details).
Meaning of Surrogate Split Surrogate splits are referenced elsewhere on this site, but I don't find an explanation for what they are. E.g.: how does rpart handle missing values in predictors? How do decision tree learning algor
25,147
How to use Naive Bayes for multi class problems?
Unlike some classifiers, multi-class labeling is trivial with Naive Bayes. For each test example $i$, and each class $k$ you want to find: $$\arg \max_k P(\textrm{class}_k | \textrm{data}_i)$$ In other words, you compute the probability of each class label in the usual way, then pick the class with the largest probability.
How to use Naive Bayes for multi class problems?
Unlike some classifiers, multi-class labeling is trivial with Naive Bayes. For each test example $i$, and each class $k$ you want to find: $$\arg \max_k P(\textrm{class}_k | \textrm{data}_i)$$ In othe
How to use Naive Bayes for multi class problems? Unlike some classifiers, multi-class labeling is trivial with Naive Bayes. For each test example $i$, and each class $k$ you want to find: $$\arg \max_k P(\textrm{class}_k | \textrm{data}_i)$$ In other words, you compute the probability of each class label in the usual way, then pick the class with the largest probability.
How to use Naive Bayes for multi class problems? Unlike some classifiers, multi-class labeling is trivial with Naive Bayes. For each test example $i$, and each class $k$ you want to find: $$\arg \max_k P(\textrm{class}_k | \textrm{data}_i)$$ In othe
25,148
What distribution does Fisher's exact test assume?
In the $2\times 2$ case the distributional assumption is given by two independent binomial random variables $X_1 \sim Bin(n_1, \theta_1)$ and $X_2 \sim Bin(n_2, \theta_2)$. The null hypothesis is the equality $\theta_1=\theta_2$. But Fisher's exact test is a conditional test: it relies on the conditional distribution of $X_1$ given $X_1+X_2$. This distribution is a hypergeometric distribution with one unknown parameter: the odds ratio $\psi=\frac{\frac{\theta_1}{1-\theta_1}}{\frac{\theta_2}{1-\theta_2}}$, and then the null hypothesis is $\psi=1$. This distribution has its Wikipedia page. To evaluate it with R, you can simply use the formula defining the conditional probability: p1 <- 7/27 p2 <- 14/70 x1 <- 7; n1 <- 27 x2 <- 14; n2 <- 56 # m <- x1+x2 dbinom(x1, n1, p1)*dbinom(x2, n2, p2)/sum(dbinom(0:m, n1, p1)*dbinom(m-(0:m), n2, p2)) [1] 0.1818838 Or use the dnoncenhypergeom function of the MCMCpack package: psi <- p1/(1-p1)/(p2/(1-p2)) # this is the odds ratio MCMCpack::dnoncenhypergeom(x=x1, n1, n2, x1+x2, psi) [1] 0.1818838
What distribution does Fisher's exact test assume?
In the $2\times 2$ case the distributional assumption is given by two independent binomial random variables $X_1 \sim Bin(n_1, \theta_1)$ and $X_2 \sim Bin(n_2, \theta_2)$. The null hypothesis is the
What distribution does Fisher's exact test assume? In the $2\times 2$ case the distributional assumption is given by two independent binomial random variables $X_1 \sim Bin(n_1, \theta_1)$ and $X_2 \sim Bin(n_2, \theta_2)$. The null hypothesis is the equality $\theta_1=\theta_2$. But Fisher's exact test is a conditional test: it relies on the conditional distribution of $X_1$ given $X_1+X_2$. This distribution is a hypergeometric distribution with one unknown parameter: the odds ratio $\psi=\frac{\frac{\theta_1}{1-\theta_1}}{\frac{\theta_2}{1-\theta_2}}$, and then the null hypothesis is $\psi=1$. This distribution has its Wikipedia page. To evaluate it with R, you can simply use the formula defining the conditional probability: p1 <- 7/27 p2 <- 14/70 x1 <- 7; n1 <- 27 x2 <- 14; n2 <- 56 # m <- x1+x2 dbinom(x1, n1, p1)*dbinom(x2, n2, p2)/sum(dbinom(0:m, n1, p1)*dbinom(m-(0:m), n2, p2)) [1] 0.1818838 Or use the dnoncenhypergeom function of the MCMCpack package: psi <- p1/(1-p1)/(p2/(1-p2)) # this is the odds ratio MCMCpack::dnoncenhypergeom(x=x1, n1, n2, x1+x2, psi) [1] 0.1818838
What distribution does Fisher's exact test assume? In the $2\times 2$ case the distributional assumption is given by two independent binomial random variables $X_1 \sim Bin(n_1, \theta_1)$ and $X_2 \sim Bin(n_2, \theta_2)$. The null hypothesis is the
25,149
What distribution does Fisher's exact test assume?
Fisher's so-called "exact" test makes the same kind of subtle assumptions that $\chi^2$ tests make. The two variables being assessed for association are truly polytomous all-or-nothing variables such as dead/alive US/Europe. If one or both of the variables is a simplification of an underlying continuum, categorical data analysis should not be undertaken at all. There are no other relevant background variables. If $Y$ is the outcome variable and $X$ is a variable being assessed for association with $Y$, the probability that $Y=y$ is identical for every subject with $X$ fixed at $x$. Contingency tables assume in effect that there is no heterogeneity in the distribution of $Y$ that is not accounted for by $X$. For example, in a randomized clinical trial studying the effect of treatment A vs. B on the probability of death, a $2\times 2$ contengency table test assumes that every subject on treatment A has the same probability of death. [One could argue that this is too stringent an assumption, but that position doesn't recognize the loss of power from doing unadjusted tests of association.] Fisher's test makes one assumption not made by unconditional tests of association such as Pearson's $\chi^2$ test: that we are interested in the "current" marginal distribution of both $X$ and $Y$, that is, we are conditioning on the frequencies of the $Y$ outcome categories. This is not reasonable for prospective studies. The use of Fisher's test leads to conservatism. Its $P$-values are on the average too large, because the test guarantees that the $P$-values are not too small. On the average, Pearson $\chi^2$ $P$-values are more acccurate than Fisher's, even with expected frequencies far lower than 5 in some of the cells.
What distribution does Fisher's exact test assume?
Fisher's so-called "exact" test makes the same kind of subtle assumptions that $\chi^2$ tests make. The two variables being assessed for association are truly polytomous all-or-nothing variables such
What distribution does Fisher's exact test assume? Fisher's so-called "exact" test makes the same kind of subtle assumptions that $\chi^2$ tests make. The two variables being assessed for association are truly polytomous all-or-nothing variables such as dead/alive US/Europe. If one or both of the variables is a simplification of an underlying continuum, categorical data analysis should not be undertaken at all. There are no other relevant background variables. If $Y$ is the outcome variable and $X$ is a variable being assessed for association with $Y$, the probability that $Y=y$ is identical for every subject with $X$ fixed at $x$. Contingency tables assume in effect that there is no heterogeneity in the distribution of $Y$ that is not accounted for by $X$. For example, in a randomized clinical trial studying the effect of treatment A vs. B on the probability of death, a $2\times 2$ contengency table test assumes that every subject on treatment A has the same probability of death. [One could argue that this is too stringent an assumption, but that position doesn't recognize the loss of power from doing unadjusted tests of association.] Fisher's test makes one assumption not made by unconditional tests of association such as Pearson's $\chi^2$ test: that we are interested in the "current" marginal distribution of both $X$ and $Y$, that is, we are conditioning on the frequencies of the $Y$ outcome categories. This is not reasonable for prospective studies. The use of Fisher's test leads to conservatism. Its $P$-values are on the average too large, because the test guarantees that the $P$-values are not too small. On the average, Pearson $\chi^2$ $P$-values are more acccurate than Fisher's, even with expected frequencies far lower than 5 in some of the cells.
What distribution does Fisher's exact test assume? Fisher's so-called "exact" test makes the same kind of subtle assumptions that $\chi^2$ tests make. The two variables being assessed for association are truly polytomous all-or-nothing variables such
25,150
How does maximum likelihood estimation have an approximate normal distribution?
Estimators are statistics, and statistics have sampling distributions (that is, we're talking about the situation where you keep drawing samples of the same size and looking at the distribution of the estimates you get, one for each sample). The quote is referring to the distribution of MLEs as sample sizes approach infinity. So let's consider an explicit example, the parameter of an exponential distribution (using the scale parameterization, not the rate parameterization). $$f(x;\mu) = \frac{_1}{^\mu} e^{-\frac{x}{\mu}};\quad x>0,\quad \mu>0$$ In this case $\hat \mu = \bar x$. The theorem gives us that as the sample size $n$ gets larger and larger, the distribution of (an appropriately standardized) $\bar X$ (on exponential data) will become more normal. If we take repeated samples, each of size 1, the resulting density of the sample means is given in the top left plot. If we take repeated samples, each of size 2, the resulting density of the sample means is given in the top right plot; by the time n=25, at the bottom right, the distribution of sample means has already started to look much more normal. (In this case, we would already anticipate that is the case because of the CLT. But the distribution of $1/\bar X$ must also approach normality because it is ML for the rate parameter $\lambda=1/\mu$ ... and you can't get that from the CLT - at least not directly* - since we're not talking about standardized means any more, which is what the CLT is about) Now consider the shape parameter of a gamma distribution with known scale mean (here using a mean&shape parameterization rather than scale&shape). The estimator is not closed form in this case, and the CLT doesn't apply to it (again, at least not directly*), but nevertheless the argmax of the likelihood function is MLE. As you take larger and larger samples, the sampling distribution of the shape parameter estimate will become more normal. These are kernel density estimates from 10000 sets of ML estimates of the shape parameter of a gamma(2,2), for the indicated sample sizes (the first two sets of results were extremely heavy-tailed; they've been truncated somewhat so you can see the shape near the mode). In this case the shape near the mode is only changing slowly so far - but the extreme tail has shortened quite dramatically. It might take an $n$ of several hundred to start looking normal. -- * As mentioned, the CLT doesn't apply directly (clearly, since we're not dealing in general with means). You can, however, make an asymptotic argument where you expand something in $\hat{\theta}$ in a series, make a suitable argument relating to higher order terms and invoke a form of CLT to obtain that a standardized version of $\hat{\theta}$ approaches normality (under suitable conditions ... ). Note also that the effect we see when we are looking at small samples (small compared to infinity, at least) -- that regular progression toward normality across a variety of situations, as we see motivated by the plots above -- would suggest that if we considered the cdf of a standardized statistic, there may be a version of something like a Berry Esseen inequality based on a similar approach to the way of using a CLT argument with MLEs that would provide bounds on how slowly the sampling distribution can approach normality. I haven't seen something like that, but it wouldn't surprise me to find that it had been done.
How does maximum likelihood estimation have an approximate normal distribution?
Estimators are statistics, and statistics have sampling distributions (that is, we're talking about the situation where you keep drawing samples of the same size and looking at the distribution of the
How does maximum likelihood estimation have an approximate normal distribution? Estimators are statistics, and statistics have sampling distributions (that is, we're talking about the situation where you keep drawing samples of the same size and looking at the distribution of the estimates you get, one for each sample). The quote is referring to the distribution of MLEs as sample sizes approach infinity. So let's consider an explicit example, the parameter of an exponential distribution (using the scale parameterization, not the rate parameterization). $$f(x;\mu) = \frac{_1}{^\mu} e^{-\frac{x}{\mu}};\quad x>0,\quad \mu>0$$ In this case $\hat \mu = \bar x$. The theorem gives us that as the sample size $n$ gets larger and larger, the distribution of (an appropriately standardized) $\bar X$ (on exponential data) will become more normal. If we take repeated samples, each of size 1, the resulting density of the sample means is given in the top left plot. If we take repeated samples, each of size 2, the resulting density of the sample means is given in the top right plot; by the time n=25, at the bottom right, the distribution of sample means has already started to look much more normal. (In this case, we would already anticipate that is the case because of the CLT. But the distribution of $1/\bar X$ must also approach normality because it is ML for the rate parameter $\lambda=1/\mu$ ... and you can't get that from the CLT - at least not directly* - since we're not talking about standardized means any more, which is what the CLT is about) Now consider the shape parameter of a gamma distribution with known scale mean (here using a mean&shape parameterization rather than scale&shape). The estimator is not closed form in this case, and the CLT doesn't apply to it (again, at least not directly*), but nevertheless the argmax of the likelihood function is MLE. As you take larger and larger samples, the sampling distribution of the shape parameter estimate will become more normal. These are kernel density estimates from 10000 sets of ML estimates of the shape parameter of a gamma(2,2), for the indicated sample sizes (the first two sets of results were extremely heavy-tailed; they've been truncated somewhat so you can see the shape near the mode). In this case the shape near the mode is only changing slowly so far - but the extreme tail has shortened quite dramatically. It might take an $n$ of several hundred to start looking normal. -- * As mentioned, the CLT doesn't apply directly (clearly, since we're not dealing in general with means). You can, however, make an asymptotic argument where you expand something in $\hat{\theta}$ in a series, make a suitable argument relating to higher order terms and invoke a form of CLT to obtain that a standardized version of $\hat{\theta}$ approaches normality (under suitable conditions ... ). Note also that the effect we see when we are looking at small samples (small compared to infinity, at least) -- that regular progression toward normality across a variety of situations, as we see motivated by the plots above -- would suggest that if we considered the cdf of a standardized statistic, there may be a version of something like a Berry Esseen inequality based on a similar approach to the way of using a CLT argument with MLEs that would provide bounds on how slowly the sampling distribution can approach normality. I haven't seen something like that, but it wouldn't surprise me to find that it had been done.
How does maximum likelihood estimation have an approximate normal distribution? Estimators are statistics, and statistics have sampling distributions (that is, we're talking about the situation where you keep drawing samples of the same size and looking at the distribution of the
25,151
Why is binomial variance calculated as $p(1-p) / (n -1)$?
I think it has been pretty much covered by whuber, but I just wish to expand on the use of $n-1$; where it comes from and whether it applies here. In an ordinary sample variance, many people use an $n-1$ denominator to make the usual sum-of-squares-based variance estimate unbiased (not everyone prefers unbiasedness to other properties though). This is called Bessel's correction but appears to have been derived by Gauss. A simple derivation is here Presumably whoever wrote that formula has concluded that the same should be done with the usual variance estimate for a binomial proportion, which is generally estimated as $p(1-p)/n$ (where $p$ is the sample proportion). Can we see whether the expectation of the usual estimator of variance is the population value? Take $\pi$ to be the corresponding population proportion. That is, does $\text{E}[p(1-p)/n]=\pi(1-\pi)/n$? Equivalently, does $\text{E}[p(1-p)]=\pi(1-\pi)$? Note that if $X$ is the observed count, $p = X/n$, where under the usual sampling assumptions, $X\sim \text{binomial}(n,\pi)$. \begin{eqnarray} \text{E}[p(1-p)] &=& 1/n^2 {E}(X(n-X))\\ &=& 1/n^2 (nEX - EX^2) \\ &=& 1/n^2 (n^2\pi - n\pi(1-\pi) - n^2\pi^2 )\\ &=& 1/n^2 (n^2\pi - n\pi +n\pi^2 - n^2\pi^2 )\\ &=& 1/n^2 \cdot n\pi(n - 1 +\pi - n\pi )\\ &=& 1/n^2 \cdot n\pi(n - 1)(1-\pi)\\ &=& \frac{n-1}{n} \pi (1-\pi) \end{eqnarray} Hence $\text{E}[p(1-p)/(n-1)]=\pi (1-\pi)/n$ It looks like (assuming I made no errors) it is the case here too - that the usual estimator of the variance of the proportion is biased, and may be unbiased by multiplying the typical estimator by $\frac{n}{n-1}$. (Edit: In retrospect this is obvious; one simply need apply the ordinary bias calculation for a sample variance to a sample of 0's and 1's) Which means it appears that the formula you have has been chosen to give an unbiased estimate. (I wonder why people seem happy to use a biased variance estimate for binomials when there's such an insistence on using an unbiased one in other situations. I have no good answer for that; I'll continue using biased estimators whenever it makes sense to me, which seems to be rather more often than most people do.)
Why is binomial variance calculated as $p(1-p) / (n -1)$?
I think it has been pretty much covered by whuber, but I just wish to expand on the use of $n-1$; where it comes from and whether it applies here. In an ordinary sample variance, many people use an $n
Why is binomial variance calculated as $p(1-p) / (n -1)$? I think it has been pretty much covered by whuber, but I just wish to expand on the use of $n-1$; where it comes from and whether it applies here. In an ordinary sample variance, many people use an $n-1$ denominator to make the usual sum-of-squares-based variance estimate unbiased (not everyone prefers unbiasedness to other properties though). This is called Bessel's correction but appears to have been derived by Gauss. A simple derivation is here Presumably whoever wrote that formula has concluded that the same should be done with the usual variance estimate for a binomial proportion, which is generally estimated as $p(1-p)/n$ (where $p$ is the sample proportion). Can we see whether the expectation of the usual estimator of variance is the population value? Take $\pi$ to be the corresponding population proportion. That is, does $\text{E}[p(1-p)/n]=\pi(1-\pi)/n$? Equivalently, does $\text{E}[p(1-p)]=\pi(1-\pi)$? Note that if $X$ is the observed count, $p = X/n$, where under the usual sampling assumptions, $X\sim \text{binomial}(n,\pi)$. \begin{eqnarray} \text{E}[p(1-p)] &=& 1/n^2 {E}(X(n-X))\\ &=& 1/n^2 (nEX - EX^2) \\ &=& 1/n^2 (n^2\pi - n\pi(1-\pi) - n^2\pi^2 )\\ &=& 1/n^2 (n^2\pi - n\pi +n\pi^2 - n^2\pi^2 )\\ &=& 1/n^2 \cdot n\pi(n - 1 +\pi - n\pi )\\ &=& 1/n^2 \cdot n\pi(n - 1)(1-\pi)\\ &=& \frac{n-1}{n} \pi (1-\pi) \end{eqnarray} Hence $\text{E}[p(1-p)/(n-1)]=\pi (1-\pi)/n$ It looks like (assuming I made no errors) it is the case here too - that the usual estimator of the variance of the proportion is biased, and may be unbiased by multiplying the typical estimator by $\frac{n}{n-1}$. (Edit: In retrospect this is obvious; one simply need apply the ordinary bias calculation for a sample variance to a sample of 0's and 1's) Which means it appears that the formula you have has been chosen to give an unbiased estimate. (I wonder why people seem happy to use a biased variance estimate for binomials when there's such an insistence on using an unbiased one in other situations. I have no good answer for that; I'll continue using biased estimators whenever it makes sense to me, which seems to be rather more often than most people do.)
Why is binomial variance calculated as $p(1-p) / (n -1)$? I think it has been pretty much covered by whuber, but I just wish to expand on the use of $n-1$; where it comes from and whether it applies here. In an ordinary sample variance, many people use an $n
25,152
Why is binomial variance calculated as $p(1-p) / (n -1)$?
Regarding the subquestion on why divide by (n-1) instead of n? I've lost my reference, but the legend that comes down to me tells that the inventor of the (n-1) divisor thought it absurd to calculate the variance for a population having a single member. Dividing by (n-1) where n=1 produces an imponderable undefined condition, preventing the absurdity. Clearly, it hardly matters at all in practice. The irreverent might argue that it's more trouble than it's worth. (Now, who was it that invented the (n-1) divisor? Or should I say "whom"?)
Why is binomial variance calculated as $p(1-p) / (n -1)$?
Regarding the subquestion on why divide by (n-1) instead of n? I've lost my reference, but the legend that comes down to me tells that the inventor of the (n-1) divisor thought it absurd to calculate
Why is binomial variance calculated as $p(1-p) / (n -1)$? Regarding the subquestion on why divide by (n-1) instead of n? I've lost my reference, but the legend that comes down to me tells that the inventor of the (n-1) divisor thought it absurd to calculate the variance for a population having a single member. Dividing by (n-1) where n=1 produces an imponderable undefined condition, preventing the absurdity. Clearly, it hardly matters at all in practice. The irreverent might argue that it's more trouble than it's worth. (Now, who was it that invented the (n-1) divisor? Or should I say "whom"?)
Why is binomial variance calculated as $p(1-p) / (n -1)$? Regarding the subquestion on why divide by (n-1) instead of n? I've lost my reference, but the legend that comes down to me tells that the inventor of the (n-1) divisor thought it absurd to calculate
25,153
How does the beta prior affect the posterior under a binomial likelihood
To answer your first question we just need to use Bayes' Theorem to update our binomial likelihood with the beta prior. To better understand how to do this, first observe the following result $$p(\theta|\mathbf{x})=\frac{p(\mathbf{x}|\theta)p(\theta)}{\int_{\Theta}p(\mathbf{x}|\theta)p(\theta)d\theta}\propto p(\mathbf{x}|\theta)p(\theta)$$ where we can make use of the proportionality result since the beta distribution is the conjugate prior for the binomial likelihood. Now, let $x_i\sim\text{Binomial}(N_i,\theta)$ and $\theta\sim\text{Beta}(\alpha,\beta)$. We can now use Bayes' Theorem to calculate the posterior as follows: \begin{align} p(\theta|\mathbf{x})&\propto p(\mathbf{x}|\theta)p(\theta)\\ &\\ &\propto \binom{N}{x_i}\theta^{s}(1-\theta)^{N-s}\frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}\\ &\\ &\propto \theta^{s}(1-\theta)^{N-s}\theta^{\alpha-1}(1-\theta)^{\beta-1}\\ &\\ &\propto\theta^{\alpha+s-1}(1-\theta)^{\beta+N-s-1} \end{align} where $s=\sum_{i=1}^nx_i$ and $N=\sum_{i=1}^nN_i$ Now, we recognize the proportional right hand side of the equation as the kernel of another beta distribution with updated parameters $$\alpha^*=\alpha+\sum_{i=1}^nx_i$$ and $$\beta^*=\beta+\sum_{i=1}^nN_i-\sum_{i=1}^nx_i$$ Now for the second part of your problem, consider the following graphs of the posteriors given differing prior distributions. The above plot is of five different prior distributions: \begin{align*} \text{Prior }1&:\,\,\theta\sim\text{Beta}(.5,.5)\\ \text{Prior }1&:\,\,\theta\sim\text{Beta}(5,1)\\ \text{Prior }1&:\,\,\theta\sim\text{Beta}(1,3)\\ \text{Prior }1&:\,\,\theta\sim\text{Beta}(2,2)\\ \text{Prior }1&:\,\,\theta\sim\text{Beta}(2,5) \end{align*} Now although the posterior distribution does not seem to be changed much by the choice of prior in this situation this is not always the case. For example, had we sampled from a Binomial distribution (in the code) where $N=2$ we would see that the posterior distribution is drastically changed by the choice of the prior distribution. Here is the R code used to generate everything: colors = c("red","blue","green","orange","purple") n = 10 N = 10 theta = .2 x = rbinom(n,N,theta) grid = seq(0,2,.01) alpha = c(.5,5,1,2,2) beta = c(.5,1,3,2,5) plot(grid,grid,type="n",xlim=c(0,1),ylim=c(0,4),xlab="",ylab="Prior Density", main="Prior Distributions", las=1) for(i in 1:length(alpha)){ prior = dbeta(grid,alpha[i],beta[i]) lines(grid,prior,col=colors[i],lwd=2) } legend("topleft", legend=c("Beta(0.5,0.5)", "Beta(5,1)", "Beta(1,3)", "Beta(2,2)", "Beta(2,5)"), lwd=rep(2,5), col=colors, bty="n", ncol=3) for(i in 1:length(alpha)){ dev.new() plot(grid,grid,,type="n",xlim=c(0,1),ylim=c(0,10),xlab="",ylab="Density",xaxs="i",yaxs="i", main="Prior and Posterior Distribution") alpha.star = alpha[i] + sum(x) beta.star = beta[i] + n*N - sum(x) prior = dbeta(grid,alpha[i],beta[i]) post = dbeta(grid,alpha.star,beta.star) lines(grid,post,lwd=2) lines(grid,prior,col=colors[i],lwd=2) legend("topright",c("Prior","Posterior"),col=c(colors[i],"black"),lwd=2) }
How does the beta prior affect the posterior under a binomial likelihood
To answer your first question we just need to use Bayes' Theorem to update our binomial likelihood with the beta prior. To better understand how to do this, first observe the following result $$p(\t
How does the beta prior affect the posterior under a binomial likelihood To answer your first question we just need to use Bayes' Theorem to update our binomial likelihood with the beta prior. To better understand how to do this, first observe the following result $$p(\theta|\mathbf{x})=\frac{p(\mathbf{x}|\theta)p(\theta)}{\int_{\Theta}p(\mathbf{x}|\theta)p(\theta)d\theta}\propto p(\mathbf{x}|\theta)p(\theta)$$ where we can make use of the proportionality result since the beta distribution is the conjugate prior for the binomial likelihood. Now, let $x_i\sim\text{Binomial}(N_i,\theta)$ and $\theta\sim\text{Beta}(\alpha,\beta)$. We can now use Bayes' Theorem to calculate the posterior as follows: \begin{align} p(\theta|\mathbf{x})&\propto p(\mathbf{x}|\theta)p(\theta)\\ &\\ &\propto \binom{N}{x_i}\theta^{s}(1-\theta)^{N-s}\frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}\\ &\\ &\propto \theta^{s}(1-\theta)^{N-s}\theta^{\alpha-1}(1-\theta)^{\beta-1}\\ &\\ &\propto\theta^{\alpha+s-1}(1-\theta)^{\beta+N-s-1} \end{align} where $s=\sum_{i=1}^nx_i$ and $N=\sum_{i=1}^nN_i$ Now, we recognize the proportional right hand side of the equation as the kernel of another beta distribution with updated parameters $$\alpha^*=\alpha+\sum_{i=1}^nx_i$$ and $$\beta^*=\beta+\sum_{i=1}^nN_i-\sum_{i=1}^nx_i$$ Now for the second part of your problem, consider the following graphs of the posteriors given differing prior distributions. The above plot is of five different prior distributions: \begin{align*} \text{Prior }1&:\,\,\theta\sim\text{Beta}(.5,.5)\\ \text{Prior }1&:\,\,\theta\sim\text{Beta}(5,1)\\ \text{Prior }1&:\,\,\theta\sim\text{Beta}(1,3)\\ \text{Prior }1&:\,\,\theta\sim\text{Beta}(2,2)\\ \text{Prior }1&:\,\,\theta\sim\text{Beta}(2,5) \end{align*} Now although the posterior distribution does not seem to be changed much by the choice of prior in this situation this is not always the case. For example, had we sampled from a Binomial distribution (in the code) where $N=2$ we would see that the posterior distribution is drastically changed by the choice of the prior distribution. Here is the R code used to generate everything: colors = c("red","blue","green","orange","purple") n = 10 N = 10 theta = .2 x = rbinom(n,N,theta) grid = seq(0,2,.01) alpha = c(.5,5,1,2,2) beta = c(.5,1,3,2,5) plot(grid,grid,type="n",xlim=c(0,1),ylim=c(0,4),xlab="",ylab="Prior Density", main="Prior Distributions", las=1) for(i in 1:length(alpha)){ prior = dbeta(grid,alpha[i],beta[i]) lines(grid,prior,col=colors[i],lwd=2) } legend("topleft", legend=c("Beta(0.5,0.5)", "Beta(5,1)", "Beta(1,3)", "Beta(2,2)", "Beta(2,5)"), lwd=rep(2,5), col=colors, bty="n", ncol=3) for(i in 1:length(alpha)){ dev.new() plot(grid,grid,,type="n",xlim=c(0,1),ylim=c(0,10),xlab="",ylab="Density",xaxs="i",yaxs="i", main="Prior and Posterior Distribution") alpha.star = alpha[i] + sum(x) beta.star = beta[i] + n*N - sum(x) prior = dbeta(grid,alpha[i],beta[i]) post = dbeta(grid,alpha.star,beta.star) lines(grid,post,lwd=2) lines(grid,prior,col=colors[i],lwd=2) legend("topright",c("Prior","Posterior"),col=c(colors[i],"black"),lwd=2) }
How does the beta prior affect the posterior under a binomial likelihood To answer your first question we just need to use Bayes' Theorem to update our binomial likelihood with the beta prior. To better understand how to do this, first observe the following result $$p(\t
25,154
Moment generating function of the inner product of two gaussian random vectors
First let's address the case $\Sigma = \sigma\mathbb{I}$. At the end is the (easy) generalization to arbitrary $\Sigma$. Begin by observing the inner product is the sum of iid variables, each of them the product of two independent Normal$(0,\sigma)$ variates, thereby reducing the question to finding the mgf of the latter, because the mgf of a sum is the product of the mgfs. The mgf can be found by integration, but there's an easier way. When $X$ and $Y$ are standard normal, $$XY = ((X+Y)/2)^2 - ((X-Y)/2)^2$$ is a difference of two independent scaled Chi-squared variates. (The scale factor is $1/2$ because the variances of $(X\pm Y)/2$ equal $1/2$.) Because the mgf of a chi-squared variate is $1/\sqrt{1 - 2\omega}$, the mgf of $((X+Y)/2)^2$ is $1/\sqrt{1-\omega}$ and the mgf of $-((X-Y)/2)^2$ is $1/\sqrt{1+\omega}$. Multiplying, we find that the desired mgf equals $1/\sqrt{1-\omega^2}$. (For later reference, notice that when $X$ and $Y$ are rescaled by $\sigma$, their product scales by $\sigma^2$, whence $\omega$ should scale by $\sigma^2$, too.) This should look familiar: up to some constant factors and a sign, it looks like the probability density for a Student t distribution with $0$ degrees of freedom. (Indeed, if we had been working with characteristic functions instead of mgfs, we would obtain $1/\sqrt{1 + \omega^2}$, which is even closer to a Student t PDF.) Never mind that there is no such thing as a Student t with $0$ dfs--all that matters is that the mgf be analytic in a neighborhood of $0$ and this clearly is (by the Binomial Theorem). It follows immediately that the distribution of the inner product of these iid Gaussian $n$-vectors has mgf equal to the $n$-fold product of this mgf, $$(1 - \omega^2 \sigma^4)^{-n/2}, \quad n=1, 2, \ldots.$$ By looking up the characteristic function of the Student t distributions, we deduce (with a tiny bit of algebra or an integration to find the normalizing constant) that the PDF itself is given by $$f_{n,\sigma}(x) = \frac{2^{\frac{1-n}{2}} |x|^{\frac{n-1}{2}} K_{\frac{n-1}{2}}\left(\frac{|x|}{\sigma ^2}\right)}{\sqrt{\pi } \sigma ^4 \Gamma \left(\frac{n}{2}\right)}$$ ($K$ is a Bessel function). For instance, here is a plot of that PDF superimposed on the histogram of a random sample of $10^5$ such inner products where $\sigma=1/2$ and $n=3$: It's harder to confirm the accuracy of the mgf from a simulation, but note (from the Binomial Theorem) that $$(1 + t^2 \sigma^4)^{-3/2} = 1-\frac{3 \sigma ^4 t^2}{2}+\frac{15 \sigma ^8 t^4}{8}-\frac{35 \sigma ^{12} t^6}{16}+\frac{315 \sigma ^{16} t^8}{128}+\ldots,$$ from which we may read off the moments (divided by factorials). Due to the symmetry about $0$, only the even moments matter. For $\sigma=1/2$ we obtain the following values, to be compared to the raw moments of this simulation: k mgf simulation/k! 2 0.09375 0.09424920 4 0.00732422 0.00740436 6 0.00053406 0.00054128 8 0.00003755 0.00003674 10 2.58 e-6 2.17 e-6 As to be expected, the high moments of the simulation will begin departing from the moments given by the mgf; but at least up through the tenth moment, there is excellent agreement. Incidentally, when $n=2$ the distribution is bi-exponential. To handle the general case, begin by noting that the inner product is a coordinate-independent object. We may therefore take the principal directions (eigenvectors) of $\Sigma$ as coordinates. In these coordinates the inner product is the sum of independent products of independent Normal variates, each component distributed with a variance equal to its associated eigenvalue. Thus, letting the nonzero eigenvalues be $\sigma_1^2, \sigma_2^2, \ldots, \sigma_d^2$ (with $0 \le d \le n$), the mgf must equal $$\left(\prod_{i=1}^d (1 - \omega^2\sigma_i^4)\right)^{-1/2}.$$ To confirm that I made no error in this reasoning, I worked out an example where $\Sigma$ is the matrix $$\left( \begin{array}{ccc} 1 & \frac{1}{2} & -\frac{1}{8} \\ \frac{1}{2} & 1 & -\frac{1}{4} \\ -\frac{1}{8} & -\frac{1}{4} & \frac{1}{2} \end{array} \right)$$ and computed that its eigenvalues are $$\left(\sigma_1^2, \sigma_2^2, \sigma_3^2\right) = \left(\frac{1}{16} \left(17+\sqrt{65}\right),\frac{1}{16} \left(17-\sqrt{65}\right),\frac{3}{8}\right)\approx \left(1.56639,0.558609,0.375\right).$$ It was possible to compute the PDF by numerically evaluating the Fourier Transform of the characteristic function (as derived from the mgf formula given here): a plot of this PDF is shown in the following figure as a red line. At the same time, I generated $10^6$ iid variates $X_i$ from the Normal$(0,\Sigma)$ distribution and another $10^6$ iid variates $Y_i$ in the same way, and computed the $10^6$ dot products $X_i\cdot Y_i$. The plot shows the histogram of these dot products (omitting some of the most extreme values--the range was from $-12$ to $15$): As before, the agreement is excellent. Furthermore, the moments match well through the eighth and reasonably well even at the tenth: k mgf simulation/k! 2 1.45313 1.45208 4 2.59009 2.59605 6 5.20824 5.29333 8 11.0994 11.3115 10 24.4166 22.9982 Addendum (Added 9 August 2013.) $f_{n,\sigma}$ is an instance of the variance-gamma distribution, which originally was defined as " the normal variance-mean mixture where the mixing density is the gamma distribution." It has a standard location ($0$), asymmetry parameter of $0$ (it is symmetric), scale parameter $\sigma^2$, and shape parameter $n/2$ (according to the Wikipedia parameterization).
Moment generating function of the inner product of two gaussian random vectors
First let's address the case $\Sigma = \sigma\mathbb{I}$. At the end is the (easy) generalization to arbitrary $\Sigma$. Begin by observing the inner product is the sum of iid variables, each of them
Moment generating function of the inner product of two gaussian random vectors First let's address the case $\Sigma = \sigma\mathbb{I}$. At the end is the (easy) generalization to arbitrary $\Sigma$. Begin by observing the inner product is the sum of iid variables, each of them the product of two independent Normal$(0,\sigma)$ variates, thereby reducing the question to finding the mgf of the latter, because the mgf of a sum is the product of the mgfs. The mgf can be found by integration, but there's an easier way. When $X$ and $Y$ are standard normal, $$XY = ((X+Y)/2)^2 - ((X-Y)/2)^2$$ is a difference of two independent scaled Chi-squared variates. (The scale factor is $1/2$ because the variances of $(X\pm Y)/2$ equal $1/2$.) Because the mgf of a chi-squared variate is $1/\sqrt{1 - 2\omega}$, the mgf of $((X+Y)/2)^2$ is $1/\sqrt{1-\omega}$ and the mgf of $-((X-Y)/2)^2$ is $1/\sqrt{1+\omega}$. Multiplying, we find that the desired mgf equals $1/\sqrt{1-\omega^2}$. (For later reference, notice that when $X$ and $Y$ are rescaled by $\sigma$, their product scales by $\sigma^2$, whence $\omega$ should scale by $\sigma^2$, too.) This should look familiar: up to some constant factors and a sign, it looks like the probability density for a Student t distribution with $0$ degrees of freedom. (Indeed, if we had been working with characteristic functions instead of mgfs, we would obtain $1/\sqrt{1 + \omega^2}$, which is even closer to a Student t PDF.) Never mind that there is no such thing as a Student t with $0$ dfs--all that matters is that the mgf be analytic in a neighborhood of $0$ and this clearly is (by the Binomial Theorem). It follows immediately that the distribution of the inner product of these iid Gaussian $n$-vectors has mgf equal to the $n$-fold product of this mgf, $$(1 - \omega^2 \sigma^4)^{-n/2}, \quad n=1, 2, \ldots.$$ By looking up the characteristic function of the Student t distributions, we deduce (with a tiny bit of algebra or an integration to find the normalizing constant) that the PDF itself is given by $$f_{n,\sigma}(x) = \frac{2^{\frac{1-n}{2}} |x|^{\frac{n-1}{2}} K_{\frac{n-1}{2}}\left(\frac{|x|}{\sigma ^2}\right)}{\sqrt{\pi } \sigma ^4 \Gamma \left(\frac{n}{2}\right)}$$ ($K$ is a Bessel function). For instance, here is a plot of that PDF superimposed on the histogram of a random sample of $10^5$ such inner products where $\sigma=1/2$ and $n=3$: It's harder to confirm the accuracy of the mgf from a simulation, but note (from the Binomial Theorem) that $$(1 + t^2 \sigma^4)^{-3/2} = 1-\frac{3 \sigma ^4 t^2}{2}+\frac{15 \sigma ^8 t^4}{8}-\frac{35 \sigma ^{12} t^6}{16}+\frac{315 \sigma ^{16} t^8}{128}+\ldots,$$ from which we may read off the moments (divided by factorials). Due to the symmetry about $0$, only the even moments matter. For $\sigma=1/2$ we obtain the following values, to be compared to the raw moments of this simulation: k mgf simulation/k! 2 0.09375 0.09424920 4 0.00732422 0.00740436 6 0.00053406 0.00054128 8 0.00003755 0.00003674 10 2.58 e-6 2.17 e-6 As to be expected, the high moments of the simulation will begin departing from the moments given by the mgf; but at least up through the tenth moment, there is excellent agreement. Incidentally, when $n=2$ the distribution is bi-exponential. To handle the general case, begin by noting that the inner product is a coordinate-independent object. We may therefore take the principal directions (eigenvectors) of $\Sigma$ as coordinates. In these coordinates the inner product is the sum of independent products of independent Normal variates, each component distributed with a variance equal to its associated eigenvalue. Thus, letting the nonzero eigenvalues be $\sigma_1^2, \sigma_2^2, \ldots, \sigma_d^2$ (with $0 \le d \le n$), the mgf must equal $$\left(\prod_{i=1}^d (1 - \omega^2\sigma_i^4)\right)^{-1/2}.$$ To confirm that I made no error in this reasoning, I worked out an example where $\Sigma$ is the matrix $$\left( \begin{array}{ccc} 1 & \frac{1}{2} & -\frac{1}{8} \\ \frac{1}{2} & 1 & -\frac{1}{4} \\ -\frac{1}{8} & -\frac{1}{4} & \frac{1}{2} \end{array} \right)$$ and computed that its eigenvalues are $$\left(\sigma_1^2, \sigma_2^2, \sigma_3^2\right) = \left(\frac{1}{16} \left(17+\sqrt{65}\right),\frac{1}{16} \left(17-\sqrt{65}\right),\frac{3}{8}\right)\approx \left(1.56639,0.558609,0.375\right).$$ It was possible to compute the PDF by numerically evaluating the Fourier Transform of the characteristic function (as derived from the mgf formula given here): a plot of this PDF is shown in the following figure as a red line. At the same time, I generated $10^6$ iid variates $X_i$ from the Normal$(0,\Sigma)$ distribution and another $10^6$ iid variates $Y_i$ in the same way, and computed the $10^6$ dot products $X_i\cdot Y_i$. The plot shows the histogram of these dot products (omitting some of the most extreme values--the range was from $-12$ to $15$): As before, the agreement is excellent. Furthermore, the moments match well through the eighth and reasonably well even at the tenth: k mgf simulation/k! 2 1.45313 1.45208 4 2.59009 2.59605 6 5.20824 5.29333 8 11.0994 11.3115 10 24.4166 22.9982 Addendum (Added 9 August 2013.) $f_{n,\sigma}$ is an instance of the variance-gamma distribution, which originally was defined as " the normal variance-mean mixture where the mixing density is the gamma distribution." It has a standard location ($0$), asymmetry parameter of $0$ (it is symmetric), scale parameter $\sigma^2$, and shape parameter $n/2$ (according to the Wikipedia parameterization).
Moment generating function of the inner product of two gaussian random vectors First let's address the case $\Sigma = \sigma\mathbb{I}$. At the end is the (easy) generalization to arbitrary $\Sigma$. Begin by observing the inner product is the sum of iid variables, each of them
25,155
Fitting a Poisson GLM mixed model with a random slope and intercept
In R: library(lme4) lmer(counts ~ dependent_variable + (1+time|ID), family="poisson") In this case $Y_i \sim {\rm Poisson}(\lambda_i)$ and this code fits the model $$ \log(\lambda_i) = \beta_0 + \beta_1 X_i + \eta_{i1} + \eta_{i2}t $$ where $X_i$ is dependent_variable, $t$ is time and $i$ is ID. $\beta_0, \beta_1$ are fixed effects and $\eta_{i1}, \eta_{i2}$ are random effects whose variances are estimated by the model. Here's an example with some quickly simulated data where the random effect variances truly are 0, the covariate has no effect, every outcome is ${\rm Poisson}(1)$, and each individual is seen 10 times at times $t = 1,...,10$. x = rnorm(100) t = rep(1:10,each=10) ID = rep(1:10,10) y = rpois(100,1) g <- lmer(y ~ x + (1+t|ID), family="poisson") summary(g) Generalized linear mixed model fit by the Laplace approximation Formula: y ~ x + (1 + t | ID) AIC BIC logLik deviance 108.8 121.9 -49.42 98.85 Random effects: Groups Name Variance Std.Dev. Corr ID (Intercept) 0.0285038 0.168831 t 0.0027741 0.052669 -1.000 Number of obs: 100, groups: ID, 10 Fixed effects: Estimate Std. Error z value Pr(>|z|) (Intercept) -0.09078 0.11808 -0.769 0.442 x 0.13670 0.08845 1.546 0.122 Correlation of Fixed Effects: (Intr) x -0.127 One point of caution - the Std.Dev. column is just the square root of the Variance column, NOT the standard error of the variance estimate!
Fitting a Poisson GLM mixed model with a random slope and intercept
In R: library(lme4) lmer(counts ~ dependent_variable + (1+time|ID), family="poisson") In this case $Y_i \sim {\rm Poisson}(\lambda_i)$ and this code fits the model $$ \log(\lambda_i) = \beta_0 + \
Fitting a Poisson GLM mixed model with a random slope and intercept In R: library(lme4) lmer(counts ~ dependent_variable + (1+time|ID), family="poisson") In this case $Y_i \sim {\rm Poisson}(\lambda_i)$ and this code fits the model $$ \log(\lambda_i) = \beta_0 + \beta_1 X_i + \eta_{i1} + \eta_{i2}t $$ where $X_i$ is dependent_variable, $t$ is time and $i$ is ID. $\beta_0, \beta_1$ are fixed effects and $\eta_{i1}, \eta_{i2}$ are random effects whose variances are estimated by the model. Here's an example with some quickly simulated data where the random effect variances truly are 0, the covariate has no effect, every outcome is ${\rm Poisson}(1)$, and each individual is seen 10 times at times $t = 1,...,10$. x = rnorm(100) t = rep(1:10,each=10) ID = rep(1:10,10) y = rpois(100,1) g <- lmer(y ~ x + (1+t|ID), family="poisson") summary(g) Generalized linear mixed model fit by the Laplace approximation Formula: y ~ x + (1 + t | ID) AIC BIC logLik deviance 108.8 121.9 -49.42 98.85 Random effects: Groups Name Variance Std.Dev. Corr ID (Intercept) 0.0285038 0.168831 t 0.0027741 0.052669 -1.000 Number of obs: 100, groups: ID, 10 Fixed effects: Estimate Std. Error z value Pr(>|z|) (Intercept) -0.09078 0.11808 -0.769 0.442 x 0.13670 0.08845 1.546 0.122 Correlation of Fixed Effects: (Intr) x -0.127 One point of caution - the Std.Dev. column is just the square root of the Variance column, NOT the standard error of the variance estimate!
Fitting a Poisson GLM mixed model with a random slope and intercept In R: library(lme4) lmer(counts ~ dependent_variable + (1+time|ID), family="poisson") In this case $Y_i \sim {\rm Poisson}(\lambda_i)$ and this code fits the model $$ \log(\lambda_i) = \beta_0 + \
25,156
Fitting a Poisson GLM mixed model with a random slope and intercept
In SAS: proc glimmix data = yourdata ic = q; class id; model y = x / dist = poisson solution; random intercept t / subject = id; run; But then of course there are plenty of options, more or less useful, to play with.
Fitting a Poisson GLM mixed model with a random slope and intercept
In SAS: proc glimmix data = yourdata ic = q; class id; model y = x / dist = poisson solution; random intercept t / subject = id; run; But then of course there are plenty of options, more
Fitting a Poisson GLM mixed model with a random slope and intercept In SAS: proc glimmix data = yourdata ic = q; class id; model y = x / dist = poisson solution; random intercept t / subject = id; run; But then of course there are plenty of options, more or less useful, to play with.
Fitting a Poisson GLM mixed model with a random slope and intercept In SAS: proc glimmix data = yourdata ic = q; class id; model y = x / dist = poisson solution; random intercept t / subject = id; run; But then of course there are plenty of options, more
25,157
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions?
There is quite a bit of discussion about this on the AP site. You can use whatever statistic you want, provided that you are clear about what you do and look at the appropriate null distribution to calculate p-values or thresholds. But some statistics are better than others; in this case you'd be looking for (a) null distribution easily calculated and (b) power to detect difference. But I don't know why you'd favor the unpooled variance over the pooled variance for the test, though it could be preferred in calculating a confidence interval for the difference.
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions?
There is quite a bit of discussion about this on the AP site. You can use whatever statistic you want, provided that you are clear about what you do and look at the appropriate null distribution to ca
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions? There is quite a bit of discussion about this on the AP site. You can use whatever statistic you want, provided that you are clear about what you do and look at the appropriate null distribution to calculate p-values or thresholds. But some statistics are better than others; in this case you'd be looking for (a) null distribution easily calculated and (b) power to detect difference. But I don't know why you'd favor the unpooled variance over the pooled variance for the test, though it could be preferred in calculating a confidence interval for the difference.
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions? There is quite a bit of discussion about this on the AP site. You can use whatever statistic you want, provided that you are clear about what you do and look at the appropriate null distribution to ca
25,158
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions?
The unpooled variance tends to be too small. This is because under the null hypothesis there will still be chance variation in the two observed proportions, although the underlying probabilities are equal. This chance variation contributes to the pooled variance but not to the unpooled variance. As a result, $z$ for the unpooled statistic does not even approximately have a standard normal distribution. For instance, when $n_1 = n_2$ and the true probabilities are both $1/2$, the variance of $z$ is only $1/2$ instead of $1$. By using tables of the standard normal distribution, you will get incorrect p-values: they will tend to be artificially small, too often rejecting the null when the evidence is not really there. Nevertheless, one wonders whether this could be corrected. It can. The question becomes whether a corrected value of $z$, based on unpooled estimates, could have greater power to detect deviations from the null hypothesis. A few quick simulations suggest this is not the case: the pooled test (compared to a properly adjusted unpooled test) has a better chance of rejecting the null whenever the null is false. Therefore I haven't bothered to work out the formula for the unpooled correction; it seems pointless. In summary, the unpooled test is wrong, but with an appropriate correction, it can be made legitimate. However, it appears to be inferior to the pooled test.
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions?
The unpooled variance tends to be too small. This is because under the null hypothesis there will still be chance variation in the two observed proportions, although the underlying probabilities are
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions? The unpooled variance tends to be too small. This is because under the null hypothesis there will still be chance variation in the two observed proportions, although the underlying probabilities are equal. This chance variation contributes to the pooled variance but not to the unpooled variance. As a result, $z$ for the unpooled statistic does not even approximately have a standard normal distribution. For instance, when $n_1 = n_2$ and the true probabilities are both $1/2$, the variance of $z$ is only $1/2$ instead of $1$. By using tables of the standard normal distribution, you will get incorrect p-values: they will tend to be artificially small, too often rejecting the null when the evidence is not really there. Nevertheless, one wonders whether this could be corrected. It can. The question becomes whether a corrected value of $z$, based on unpooled estimates, could have greater power to detect deviations from the null hypothesis. A few quick simulations suggest this is not the case: the pooled test (compared to a properly adjusted unpooled test) has a better chance of rejecting the null whenever the null is false. Therefore I haven't bothered to work out the formula for the unpooled correction; it seems pointless. In summary, the unpooled test is wrong, but with an appropriate correction, it can be made legitimate. However, it appears to be inferior to the pooled test.
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions? The unpooled variance tends to be too small. This is because under the null hypothesis there will still be chance variation in the two observed proportions, although the underlying probabilities are
25,159
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions?
The unpooled z-test is valid, but in general has worse small-sample properties than the pooled z-test Consider the estimated difference of proportions $\hat{d} = \hat{p}_1 - \hat{p}_2$. There is nothing fundamentally wrong with using the following unpooled estimate of the variance of $\hat{d}$: $$ \hat{V}_{U} = \frac{\hat{p}_1 (1 - \hat{p}_1)}{n_1} + \frac{\hat{p}_2 (1 - \hat{p}_2)}{n_2} $$ In fact, it is frequently used when constructing confidence intervals. Most elementary textbooks suggest the following approximate $100(1 - \alpha)$ confidence interval for $p_1 - p_2$: $$\hat{d} \pm z_{\alpha/2} \sqrt{\frac{\hat{p}_1 (1 - \hat{p}_1)}{n_1} + \frac{\hat{p}_2 (1 - \hat{p}_2)}{n_2}} $$ which directly involves $\hat{V}_U$. However, when testing $p_1 = p_2$, the following pooled estimator is often preferable: $$ \hat{V}_{P} = \hat{p}(1 - \hat{p})\left(\frac{1}{n_1} + \frac{1}{n_2}\right)$$ The pooled estimator is only valid when $p_1 = p_2$, which is why it can't be used while constructing confidence intervals. The unpooled estimated variance of $\hat{d}$ is slightly more biased Let $n = n_1 + n_2$. The true variance of $\hat{d} = \hat{p}_1 - \hat{p}_2$ is equal to $$\begin{aligned}V(\hat{d}) &= Var(\hat{p}_1) + Var(\hat{p}_2) \\ &= \frac{p_1(1-p_1)}{n_1} + \frac{p_2(1-p_2)}{n_2} \end{aligned}$$ When $p_1 = p_2 = p$, this reduces to $$V(\hat{d}) = p(1-p)\left(\frac{1}{n_1} + \frac{1}{n_2}\right) $$ The pooled estimator of the variance of $\hat{d}$ has bias equal to $$E[\hat{V}_P] - V[\hat{p}] = \frac{-p(1 -p)}{n}\left(\frac{1}{n_1} + \frac{1}{n_2} \right)$$ Similarly, the unpooled estimator of the variance has bias equals to $$E[\hat{V}_U] - V[\hat{p}] = -p(1-p)\left(\frac{1}{n_1^2} + \frac{1}{n_2^2} \right)$$ Both biases go to zero as $n \to \infty$, but because $n = n_1 + n_2$, the bias of $\hat{V}_P$ will always be less than $\hat{V}_U$. Specifically, when $n_1 = n_2$, the pooled estimate of the variance will be half as biased as the unpooled estimator. It is unclear which test rejects more often The z-test statistic for the unpooled test will be more extreme than the pooled z-test statistic when $$\frac{|\hat{d}|}{\sqrt{\hat{V}_P}} = \frac{|\hat{d}|}{\sqrt{\hat{p}(1 - \hat{p})(\frac{1}{n_1} + \frac{1}{n_2})}} < \frac{|\hat{d}|}{ \sqrt{ \frac{ \hat{p}_1 (1 - \hat{p}_1)}{n_1} + \frac{ \hat{p}_2 (1 - \hat{p}_2)}{n_2} } } = \frac{|\hat{d}|}{\sqrt{\hat{V}_U}}$$ or equivalently, when the estimated variance of the unpooled test is smaller than that of the pooled test, $$ \hat{p}(1 - \hat{p})\left(\frac{1}{n_1} + \frac{1}{n_2}\right) > \frac{ \hat{p}_1 (1 - \hat{p}_1)}{n_1} + \frac{ \hat{p}_2 (1 - \hat{p}_2)}{n_2} $$ It is unclear when this holds. However, for samples of equal size, $n_1 = n_2 = 0.5$, this simplifies to $$\hat{p}(1 - \hat{p}) > \frac{\hat{p}_1 (1 - \hat{p}_1) + \hat{p}_2 (1 - \hat{p}_2)}{2} $$ Because $f(x) = x(1-x)$ is strictly concave, the previous inequality will be always true. Therefore, for equal sample sizes, the unpooled test always reject as or more often than the pooled test. Simulations To simulate the two estimators, I ran 100 millions simulations in R with low sample sizes ($n_1 = n_2 = 20$, $p_1 = p_2 = 0.5$). Under these parameters, the true variance of $\hat{d}$ equals $0.025$. Parameter Pooled Unpooled Variance of $\hat{z}$ 1.0255 1.1146 Mean of $\hat{V}$ 0.0244 0.0237 Rejection rate when $\alpha$ = 0.05 0.0425 0.0807 We see that the bias of the unpooled variance is twice as large as the bias of the pooled variance, leading to a $z$ statistic with a higher variance than a standard normal (1.115 vs 1) and that this leads to a higher null rejection rate than specified ($\alpha$ = 0.05). However, as we increase the sample size, this difference vanishes. If $n_1 = n_2 = 100$, we get a true standard error of 0.005, and the following results: Parameter Pooled Unpooled Variance of $\hat{z}$ 1.005 1.020 Mean of $\hat{V}$ 0.004975 0.004950 Rejection rate when $\alpha$ = 0.05 0.056 0.056 The bias of $ \hat{V}_U$ is still twice as high as $\hat{V}_B$, but the bias of either is so low that it does not matter, and both tests have a similar rejection rate. This goes against the results of @whuber, who claims without justification that the variance of the z-test statistic $\hat{z}_{U}$ is 1/2, while in fact it is slightly above 1. The pooled and unpooled z-tests are asymptotically equivalent when the null hypothesis is true. I define $c_{nk} = \frac{n_k}{n}$, $k = 1,2$. The true variance of $\hat{d}$ can be written as $$\begin{aligned} Var(\hat{d}) &= \frac{1}{n} p(1 - p)\left( \frac{1}{c_{n1}} + \frac{1}{c_{n2}}\right) \end{aligned}$$ If we assume that the two samples grow roughly at the same speed, $c_{nk} \to c_k$, with $0 < c_k < 1$, then from the Central Limit Theorem $$\frac{\hat{d}}{Var(\hat{d})} = n^{-1/2}\frac{\hat{d}}{\sqrt{ p(1 - p)\left( \frac{1}{c_{n1}} + \frac{1}{c_{n2}} \right)}} \to_d n^{-1/2}\frac{\hat{d}}{\sqrt{ p(1 - p)\left( \frac{1}{c_{1}} + \frac{1}{c_{2}} \right)}} \to_d N(0,1) $$ which justifies the use of the normal distribution. However since $p$ is unknown, we can't use this to construct the test statistic. Instead, we need to use our sample estimates to get an asymptotically valid estimator. According to the Strong Law of Large Numbers, we have $$\begin{aligned} \hat{p}_1 \to_{a.s.} p \\ \hat{p}_2 \to_{a.s.} p \\ \hat{p} = \frac{x_1 + x_2}{n} \to_{a.s.} p \end{aligned}$$ From the Continuous Mapping Theorem, we have $$\begin{aligned} \hat{p} (1 - \hat{p})\left(\frac{1}{c_{n1}} + \frac{1}{c_{n2}} \right)\to_{a.s.} p(1-p)\left(\frac{1}{c_1} + \frac{1}{c_2} \right) \\ \frac{\hat{p}_1(1 - \hat{p}_1)}{c_{n1}} + \frac{\hat{p}_2(1 - \hat{p}_2)}{c_{n2}} \to_{a.s.} p(1-p)\left(\frac{1}{c_1} + \frac{1}{c_2} \right) \end{aligned}$$ Therefore, from Slutsky's theorem, where can $$ \begin{aligned} n^{-1/2}\frac{\hat{d}}{\sqrt{ \hat{p}(1 - \hat{p})\left( \frac{1}{c_{n1}} + \frac{1}{c_{n2}} \right)}} &\to_{d} n^{-1/2}\frac{\hat{d}}{\sqrt{ \frac{\hat{p}_1(1 - \hat{p}_1)}{c_{n1}} + \frac{\hat{p}_2(1 - \hat{p}_2)}{c_{n2}}}} \\ &\to_{d} n^{-1/2}\frac{\hat{d}}{\sqrt{ p(1 - p)\left( \frac{1}{c_{n1}} + \frac{1}{c_{n2}} \right)}} \\ &\to_{d} N(0,1) \end{aligned}$$ In order words, asymptotically and when the null hypothesis is true, there is no difference between using the exact variance, the unpooled variance, or the pooled variance. The power of the pooled and unpooled z-test will be different when the alternative is true Under the alternative hypothesis that $p_1 \ne p_2$, we have $$ \hat{p} \to_{a.s} p_1 c_{1} + p_2 c_{2} = \tilde{p} $$ Therefore, we will asymptotically have, for the pooled estimator $$ \hat{p} (1 - \hat{p}) \left(\frac{1}{c_{n1}} + \frac{1}{c_{n2}}\right) \to_{a.s.} \tilde{p}(1 - \tilde{p})(\frac{1}{c_1} + \frac{1}{c_2}) $$ Meanwhile, the unpooled estimator will keep converging to the actual variance, because $$ \frac{ \hat{p}_1 (1 - \hat{p}_1)}{c_{n1}} + \frac{ \hat{p}_2 (1 - \hat{p}_2)}{c_{n2}} \to_{a.s.} = \frac{ p_1 (1 - p_1)}{c_{1}} + \frac{ p_2 (1 - p_2)}{c_{2}} $$ The unpooled estimator will be asymptotically more powerful when $$\frac{1}{\sqrt{\tilde{p}(1 - \tilde{p})(\frac{1}{c_1} + \frac{1}{c_2})}} < \frac{1}{ \sqrt{ \frac{ p_1 (1 - p_1)}{c_{1}} + \frac{ p_2 (1 - p_2)}{c_{2}} } }$$ or equivalently $$ \tilde{p}(1 - \tilde{p})(\frac{1}{c_1} + \frac{1}{c_2}) > \frac{ p_1 (1 - p_1)}{c_{1}} + \frac{ p_2 (1 - p_2)}{c_{2}} $$ Either estimator could be more powerful, depending on $p_1$, $p_2$, $c_1$ and $c_2$. However, when the two sample sizes are equal ($c_1 = c_2 = 0.5$), the condition simplifies to $$ \tilde{p}(1 - \tilde{p}) > \frac{p_1 (1 - p_1) + p_2 (1 - p_2)}{2} $$ Because $f(x) = x(1-x)$ is strictly concave, the previous inequality will be always true. Therefore, for equal sample sizes, the unpooled test is always asymptotically more powerful.
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions?
The unpooled z-test is valid, but in general has worse small-sample properties than the pooled z-test Consider the estimated difference of proportions $\hat{d} = \hat{p}_1 - \hat{p}_2$. There is nothi
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions? The unpooled z-test is valid, but in general has worse small-sample properties than the pooled z-test Consider the estimated difference of proportions $\hat{d} = \hat{p}_1 - \hat{p}_2$. There is nothing fundamentally wrong with using the following unpooled estimate of the variance of $\hat{d}$: $$ \hat{V}_{U} = \frac{\hat{p}_1 (1 - \hat{p}_1)}{n_1} + \frac{\hat{p}_2 (1 - \hat{p}_2)}{n_2} $$ In fact, it is frequently used when constructing confidence intervals. Most elementary textbooks suggest the following approximate $100(1 - \alpha)$ confidence interval for $p_1 - p_2$: $$\hat{d} \pm z_{\alpha/2} \sqrt{\frac{\hat{p}_1 (1 - \hat{p}_1)}{n_1} + \frac{\hat{p}_2 (1 - \hat{p}_2)}{n_2}} $$ which directly involves $\hat{V}_U$. However, when testing $p_1 = p_2$, the following pooled estimator is often preferable: $$ \hat{V}_{P} = \hat{p}(1 - \hat{p})\left(\frac{1}{n_1} + \frac{1}{n_2}\right)$$ The pooled estimator is only valid when $p_1 = p_2$, which is why it can't be used while constructing confidence intervals. The unpooled estimated variance of $\hat{d}$ is slightly more biased Let $n = n_1 + n_2$. The true variance of $\hat{d} = \hat{p}_1 - \hat{p}_2$ is equal to $$\begin{aligned}V(\hat{d}) &= Var(\hat{p}_1) + Var(\hat{p}_2) \\ &= \frac{p_1(1-p_1)}{n_1} + \frac{p_2(1-p_2)}{n_2} \end{aligned}$$ When $p_1 = p_2 = p$, this reduces to $$V(\hat{d}) = p(1-p)\left(\frac{1}{n_1} + \frac{1}{n_2}\right) $$ The pooled estimator of the variance of $\hat{d}$ has bias equal to $$E[\hat{V}_P] - V[\hat{p}] = \frac{-p(1 -p)}{n}\left(\frac{1}{n_1} + \frac{1}{n_2} \right)$$ Similarly, the unpooled estimator of the variance has bias equals to $$E[\hat{V}_U] - V[\hat{p}] = -p(1-p)\left(\frac{1}{n_1^2} + \frac{1}{n_2^2} \right)$$ Both biases go to zero as $n \to \infty$, but because $n = n_1 + n_2$, the bias of $\hat{V}_P$ will always be less than $\hat{V}_U$. Specifically, when $n_1 = n_2$, the pooled estimate of the variance will be half as biased as the unpooled estimator. It is unclear which test rejects more often The z-test statistic for the unpooled test will be more extreme than the pooled z-test statistic when $$\frac{|\hat{d}|}{\sqrt{\hat{V}_P}} = \frac{|\hat{d}|}{\sqrt{\hat{p}(1 - \hat{p})(\frac{1}{n_1} + \frac{1}{n_2})}} < \frac{|\hat{d}|}{ \sqrt{ \frac{ \hat{p}_1 (1 - \hat{p}_1)}{n_1} + \frac{ \hat{p}_2 (1 - \hat{p}_2)}{n_2} } } = \frac{|\hat{d}|}{\sqrt{\hat{V}_U}}$$ or equivalently, when the estimated variance of the unpooled test is smaller than that of the pooled test, $$ \hat{p}(1 - \hat{p})\left(\frac{1}{n_1} + \frac{1}{n_2}\right) > \frac{ \hat{p}_1 (1 - \hat{p}_1)}{n_1} + \frac{ \hat{p}_2 (1 - \hat{p}_2)}{n_2} $$ It is unclear when this holds. However, for samples of equal size, $n_1 = n_2 = 0.5$, this simplifies to $$\hat{p}(1 - \hat{p}) > \frac{\hat{p}_1 (1 - \hat{p}_1) + \hat{p}_2 (1 - \hat{p}_2)}{2} $$ Because $f(x) = x(1-x)$ is strictly concave, the previous inequality will be always true. Therefore, for equal sample sizes, the unpooled test always reject as or more often than the pooled test. Simulations To simulate the two estimators, I ran 100 millions simulations in R with low sample sizes ($n_1 = n_2 = 20$, $p_1 = p_2 = 0.5$). Under these parameters, the true variance of $\hat{d}$ equals $0.025$. Parameter Pooled Unpooled Variance of $\hat{z}$ 1.0255 1.1146 Mean of $\hat{V}$ 0.0244 0.0237 Rejection rate when $\alpha$ = 0.05 0.0425 0.0807 We see that the bias of the unpooled variance is twice as large as the bias of the pooled variance, leading to a $z$ statistic with a higher variance than a standard normal (1.115 vs 1) and that this leads to a higher null rejection rate than specified ($\alpha$ = 0.05). However, as we increase the sample size, this difference vanishes. If $n_1 = n_2 = 100$, we get a true standard error of 0.005, and the following results: Parameter Pooled Unpooled Variance of $\hat{z}$ 1.005 1.020 Mean of $\hat{V}$ 0.004975 0.004950 Rejection rate when $\alpha$ = 0.05 0.056 0.056 The bias of $ \hat{V}_U$ is still twice as high as $\hat{V}_B$, but the bias of either is so low that it does not matter, and both tests have a similar rejection rate. This goes against the results of @whuber, who claims without justification that the variance of the z-test statistic $\hat{z}_{U}$ is 1/2, while in fact it is slightly above 1. The pooled and unpooled z-tests are asymptotically equivalent when the null hypothesis is true. I define $c_{nk} = \frac{n_k}{n}$, $k = 1,2$. The true variance of $\hat{d}$ can be written as $$\begin{aligned} Var(\hat{d}) &= \frac{1}{n} p(1 - p)\left( \frac{1}{c_{n1}} + \frac{1}{c_{n2}}\right) \end{aligned}$$ If we assume that the two samples grow roughly at the same speed, $c_{nk} \to c_k$, with $0 < c_k < 1$, then from the Central Limit Theorem $$\frac{\hat{d}}{Var(\hat{d})} = n^{-1/2}\frac{\hat{d}}{\sqrt{ p(1 - p)\left( \frac{1}{c_{n1}} + \frac{1}{c_{n2}} \right)}} \to_d n^{-1/2}\frac{\hat{d}}{\sqrt{ p(1 - p)\left( \frac{1}{c_{1}} + \frac{1}{c_{2}} \right)}} \to_d N(0,1) $$ which justifies the use of the normal distribution. However since $p$ is unknown, we can't use this to construct the test statistic. Instead, we need to use our sample estimates to get an asymptotically valid estimator. According to the Strong Law of Large Numbers, we have $$\begin{aligned} \hat{p}_1 \to_{a.s.} p \\ \hat{p}_2 \to_{a.s.} p \\ \hat{p} = \frac{x_1 + x_2}{n} \to_{a.s.} p \end{aligned}$$ From the Continuous Mapping Theorem, we have $$\begin{aligned} \hat{p} (1 - \hat{p})\left(\frac{1}{c_{n1}} + \frac{1}{c_{n2}} \right)\to_{a.s.} p(1-p)\left(\frac{1}{c_1} + \frac{1}{c_2} \right) \\ \frac{\hat{p}_1(1 - \hat{p}_1)}{c_{n1}} + \frac{\hat{p}_2(1 - \hat{p}_2)}{c_{n2}} \to_{a.s.} p(1-p)\left(\frac{1}{c_1} + \frac{1}{c_2} \right) \end{aligned}$$ Therefore, from Slutsky's theorem, where can $$ \begin{aligned} n^{-1/2}\frac{\hat{d}}{\sqrt{ \hat{p}(1 - \hat{p})\left( \frac{1}{c_{n1}} + \frac{1}{c_{n2}} \right)}} &\to_{d} n^{-1/2}\frac{\hat{d}}{\sqrt{ \frac{\hat{p}_1(1 - \hat{p}_1)}{c_{n1}} + \frac{\hat{p}_2(1 - \hat{p}_2)}{c_{n2}}}} \\ &\to_{d} n^{-1/2}\frac{\hat{d}}{\sqrt{ p(1 - p)\left( \frac{1}{c_{n1}} + \frac{1}{c_{n2}} \right)}} \\ &\to_{d} N(0,1) \end{aligned}$$ In order words, asymptotically and when the null hypothesis is true, there is no difference between using the exact variance, the unpooled variance, or the pooled variance. The power of the pooled and unpooled z-test will be different when the alternative is true Under the alternative hypothesis that $p_1 \ne p_2$, we have $$ \hat{p} \to_{a.s} p_1 c_{1} + p_2 c_{2} = \tilde{p} $$ Therefore, we will asymptotically have, for the pooled estimator $$ \hat{p} (1 - \hat{p}) \left(\frac{1}{c_{n1}} + \frac{1}{c_{n2}}\right) \to_{a.s.} \tilde{p}(1 - \tilde{p})(\frac{1}{c_1} + \frac{1}{c_2}) $$ Meanwhile, the unpooled estimator will keep converging to the actual variance, because $$ \frac{ \hat{p}_1 (1 - \hat{p}_1)}{c_{n1}} + \frac{ \hat{p}_2 (1 - \hat{p}_2)}{c_{n2}} \to_{a.s.} = \frac{ p_1 (1 - p_1)}{c_{1}} + \frac{ p_2 (1 - p_2)}{c_{2}} $$ The unpooled estimator will be asymptotically more powerful when $$\frac{1}{\sqrt{\tilde{p}(1 - \tilde{p})(\frac{1}{c_1} + \frac{1}{c_2})}} < \frac{1}{ \sqrt{ \frac{ p_1 (1 - p_1)}{c_{1}} + \frac{ p_2 (1 - p_2)}{c_{2}} } }$$ or equivalently $$ \tilde{p}(1 - \tilde{p})(\frac{1}{c_1} + \frac{1}{c_2}) > \frac{ p_1 (1 - p_1)}{c_{1}} + \frac{ p_2 (1 - p_2)}{c_{2}} $$ Either estimator could be more powerful, depending on $p_1$, $p_2$, $c_1$ and $c_2$. However, when the two sample sizes are equal ($c_1 = c_2 = 0.5$), the condition simplifies to $$ \tilde{p}(1 - \tilde{p}) > \frac{p_1 (1 - p_1) + p_2 (1 - p_2)}{2} $$ Because $f(x) = x(1-x)$ is strictly concave, the previous inequality will be always true. Therefore, for equal sample sizes, the unpooled test is always asymptotically more powerful.
Is there a reference that legitimises the use of the unpooled z-test to compare two proportions? The unpooled z-test is valid, but in general has worse small-sample properties than the pooled z-test Consider the estimated difference of proportions $\hat{d} = \hat{p}_1 - \hat{p}_2$. There is nothi
25,160
Is it valid to aggregate a time series to make it look more meaningful?
This totally depends on your time series and what effect you want to discover/proof etc. An important thing here is, what kind of periods do you have in your data. Make a spectrum of you data and see what frequencies are common in you data. Anyway, you are not lying when you decide to display aggregated values. When you are looking to effects that are occurring over weeks (like, more violence in summer when it's hot weather) it is the right thing to do. Maybe you can also take a look at the Hilbert Huang Transform. This will give you Intrinsic Mode Functions that are very handy for visual analyses.
Is it valid to aggregate a time series to make it look more meaningful?
This totally depends on your time series and what effect you want to discover/proof etc. An important thing here is, what kind of periods do you have in your data. Make a spectrum of you data and see
Is it valid to aggregate a time series to make it look more meaningful? This totally depends on your time series and what effect you want to discover/proof etc. An important thing here is, what kind of periods do you have in your data. Make a spectrum of you data and see what frequencies are common in you data. Anyway, you are not lying when you decide to display aggregated values. When you are looking to effects that are occurring over weeks (like, more violence in summer when it's hot weather) it is the right thing to do. Maybe you can also take a look at the Hilbert Huang Transform. This will give you Intrinsic Mode Functions that are very handy for visual analyses.
Is it valid to aggregate a time series to make it look more meaningful? This totally depends on your time series and what effect you want to discover/proof etc. An important thing here is, what kind of periods do you have in your data. Make a spectrum of you data and see
25,161
Is it valid to aggregate a time series to make it look more meaningful?
It's very common in forecasting to aggregate data in order to increase the signal/noise ratio. There are several papers on the effect of temporal aggregation on forecast accuracy in economics, for example. What you're probably seeing in the daily data is a weak signal that is being swamped by noise, whereas the weekly and monthly data are showing a stronger signal that is more visible. Whether you want to use temporal aggregation depends entirely on what your purpose is. If you need forecasts of daily incidents, then aggregation isn't going to be much use. If you are interested in exploring the effects of several covariates on the frequency of incidence, and all your data are available on a daily basis, then I would probably use the daily data as it will give a larger sample size and probably enable you to detect the effects more easily. Since you are using the forecast package, presumably you are interested in time series forecasting. So do you need daily forecasts, weekly forecasts or monthly forecasts? The answer will determine whether aggregation is appropriate for you.
Is it valid to aggregate a time series to make it look more meaningful?
It's very common in forecasting to aggregate data in order to increase the signal/noise ratio. There are several papers on the effect of temporal aggregation on forecast accuracy in economics, for ex
Is it valid to aggregate a time series to make it look more meaningful? It's very common in forecasting to aggregate data in order to increase the signal/noise ratio. There are several papers on the effect of temporal aggregation on forecast accuracy in economics, for example. What you're probably seeing in the daily data is a weak signal that is being swamped by noise, whereas the weekly and monthly data are showing a stronger signal that is more visible. Whether you want to use temporal aggregation depends entirely on what your purpose is. If you need forecasts of daily incidents, then aggregation isn't going to be much use. If you are interested in exploring the effects of several covariates on the frequency of incidence, and all your data are available on a daily basis, then I would probably use the daily data as it will give a larger sample size and probably enable you to detect the effects more easily. Since you are using the forecast package, presumably you are interested in time series forecasting. So do you need daily forecasts, weekly forecasts or monthly forecasts? The answer will determine whether aggregation is appropriate for you.
Is it valid to aggregate a time series to make it look more meaningful? It's very common in forecasting to aggregate data in order to increase the signal/noise ratio. There are several papers on the effect of temporal aggregation on forecast accuracy in economics, for ex
25,162
Is it valid to aggregate a time series to make it look more meaningful?
The problem (dilemma) you face appears to be the one of selecting an optimal (or otherwise good) sampling interval for revising your forecasts. To start with, see link text of Brown's famous book, which would also qualify as a good reference. It all boils down to "balancing the risk of not noticing a change quickly against the inherent variability of the data and the cost of revising plans frequently". If you are not prepared to revise your forecast (and the decisions that motivated it) daily, you don't really need to use the (noisiest) daily data. An important point, often lost in the contemporary forecasting literature, is that forecasts are only necessary to assist with making a decision (unless one also knows how to derive fun from them).
Is it valid to aggregate a time series to make it look more meaningful?
The problem (dilemma) you face appears to be the one of selecting an optimal (or otherwise good) sampling interval for revising your forecasts. To start with, see link text of Brown's famous book, whi
Is it valid to aggregate a time series to make it look more meaningful? The problem (dilemma) you face appears to be the one of selecting an optimal (or otherwise good) sampling interval for revising your forecasts. To start with, see link text of Brown's famous book, which would also qualify as a good reference. It all boils down to "balancing the risk of not noticing a change quickly against the inherent variability of the data and the cost of revising plans frequently". If you are not prepared to revise your forecast (and the decisions that motivated it) daily, you don't really need to use the (noisiest) daily data. An important point, often lost in the contemporary forecasting literature, is that forecasts are only necessary to assist with making a decision (unless one also knows how to derive fun from them).
Is it valid to aggregate a time series to make it look more meaningful? The problem (dilemma) you face appears to be the one of selecting an optimal (or otherwise good) sampling interval for revising your forecasts. To start with, see link text of Brown's famous book, whi
25,163
Rationale behind defining distribution function with strict inequality
In Section "1.1 Monotone Functions" of Chung's classic probability textbook A Course in Probability Theory, it is stated: How can $f_1$ and $f_2$ differ at all? This can happen only when $f_1(x)$ and $f_2(x)$ assume different values in the interval $(f_1(x-), f_1(x+))= (f_2(x-), f_2(x+))$. It will turn out in Chapter 2 (see in particular Exercise 21 of Sec. 2.2) that the precise value of $f$ at a jump is quite unessential for our purposes and may be modified, subject to (3), to suit our convenience. More precisely, given the function $f$, we can define a new function $\tilde{f}$ in several different ways, such as \begin{align} \tilde{f}(x) = f(x-), \tilde{f}(x) = f(x+), \tilde{f}(x) = \frac{f(x-) + f(x+)}{2}, \end{align} and use one of these instead of the original one. The third modification is found to be convenient in Fourier analysis, but either one of the first two is more suitable for probability theory. We have a free choice between them and we shall choose the second, namely, right continuity. You can interpret $f_1(x), f_2(x)$ in the above quote as $P(X < x), P(X \leq x)$ respectively (in the original text, $f_1$ and $f_2$ are two nondecreasing functions agreed on a dense set $D \subset (-\infty, +\infty)$, which are discussed for introducing the probability distribution function aftermath). And as the highlighted text shows, in probability theory, there is no particular reason of preferring $f_2(x)$ to $f_1(x)$ (or vice versa). The cited "Exercise 21 of Sec 2.2" basically stated that, with some obvious minor modifications on the relationship between $f_2$ and $\mu$, the fundamental theorem Each distribution function $f_2$ determines a probability measure $\mu$ on $\mathscr{B}^1$. still holds for $f_1$ and $\mu$, supporting the highlighted statement above. To conclude, my short answer to your question is "yes, it is just a matter of taste" -- I remember that my college probability professor, who learned probability theory from Soviet Union's (where the father of modern probability theory A. N. Kolmogorov is from) literature, told us that in Russian probability texts (e.g., the reference mentioned by @User1865345 in the comment), $F(x)$ is defined as $P(X < x)$. On the other hand, in most classical English probability texts that I have seen, such as A Course in Probability Theory by Kai Lai Chung Probability and Measure by Patrick Billingsley Probability: Theory and Examples by Rick Durrett Probability with Martingales by David Williams $F(x)$ is defined as $P(X \leq x)$. One exception is Probability Theory: Independence, Interchangeability, Martingales by Yuan Shih Chow and Henry Teicher, where $F(x)$ is defined as $P[X < x]$.
Rationale behind defining distribution function with strict inequality
In Section "1.1 Monotone Functions" of Chung's classic probability textbook A Course in Probability Theory, it is stated: How can $f_1$ and $f_2$ differ at all? This can happen only when $f_1(x)$ an
Rationale behind defining distribution function with strict inequality In Section "1.1 Monotone Functions" of Chung's classic probability textbook A Course in Probability Theory, it is stated: How can $f_1$ and $f_2$ differ at all? This can happen only when $f_1(x)$ and $f_2(x)$ assume different values in the interval $(f_1(x-), f_1(x+))= (f_2(x-), f_2(x+))$. It will turn out in Chapter 2 (see in particular Exercise 21 of Sec. 2.2) that the precise value of $f$ at a jump is quite unessential for our purposes and may be modified, subject to (3), to suit our convenience. More precisely, given the function $f$, we can define a new function $\tilde{f}$ in several different ways, such as \begin{align} \tilde{f}(x) = f(x-), \tilde{f}(x) = f(x+), \tilde{f}(x) = \frac{f(x-) + f(x+)}{2}, \end{align} and use one of these instead of the original one. The third modification is found to be convenient in Fourier analysis, but either one of the first two is more suitable for probability theory. We have a free choice between them and we shall choose the second, namely, right continuity. You can interpret $f_1(x), f_2(x)$ in the above quote as $P(X < x), P(X \leq x)$ respectively (in the original text, $f_1$ and $f_2$ are two nondecreasing functions agreed on a dense set $D \subset (-\infty, +\infty)$, which are discussed for introducing the probability distribution function aftermath). And as the highlighted text shows, in probability theory, there is no particular reason of preferring $f_2(x)$ to $f_1(x)$ (or vice versa). The cited "Exercise 21 of Sec 2.2" basically stated that, with some obvious minor modifications on the relationship between $f_2$ and $\mu$, the fundamental theorem Each distribution function $f_2$ determines a probability measure $\mu$ on $\mathscr{B}^1$. still holds for $f_1$ and $\mu$, supporting the highlighted statement above. To conclude, my short answer to your question is "yes, it is just a matter of taste" -- I remember that my college probability professor, who learned probability theory from Soviet Union's (where the father of modern probability theory A. N. Kolmogorov is from) literature, told us that in Russian probability texts (e.g., the reference mentioned by @User1865345 in the comment), $F(x)$ is defined as $P(X < x)$. On the other hand, in most classical English probability texts that I have seen, such as A Course in Probability Theory by Kai Lai Chung Probability and Measure by Patrick Billingsley Probability: Theory and Examples by Rick Durrett Probability with Martingales by David Williams $F(x)$ is defined as $P(X \leq x)$. One exception is Probability Theory: Independence, Interchangeability, Martingales by Yuan Shih Chow and Henry Teicher, where $F(x)$ is defined as $P[X < x]$.
Rationale behind defining distribution function with strict inequality In Section "1.1 Monotone Functions" of Chung's classic probability textbook A Course in Probability Theory, it is stated: How can $f_1$ and $f_2$ differ at all? This can happen only when $f_1(x)$ an
25,164
Rationale behind defining distribution function with strict inequality
Like others have mentioned the use of $<$ instead of $\leq$ is just a convention. Here I want to post a remark which is, I believe, interesting enoughy to be placed as an answer. The convention $<$ was used by Kolmogorov in 'Foundations of the Theory of Probability' (see page 15 of this 1956 second edition of the English translation). The function $$F^{(x)}(a) = P^{(x)}(-\infty,a) = P \{ x<a \}$$ where $-\infty$ and $\infty$ are allowable values of $a$ is called the distribution function of the randome variable $x$. It is remarkable that he uses the interval $(-\infty,a)$ instead of $[-\infty,a)$. Maybe Kolmogorov used the $<$ convention, instead of the $\leq$ convention, because he didn't want to use an interval with infinity inclusive. If $a = \infty$ then $F^{(x)}(a) = P^{(x)}(-\infty,\infty)$ and using $P^{(x)}(-\infty,\infty]$ instead would be problematic. I believe this might be a reason for Kolmogorov's convention, although I would not understand exactly why there would be a problem with including infinity in the interval. Maybe because it is not an element in the sample space?
Rationale behind defining distribution function with strict inequality
Like others have mentioned the use of $<$ instead of $\leq$ is just a convention. Here I want to post a remark which is, I believe, interesting enoughy to be placed as an answer. The convention $<$ wa
Rationale behind defining distribution function with strict inequality Like others have mentioned the use of $<$ instead of $\leq$ is just a convention. Here I want to post a remark which is, I believe, interesting enoughy to be placed as an answer. The convention $<$ was used by Kolmogorov in 'Foundations of the Theory of Probability' (see page 15 of this 1956 second edition of the English translation). The function $$F^{(x)}(a) = P^{(x)}(-\infty,a) = P \{ x<a \}$$ where $-\infty$ and $\infty$ are allowable values of $a$ is called the distribution function of the randome variable $x$. It is remarkable that he uses the interval $(-\infty,a)$ instead of $[-\infty,a)$. Maybe Kolmogorov used the $<$ convention, instead of the $\leq$ convention, because he didn't want to use an interval with infinity inclusive. If $a = \infty$ then $F^{(x)}(a) = P^{(x)}(-\infty,\infty)$ and using $P^{(x)}(-\infty,\infty]$ instead would be problematic. I believe this might be a reason for Kolmogorov's convention, although I would not understand exactly why there would be a problem with including infinity in the interval. Maybe because it is not an element in the sample space?
Rationale behind defining distribution function with strict inequality Like others have mentioned the use of $<$ instead of $\leq$ is just a convention. Here I want to post a remark which is, I believe, interesting enoughy to be placed as an answer. The convention $<$ wa
25,165
Rationale behind defining distribution function with strict inequality
A "conceptual consistency criterion" to choose between them per case, is when a value $x^*$ in the support is a "threshold", and then it matters whether consequences kick in if one reaches this threshold or if ones exceeds it. In the first case (consequences kick in when reaching the threshold), using $F_X(x) \equiv \Pr(X<x)$ appears to be the appropriate choice to reflect the conceptual separation of the two "states of the world," since $\Pr(X<x^*)$ describes the probability of "no consequences". In the second case (consequences kick in when exceeding the threshold), one would use $F_X(x) \equiv\Pr(X\leq x)$, which is the "no-consequences" situation in this case. This is just conceptual for a continuous r.v., but becomes important when the random variable has jumps or is discrete.
Rationale behind defining distribution function with strict inequality
A "conceptual consistency criterion" to choose between them per case, is when a value $x^*$ in the support is a "threshold", and then it matters whether consequences kick in if one reaches this thresh
Rationale behind defining distribution function with strict inequality A "conceptual consistency criterion" to choose between them per case, is when a value $x^*$ in the support is a "threshold", and then it matters whether consequences kick in if one reaches this threshold or if ones exceeds it. In the first case (consequences kick in when reaching the threshold), using $F_X(x) \equiv \Pr(X<x)$ appears to be the appropriate choice to reflect the conceptual separation of the two "states of the world," since $\Pr(X<x^*)$ describes the probability of "no consequences". In the second case (consequences kick in when exceeding the threshold), one would use $F_X(x) \equiv\Pr(X\leq x)$, which is the "no-consequences" situation in this case. This is just conceptual for a continuous r.v., but becomes important when the random variable has jumps or is discrete.
Rationale behind defining distribution function with strict inequality A "conceptual consistency criterion" to choose between them per case, is when a value $x^*$ in the support is a "threshold", and then it matters whether consequences kick in if one reaches this thresh
25,166
What kind of distribution does this have?
Let $Z$ have a Gamma$(n,1)$ distribution, which has density $$f_Z(z) = \frac{1}{\Gamma(n)}\, z^{n-1} \,e^{-z}\,\mathrm{d}z.$$ Let $\lambda \gt 0.$ Then $$X = \sqrt{\lambda}Z^{-1/2}$$ ranges from $0$ to $\infty$ and $$Z = \frac{\lambda}{X^2}.$$ Substituting $z = \lambda x^{-2}$ and (therefore) $|\mathrm{d}z| = 2\lambda x^{-3}\mathrm{d}x$ we find $$f_X(x)\mathrm{d}x = \frac{1}{\Gamma(n)} (\lambda x^{-2})^{n-1}\,e^{-\lambda/x^2}\,2\lambda x^{-3}\mathrm{d} x = \frac{2\lambda^{n}}{\Gamma(n)}\, x^{-2n-1}\,e^{-\lambda/x^2}\,\mathrm{d}x.$$ Set $\lambda = \sqrt{n/\beta}$ or $\lambda=\sqrt{n\beta}$ depending on whether $\beta$ is a scale or rate parameter, respectively. This is a Generalized Inverse Gamma distribution. To find the moments of $X$ it's simpler to ignore all this. Let $k$ be the moment ($k=1$ for the expectation, etc.) and observe $$E(X^k) = E\left(\lambda^{k/2} Z^{-k/2}\right) = \lambda^{k/2} \frac{1}{\Gamma(n)}\int_0^\infty z^{-k/2}\,z^{n-1}\,e^{-z}\,\mathrm{d}z = \lambda^{k/2}\frac{\Gamma(n-k/2)}{\Gamma(n)}.$$ Here is a histogram for $10^5$ realizations of $Z$ with $n=8,$ $\beta=1/3$ (the rate). On it I have superimposed the theoretical distribution, which is in close agreement. The following R code reports the mean and variance of this sample and the theoretical values; they, too, agree closely. n <- 8 beta <- 1/3 n.sim <- 1e5 Z <- rgamma(n.sim, n, beta) X <- sqrt(n)/sqrt(Z) hist(X, freq=FALSE, breaks=50, col="#f8f8f8") curve(dgamma(n/x^2, n, beta) * 2*n/x^3, xname="x", add=TRUE, col="Red", lwd=2) c(Mean=mean(X), Formula=sqrt(n*beta) * exp(lgamma(n-1/2) - lgamma(n))) c(mu2=mean(X^2), Formula=n*beta / (n-1)) c(Variance=var(X), Formula=n*beta*(1/(n-1) - exp(2*(lgamma(n-1/2) - lgamma(n)))))
What kind of distribution does this have?
Let $Z$ have a Gamma$(n,1)$ distribution, which has density $$f_Z(z) = \frac{1}{\Gamma(n)}\, z^{n-1} \,e^{-z}\,\mathrm{d}z.$$ Let $\lambda \gt 0.$ Then $$X = \sqrt{\lambda}Z^{-1/2}$$ ranges from $0$
What kind of distribution does this have? Let $Z$ have a Gamma$(n,1)$ distribution, which has density $$f_Z(z) = \frac{1}{\Gamma(n)}\, z^{n-1} \,e^{-z}\,\mathrm{d}z.$$ Let $\lambda \gt 0.$ Then $$X = \sqrt{\lambda}Z^{-1/2}$$ ranges from $0$ to $\infty$ and $$Z = \frac{\lambda}{X^2}.$$ Substituting $z = \lambda x^{-2}$ and (therefore) $|\mathrm{d}z| = 2\lambda x^{-3}\mathrm{d}x$ we find $$f_X(x)\mathrm{d}x = \frac{1}{\Gamma(n)} (\lambda x^{-2})^{n-1}\,e^{-\lambda/x^2}\,2\lambda x^{-3}\mathrm{d} x = \frac{2\lambda^{n}}{\Gamma(n)}\, x^{-2n-1}\,e^{-\lambda/x^2}\,\mathrm{d}x.$$ Set $\lambda = \sqrt{n/\beta}$ or $\lambda=\sqrt{n\beta}$ depending on whether $\beta$ is a scale or rate parameter, respectively. This is a Generalized Inverse Gamma distribution. To find the moments of $X$ it's simpler to ignore all this. Let $k$ be the moment ($k=1$ for the expectation, etc.) and observe $$E(X^k) = E\left(\lambda^{k/2} Z^{-k/2}\right) = \lambda^{k/2} \frac{1}{\Gamma(n)}\int_0^\infty z^{-k/2}\,z^{n-1}\,e^{-z}\,\mathrm{d}z = \lambda^{k/2}\frac{\Gamma(n-k/2)}{\Gamma(n)}.$$ Here is a histogram for $10^5$ realizations of $Z$ with $n=8,$ $\beta=1/3$ (the rate). On it I have superimposed the theoretical distribution, which is in close agreement. The following R code reports the mean and variance of this sample and the theoretical values; they, too, agree closely. n <- 8 beta <- 1/3 n.sim <- 1e5 Z <- rgamma(n.sim, n, beta) X <- sqrt(n)/sqrt(Z) hist(X, freq=FALSE, breaks=50, col="#f8f8f8") curve(dgamma(n/x^2, n, beta) * 2*n/x^3, xname="x", add=TRUE, col="Red", lwd=2) c(Mean=mean(X), Formula=sqrt(n*beta) * exp(lgamma(n-1/2) - lgamma(n))) c(mu2=mean(X^2), Formula=n*beta / (n-1)) c(Variance=var(X), Formula=n*beta*(1/(n-1) - exp(2*(lgamma(n-1/2) - lgamma(n)))))
What kind of distribution does this have? Let $Z$ have a Gamma$(n,1)$ distribution, which has density $$f_Z(z) = \frac{1}{\Gamma(n)}\, z^{n-1} \,e^{-z}\,\mathrm{d}z.$$ Let $\lambda \gt 0.$ Then $$X = \sqrt{\lambda}Z^{-1/2}$$ ranges from $0$
25,167
What kind of distribution does this have?
The $\sqrt{n}$ term in the numerator only scales your random variable, so we can disregard it for now. The square root of a gamma distributed variable is Nakagami distributed. We are looking for the reciprocal of that, which could be called an "inverse Nakagami distribution". Louzada et al. (2018) looks like it might be helpful. It defines exactly the kind of inverse Nakagami you are looking for and gives a number of propositions, such as the moments. You would just need to scale them appropriately by your $\sqrt{n}$ scaling factor.
What kind of distribution does this have?
The $\sqrt{n}$ term in the numerator only scales your random variable, so we can disregard it for now. The square root of a gamma distributed variable is Nakagami distributed. We are looking for the
What kind of distribution does this have? The $\sqrt{n}$ term in the numerator only scales your random variable, so we can disregard it for now. The square root of a gamma distributed variable is Nakagami distributed. We are looking for the reciprocal of that, which could be called an "inverse Nakagami distribution". Louzada et al. (2018) looks like it might be helpful. It defines exactly the kind of inverse Nakagami you are looking for and gives a number of propositions, such as the moments. You would just need to scale them appropriately by your $\sqrt{n}$ scaling factor.
What kind of distribution does this have? The $\sqrt{n}$ term in the numerator only scales your random variable, so we can disregard it for now. The square root of a gamma distributed variable is Nakagami distributed. We are looking for the
25,168
What‘s wrong with my proof of the Law of Total Variance?
The third line is wrong, because you don't have $\text{E}[X|Y]$ in the second line. For example, if $Y$ is Bernoulli(1/2) and $X$ is 1 if $Y$ is 1 and -1 if $Y$ is 0, then $\text{E}[(X-\text{E}[X|Y])^2|Y] = 0$ (this is what you want) because $Y$ is totally informative of $X$, but what you have will give you $\text{E}[(X-\text{E}[X])^2|Y] = \text{E}[(X-0)^2|Y] = \text{E}[X^2|Y] = 1 \ne 0$. Not gonna lie, you had me questioning myself and I had to stare at this for a bit before it hit me even though I've had to prove LOTV to myself a billion times :P
What‘s wrong with my proof of the Law of Total Variance?
The third line is wrong, because you don't have $\text{E}[X|Y]$ in the second line. For example, if $Y$ is Bernoulli(1/2) and $X$ is 1 if $Y$ is 1 and -1 if $Y$ is 0, then $\text{E}[(X-\text{E}[X|Y])^
What‘s wrong with my proof of the Law of Total Variance? The third line is wrong, because you don't have $\text{E}[X|Y]$ in the second line. For example, if $Y$ is Bernoulli(1/2) and $X$ is 1 if $Y$ is 1 and -1 if $Y$ is 0, then $\text{E}[(X-\text{E}[X|Y])^2|Y] = 0$ (this is what you want) because $Y$ is totally informative of $X$, but what you have will give you $\text{E}[(X-\text{E}[X])^2|Y] = \text{E}[(X-0)^2|Y] = \text{E}[X^2|Y] = 1 \ne 0$. Not gonna lie, you had me questioning myself and I had to stare at this for a bit before it hit me even though I've had to prove LOTV to myself a billion times :P
What‘s wrong with my proof of the Law of Total Variance? The third line is wrong, because you don't have $\text{E}[X|Y]$ in the second line. For example, if $Y$ is Bernoulli(1/2) and $X$ is 1 if $Y$ is 1 and -1 if $Y$ is 0, then $\text{E}[(X-\text{E}[X|Y])^
25,169
What‘s wrong with my proof of the Law of Total Variance?
The transition from the second to the third line does not follow. Since $\mathbb{E}(X) \neq \mathbb{E}(X|Y)$ you have: $$\mathbb{E}[ (X - \mathbb{E}(X))^2 | Y ] \neq \mathbb{E}[ (X - \mathbb{E}(X|Y))^2 | Y ] = \mathbb{E}[ \mathbb{V}(X|Y) ].$$ In the special case where $\mathbb{E}(X) = \mathbb{E}(X|Y=y)$ for all $y \in \mathbb{R}$ your working and result would hold, and would be a special case of the more general result.
What‘s wrong with my proof of the Law of Total Variance?
The transition from the second to the third line does not follow. Since $\mathbb{E}(X) \neq \mathbb{E}(X|Y)$ you have: $$\mathbb{E}[ (X - \mathbb{E}(X))^2 | Y ] \neq \mathbb{E}[ (X - \mathbb{E}(X|Y)
What‘s wrong with my proof of the Law of Total Variance? The transition from the second to the third line does not follow. Since $\mathbb{E}(X) \neq \mathbb{E}(X|Y)$ you have: $$\mathbb{E}[ (X - \mathbb{E}(X))^2 | Y ] \neq \mathbb{E}[ (X - \mathbb{E}(X|Y))^2 | Y ] = \mathbb{E}[ \mathbb{V}(X|Y) ].$$ In the special case where $\mathbb{E}(X) = \mathbb{E}(X|Y=y)$ for all $y \in \mathbb{R}$ your working and result would hold, and would be a special case of the more general result.
What‘s wrong with my proof of the Law of Total Variance? The transition from the second to the third line does not follow. Since $\mathbb{E}(X) \neq \mathbb{E}(X|Y)$ you have: $$\mathbb{E}[ (X - \mathbb{E}(X))^2 | Y ] \neq \mathbb{E}[ (X - \mathbb{E}(X|Y)
25,170
What‘s wrong with my proof of the Law of Total Variance?
$$\require{cancel} \begin{aligned} \operatorname{Var}(X) &= \operatorname{E}(X - \operatorname{E}X)^2 \\ &= \operatorname{E}\left(\operatorname{E}\left[(X - \operatorname{E}X)^2\mid Y\right]\right) \\ &\ne \operatorname E\left( \operatorname E\left[ (X-\operatorname E(X\mid Y))^2 \right] \mid Y \right) \\ &= \operatorname{E}(\operatorname{Var}(X\mid Y)) \end{aligned} $$
What‘s wrong with my proof of the Law of Total Variance?
$$\require{cancel} \begin{aligned} \operatorname{Var}(X) &= \operatorname{E}(X - \operatorname{E}X)^2 \\ &= \operatorname{E}\left(\operatorname{E}\left[(X - \operatorname{E}X)^2\mid Y\right]\right) \\
What‘s wrong with my proof of the Law of Total Variance? $$\require{cancel} \begin{aligned} \operatorname{Var}(X) &= \operatorname{E}(X - \operatorname{E}X)^2 \\ &= \operatorname{E}\left(\operatorname{E}\left[(X - \operatorname{E}X)^2\mid Y\right]\right) \\ &\ne \operatorname E\left( \operatorname E\left[ (X-\operatorname E(X\mid Y))^2 \right] \mid Y \right) \\ &= \operatorname{E}(\operatorname{Var}(X\mid Y)) \end{aligned} $$
What‘s wrong with my proof of the Law of Total Variance? $$\require{cancel} \begin{aligned} \operatorname{Var}(X) &= \operatorname{E}(X - \operatorname{E}X)^2 \\ &= \operatorname{E}\left(\operatorname{E}\left[(X - \operatorname{E}X)^2\mid Y\right]\right) \\
25,171
Inverse word embedding: vector to word
There is no one 'right' way to turn wordvectors back into words. The issue is that the words themselves form a discrete set of points in the embedding space, and so the output of a model is very unlikely to be exactly equal to the location of any word. Typically if your model emits a vector $v$ then interpreting it as a word is done by finding a word $w$ with embedding $v_w$ such that $d(v, v_w)$ is small, i.e. $v$ is 'close' to the embedding of $w$. Choosing the distance function $d$ is up to you, although typically the cosine similarity is used. Depending on the application, you could also consider showing the top-$k$ similar words to your wordvector, which could offer a bit more diversity.
Inverse word embedding: vector to word
There is no one 'right' way to turn wordvectors back into words. The issue is that the words themselves form a discrete set of points in the embedding space, and so the output of a model is very unli
Inverse word embedding: vector to word There is no one 'right' way to turn wordvectors back into words. The issue is that the words themselves form a discrete set of points in the embedding space, and so the output of a model is very unlikely to be exactly equal to the location of any word. Typically if your model emits a vector $v$ then interpreting it as a word is done by finding a word $w$ with embedding $v_w$ such that $d(v, v_w)$ is small, i.e. $v$ is 'close' to the embedding of $w$. Choosing the distance function $d$ is up to you, although typically the cosine similarity is used. Depending on the application, you could also consider showing the top-$k$ similar words to your wordvector, which could offer a bit more diversity.
Inverse word embedding: vector to word There is no one 'right' way to turn wordvectors back into words. The issue is that the words themselves form a discrete set of points in the embedding space, and so the output of a model is very unli
25,172
Inverse word embedding: vector to word
Are you familiar with autoencoders? They are defined in terms of two networks: encoder and decoder, that are usually symmetrical. The general assumption is that to decode the data from the latent representation, you probably need similar kind of architecture, as was needed for encoding it. While re-using the weights from encoder in many cases would be possible and may seem reasonable, defining septate decoder network is more popular solution, because it is much simpler. The embeddings are floating-point numbers, to translate them to words you need a function that will map the numbers to words. There are many ways how this can be achieved, e.g. with recurrent neural networks that create words byte by byte, or $n$-gram by $n$-gram, or predicting the one-hot encodings for the words (usually the number of words is huge, so you need approximate solutions), you may take into consideration the words that appear before or after the predicted word and use etc. There is no single best approach, because this is problem specific.
Inverse word embedding: vector to word
Are you familiar with autoencoders? They are defined in terms of two networks: encoder and decoder, that are usually symmetrical. The general assumption is that to decode the data from the latent repr
Inverse word embedding: vector to word Are you familiar with autoencoders? They are defined in terms of two networks: encoder and decoder, that are usually symmetrical. The general assumption is that to decode the data from the latent representation, you probably need similar kind of architecture, as was needed for encoding it. While re-using the weights from encoder in many cases would be possible and may seem reasonable, defining septate decoder network is more popular solution, because it is much simpler. The embeddings are floating-point numbers, to translate them to words you need a function that will map the numbers to words. There are many ways how this can be achieved, e.g. with recurrent neural networks that create words byte by byte, or $n$-gram by $n$-gram, or predicting the one-hot encodings for the words (usually the number of words is huge, so you need approximate solutions), you may take into consideration the words that appear before or after the predicted word and use etc. There is no single best approach, because this is problem specific.
Inverse word embedding: vector to word Are you familiar with autoencoders? They are defined in terms of two networks: encoder and decoder, that are usually symmetrical. The general assumption is that to decode the data from the latent repr
25,173
Inverse word embedding: vector to word
I do like the idea of using a decoder network at the end of your architecture. This allows you to train on one-hot encoded words. Then your output will be a probability distribution over the words in your vocabulary. You can then draw randomly from the probability distribution. In some ways, what you get is more of "a smear" of possible words. More probable words would have a higher chance of being selected. This of course gives you a probabilistic response words. A second run of the algorithm, given that you didn't fix the seed, will result in slightly different output.
Inverse word embedding: vector to word
I do like the idea of using a decoder network at the end of your architecture. This allows you to train on one-hot encoded words. Then your output will be a probability distribution over the words in
Inverse word embedding: vector to word I do like the idea of using a decoder network at the end of your architecture. This allows you to train on one-hot encoded words. Then your output will be a probability distribution over the words in your vocabulary. You can then draw randomly from the probability distribution. In some ways, what you get is more of "a smear" of possible words. More probable words would have a higher chance of being selected. This of course gives you a probabilistic response words. A second run of the algorithm, given that you didn't fix the seed, will result in slightly different output.
Inverse word embedding: vector to word I do like the idea of using a decoder network at the end of your architecture. This allows you to train on one-hot encoded words. Then your output will be a probability distribution over the words in
25,174
Inverse word embedding: vector to word
If you look at seq2seq models and transformers, the way this is usually done is by outputting a one-hot encoded vector using a softmax layer. Basically, the output will be a vector whose length is the size of the vocabulary.
Inverse word embedding: vector to word
If you look at seq2seq models and transformers, the way this is usually done is by outputting a one-hot encoded vector using a softmax layer. Basically, the output will be a vector whose length is the
Inverse word embedding: vector to word If you look at seq2seq models and transformers, the way this is usually done is by outputting a one-hot encoded vector using a softmax layer. Basically, the output will be a vector whose length is the size of the vocabulary.
Inverse word embedding: vector to word If you look at seq2seq models and transformers, the way this is usually done is by outputting a one-hot encoded vector using a softmax layer. Basically, the output will be a vector whose length is the
25,175
Can a linear regression be significant if the data is not linear?
Monotonic nonlinear relationships will almost always show up significant when modeling as linear models. If the relationship is nonlinear and not monotonic then it depends on the sample. Examples of monotonic relationships is logarithm $y=\ln x$ and odd powers such as $y=x^3$. Example of non monotonic relationships are even powers $y=x^2$ and trigonomtric functions such as $y=\sin x$. For instance, if your sample is for $x\in[-1,1]$, then $y=\sin x$ modeled as $y\sim x$ will likely be significant, see the plot: However, if your sample is in $x\in[0,\pi]$, then linear modeling will not work at all:
Can a linear regression be significant if the data is not linear?
Monotonic nonlinear relationships will almost always show up significant when modeling as linear models. If the relationship is nonlinear and not monotonic then it depends on the sample. Examples of m
Can a linear regression be significant if the data is not linear? Monotonic nonlinear relationships will almost always show up significant when modeling as linear models. If the relationship is nonlinear and not monotonic then it depends on the sample. Examples of monotonic relationships is logarithm $y=\ln x$ and odd powers such as $y=x^3$. Example of non monotonic relationships are even powers $y=x^2$ and trigonomtric functions such as $y=\sin x$. For instance, if your sample is for $x\in[-1,1]$, then $y=\sin x$ modeled as $y\sim x$ will likely be significant, see the plot: However, if your sample is in $x\in[0,\pi]$, then linear modeling will not work at all:
Can a linear regression be significant if the data is not linear? Monotonic nonlinear relationships will almost always show up significant when modeling as linear models. If the relationship is nonlinear and not monotonic then it depends on the sample. Examples of m
25,176
Can a linear regression be significant if the data is not linear?
Yes, Aksakal is right and a linear regression can be significant if the true relationship is non-linear. A linear regression finds a line of best fit through your data and simply tests, whether the slope is significantly different from 0. Before trying to find a statistical test for non-linearity, I would suggest reflecting on what you want to model first. Are you expecting a linear (non-linear) relationship between your two variables? What exactly are you trying to uncover? If it makes sense to assume that there is a non-linear relationship as for example between car speed and braking distance, then you can add squared terms (or other transformations) of your independent variable. Also, a visual inspection of your data (scatterplot) is a very powerful method and an essential first step in your analysis.
Can a linear regression be significant if the data is not linear?
Yes, Aksakal is right and a linear regression can be significant if the true relationship is non-linear. A linear regression finds a line of best fit through your data and simply tests, whether the sl
Can a linear regression be significant if the data is not linear? Yes, Aksakal is right and a linear regression can be significant if the true relationship is non-linear. A linear regression finds a line of best fit through your data and simply tests, whether the slope is significantly different from 0. Before trying to find a statistical test for non-linearity, I would suggest reflecting on what you want to model first. Are you expecting a linear (non-linear) relationship between your two variables? What exactly are you trying to uncover? If it makes sense to assume that there is a non-linear relationship as for example between car speed and braking distance, then you can add squared terms (or other transformations) of your independent variable. Also, a visual inspection of your data (scatterplot) is a very powerful method and an essential first step in your analysis.
Can a linear regression be significant if the data is not linear? Yes, Aksakal is right and a linear regression can be significant if the true relationship is non-linear. A linear regression finds a line of best fit through your data and simply tests, whether the sl
25,177
Can a linear regression be significant if the data is not linear?
I agree with everything Aksakal says. But as to the first question I think the answer is correlation. Correlation measures the extent to which there is a linear relationship between the data sets x and y.
Can a linear regression be significant if the data is not linear?
I agree with everything Aksakal says. But as to the first question I think the answer is correlation. Correlation measures the extent to which there is a linear relationship between the data sets x
Can a linear regression be significant if the data is not linear? I agree with everything Aksakal says. But as to the first question I think the answer is correlation. Correlation measures the extent to which there is a linear relationship between the data sets x and y.
Can a linear regression be significant if the data is not linear? I agree with everything Aksakal says. But as to the first question I think the answer is correlation. Correlation measures the extent to which there is a linear relationship between the data sets x
25,178
How is a Poisson rate regression equal to a Poisson regression with corresponding offset term?
This also confused me. I thought, "what is the point of explicitly including an offset instead of just pretending that the response divided by the offset / exposure is the $y$ value?". You actually get two different loss functions if you do so. The correct way (use an exposure/offset $s_i$) Model $\log \lambda_i = \log s_i + \theta^T x$ so that $\lambda_i = s_i e^{\theta^Tx}$. This makes complete sense: the exposure $s_i$ just multiplies the $\hat{\lambda_i}=e^{\hat{\theta}^Tx}$ in a Poisson regression model without different exposures. We model the random variable $Y$, a response to $x_i$, with a Poisson distribution with parameter $\lambda_i$. Then the likelihood for $N$ data points is: $$\prod_{i=1}^N \dfrac{(s_ie^{\theta^Tx})^{y_i}}{y_i!}e^{-s_i e^{\theta^Tx}}$$ The log likelihood $\ell$, keeping only terms that depend on $\theta$ since others will drop out after differentiation: $$\ell = \displaystyle \sum_{i=1}^N\big[ y_i\theta_Tx_i -s_i e^{\theta^Tx_i}\big]$$ The incorrect way (using $y_i/s_i$ as the y-values) Now we still model: $$\log \lambda_i = \log s_i + \theta^T x$$ The difference is that now we assume $y_i/s_i$ has a Poisson distribution. This is essentially what makes the model incorrect. It violates the assumption that $y_i$ has a Poisson distribution. Now you are modeling the rate as having a Poisson distribution. So the likelihood is now: $$\prod_{i=1}^N \dfrac{(e^{\theta^Tx})^{y_i/s_i}}{(y_i/s_i)!}e^{- e^{\theta^Tx}}$$ [Awkward to have $y_i/s_i$ in the factorial term but it drops out anyway after differentiation of the log likelihood so let's carry on.] The log likelihood $\hat{\ell}$, keeping only terms that depend on $\theta$ since others will drop out after differentiation: $$\hat{\ell} = \displaystyle \sum_{i=1}^N\bigg[ \frac{y_i}{s_i}\theta_Tx_i - e^{\theta^Tx_i}\bigg]$$ Conclusion $\ell$ and $\hat{\ell}$ look strikingly similar, and you might think they are the same, but they are not (you can't just divide by $s_i$ because it is different for every term!) However, if we consider a weighted Poisson regression when we model $y_i/s_i$ as distributed Poissonian (is that a word?), each data point in the log likelihood gets a weight of $s_i$, then: $$\hat{\ell}_{{\rm weighted}}=\displaystyle \sum_{i=1}^N s_i[ \frac{y_i}{s_i}\theta_Tx_i - e^{\theta^Tx_i}]$$ is equivalent to $\ell$!
How is a Poisson rate regression equal to a Poisson regression with corresponding offset term?
This also confused me. I thought, "what is the point of explicitly including an offset instead of just pretending that the response divided by the offset / exposure is the $y$ value?". You actually ge
How is a Poisson rate regression equal to a Poisson regression with corresponding offset term? This also confused me. I thought, "what is the point of explicitly including an offset instead of just pretending that the response divided by the offset / exposure is the $y$ value?". You actually get two different loss functions if you do so. The correct way (use an exposure/offset $s_i$) Model $\log \lambda_i = \log s_i + \theta^T x$ so that $\lambda_i = s_i e^{\theta^Tx}$. This makes complete sense: the exposure $s_i$ just multiplies the $\hat{\lambda_i}=e^{\hat{\theta}^Tx}$ in a Poisson regression model without different exposures. We model the random variable $Y$, a response to $x_i$, with a Poisson distribution with parameter $\lambda_i$. Then the likelihood for $N$ data points is: $$\prod_{i=1}^N \dfrac{(s_ie^{\theta^Tx})^{y_i}}{y_i!}e^{-s_i e^{\theta^Tx}}$$ The log likelihood $\ell$, keeping only terms that depend on $\theta$ since others will drop out after differentiation: $$\ell = \displaystyle \sum_{i=1}^N\big[ y_i\theta_Tx_i -s_i e^{\theta^Tx_i}\big]$$ The incorrect way (using $y_i/s_i$ as the y-values) Now we still model: $$\log \lambda_i = \log s_i + \theta^T x$$ The difference is that now we assume $y_i/s_i$ has a Poisson distribution. This is essentially what makes the model incorrect. It violates the assumption that $y_i$ has a Poisson distribution. Now you are modeling the rate as having a Poisson distribution. So the likelihood is now: $$\prod_{i=1}^N \dfrac{(e^{\theta^Tx})^{y_i/s_i}}{(y_i/s_i)!}e^{- e^{\theta^Tx}}$$ [Awkward to have $y_i/s_i$ in the factorial term but it drops out anyway after differentiation of the log likelihood so let's carry on.] The log likelihood $\hat{\ell}$, keeping only terms that depend on $\theta$ since others will drop out after differentiation: $$\hat{\ell} = \displaystyle \sum_{i=1}^N\bigg[ \frac{y_i}{s_i}\theta_Tx_i - e^{\theta^Tx_i}\bigg]$$ Conclusion $\ell$ and $\hat{\ell}$ look strikingly similar, and you might think they are the same, but they are not (you can't just divide by $s_i$ because it is different for every term!) However, if we consider a weighted Poisson regression when we model $y_i/s_i$ as distributed Poissonian (is that a word?), each data point in the log likelihood gets a weight of $s_i$, then: $$\hat{\ell}_{{\rm weighted}}=\displaystyle \sum_{i=1}^N s_i[ \frac{y_i}{s_i}\theta_Tx_i - e^{\theta^Tx_i}]$$ is equivalent to $\ell$!
How is a Poisson rate regression equal to a Poisson regression with corresponding offset term? This also confused me. I thought, "what is the point of explicitly including an offset instead of just pretending that the response divided by the offset / exposure is the $y$ value?". You actually ge
25,179
Gradients for skipgram word2vec
First, let's lay out what we have got and our assumptions about the shapes of different vectors. Let, $|W|$ be the number of words in the vocab $y$ and $\hat{y}$ be column vectors of shape $|W|$ x 1 $u_i$ and $v_j$ be the column vectors of shape $D$ X 1 ($D$ = dimension of embeddings) $y$ be the one-hot encoded column vector of shape $|W|$ x 1 $\hat{y}$ be the softmax prediction column vector of shape $|W|$ x 1 $\hat{y}_i = P(i|c) = \frac{exp(u_i^Tv_c)}{\sum_{w=1}^Wexp(u_w^Tv_c)}$ Cross entropy loss: $J = -\sum_{i=1}^Wy_ilog({\hat{y_i}})$ $U = [u_1, u_2, ...,u_k, ...u_W]$ be a matrix composed of $u_k$ column vectors. Now, we can write $$J = - \sum_{i=1}^W y_i log(\frac{exp(u_i^Tv_c)}{\sum_{w=1}^Wexp(u_w^Tv_c)})$$ Simplifying, $$ J = - \sum_{i=1}^Wy_i[u_i^Tv_c - log(\sum_{w=1}^Wexp(u_w^Tv_c))] $$ Now, we know that $y$ is one-hot encoded, so all its elements are zero except the one at, say, $k^{th}$ index. Which means, there's only one non-zero term in the summation above corresponding to $y_k$ and all others terms in the summation are zeros. So the cost can also be written as: $$J = -y_k[u_k^Tv_c - log(\sum_{w=1}^Wexp(u_w^Tv_c))]$$ Note: above $y_k$ is 1. Solving for $\frac{\partial J}{\partial v_c}$ : $$ \frac{\partial J}{\partial v_c} = -[u_k - \frac{\sum_{w=1}^Wexp(u_w^Tv_c)u_w}{\sum_{x=1}^Wexp(u_x^Tv_c)}]$$ Which can be re-arranged as: $$\frac{\partial J}{\partial v_c} = \sum_{w=1}^W (\frac{exp(u_w^Tv_c)}{\sum_{x=1}^W exp(u_x^Tv_c)}u_w) - u_k$$ Using definition (6), we can rewrite the above equation as: $$\frac{\partial J}{\partial v_c} = \sum_{w=1}^W (\hat{y}_w u_w) - u_k$$ Now let's see how this can be written in Matrix notation.Note that: $u_k$ can be written as Matrix vector multiplication: $U.y$ And $\sum_{w=1}^W (\hat{y}_w u_w)$ is a linear transformation of vectors $u_w$ in $U$ scaled by $\hat{y}_w$ respectively. This again can be written as $U.\hat{y}$ So the whole thing can be succinctly written as: $$U[\hat{y} -y]$$ Finally, note that we assumed $u_i$s to be a column vectors. If we had started with row vectors, we would get $U^T[\hat{y} -y]$, same as what you were looking for.
Gradients for skipgram word2vec
First, let's lay out what we have got and our assumptions about the shapes of different vectors. Let, $|W|$ be the number of words in the vocab $y$ and $\hat{y}$ be column vectors of shape $|W|$ x
Gradients for skipgram word2vec First, let's lay out what we have got and our assumptions about the shapes of different vectors. Let, $|W|$ be the number of words in the vocab $y$ and $\hat{y}$ be column vectors of shape $|W|$ x 1 $u_i$ and $v_j$ be the column vectors of shape $D$ X 1 ($D$ = dimension of embeddings) $y$ be the one-hot encoded column vector of shape $|W|$ x 1 $\hat{y}$ be the softmax prediction column vector of shape $|W|$ x 1 $\hat{y}_i = P(i|c) = \frac{exp(u_i^Tv_c)}{\sum_{w=1}^Wexp(u_w^Tv_c)}$ Cross entropy loss: $J = -\sum_{i=1}^Wy_ilog({\hat{y_i}})$ $U = [u_1, u_2, ...,u_k, ...u_W]$ be a matrix composed of $u_k$ column vectors. Now, we can write $$J = - \sum_{i=1}^W y_i log(\frac{exp(u_i^Tv_c)}{\sum_{w=1}^Wexp(u_w^Tv_c)})$$ Simplifying, $$ J = - \sum_{i=1}^Wy_i[u_i^Tv_c - log(\sum_{w=1}^Wexp(u_w^Tv_c))] $$ Now, we know that $y$ is one-hot encoded, so all its elements are zero except the one at, say, $k^{th}$ index. Which means, there's only one non-zero term in the summation above corresponding to $y_k$ and all others terms in the summation are zeros. So the cost can also be written as: $$J = -y_k[u_k^Tv_c - log(\sum_{w=1}^Wexp(u_w^Tv_c))]$$ Note: above $y_k$ is 1. Solving for $\frac{\partial J}{\partial v_c}$ : $$ \frac{\partial J}{\partial v_c} = -[u_k - \frac{\sum_{w=1}^Wexp(u_w^Tv_c)u_w}{\sum_{x=1}^Wexp(u_x^Tv_c)}]$$ Which can be re-arranged as: $$\frac{\partial J}{\partial v_c} = \sum_{w=1}^W (\frac{exp(u_w^Tv_c)}{\sum_{x=1}^W exp(u_x^Tv_c)}u_w) - u_k$$ Using definition (6), we can rewrite the above equation as: $$\frac{\partial J}{\partial v_c} = \sum_{w=1}^W (\hat{y}_w u_w) - u_k$$ Now let's see how this can be written in Matrix notation.Note that: $u_k$ can be written as Matrix vector multiplication: $U.y$ And $\sum_{w=1}^W (\hat{y}_w u_w)$ is a linear transformation of vectors $u_w$ in $U$ scaled by $\hat{y}_w$ respectively. This again can be written as $U.\hat{y}$ So the whole thing can be succinctly written as: $$U[\hat{y} -y]$$ Finally, note that we assumed $u_i$s to be a column vectors. If we had started with row vectors, we would get $U^T[\hat{y} -y]$, same as what you were looking for.
Gradients for skipgram word2vec First, let's lay out what we have got and our assumptions about the shapes of different vectors. Let, $|W|$ be the number of words in the vocab $y$ and $\hat{y}$ be column vectors of shape $|W|$ x
25,180
Rao-Blackwellization of Gibbs Sampler
Assuming I take the mean of the posterior distribution rather than a random sample from it, is this what is commonly referred to as Rao-Blackwellization? I am not very familiar with stochastic volatility models, but I do know that in most settings, the reason we choose Gibbs or M-H algorithms to draw from the posterior, is because we don't know the posterior. Often we want to estimate the posterior mean, and since we don't know the posterior mean, we draw samples from the posterior and estimate it using the sample mean. So, I am not sure how you will be able to take the mean from the posterior distribution. Instead the Rao-Blackwellized estimator depends o the knowledge of the mean of the full conditional; but even then sampling is still required. I explain more below. Suppose the posterior distribution is defined on two variables, $\theta = (\mu, \phi$), such that you want to estimate the posterior mean: $E[\theta \mid \text{data}]$. Now, if a Gibbs sampler was available you could run that or run a M-H algorithm to sample from the posterior. If you can run a Gibbs sampler, then you know $f(\phi \mid \mu, data)$ in closed form and you know the mean of this distribution. Let that mean be $\phi^*$. Note that $\phi^*$ is a function of $\mu$ and the data. This also means that you can integrate out $\phi$ from the posterior, so the marginal posterior of $\mu$ is $f(\mu \mid data)$ (this is not known completely, but known upto a constant). You now want to now run a Markov chain such that $f(\mu \mid data)$ is the invariant distribution, and you obtain samples from this marginal posterior. The question is How can you now estimate the posterior mean of $\phi$ using only these samples from the marginal posterior of $\mu$? This is done via Rao-Blackwellization. \begin{align*} E[\phi \mid data]& = \int \phi \; f(\mu, \phi \mid data) d\mu \, d\phi\\ & = \int \phi \; f(\phi \mid \mu, data) f(\mu \mid data) d\mu \, d\phi\\ & = \int \phi^* f(\mu \mid data) d\mu. \end{align*} Thus suppose we have obtained samples $X_1, X_2, \dots X_N$ from the marginal posterior of $\mu$. Then $$ \hat{\phi} = \dfrac{1}{N} \sum_{i=1}^{N} \phi^*(X_i), $$ is called the Rao-Blackwellized estimator for $\phi$. The same can be done by simulating from the joint marginals as well. Example (Purely for demonstration). Suppose you have a joint unknown posterior for $\theta = (\mu, \phi)$ from which you want to sample. Your data is some $y$, and you have the following full conditionals $$\mu \mid \phi, y \sim N(\phi^2 + 2y, y^2) $$ $$\phi \mid \mu, y \sim Gamma(2\mu + y, y + 1) $$ You run the Gibbs sampler using these conditionals, and obtained samples from the joint posterior $f(\mu, \phi \mid y)$. Let these samples be $(\mu_1, \phi_1), (\mu_2, \phi_2), \dots, (\mu_N, \phi_N)$. You can find the sample mean of the $\phi$s, and that would be the usual Monte Carlo estimator for the posterior mean for $\phi$.. Or, note that by the properties of the Gamma distribution $$E[\phi | \mu, y] = \dfrac{2 \mu + y}{y + 1} = \phi^*.$$ Here $y$ is the data given to you and is thus known. The Rao Blackwellized estimator would then be $$\hat{\phi} = \dfrac{1}{N} \sum_{i=1}^{N} \dfrac{2 \mu_i + y}{y + 1}. $$ Notice how the estimator for the posterior mean of $\phi$ does not even use the $\phi$ samples, and only uses the $\mu$ samples. In any case, as you can see you are still using the samples you obtained from a Markov chain. This is not a deterministic process.
Rao-Blackwellization of Gibbs Sampler
Assuming I take the mean of the posterior distribution rather than a random sample from it, is this what is commonly referred to as Rao-Blackwellization? I am not very familiar with stochastic vo
Rao-Blackwellization of Gibbs Sampler Assuming I take the mean of the posterior distribution rather than a random sample from it, is this what is commonly referred to as Rao-Blackwellization? I am not very familiar with stochastic volatility models, but I do know that in most settings, the reason we choose Gibbs or M-H algorithms to draw from the posterior, is because we don't know the posterior. Often we want to estimate the posterior mean, and since we don't know the posterior mean, we draw samples from the posterior and estimate it using the sample mean. So, I am not sure how you will be able to take the mean from the posterior distribution. Instead the Rao-Blackwellized estimator depends o the knowledge of the mean of the full conditional; but even then sampling is still required. I explain more below. Suppose the posterior distribution is defined on two variables, $\theta = (\mu, \phi$), such that you want to estimate the posterior mean: $E[\theta \mid \text{data}]$. Now, if a Gibbs sampler was available you could run that or run a M-H algorithm to sample from the posterior. If you can run a Gibbs sampler, then you know $f(\phi \mid \mu, data)$ in closed form and you know the mean of this distribution. Let that mean be $\phi^*$. Note that $\phi^*$ is a function of $\mu$ and the data. This also means that you can integrate out $\phi$ from the posterior, so the marginal posterior of $\mu$ is $f(\mu \mid data)$ (this is not known completely, but known upto a constant). You now want to now run a Markov chain such that $f(\mu \mid data)$ is the invariant distribution, and you obtain samples from this marginal posterior. The question is How can you now estimate the posterior mean of $\phi$ using only these samples from the marginal posterior of $\mu$? This is done via Rao-Blackwellization. \begin{align*} E[\phi \mid data]& = \int \phi \; f(\mu, \phi \mid data) d\mu \, d\phi\\ & = \int \phi \; f(\phi \mid \mu, data) f(\mu \mid data) d\mu \, d\phi\\ & = \int \phi^* f(\mu \mid data) d\mu. \end{align*} Thus suppose we have obtained samples $X_1, X_2, \dots X_N$ from the marginal posterior of $\mu$. Then $$ \hat{\phi} = \dfrac{1}{N} \sum_{i=1}^{N} \phi^*(X_i), $$ is called the Rao-Blackwellized estimator for $\phi$. The same can be done by simulating from the joint marginals as well. Example (Purely for demonstration). Suppose you have a joint unknown posterior for $\theta = (\mu, \phi)$ from which you want to sample. Your data is some $y$, and you have the following full conditionals $$\mu \mid \phi, y \sim N(\phi^2 + 2y, y^2) $$ $$\phi \mid \mu, y \sim Gamma(2\mu + y, y + 1) $$ You run the Gibbs sampler using these conditionals, and obtained samples from the joint posterior $f(\mu, \phi \mid y)$. Let these samples be $(\mu_1, \phi_1), (\mu_2, \phi_2), \dots, (\mu_N, \phi_N)$. You can find the sample mean of the $\phi$s, and that would be the usual Monte Carlo estimator for the posterior mean for $\phi$.. Or, note that by the properties of the Gamma distribution $$E[\phi | \mu, y] = \dfrac{2 \mu + y}{y + 1} = \phi^*.$$ Here $y$ is the data given to you and is thus known. The Rao Blackwellized estimator would then be $$\hat{\phi} = \dfrac{1}{N} \sum_{i=1}^{N} \dfrac{2 \mu_i + y}{y + 1}. $$ Notice how the estimator for the posterior mean of $\phi$ does not even use the $\phi$ samples, and only uses the $\mu$ samples. In any case, as you can see you are still using the samples you obtained from a Markov chain. This is not a deterministic process.
Rao-Blackwellization of Gibbs Sampler Assuming I take the mean of the posterior distribution rather than a random sample from it, is this what is commonly referred to as Rao-Blackwellization? I am not very familiar with stochastic vo
25,181
Rao-Blackwellization of Gibbs Sampler
The Gibbs sampler can then be used to improve efficiency of (say) samples from a marginal posterior, call it $\pi_2(\theta_2|y)$. Note \begin{eqnarray*} \pi_2(\theta_2|y)&=&\int \pi(\theta_1,\theta_2|y)d\theta_1\\ &=&\int \pi_{2|1}(\theta_2|\theta_1,y)\pi_1(\theta_1|y)d\theta_1\\ &=&E(\pi_{2|1}(\theta_2|\theta_1,y)) \end{eqnarray*} Thus, the marginal density of $\theta_2$ at some value $\theta_2$ is the expected value of the conditional density of $\theta_2$ given $\theta_1$ at the point $\theta_2$. This is interesting due to the Variance Decomposition Lemma $$ Var(X)=E[Var(X|Y)]+Var[E(X|Y)], $$ where the conditional variance $Var(X|Y)$ is $E\left\{(X-E(X|Y))^2|Y\right\}$. Also, $Var(E(X|Y))=E\left[(E(X|Y)-E(X))^2\right]$. In particular, $$ Var(X)\geq Var[E(X|Y)]. $$ A Gibbs sampler will give us realizations $(\theta_{1i},\theta_{2i})$. The upshot is that it is better to estimate $\pi_2(\theta_2|y)$ by $$ \hat{\pi}_2(\theta_2|y)=\frac{1}{M}\sum_{i=1}^M\pi_{2|1}(\theta_2|\theta_{1i},y) $$ than by some conventional kernel density estimate using the $\theta_{2i}$ for the point $\theta_2$ - provided we know the conditional distributions (which is of course why we use Gibbs sampling in the first place). Example Suppose $X$ and $Y$ are bivariate normal with means zero, variances 1 and correlation $\rho$. That is, $$ \pi(x,y)\propto\exp\left\{-\frac{1}{2(1-\rho^2)}(x^2+y^2-2\rho x y)\right\} $$ Clearly, marginally, $Y\sim N(0,1)$, but let us pretend we do not know this. It is well-known that the conditional distribution of $Y$ given $X=x$ is $N(\rho x,1-\rho^2)$. Given some $M$ realizations of $(X,Y)$ the "Rao-Blackwell" estimate of the density of $Y$ at $y$ then is $$ \hat\pi_Y(y)=\frac{1}{M}\sum_{i=1}^M\frac{1}{\sqrt{1-\rho^2}\sqrt{2\pi}}\exp\left\{-\frac{1}{2(1-\rho^2)}(y-\rho x_i)^2\right\} $$ As an illustration, let us compare a kernel density estimate to the RB-approach library(mvtnorm) rho <- 0.5 R <- 50 xy <- rmvnorm(n=R, mean=c(0,0), sigma= matrix(c(1,rho,rho,1), ncol=2)) x <- xy[,1] y <- xy[,2] kernel_density <- density(y, kernel = "gaussian") plot(kernel_density,col = "blue",lty=2,main="Rao-Blackwell estimates from conditional normals",ylim=c(0,0.4)) legend(1.5,.37,c("Kernel","N(0,1)","Rao-Blackwell"),lty=c(2,1,3),col=c("blue","black","red")) g <- seq(-3.5,3.5,length=100) lines(g,dnorm(g),lty=1) # here's what we pretend not to know density_RB <- rep(0,100) for(i in 1:100) {density_RB[i] <- mean(dnorm(g[i], rho*x, sd = sqrt(1-rho^2)))} lines(g,density_RB,col = "red",lty=3) We observe that the RB estimate does much better (as it exploits the conditional information):
Rao-Blackwellization of Gibbs Sampler
The Gibbs sampler can then be used to improve efficiency of (say) samples from a marginal posterior, call it $\pi_2(\theta_2|y)$. Note \begin{eqnarray*} \pi_2(\theta_2|y)&=&\int \pi(\theta_1,\theta_2|
Rao-Blackwellization of Gibbs Sampler The Gibbs sampler can then be used to improve efficiency of (say) samples from a marginal posterior, call it $\pi_2(\theta_2|y)$. Note \begin{eqnarray*} \pi_2(\theta_2|y)&=&\int \pi(\theta_1,\theta_2|y)d\theta_1\\ &=&\int \pi_{2|1}(\theta_2|\theta_1,y)\pi_1(\theta_1|y)d\theta_1\\ &=&E(\pi_{2|1}(\theta_2|\theta_1,y)) \end{eqnarray*} Thus, the marginal density of $\theta_2$ at some value $\theta_2$ is the expected value of the conditional density of $\theta_2$ given $\theta_1$ at the point $\theta_2$. This is interesting due to the Variance Decomposition Lemma $$ Var(X)=E[Var(X|Y)]+Var[E(X|Y)], $$ where the conditional variance $Var(X|Y)$ is $E\left\{(X-E(X|Y))^2|Y\right\}$. Also, $Var(E(X|Y))=E\left[(E(X|Y)-E(X))^2\right]$. In particular, $$ Var(X)\geq Var[E(X|Y)]. $$ A Gibbs sampler will give us realizations $(\theta_{1i},\theta_{2i})$. The upshot is that it is better to estimate $\pi_2(\theta_2|y)$ by $$ \hat{\pi}_2(\theta_2|y)=\frac{1}{M}\sum_{i=1}^M\pi_{2|1}(\theta_2|\theta_{1i},y) $$ than by some conventional kernel density estimate using the $\theta_{2i}$ for the point $\theta_2$ - provided we know the conditional distributions (which is of course why we use Gibbs sampling in the first place). Example Suppose $X$ and $Y$ are bivariate normal with means zero, variances 1 and correlation $\rho$. That is, $$ \pi(x,y)\propto\exp\left\{-\frac{1}{2(1-\rho^2)}(x^2+y^2-2\rho x y)\right\} $$ Clearly, marginally, $Y\sim N(0,1)$, but let us pretend we do not know this. It is well-known that the conditional distribution of $Y$ given $X=x$ is $N(\rho x,1-\rho^2)$. Given some $M$ realizations of $(X,Y)$ the "Rao-Blackwell" estimate of the density of $Y$ at $y$ then is $$ \hat\pi_Y(y)=\frac{1}{M}\sum_{i=1}^M\frac{1}{\sqrt{1-\rho^2}\sqrt{2\pi}}\exp\left\{-\frac{1}{2(1-\rho^2)}(y-\rho x_i)^2\right\} $$ As an illustration, let us compare a kernel density estimate to the RB-approach library(mvtnorm) rho <- 0.5 R <- 50 xy <- rmvnorm(n=R, mean=c(0,0), sigma= matrix(c(1,rho,rho,1), ncol=2)) x <- xy[,1] y <- xy[,2] kernel_density <- density(y, kernel = "gaussian") plot(kernel_density,col = "blue",lty=2,main="Rao-Blackwell estimates from conditional normals",ylim=c(0,0.4)) legend(1.5,.37,c("Kernel","N(0,1)","Rao-Blackwell"),lty=c(2,1,3),col=c("blue","black","red")) g <- seq(-3.5,3.5,length=100) lines(g,dnorm(g),lty=1) # here's what we pretend not to know density_RB <- rep(0,100) for(i in 1:100) {density_RB[i] <- mean(dnorm(g[i], rho*x, sd = sqrt(1-rho^2)))} lines(g,density_RB,col = "red",lty=3) We observe that the RB estimate does much better (as it exploits the conditional information):
Rao-Blackwellization of Gibbs Sampler The Gibbs sampler can then be used to improve efficiency of (say) samples from a marginal posterior, call it $\pi_2(\theta_2|y)$. Note \begin{eqnarray*} \pi_2(\theta_2|y)&=&\int \pi(\theta_1,\theta_2|
25,182
What is the difference between multinomial and ordinal logistic regression?
In the case of the multinomial one has no intrinsic ordering; in contrast in the case of ordinal regression there is an association between the levels. For example if you examine the variable $V1$ that has green, yellow and red as independent levels then $V1$ encodes a multinomial variable. If you have a new variable $V2$ were the levels green, yellow and red represent some sort of increased urgency then they define an ordinal variable. So how would these variables be encoded: In the case of an multinomial variable this variable is encoded as an indicator matrix. The arbitrary encoding for green can be [1 0 0], yellow can be [0 1 0] and [0 0 1] for red. In the case of an ordinal variable the encoding is a bit different. If you are in the yellow level you are assumed that you have reached and exceed the green level. Similarly if you are in the red level you have reached the green and the yellow level and now you are in the red level. Therefore the encoding is for the green value would be something like [1 0 0]. For the yellow, [1 1 0] and for red, [1 1 1]. So for the multinomial $V1$ with 7 samples would look something like: \begin{align} V1 = \left( \begin{array}{ccc} 0 & 0 & 1 \\ 0 & 0 & 1 \\ 0 & 1 & 0 \\ 1 & 0 & 0 \\ 1 & 0 & 0 \\ 1 & 0 & 0 \\ 0 & 1 & 0 \end{array} \right) \end{align} while the ordinal $V2$ with 7 samples would look something like: \begin{align} V2 = \left( \begin{array}{ccc} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 0 \\ 1 & 0 & 0 \\ 1 & 0 & 0 \\ 1 & 0 & 0 \\ 1 & 1 & 0 \end{array} \right) \end{align} Notice that in both case you are encoding the same information. Namely red, red, yellow, green, green, green, yellow. As you see the difference between the variable $V1$ and $V2$ is obvious now and if you attempt to fit a model in $V1$ that model will almost surely be suboptimal to predict $V2$. The estimation procedures for these models are not vastly different actually. Without going in details both of them rely on numerical optimisation where something called Fisher scoring is extensively used. Let's look at an actual example now using R. We define a multinomial variable V1 and we then use it to define the ordinal variable V2. True to a real-life setting we only have irrelevant information which is encoded in GarbageInfo. (I use the function multinom from the nnet package to fit the multinomial and the function polr from the MASS package to fit the ordered logit, you can get more information from the documentation of these functions directly.) set.seed(1234); N = 100; V1 = sample(c('green','yellow','red'), N, replace = TRUE) V2 = ordered(V1, c('green', 'yellow', 'red')) GarbageInfo = runif(N); # This is used only for illustration purposes m1 = nnet::multinom(V1 ~ GarbageInfo) m2 = MASS::polr(V2 ~ GarbageInfo) We then check the model summaries and notice very interesting. > summary(m1) Call: nnet::multinom(formula = V1 ~ GarbageInfo) Coefficients: (Intercept) GarbageInfo red -0.6011338 -0.1331142 yellow -0.3221203 -0.5995860 Std. Errors: (Intercept) GarbageInfo red 0.5164521 0.8448432 yellow 0.4932972 0.8380932 ... > summary(m2) ... Call: MASS::polr(formula = V2 ~ GarbageInfo) Coefficients: Value Std. Error t value GarbageInfo -0.2181 0.6431 -0.3391 Intercepts: Value Std. Error t value green|yellow -0.1541 0.3910 -0.3941 yellow|red 0.9856 0.4045 2.4364 ... While in the case of m1 your intercepts are defined for red and yellow against the green baseline, the intercepts for m2 are defined as green|yellow and yellow|red, ie. they are cut-points rather than simple intercepts. Furthermore your GarbageInfo variable coefficient is common in m2 throughout the model in the case of the ordinal regression rather than being estimated independently for each level in the case of the multinomial. That is because you exploit the fact that your data have more information and (in this case) you have an additional degree of freedom. This brings us back to the first sentence of this post: Multinomial and ordinal variables (and their respective) regression procedures are different because they encode different information.
What is the difference between multinomial and ordinal logistic regression?
In the case of the multinomial one has no intrinsic ordering; in contrast in the case of ordinal regression there is an association between the levels. For example if you examine the variable $V1$ tha
What is the difference between multinomial and ordinal logistic regression? In the case of the multinomial one has no intrinsic ordering; in contrast in the case of ordinal regression there is an association between the levels. For example if you examine the variable $V1$ that has green, yellow and red as independent levels then $V1$ encodes a multinomial variable. If you have a new variable $V2$ were the levels green, yellow and red represent some sort of increased urgency then they define an ordinal variable. So how would these variables be encoded: In the case of an multinomial variable this variable is encoded as an indicator matrix. The arbitrary encoding for green can be [1 0 0], yellow can be [0 1 0] and [0 0 1] for red. In the case of an ordinal variable the encoding is a bit different. If you are in the yellow level you are assumed that you have reached and exceed the green level. Similarly if you are in the red level you have reached the green and the yellow level and now you are in the red level. Therefore the encoding is for the green value would be something like [1 0 0]. For the yellow, [1 1 0] and for red, [1 1 1]. So for the multinomial $V1$ with 7 samples would look something like: \begin{align} V1 = \left( \begin{array}{ccc} 0 & 0 & 1 \\ 0 & 0 & 1 \\ 0 & 1 & 0 \\ 1 & 0 & 0 \\ 1 & 0 & 0 \\ 1 & 0 & 0 \\ 0 & 1 & 0 \end{array} \right) \end{align} while the ordinal $V2$ with 7 samples would look something like: \begin{align} V2 = \left( \begin{array}{ccc} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 0 \\ 1 & 0 & 0 \\ 1 & 0 & 0 \\ 1 & 0 & 0 \\ 1 & 1 & 0 \end{array} \right) \end{align} Notice that in both case you are encoding the same information. Namely red, red, yellow, green, green, green, yellow. As you see the difference between the variable $V1$ and $V2$ is obvious now and if you attempt to fit a model in $V1$ that model will almost surely be suboptimal to predict $V2$. The estimation procedures for these models are not vastly different actually. Without going in details both of them rely on numerical optimisation where something called Fisher scoring is extensively used. Let's look at an actual example now using R. We define a multinomial variable V1 and we then use it to define the ordinal variable V2. True to a real-life setting we only have irrelevant information which is encoded in GarbageInfo. (I use the function multinom from the nnet package to fit the multinomial and the function polr from the MASS package to fit the ordered logit, you can get more information from the documentation of these functions directly.) set.seed(1234); N = 100; V1 = sample(c('green','yellow','red'), N, replace = TRUE) V2 = ordered(V1, c('green', 'yellow', 'red')) GarbageInfo = runif(N); # This is used only for illustration purposes m1 = nnet::multinom(V1 ~ GarbageInfo) m2 = MASS::polr(V2 ~ GarbageInfo) We then check the model summaries and notice very interesting. > summary(m1) Call: nnet::multinom(formula = V1 ~ GarbageInfo) Coefficients: (Intercept) GarbageInfo red -0.6011338 -0.1331142 yellow -0.3221203 -0.5995860 Std. Errors: (Intercept) GarbageInfo red 0.5164521 0.8448432 yellow 0.4932972 0.8380932 ... > summary(m2) ... Call: MASS::polr(formula = V2 ~ GarbageInfo) Coefficients: Value Std. Error t value GarbageInfo -0.2181 0.6431 -0.3391 Intercepts: Value Std. Error t value green|yellow -0.1541 0.3910 -0.3941 yellow|red 0.9856 0.4045 2.4364 ... While in the case of m1 your intercepts are defined for red and yellow against the green baseline, the intercepts for m2 are defined as green|yellow and yellow|red, ie. they are cut-points rather than simple intercepts. Furthermore your GarbageInfo variable coefficient is common in m2 throughout the model in the case of the ordinal regression rather than being estimated independently for each level in the case of the multinomial. That is because you exploit the fact that your data have more information and (in this case) you have an additional degree of freedom. This brings us back to the first sentence of this post: Multinomial and ordinal variables (and their respective) regression procedures are different because they encode different information.
What is the difference between multinomial and ordinal logistic regression? In the case of the multinomial one has no intrinsic ordering; in contrast in the case of ordinal regression there is an association between the levels. For example if you examine the variable $V1$ tha
25,183
What is the null hypothesis of a MANOVA?
The null hypothesis $H_0$ of a one-way ANOVA is that the means of all groups are equal: $$H_0: \mu_1 = \mu_2 = ... = \mu_k.$$ The null hypothesis $H_0$ of a one-way MANOVA is that the [multivariate] means of all groups are equal: $$H_0: \boldsymbol \mu_1 = \boldsymbol \mu_2 = ... = \boldsymbol \mu_k.$$ This is equivalent to saying that the means are equal for each response variable, i.e. your first option is correct. In both cases the alternative hypothesis $H_1$ is the negation of the null. In both cases the assumptions are (a) Gaussian within-group distributions, and (b) equal variances (for ANOVA) / covariance matrices (for MANOVA) across groups. Difference between MANOVA and ANOVAs This might appear a bit confusing: the null hypothesis of MANOVA is exactly the same as the combination of null hypotheses for a collection of univariate ANOVAs, but at the same time we know that doing MANOVA is not equivalent to doing univariate ANOVAs and then somehow "combining" the results (one could come up with various ways of combining). Why not? The answer is that running all univariate ANOVAs, even though would test the same null hypothesis, will have less power. See my answer here for an illustration: How can MANOVA report a significant difference when none of the univariate ANOVAs reaches significance? Naive method of "combining" (reject the global null if at least one ANOVA rejects the null) would also lead to a huge inflation of type I error rate; but even if one chooses some smart way of "combining" to maintain the correct error rate, one would lose in power. How the testing works ANOVA decomposes the total sum-of-squares $T$ into between-group sum-of-squares $B$ and within-group sum-of-squares $W$, so that $T=B+W$. It then computes the ratio $B/W$. Under the null hypothesis, this ratio should be small (around $1$); one can work out the exact distribution of this ratio expected under the null hypothesis (it will depend on $n$ and on the number of groups). Comparing the observed value $B/W$ with this distribution yields a p-value. MANOVA decomposes the total scatter matrix $\mathbf T$ into between-group scatter matrix $\mathbf B$ and within-group scatter matrix $\mathbf W$, so that $\mathbf T = \mathbf B + \mathbf W$. It then computes the matrix $\mathbf W^{-1} \mathbf B$. Under the null hypothesis, this matrix should be "small" (around $\mathbf{I}$); but how to quantify how "small" it is? MANOVA looks at the eigenvalues $\lambda_i$ of this matrix (they are all positive). Again, under the null hypothesis, these eigenvalues should be "small" (all around $1$). But to compute a p-value, we need one number (called "statistic") in order to be able to compare it with its expected distribution under the null. There are several ways to do it: take the sum of all eigenvalues $\sum \lambda_i$; take maximal eigenvalue $\max\{\lambda_i\}$, etc. In each case, this number is compared with the distribution of this quantity expected under the null, resulting in a p-value. Different choices of the test statistic lead to slightly different p-values, but it is important to realize that in each case the same null hypothesis is being tested.
What is the null hypothesis of a MANOVA?
The null hypothesis $H_0$ of a one-way ANOVA is that the means of all groups are equal: $$H_0: \mu_1 = \mu_2 = ... = \mu_k.$$ The null hypothesis $H_0$ of a one-way MANOVA is that the [multivariate] m
What is the null hypothesis of a MANOVA? The null hypothesis $H_0$ of a one-way ANOVA is that the means of all groups are equal: $$H_0: \mu_1 = \mu_2 = ... = \mu_k.$$ The null hypothesis $H_0$ of a one-way MANOVA is that the [multivariate] means of all groups are equal: $$H_0: \boldsymbol \mu_1 = \boldsymbol \mu_2 = ... = \boldsymbol \mu_k.$$ This is equivalent to saying that the means are equal for each response variable, i.e. your first option is correct. In both cases the alternative hypothesis $H_1$ is the negation of the null. In both cases the assumptions are (a) Gaussian within-group distributions, and (b) equal variances (for ANOVA) / covariance matrices (for MANOVA) across groups. Difference between MANOVA and ANOVAs This might appear a bit confusing: the null hypothesis of MANOVA is exactly the same as the combination of null hypotheses for a collection of univariate ANOVAs, but at the same time we know that doing MANOVA is not equivalent to doing univariate ANOVAs and then somehow "combining" the results (one could come up with various ways of combining). Why not? The answer is that running all univariate ANOVAs, even though would test the same null hypothesis, will have less power. See my answer here for an illustration: How can MANOVA report a significant difference when none of the univariate ANOVAs reaches significance? Naive method of "combining" (reject the global null if at least one ANOVA rejects the null) would also lead to a huge inflation of type I error rate; but even if one chooses some smart way of "combining" to maintain the correct error rate, one would lose in power. How the testing works ANOVA decomposes the total sum-of-squares $T$ into between-group sum-of-squares $B$ and within-group sum-of-squares $W$, so that $T=B+W$. It then computes the ratio $B/W$. Under the null hypothesis, this ratio should be small (around $1$); one can work out the exact distribution of this ratio expected under the null hypothesis (it will depend on $n$ and on the number of groups). Comparing the observed value $B/W$ with this distribution yields a p-value. MANOVA decomposes the total scatter matrix $\mathbf T$ into between-group scatter matrix $\mathbf B$ and within-group scatter matrix $\mathbf W$, so that $\mathbf T = \mathbf B + \mathbf W$. It then computes the matrix $\mathbf W^{-1} \mathbf B$. Under the null hypothesis, this matrix should be "small" (around $\mathbf{I}$); but how to quantify how "small" it is? MANOVA looks at the eigenvalues $\lambda_i$ of this matrix (they are all positive). Again, under the null hypothesis, these eigenvalues should be "small" (all around $1$). But to compute a p-value, we need one number (called "statistic") in order to be able to compare it with its expected distribution under the null. There are several ways to do it: take the sum of all eigenvalues $\sum \lambda_i$; take maximal eigenvalue $\max\{\lambda_i\}$, etc. In each case, this number is compared with the distribution of this quantity expected under the null, resulting in a p-value. Different choices of the test statistic lead to slightly different p-values, but it is important to realize that in each case the same null hypothesis is being tested.
What is the null hypothesis of a MANOVA? The null hypothesis $H_0$ of a one-way ANOVA is that the means of all groups are equal: $$H_0: \mu_1 = \mu_2 = ... = \mu_k.$$ The null hypothesis $H_0$ of a one-way MANOVA is that the [multivariate] m
25,184
What is the null hypothesis of a MANOVA?
It is the former. However, the way it does it isn't literally to compare the means of each of the original variables in turn. Instead the response variables are linearly transformed in a way that is very similar to principal components analysis. (There is an excellent thread on PCA here: Making sense of principal component analysis, eigenvectors & eigenvalues.) The difference is that PCA orients your axes so as to align with the directions of maximal variation, whereas MANOVA rotates your axes in the directions that maximize the separation of your groups. To be clear though, none of the tests associated with a MANOVA is testing all the means one after another in a direct sense, either with the means in the original space or in the transformed space. There are several different test statistics that each work in a slightly different way, nonetheless they tend to operate over the eigenvalues of the decomposition that transforms the space. But as far as the nature of the null hypothesis goes, it is that all means of all groups are the same on each response variable, not that they can differ on some variables but are the same on at least one.
What is the null hypothesis of a MANOVA?
It is the former. However, the way it does it isn't literally to compare the means of each of the original variables in turn. Instead the response variables are linearly transformed in a way that is
What is the null hypothesis of a MANOVA? It is the former. However, the way it does it isn't literally to compare the means of each of the original variables in turn. Instead the response variables are linearly transformed in a way that is very similar to principal components analysis. (There is an excellent thread on PCA here: Making sense of principal component analysis, eigenvectors & eigenvalues.) The difference is that PCA orients your axes so as to align with the directions of maximal variation, whereas MANOVA rotates your axes in the directions that maximize the separation of your groups. To be clear though, none of the tests associated with a MANOVA is testing all the means one after another in a direct sense, either with the means in the original space or in the transformed space. There are several different test statistics that each work in a slightly different way, nonetheless they tend to operate over the eigenvalues of the decomposition that transforms the space. But as far as the nature of the null hypothesis goes, it is that all means of all groups are the same on each response variable, not that they can differ on some variables but are the same on at least one.
What is the null hypothesis of a MANOVA? It is the former. However, the way it does it isn't literally to compare the means of each of the original variables in turn. Instead the response variables are linearly transformed in a way that is
25,185
Can independent variables with low correlation with dependent variable be significant predictors?
With a correlation matrix, you are examining unconditional (crude) associations between your variables. With a regression model, you are examining the joint associations of your IVs with your DVs, thus looking at conditional associations (for each IV, its association with the DV conditional on the other IVs). Depending on the structure of your data, these two can yield very different, even contrary results.
Can independent variables with low correlation with dependent variable be significant predictors?
With a correlation matrix, you are examining unconditional (crude) associations between your variables. With a regression model, you are examining the joint associations of your IVs with your DVs, thu
Can independent variables with low correlation with dependent variable be significant predictors? With a correlation matrix, you are examining unconditional (crude) associations between your variables. With a regression model, you are examining the joint associations of your IVs with your DVs, thus looking at conditional associations (for each IV, its association with the DV conditional on the other IVs). Depending on the structure of your data, these two can yield very different, even contrary results.
Can independent variables with low correlation with dependent variable be significant predictors? With a correlation matrix, you are examining unconditional (crude) associations between your variables. With a regression model, you are examining the joint associations of your IVs with your DVs, thu
25,186
Can independent variables with low correlation with dependent variable be significant predictors?
Coincidentally I was just looking at an example that I had created earlier to show similar concepts (actually to show one of the problems with stepwise regression). Here is R code to create and analyze a simulated dataset: set.seed(1) x1 <- rnorm(25) x2 <- rnorm(25, x1) y <- x1-x2 + rnorm(25) pairs( cbind(y,x1,x2) ) # Relevant results of each following line appear below... cor( cbind(y,x1,x2) ) # rx1y = .08 rx2y = -.26 rx1x2 = .79 summary(lm(y~x1)) # t(23) = .39 p = .70 summary(lm(y~x2)) # t(23) = -1.28 p = .21 summary(lm(y~x1+x2)) # t(22) = 2.54, -2.88 p = .02, .01 (for x1 & x2, respectively) The correlations and simple linear regressions show low (not statistically significant) relationships between $y$ and each of the $x$ variables. But $y$ was defined as a function of both $x$s, and the multiple regression shows both as significant predictors.
Can independent variables with low correlation with dependent variable be significant predictors?
Coincidentally I was just looking at an example that I had created earlier to show similar concepts (actually to show one of the problems with stepwise regression). Here is R code to create and analy
Can independent variables with low correlation with dependent variable be significant predictors? Coincidentally I was just looking at an example that I had created earlier to show similar concepts (actually to show one of the problems with stepwise regression). Here is R code to create and analyze a simulated dataset: set.seed(1) x1 <- rnorm(25) x2 <- rnorm(25, x1) y <- x1-x2 + rnorm(25) pairs( cbind(y,x1,x2) ) # Relevant results of each following line appear below... cor( cbind(y,x1,x2) ) # rx1y = .08 rx2y = -.26 rx1x2 = .79 summary(lm(y~x1)) # t(23) = .39 p = .70 summary(lm(y~x2)) # t(23) = -1.28 p = .21 summary(lm(y~x1+x2)) # t(22) = 2.54, -2.88 p = .02, .01 (for x1 & x2, respectively) The correlations and simple linear regressions show low (not statistically significant) relationships between $y$ and each of the $x$ variables. But $y$ was defined as a function of both $x$s, and the multiple regression shows both as significant predictors.
Can independent variables with low correlation with dependent variable be significant predictors? Coincidentally I was just looking at an example that I had created earlier to show similar concepts (actually to show one of the problems with stepwise regression). Here is R code to create and analy
25,187
Can independent variables with low correlation with dependent variable be significant predictors?
Your question would be easier to answer if we could see quantitative detail from your software output and ideally have a sight of the data too. What is "low correlation", in particular? What significance level are you using? Are there built-in relationships between predictors that result in SPSS dropping some? Note that we have no scope for judging whether you used the best or most appropriate syntax for your purpose, as you don't state exactly what you did. In broad terms, low correlations between predictors and outcomes imply that regression may be disappointing in much the same way that you need chocolate to make chocolate cake. Give us more detail, and you should get a better answer. Also in broad terms, the disappointment of your supervisor doesn't imply that you did the wrong thing. If your supervisor knows less statistics than you do, you need to seek advice and support from other people in your institution.
Can independent variables with low correlation with dependent variable be significant predictors?
Your question would be easier to answer if we could see quantitative detail from your software output and ideally have a sight of the data too. What is "low correlation", in particular? What signific
Can independent variables with low correlation with dependent variable be significant predictors? Your question would be easier to answer if we could see quantitative detail from your software output and ideally have a sight of the data too. What is "low correlation", in particular? What significance level are you using? Are there built-in relationships between predictors that result in SPSS dropping some? Note that we have no scope for judging whether you used the best or most appropriate syntax for your purpose, as you don't state exactly what you did. In broad terms, low correlations between predictors and outcomes imply that regression may be disappointing in much the same way that you need chocolate to make chocolate cake. Give us more detail, and you should get a better answer. Also in broad terms, the disappointment of your supervisor doesn't imply that you did the wrong thing. If your supervisor knows less statistics than you do, you need to seek advice and support from other people in your institution.
Can independent variables with low correlation with dependent variable be significant predictors? Your question would be easier to answer if we could see quantitative detail from your software output and ideally have a sight of the data too. What is "low correlation", in particular? What signific
25,188
Can I use the Cholesky-method for generating correlated random variables with given mean?
Let Z be uncorrelated random variables normally distributed with mean 0 and variance 1. This means $$Z\sim N\left(0,I\right)$$ If you make an affine transformation $$X\equiv A+BZ$$ then $X$ has a distribution $$X\sim N\left(A,BB'\right)$$ In our case, we want $BB'=\Sigma$, so applying the cholesky decomposition to $\Sigma$ is one way to find a suitable $B$. Thus, to simulate from $X\sim N\left(\mu,\Sigma\right)$, you would simulate $Z$, set $A=\mu$ and $B=chol(\Sigma)$, and apply the transformation above. So to answer your question, uncorrelated variables of mean 0 and variance 1 can be transformed to generic multivariate normal distributions through the use of affine transformations, depending on the mean vector and cholesky decomposition of the covariance matrix. This is how multivariate normal random number generators generally work. To address your other point in the comments, suppose you simulate $Z$ and make a transformation $$Y\equiv chol(C)Z$$ so that $Y\sim N(0, C)$. You can still get to $X$ from $Y$. As I discussed in the comments, you can easily do this by multiplying the univariate distributions by the respective standard deviations and adding the respective mean. More formally, you can consider this another affine transformation $$X\equiv A+SY$$ However, since $Y$ is not uncorrelated, the affine transformation would give $$X\sim N\left(A,SCS'\right)$$ In this case, to get $SCS'=\Sigma$, you would need to set $S$ equal to a matrix with the standard deviations on the diagonal and zeros elsewhere. This is equivalent to applying the transformations on a univariate basis.
Can I use the Cholesky-method for generating correlated random variables with given mean?
Let Z be uncorrelated random variables normally distributed with mean 0 and variance 1. This means $$Z\sim N\left(0,I\right)$$ If you make an affine transformation $$X\equiv A+BZ$$ then $X$ has a dist
Can I use the Cholesky-method for generating correlated random variables with given mean? Let Z be uncorrelated random variables normally distributed with mean 0 and variance 1. This means $$Z\sim N\left(0,I\right)$$ If you make an affine transformation $$X\equiv A+BZ$$ then $X$ has a distribution $$X\sim N\left(A,BB'\right)$$ In our case, we want $BB'=\Sigma$, so applying the cholesky decomposition to $\Sigma$ is one way to find a suitable $B$. Thus, to simulate from $X\sim N\left(\mu,\Sigma\right)$, you would simulate $Z$, set $A=\mu$ and $B=chol(\Sigma)$, and apply the transformation above. So to answer your question, uncorrelated variables of mean 0 and variance 1 can be transformed to generic multivariate normal distributions through the use of affine transformations, depending on the mean vector and cholesky decomposition of the covariance matrix. This is how multivariate normal random number generators generally work. To address your other point in the comments, suppose you simulate $Z$ and make a transformation $$Y\equiv chol(C)Z$$ so that $Y\sim N(0, C)$. You can still get to $X$ from $Y$. As I discussed in the comments, you can easily do this by multiplying the univariate distributions by the respective standard deviations and adding the respective mean. More formally, you can consider this another affine transformation $$X\equiv A+SY$$ However, since $Y$ is not uncorrelated, the affine transformation would give $$X\sim N\left(A,SCS'\right)$$ In this case, to get $SCS'=\Sigma$, you would need to set $S$ equal to a matrix with the standard deviations on the diagonal and zeros elsewhere. This is equivalent to applying the transformations on a univariate basis.
Can I use the Cholesky-method for generating correlated random variables with given mean? Let Z be uncorrelated random variables normally distributed with mean 0 and variance 1. This means $$Z\sim N\left(0,I\right)$$ If you make an affine transformation $$X\equiv A+BZ$$ then $X$ has a dist
25,189
Can I use the Cholesky-method for generating correlated random variables with given mean?
Additionnal items: We need to decompose the convariance matrix Σ into orthogonal matrix product as mentionned above. There are different ways to get the orthogonal matrix B, Cholesky is one of them. We can also use SVD (Singular Value Decomposition) to get B, equivalent to calculate the eigenvalues/vectors for PDM. If you want to use the decomposition to simulate brownians over time, you can also use Brownian Bridge with Haar transformation.
Can I use the Cholesky-method for generating correlated random variables with given mean?
Additionnal items: We need to decompose the convariance matrix Σ into orthogonal matrix product as mentionned above. There are different ways to get the orthogonal matrix B, Cholesky is one of them. W
Can I use the Cholesky-method for generating correlated random variables with given mean? Additionnal items: We need to decompose the convariance matrix Σ into orthogonal matrix product as mentionned above. There are different ways to get the orthogonal matrix B, Cholesky is one of them. We can also use SVD (Singular Value Decomposition) to get B, equivalent to calculate the eigenvalues/vectors for PDM. If you want to use the decomposition to simulate brownians over time, you can also use Brownian Bridge with Haar transformation.
Can I use the Cholesky-method for generating correlated random variables with given mean? Additionnal items: We need to decompose the convariance matrix Σ into orthogonal matrix product as mentionned above. There are different ways to get the orthogonal matrix B, Cholesky is one of them. W
25,190
Using control variables in experiments?
From a frequentist perspective, an unadjusted comparison based on the permutation distribution can always be justified following a (properly) randomized study. A similar justification can be made for inference based on common parametric distributions (e.g., the $t$ distribution or $F$ distribution) due to their similarity to the permutation distribution. In fact, adjusting for covariates—when they are selected based on post-hoc analyses—actually risks inflating the Type I error. Note that this justification has nothing to do with the degree of balance in the observed sample, or with the size of the sample (except that for small samples the permutation distribution will be more discrete, and less well approximated by the $t$ or $F$ distributions). That said, many people are aware that adjusting for covariates can increase precision in the linear model. Specifically, adjusting for covariates increases the precision of the estimated treatment effect when they are predictive of the outcome and not correlated with the treatment variable (as is true in the case of a randomized study). What is less well known, however, is that this does not automatically carry over to non-linear models. For example, Robinson and Jewell [1] show that in the case of logistic regression, controlling for covariates reduces the precision of the estimated treatment effect, even when they are predictive of the outcome. However, because the estimated treatment effect is also larger in the adjusted model, controlling for covariates predictive of the outcome does increase efficiency when testing the null hypothesis of no treatment effect following a randomized study. [1] L. D. Robinson and N. P. Jewell. Some surprising results about covariate adjustment in logistic regression models. International Statistical Review, 58(2):227–40, 1991.
Using control variables in experiments?
From a frequentist perspective, an unadjusted comparison based on the permutation distribution can always be justified following a (properly) randomized study. A similar justification can be made for
Using control variables in experiments? From a frequentist perspective, an unadjusted comparison based on the permutation distribution can always be justified following a (properly) randomized study. A similar justification can be made for inference based on common parametric distributions (e.g., the $t$ distribution or $F$ distribution) due to their similarity to the permutation distribution. In fact, adjusting for covariates—when they are selected based on post-hoc analyses—actually risks inflating the Type I error. Note that this justification has nothing to do with the degree of balance in the observed sample, or with the size of the sample (except that for small samples the permutation distribution will be more discrete, and less well approximated by the $t$ or $F$ distributions). That said, many people are aware that adjusting for covariates can increase precision in the linear model. Specifically, adjusting for covariates increases the precision of the estimated treatment effect when they are predictive of the outcome and not correlated with the treatment variable (as is true in the case of a randomized study). What is less well known, however, is that this does not automatically carry over to non-linear models. For example, Robinson and Jewell [1] show that in the case of logistic regression, controlling for covariates reduces the precision of the estimated treatment effect, even when they are predictive of the outcome. However, because the estimated treatment effect is also larger in the adjusted model, controlling for covariates predictive of the outcome does increase efficiency when testing the null hypothesis of no treatment effect following a randomized study. [1] L. D. Robinson and N. P. Jewell. Some surprising results about covariate adjustment in logistic regression models. International Statistical Review, 58(2):227–40, 1991.
Using control variables in experiments? From a frequentist perspective, an unadjusted comparison based on the permutation distribution can always be justified following a (properly) randomized study. A similar justification can be made for
25,191
Using control variables in experiments?
If the outcome depends on treatment as well as other observable factors, controlling for the latter often improves the precision of the impact estimate (i.e., the standard error of the treatment effect will be smaller). When sample size is small, this can be helpful. Here's a simple simulation where even though treatment is random, the standard error shrinks by a third: . set obs 100 obs was 0, now 100 . gen treat =mod(_n,2) . gen x=rnormal() . gen y = 2 + 3*treat + 1*x + rnormal() . reg y treat Source | SS df MS Number of obs = 100 -------------+------------------------------ F( 1, 98) = 112.75 Model | 209.354021 1 209.354021 Prob > F = 0.0000 Residual | 181.973854 98 1.85687606 R-squared = 0.5350 -------------+------------------------------ Adj R-squared = 0.5302 Total | 391.327875 99 3.95280682 Root MSE = 1.3627 ------------------------------------------------------------------------------ y | Coef. Std. Err. t P>|t| [95% Conf. Interval] -------------+---------------------------------------------------------------- treat | 2.893814 .2725345 10.62 0.000 2.352978 3.43465 _cons | 2.051611 .192711 10.65 0.000 1.669183 2.43404 ------------------------------------------------------------------------------ . reg y treat x Source | SS df MS Number of obs = 100 -------------+------------------------------ F( 2, 97) = 180.50 Model | 308.447668 2 154.223834 Prob > F = 0.0000 Residual | 82.8802074 97 .854435127 R-squared = 0.7882 -------------+------------------------------ Adj R-squared = 0.7838 Total | 391.327875 99 3.95280682 Root MSE = .92436 ------------------------------------------------------------------------------ y | Coef. Std. Err. t P>|t| [95% Conf. Interval] -------------+---------------------------------------------------------------- treat | 2.918349 .1848854 15.78 0.000 2.551403 3.285295 x | 1.058636 .0983022 10.77 0.000 .8635335 1.253739 _cons | 1.996209 .130825 15.26 0.000 1.736558 2.25586 ------------------------------------------------------------------------------
Using control variables in experiments?
If the outcome depends on treatment as well as other observable factors, controlling for the latter often improves the precision of the impact estimate (i.e., the standard error of the treatment effec
Using control variables in experiments? If the outcome depends on treatment as well as other observable factors, controlling for the latter often improves the precision of the impact estimate (i.e., the standard error of the treatment effect will be smaller). When sample size is small, this can be helpful. Here's a simple simulation where even though treatment is random, the standard error shrinks by a third: . set obs 100 obs was 0, now 100 . gen treat =mod(_n,2) . gen x=rnormal() . gen y = 2 + 3*treat + 1*x + rnormal() . reg y treat Source | SS df MS Number of obs = 100 -------------+------------------------------ F( 1, 98) = 112.75 Model | 209.354021 1 209.354021 Prob > F = 0.0000 Residual | 181.973854 98 1.85687606 R-squared = 0.5350 -------------+------------------------------ Adj R-squared = 0.5302 Total | 391.327875 99 3.95280682 Root MSE = 1.3627 ------------------------------------------------------------------------------ y | Coef. Std. Err. t P>|t| [95% Conf. Interval] -------------+---------------------------------------------------------------- treat | 2.893814 .2725345 10.62 0.000 2.352978 3.43465 _cons | 2.051611 .192711 10.65 0.000 1.669183 2.43404 ------------------------------------------------------------------------------ . reg y treat x Source | SS df MS Number of obs = 100 -------------+------------------------------ F( 2, 97) = 180.50 Model | 308.447668 2 154.223834 Prob > F = 0.0000 Residual | 82.8802074 97 .854435127 R-squared = 0.7882 -------------+------------------------------ Adj R-squared = 0.7838 Total | 391.327875 99 3.95280682 Root MSE = .92436 ------------------------------------------------------------------------------ y | Coef. Std. Err. t P>|t| [95% Conf. Interval] -------------+---------------------------------------------------------------- treat | 2.918349 .1848854 15.78 0.000 2.551403 3.285295 x | 1.058636 .0983022 10.77 0.000 .8635335 1.253739 _cons | 1.996209 .130825 15.26 0.000 1.736558 2.25586 ------------------------------------------------------------------------------
Using control variables in experiments? If the outcome depends on treatment as well as other observable factors, controlling for the latter often improves the precision of the impact estimate (i.e., the standard error of the treatment effec
25,192
What are the assumptions of ARIMA/Box-Jenkins modeling for forecasting time series?
There are no known/suspected predictor variables There are no level shifts There are no deterministic time trends of the form $1,2,3,...,t$ There are no seasonal dummies There are no one time anomalies The model parameters are constant over time The error process is homoscedastic (constant) over time Most software solutions proceed to ignore all of these assumptions. AUTOBOX a piece of software that I have helped develop identifies and tests and remedies any violations of the above (save 1) leading to a Robust ARIMA solution.
What are the assumptions of ARIMA/Box-Jenkins modeling for forecasting time series?
There are no known/suspected predictor variables There are no level shifts There are no deterministic time trends of the form $1,2,3,...,t$ There are no seasonal dummies There are no one time anomal
What are the assumptions of ARIMA/Box-Jenkins modeling for forecasting time series? There are no known/suspected predictor variables There are no level shifts There are no deterministic time trends of the form $1,2,3,...,t$ There are no seasonal dummies There are no one time anomalies The model parameters are constant over time The error process is homoscedastic (constant) over time Most software solutions proceed to ignore all of these assumptions. AUTOBOX a piece of software that I have helped develop identifies and tests and remedies any violations of the above (save 1) leading to a Robust ARIMA solution.
What are the assumptions of ARIMA/Box-Jenkins modeling for forecasting time series? There are no known/suspected predictor variables There are no level shifts There are no deterministic time trends of the form $1,2,3,...,t$ There are no seasonal dummies There are no one time anomal
25,193
What are the assumptions of ARIMA/Box-Jenkins modeling for forecasting time series?
For the "pure" ARIMA models, That the time-series involved are weakly stationary or Integrated of some order (which implies restrictions on the values of the unknown coefficients, as well as their constancy). That all observed time series are combinations of white noises only, and perhaps a constant. Moreover, the very fact that you use the abbreviation "ARIMA", implies in itself that There are no other predictors (in which case you would have an "ARIMA-X" model) and The relations are exclusively linear (to indicate the possibility of non-linear modelling, you should abbreviate to "NARIMA").
What are the assumptions of ARIMA/Box-Jenkins modeling for forecasting time series?
For the "pure" ARIMA models, That the time-series involved are weakly stationary or Integrated of some order (which implies restrictions on the values of the unknown coefficients, as well as their co
What are the assumptions of ARIMA/Box-Jenkins modeling for forecasting time series? For the "pure" ARIMA models, That the time-series involved are weakly stationary or Integrated of some order (which implies restrictions on the values of the unknown coefficients, as well as their constancy). That all observed time series are combinations of white noises only, and perhaps a constant. Moreover, the very fact that you use the abbreviation "ARIMA", implies in itself that There are no other predictors (in which case you would have an "ARIMA-X" model) and The relations are exclusively linear (to indicate the possibility of non-linear modelling, you should abbreviate to "NARIMA").
What are the assumptions of ARIMA/Box-Jenkins modeling for forecasting time series? For the "pure" ARIMA models, That the time-series involved are weakly stationary or Integrated of some order (which implies restrictions on the values of the unknown coefficients, as well as their co
25,194
Robust regression inference and Sandwich estimators
I think there are a few approaches. I haven't looked at them all and not sure which is the best: The sandwich package: library(sandwich) coeftest(model, vcov=sandwich) But this doesn't give me the same answers I get from Stata for some reason. I've never tried to work out why, I just don't use this package. The rms package: I find this a bit of a pain to work with but usually get good answers with some effort. And it is the most useful for me. model = ols(a~b, x=TRUE) robcov(model) You can code it from scratch (see this blog post). It looks like the most painful option, but remarkably easy and this option often works the best. A simple / quick explanation is that Huber-White or Robust SE are derived from the data rather than from the model, and thus are robust to many model assumptions. But as always, a quick Google search will lay this out in excruciating detail if you're interested.
Robust regression inference and Sandwich estimators
I think there are a few approaches. I haven't looked at them all and not sure which is the best: The sandwich package: library(sandwich) coeftest(model, vcov=sandwich) But this doesn't give me
Robust regression inference and Sandwich estimators I think there are a few approaches. I haven't looked at them all and not sure which is the best: The sandwich package: library(sandwich) coeftest(model, vcov=sandwich) But this doesn't give me the same answers I get from Stata for some reason. I've never tried to work out why, I just don't use this package. The rms package: I find this a bit of a pain to work with but usually get good answers with some effort. And it is the most useful for me. model = ols(a~b, x=TRUE) robcov(model) You can code it from scratch (see this blog post). It looks like the most painful option, but remarkably easy and this option often works the best. A simple / quick explanation is that Huber-White or Robust SE are derived from the data rather than from the model, and thus are robust to many model assumptions. But as always, a quick Google search will lay this out in excruciating detail if you're interested.
Robust regression inference and Sandwich estimators I think there are a few approaches. I haven't looked at them all and not sure which is the best: The sandwich package: library(sandwich) coeftest(model, vcov=sandwich) But this doesn't give me
25,195
Robust regression inference and Sandwich estimators
One can use an alternative summary function to perform a robust regression. lm.object <- lm(a~b+c) summary(lm.object, robust=TRUE) To obtain robust standard errors you set the parameter ''robust'' in your summary function to TRUE. The following blog entry provides the function and a detailed description of the function: https://economictheoryblog.com/2016/08/08/robust-standard-errors-in-r
Robust regression inference and Sandwich estimators
One can use an alternative summary function to perform a robust regression. lm.object <- lm(a~b+c) summary(lm.object, robust=TRUE) To obtain robust standard errors you set the parameter ''robust'' i
Robust regression inference and Sandwich estimators One can use an alternative summary function to perform a robust regression. lm.object <- lm(a~b+c) summary(lm.object, robust=TRUE) To obtain robust standard errors you set the parameter ''robust'' in your summary function to TRUE. The following blog entry provides the function and a detailed description of the function: https://economictheoryblog.com/2016/08/08/robust-standard-errors-in-r
Robust regression inference and Sandwich estimators One can use an alternative summary function to perform a robust regression. lm.object <- lm(a~b+c) summary(lm.object, robust=TRUE) To obtain robust standard errors you set the parameter ''robust'' i
25,196
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis?
Two or three items per factor is a question of identification of your CFA (confirmatory FA) model. Let us for simplicity assume that the model is identified by setting the variance of each factor to 1. Assume also that there are no correlated measurement errors. A single factor model with two items has two loadings and two error variances to be estimated = 4 parameters, but there are only 3 non-trivial entries in the variance-covariance matrix, so you don't have enough information to estimate the four parameters that you need. A single factor model with three items has three loadings and three error variances. The variance-covariance matrix has six entries, and careful analytic examination shows that the model is exactly identified, and you can algebraically express the parameter estimates as functions of the variance-covariance matrix entries. With more items per single factor, you have an overidentified model (more degrees of freedom than parameters), which usually means you are good to go. With more that one factor, the CFA model is always identified with 3+ items per each factor (because a simple measurement model is identified for each factor, so roughly speaking you can get predictions for each factor and estimate their covariances based on that). However, a CFA with two items per factor is identified provided that each factor has a non-zero covariance with at least one other factor in population. (Otherwise, the factor in question falls out of the system, and a two-item single factor model is not identified.) The proof of identification is rather technical, and requires good understanding of matrix algebra. Bollen (1989) fully and thoroughly discusses the issues of identification of CFA models in chapter 7. See p. 244 specifically regarding three- and two-indicator rules.
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis?
Two or three items per factor is a question of identification of your CFA (confirmatory FA) model. Let us for simplicity assume that the model is identified by setting the variance of each factor to 1
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis? Two or three items per factor is a question of identification of your CFA (confirmatory FA) model. Let us for simplicity assume that the model is identified by setting the variance of each factor to 1. Assume also that there are no correlated measurement errors. A single factor model with two items has two loadings and two error variances to be estimated = 4 parameters, but there are only 3 non-trivial entries in the variance-covariance matrix, so you don't have enough information to estimate the four parameters that you need. A single factor model with three items has three loadings and three error variances. The variance-covariance matrix has six entries, and careful analytic examination shows that the model is exactly identified, and you can algebraically express the parameter estimates as functions of the variance-covariance matrix entries. With more items per single factor, you have an overidentified model (more degrees of freedom than parameters), which usually means you are good to go. With more that one factor, the CFA model is always identified with 3+ items per each factor (because a simple measurement model is identified for each factor, so roughly speaking you can get predictions for each factor and estimate their covariances based on that). However, a CFA with two items per factor is identified provided that each factor has a non-zero covariance with at least one other factor in population. (Otherwise, the factor in question falls out of the system, and a two-item single factor model is not identified.) The proof of identification is rather technical, and requires good understanding of matrix algebra. Bollen (1989) fully and thoroughly discusses the issues of identification of CFA models in chapter 7. See p. 244 specifically regarding three- and two-indicator rules.
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis? Two or three items per factor is a question of identification of your CFA (confirmatory FA) model. Let us for simplicity assume that the model is identified by setting the variance of each factor to 1
25,197
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis?
I never heard about the "3 items per factor" criterium. I would reverse the question and ask your professor to come up with a sound reference for this statement. Besides that, "for purposes of the research, I need to develop 6 factors." is a weird thing to say. The basic purpose of factor analysis is 1) find out how many factors (often psychological traits) underlie a (larger) number of measured variables. Then 2), based on the factor loadings, one tries to describe what these factors really are. You don't "develop" 6 factors, you're "trying to measure" 6 factors. However, cross loadings (variables loaded by several factors) present are often an indication that the factors are "trying to correlate" with each other. Which makes sense since we know that basically everything correlates with everything in the real world. Implementing this observation in your analysis by using an oblique (instead of the orthogonal varimax) rotation often gets rid of many cross loadings. IMHO, it is more sound theoretically too. Give that a shot, you may end up with more items per factor. That may (partly) solve your problem too.
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis?
I never heard about the "3 items per factor" criterium. I would reverse the question and ask your professor to come up with a sound reference for this statement. Besides that, "for purposes of the res
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis? I never heard about the "3 items per factor" criterium. I would reverse the question and ask your professor to come up with a sound reference for this statement. Besides that, "for purposes of the research, I need to develop 6 factors." is a weird thing to say. The basic purpose of factor analysis is 1) find out how many factors (often psychological traits) underlie a (larger) number of measured variables. Then 2), based on the factor loadings, one tries to describe what these factors really are. You don't "develop" 6 factors, you're "trying to measure" 6 factors. However, cross loadings (variables loaded by several factors) present are often an indication that the factors are "trying to correlate" with each other. Which makes sense since we know that basically everything correlates with everything in the real world. Implementing this observation in your analysis by using an oblique (instead of the orthogonal varimax) rotation often gets rid of many cross loadings. IMHO, it is more sound theoretically too. Give that a shot, you may end up with more items per factor. That may (partly) solve your problem too.
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis? I never heard about the "3 items per factor" criterium. I would reverse the question and ask your professor to come up with a sound reference for this statement. Besides that, "for purposes of the res
25,198
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis?
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 have the same problem now. Here is an article which recommends to use at least 3 items per factor. In exceptional cases, however, you might use to items per factor (p.60). http://www.sajip.co.za/index.php/sajip/article/download/168/165 My case seems to be exceptional, since there are only two variables in my web-based experiment, that provide information on player's strategy and strategy power. May be it could help you too to legitimize the use of 2 items for some factors.
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis?
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.
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis? 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 have the same problem now. Here is an article which recommends to use at least 3 items per factor. In exceptional cases, however, you might use to items per factor (p.60). http://www.sajip.co.za/index.php/sajip/article/download/168/165 My case seems to be exceptional, since there are only two variables in my web-based experiment, that provide information on player's strategy and strategy power. May be it could help you too to legitimize the use of 2 items for some factors.
Is it acceptable to have only two (or less) items (variables) loaded by a factor in factor analysis? 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.
25,199
Logistic regression for multiclass
Your formula is wrong (the upper limit of the sum). In logistic regression with $K$ classes ($K> 2$) you basically create $K-1$ binary logistic regression models where you choose one class as reference or pivot. Usually, the last class $K$ is selected as the reference. Thus, the probability of the reference class can be calculated by $$P(y_i = K | x_i) = 1 - \sum_{k=1}^{K-1} P(y_i = k | x_i) .$$ The general form of the probability is $$P(y_i = k | x_i) = \frac{\exp(\theta_i^T x_i)}{\sum_{i=1}^K \exp(\theta_i^T x_i)} .$$ As the $K$-th class is your reference $\theta_K = (0, \ldots, 0)^T$ and therefore $$\sum_{i=1}^K \exp(\theta_i^T x_i) = \exp(0) + \sum_{i=1}^{K-1} \exp(\theta_i^T x_i) = 1 + \sum_{i=1}^{K-1} \exp(\theta_i^T x_i) .$$ In the end you get the following formula for all $k < K$: $$ P(y_i = k | x_i) = \frac{\exp(\theta_i^T x_i)}{1 + \sum_{i=1}^{K-1} \exp(\theta_i^T x_i)} $$
Logistic regression for multiclass
Your formula is wrong (the upper limit of the sum). In logistic regression with $K$ classes ($K> 2$) you basically create $K-1$ binary logistic regression models where you choose one class as referenc
Logistic regression for multiclass Your formula is wrong (the upper limit of the sum). In logistic regression with $K$ classes ($K> 2$) you basically create $K-1$ binary logistic regression models where you choose one class as reference or pivot. Usually, the last class $K$ is selected as the reference. Thus, the probability of the reference class can be calculated by $$P(y_i = K | x_i) = 1 - \sum_{k=1}^{K-1} P(y_i = k | x_i) .$$ The general form of the probability is $$P(y_i = k | x_i) = \frac{\exp(\theta_i^T x_i)}{\sum_{i=1}^K \exp(\theta_i^T x_i)} .$$ As the $K$-th class is your reference $\theta_K = (0, \ldots, 0)^T$ and therefore $$\sum_{i=1}^K \exp(\theta_i^T x_i) = \exp(0) + \sum_{i=1}^{K-1} \exp(\theta_i^T x_i) = 1 + \sum_{i=1}^{K-1} \exp(\theta_i^T x_i) .$$ In the end you get the following formula for all $k < K$: $$ P(y_i = k | x_i) = \frac{\exp(\theta_i^T x_i)}{1 + \sum_{i=1}^{K-1} \exp(\theta_i^T x_i)} $$
Logistic regression for multiclass Your formula is wrong (the upper limit of the sum). In logistic regression with $K$ classes ($K> 2$) you basically create $K-1$ binary logistic regression models where you choose one class as referenc
25,200
Logistic regression for multiclass
I think you're being confused by a typo: Your $k$ should be $k-1$ in the first equation. The 1's you see in the logistic case are actually $\exp(0)$s, e.g., when there is a $k$th $\theta=0$. Assume that $\theta_1 X=b$. Now notice that you can get from the last formulation to the logistic regression version like $$ \frac{\exp(b)}{\exp(0)+\exp(b)} = \frac{\exp(0)}{\exp(0)+\exp(-b)} = \frac{1}{1+\exp(-b)} $$ For multiple classes, just replace the denominator in the first two quantities by a sum over exponentiated linear predictors.
Logistic regression for multiclass
I think you're being confused by a typo: Your $k$ should be $k-1$ in the first equation. The 1's you see in the logistic case are actually $\exp(0)$s, e.g., when there is a $k$th $\theta=0$. Assum
Logistic regression for multiclass I think you're being confused by a typo: Your $k$ should be $k-1$ in the first equation. The 1's you see in the logistic case are actually $\exp(0)$s, e.g., when there is a $k$th $\theta=0$. Assume that $\theta_1 X=b$. Now notice that you can get from the last formulation to the logistic regression version like $$ \frac{\exp(b)}{\exp(0)+\exp(b)} = \frac{\exp(0)}{\exp(0)+\exp(-b)} = \frac{1}{1+\exp(-b)} $$ For multiple classes, just replace the denominator in the first two quantities by a sum over exponentiated linear predictors.
Logistic regression for multiclass I think you're being confused by a typo: Your $k$ should be $k-1$ in the first equation. The 1's you see in the logistic case are actually $\exp(0)$s, e.g., when there is a $k$th $\theta=0$. Assum