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 |
|---|---|---|---|---|---|---|
35,101 | Shapes of ROC curves for different classifiers ('steppy' for SVM and smooth for k-NN) | Diagonal lines occur in ROC curves when you have ties, that is when you have one or more observation with the exact same test value in both the positive and negative groups.
SVM classifiers output continuous probabilities. The chance to get a tie is normally very low. This is why you get a "steppy" curve.
On the other hand, due to the limited number of observations that make a k-NN decision, the output probabilities are typically not continuous. For instance if you considered a k-NN classifier with k = 3, probabilities can only be 1.0, 0.67, 0.33, 0. It is very likely that you observe these values in both groups, hence the tie and the diagonal line. | Shapes of ROC curves for different classifiers ('steppy' for SVM and smooth for k-NN) | Diagonal lines occur in ROC curves when you have ties, that is when you have one or more observation with the exact same test value in both the positive and negative groups.
SVM classifiers output co | Shapes of ROC curves for different classifiers ('steppy' for SVM and smooth for k-NN)
Diagonal lines occur in ROC curves when you have ties, that is when you have one or more observation with the exact same test value in both the positive and negative groups.
SVM classifiers output continuous probabilities. The chance to get a tie is normally very low. This is why you get a "steppy" curve.
On the other hand, due to the limited number of observations that make a k-NN decision, the output probabilities are typically not continuous. For instance if you considered a k-NN classifier with k = 3, probabilities can only be 1.0, 0.67, 0.33, 0. It is very likely that you observe these values in both groups, hence the tie and the diagonal line. | Shapes of ROC curves for different classifiers ('steppy' for SVM and smooth for k-NN)
Diagonal lines occur in ROC curves when you have ties, that is when you have one or more observation with the exact same test value in both the positive and negative groups.
SVM classifiers output co |
35,102 | What's the difference between binary and binomial data? | Possibly what is meant is that binary data consists only of 0's and 1's for "failures" and "successes" (notice that what you consider as a "success" is arbitrary) and follows a Bernoulli distribution. Binomial data is data that emerged after observing $n$ Bernoulli trials, i.e. it is a sum of Bernoulli random variables and it consists of non-negative integers, it follows a binomial distribution. I say "possibly" because this should be defined in your textbook and it is the only reference that tells you what the author meant. | What's the difference between binary and binomial data? | Possibly what is meant is that binary data consists only of 0's and 1's for "failures" and "successes" (notice that what you consider as a "success" is arbitrary) and follows a Bernoulli distribution. | What's the difference between binary and binomial data?
Possibly what is meant is that binary data consists only of 0's and 1's for "failures" and "successes" (notice that what you consider as a "success" is arbitrary) and follows a Bernoulli distribution. Binomial data is data that emerged after observing $n$ Bernoulli trials, i.e. it is a sum of Bernoulli random variables and it consists of non-negative integers, it follows a binomial distribution. I say "possibly" because this should be defined in your textbook and it is the only reference that tells you what the author meant. | What's the difference between binary and binomial data?
Possibly what is meant is that binary data consists only of 0's and 1's for "failures" and "successes" (notice that what you consider as a "success" is arbitrary) and follows a Bernoulli distribution. |
35,103 | Why are Type-II errors in hypothesis testing considered to be errors? | It's because we are not doing what we are supposed to do when the alternative hypothesis is true. For example, we are not using the new medicine which is actually better than the existing one but we were unable to prove it. | Why are Type-II errors in hypothesis testing considered to be errors? | It's because we are not doing what we are supposed to do when the alternative hypothesis is true. For example, we are not using the new medicine which is actually better than the existing one but we w | Why are Type-II errors in hypothesis testing considered to be errors?
It's because we are not doing what we are supposed to do when the alternative hypothesis is true. For example, we are not using the new medicine which is actually better than the existing one but we were unable to prove it. | Why are Type-II errors in hypothesis testing considered to be errors?
It's because we are not doing what we are supposed to do when the alternative hypothesis is true. For example, we are not using the new medicine which is actually better than the existing one but we w |
35,104 | Why are Type-II errors in hypothesis testing considered to be errors? | How we want to use the word "error" is ultimately a semantic issue and reasonable people could disagree on whether, and in what sense, we should consider a false negative to be an error.
On the one hand, I think you are right that a non-significant result really just means that we do not have enough information to be confident that the null hypothesis is false, and that this does not logically imply that the null hypothesis is true (cf., Why do statisticians say a non-significant result means “you can't reject the null” as opposed to accepting the null hypothesis?). So, given the level of confidence that you required in your situation and the level of ambiguity in your data, you made the right decision in the sense of having correctly applied the rule you had decided upon.
On the other hand, if you put yourself in the position of someone who is planning a study. They want to know if the null is false. If it really is false, they want to walk away after the study is complete having rejected the null hypothesis. Instead, they would remain unclear about the issue and perhaps have to design and run another study. From this perspective, not rejecting a false null is definitely a suboptimal outcome. | Why are Type-II errors in hypothesis testing considered to be errors? | How we want to use the word "error" is ultimately a semantic issue and reasonable people could disagree on whether, and in what sense, we should consider a false negative to be an error.
On the one | Why are Type-II errors in hypothesis testing considered to be errors?
How we want to use the word "error" is ultimately a semantic issue and reasonable people could disagree on whether, and in what sense, we should consider a false negative to be an error.
On the one hand, I think you are right that a non-significant result really just means that we do not have enough information to be confident that the null hypothesis is false, and that this does not logically imply that the null hypothesis is true (cf., Why do statisticians say a non-significant result means “you can't reject the null” as opposed to accepting the null hypothesis?). So, given the level of confidence that you required in your situation and the level of ambiguity in your data, you made the right decision in the sense of having correctly applied the rule you had decided upon.
On the other hand, if you put yourself in the position of someone who is planning a study. They want to know if the null is false. If it really is false, they want to walk away after the study is complete having rejected the null hypothesis. Instead, they would remain unclear about the issue and perhaps have to design and run another study. From this perspective, not rejecting a false null is definitely a suboptimal outcome. | Why are Type-II errors in hypothesis testing considered to be errors?
How we want to use the word "error" is ultimately a semantic issue and reasonable people could disagree on whether, and in what sense, we should consider a false negative to be an error.
On the one |
35,105 | Why are Type-II errors in hypothesis testing considered to be errors? | The word 'failure' is close to 'error'.
To me the term error makes sense since you can calculate a probability for it to occur (provided you set a certain minimal effect size that would be desirable to detect). And you want to calculate this probability in situations where you want it to be small. In those situations the failure would be considered an error.
To me it is very symmetric with type I errors.
Like p-values, which relate to type I error, you can also calculate the probability for (falsely) not rejecting the null-hypothesis. For a given effect size and a given test (e.g. number of measurements) you can calculate with what probability this 'failure' might occur.
These thoughts do require that you set a boundary for the null hypothesis.
The tendency not to consider type II errors, or at least providing the bounds of the effect size that could have been detected with sufficient probability, is large in a scientific world that is obsessed by p-values, significance, and hypothesis testing (the inverse happens as well by putting large emphasis on minor effects that happened to be significant, only by a huge number of measurements). If $p$ is larger than some $\alpha$ then the effect is said/considered not to be present (or more elegantly not shown to be present). In any way it certainly influences our future actions as if we accept the $H_0$. | Why are Type-II errors in hypothesis testing considered to be errors? | The word 'failure' is close to 'error'.
To me the term error makes sense since you can calculate a probability for it to occur (provided you set a certain minimal effect size that would be desirable | Why are Type-II errors in hypothesis testing considered to be errors?
The word 'failure' is close to 'error'.
To me the term error makes sense since you can calculate a probability for it to occur (provided you set a certain minimal effect size that would be desirable to detect). And you want to calculate this probability in situations where you want it to be small. In those situations the failure would be considered an error.
To me it is very symmetric with type I errors.
Like p-values, which relate to type I error, you can also calculate the probability for (falsely) not rejecting the null-hypothesis. For a given effect size and a given test (e.g. number of measurements) you can calculate with what probability this 'failure' might occur.
These thoughts do require that you set a boundary for the null hypothesis.
The tendency not to consider type II errors, or at least providing the bounds of the effect size that could have been detected with sufficient probability, is large in a scientific world that is obsessed by p-values, significance, and hypothesis testing (the inverse happens as well by putting large emphasis on minor effects that happened to be significant, only by a huge number of measurements). If $p$ is larger than some $\alpha$ then the effect is said/considered not to be present (or more elegantly not shown to be present). In any way it certainly influences our future actions as if we accept the $H_0$. | Why are Type-II errors in hypothesis testing considered to be errors?
The word 'failure' is close to 'error'.
To me the term error makes sense since you can calculate a probability for it to occur (provided you set a certain minimal effect size that would be desirable |
35,106 | Is it possible to simulate logistic regression without randomness? | Logistic regression does not have an "error" term as with classical linear regression. The exception to this might be thresholded linear regression with a logistic error term, but this isn't a commonly accepted probability model which results in a logistic regression model. This is because logistic models have a mean-variance relationship. The analogue to "adding an error term" to a linear regression model is actually a quasibinomial model in which the variance is merely proportional to p*(1-p).
A related question may be how to obtain regression model results which are identical over various designs or replications. This can be done with a "trick" in regression modeling software. You can generate non-integral $Y$ outcomes from the predicted risk which result in the same logistic regression results independent of the design of $X$. For instance: x1 <- seq(-3, 3, 0.1) and x2 <- rnorm(61) as two different designs. As in your case, y1 <- plogis(0.3*x1) and y2 <- plogis(0.3*x2) both result in the same logistic regression model results with 0.3 as the log odds ratio and 0.0 as the log odds for $x=0$.
> glm(y1 ~ x1, family=binomial)
Call: glm(formula = y1 ~ x1, family = binomial)
Coefficients:
(Intercept) x1
-2.528e-16 3.000e-01
This relates to your question because the parameter estimates are exactly as defined in your probability model, independent of the design of $x$, and without separation (e.g. log odds ratios, $\beta = \pm \infty$).
Modeling fractional results in a logistic model is an accepted way of analyzing ecological data, where the outcome may indeed be fractional. Not coincidentally, this is also a type of modeling when quasibinomial models are of the most use. Also not coincidentally, I think dispersion is proportional to a scale parameter for the logistic error term when doing "latent logistic regression". | Is it possible to simulate logistic regression without randomness? | Logistic regression does not have an "error" term as with classical linear regression. The exception to this might be thresholded linear regression with a logistic error term, but this isn't a commonl | Is it possible to simulate logistic regression without randomness?
Logistic regression does not have an "error" term as with classical linear regression. The exception to this might be thresholded linear regression with a logistic error term, but this isn't a commonly accepted probability model which results in a logistic regression model. This is because logistic models have a mean-variance relationship. The analogue to "adding an error term" to a linear regression model is actually a quasibinomial model in which the variance is merely proportional to p*(1-p).
A related question may be how to obtain regression model results which are identical over various designs or replications. This can be done with a "trick" in regression modeling software. You can generate non-integral $Y$ outcomes from the predicted risk which result in the same logistic regression results independent of the design of $X$. For instance: x1 <- seq(-3, 3, 0.1) and x2 <- rnorm(61) as two different designs. As in your case, y1 <- plogis(0.3*x1) and y2 <- plogis(0.3*x2) both result in the same logistic regression model results with 0.3 as the log odds ratio and 0.0 as the log odds for $x=0$.
> glm(y1 ~ x1, family=binomial)
Call: glm(formula = y1 ~ x1, family = binomial)
Coefficients:
(Intercept) x1
-2.528e-16 3.000e-01
This relates to your question because the parameter estimates are exactly as defined in your probability model, independent of the design of $x$, and without separation (e.g. log odds ratios, $\beta = \pm \infty$).
Modeling fractional results in a logistic model is an accepted way of analyzing ecological data, where the outcome may indeed be fractional. Not coincidentally, this is also a type of modeling when quasibinomial models are of the most use. Also not coincidentally, I think dispersion is proportional to a scale parameter for the logistic error term when doing "latent logistic regression". | Is it possible to simulate logistic regression without randomness?
Logistic regression does not have an "error" term as with classical linear regression. The exception to this might be thresholded linear regression with a logistic error term, but this isn't a commonl |
35,107 | Is it possible to simulate logistic regression without randomness? | I always like to think of logistic regression as what happens if you apply a binary decision to a linear model. That is, let's assume there is some underlying relationship that follows the linear model:
$$
y = X\beta+\varepsilon
$$
where $X$ is your independent variable and $\beta$ the coefficient (or slope) on that variable, and $\varepsilon$ is random noise. And then let's say we apply a function to the continuous variable $y$ that maps it onto a binary outcome:
$$
f(y) = \left\{\begin{matrix}0, ~\operatorname{if}~ y \operatorname{\leqslant \theta}
\\1, ~\operatorname{if}~ y \operatorname{>\theta}
\end{matrix}\right.
$$
where $\theta$ is a threshold. What is the probability that this function returns $1$, given a certain value of $X$? If we assume that $\varepsilon$ is Normally distributed with mean $0$ and variance $\sigma^2$, then we can calculate this probability as:
$$
p(f(y)=1|X)=p(y>\theta|X)=\int_\theta^\infty N\left(y; X\beta, \sigma^2 \right)dy
$$
In other words, this is computing the area under the Normal distribution that is to the right of the threshold. Note that this probability is essentially what a logistic regression model tries to describe. And indeed, if you plot this probability as a function of $X$, you get something pretty close in shape to the logistic function (in fact the logistic function is often used as a convenient approximation to the cumulative Normal distribution).
For values of $X\beta$ near the threshold, the probability that $y$ will be above threshold is near $0.5$, because the noise $\varepsilon$ can sway the outcome either way. As you increase $X$, $X\beta$ will get further away from $\theta$ and $f(y)=1$ becomes more likely. Crucially, how quickly $p(f(y)=1|X)$ increases with $X$ depends on two things: the slope $\beta$ and the noise variance $\sigma^2$. More precisely, it depends on the ratio $\frac{\beta}{\sigma}$. It is this (signal-to-noise) ratio which determines the (expected) coefficient you get from a logistic regression. In other words, you can think of the coefficients in a logistic regression as controlling how much each independent variable needs to change relative to the noise in the data in order to increase the probability of a certain outcome by some amount.
Now to come to your question: you're asking if it is possible to eliminate all randomness, i.e. to have no noise. This would mean that $\sigma$ equals $0$, and therefore $\frac{\beta}{\sigma}$ would be undefined (or "infinite"). This explains what you found, that you cannot estimate the coefficients when there is no noise. Indeed, you can think of the perfect separation you achieve without noise as corresponding to an infinite coefficient on your independent variable, since (for $X\beta$ near the threshold $\theta$) you only need to change $X$ an infinitesimal amount in order to go all the way from $p(y>\theta|X)=0$ to $p(y>\theta|X)=1$.
Edit: actually one thing you could do is instead of drawing samples from a binomial distribution to simulate your data, replace these samples by their expectation, i.e. the probability predicted by the simulated logistic function. That way, you're removing the randomness that derives from simulating a limited sample (i.e. the sampling variability), and thus your coefficient estimates should then equal the ground truth (since there is one logistic function that exactly fits these values). | Is it possible to simulate logistic regression without randomness? | I always like to think of logistic regression as what happens if you apply a binary decision to a linear model. That is, let's assume there is some underlying relationship that follows the linear mode | Is it possible to simulate logistic regression without randomness?
I always like to think of logistic regression as what happens if you apply a binary decision to a linear model. That is, let's assume there is some underlying relationship that follows the linear model:
$$
y = X\beta+\varepsilon
$$
where $X$ is your independent variable and $\beta$ the coefficient (or slope) on that variable, and $\varepsilon$ is random noise. And then let's say we apply a function to the continuous variable $y$ that maps it onto a binary outcome:
$$
f(y) = \left\{\begin{matrix}0, ~\operatorname{if}~ y \operatorname{\leqslant \theta}
\\1, ~\operatorname{if}~ y \operatorname{>\theta}
\end{matrix}\right.
$$
where $\theta$ is a threshold. What is the probability that this function returns $1$, given a certain value of $X$? If we assume that $\varepsilon$ is Normally distributed with mean $0$ and variance $\sigma^2$, then we can calculate this probability as:
$$
p(f(y)=1|X)=p(y>\theta|X)=\int_\theta^\infty N\left(y; X\beta, \sigma^2 \right)dy
$$
In other words, this is computing the area under the Normal distribution that is to the right of the threshold. Note that this probability is essentially what a logistic regression model tries to describe. And indeed, if you plot this probability as a function of $X$, you get something pretty close in shape to the logistic function (in fact the logistic function is often used as a convenient approximation to the cumulative Normal distribution).
For values of $X\beta$ near the threshold, the probability that $y$ will be above threshold is near $0.5$, because the noise $\varepsilon$ can sway the outcome either way. As you increase $X$, $X\beta$ will get further away from $\theta$ and $f(y)=1$ becomes more likely. Crucially, how quickly $p(f(y)=1|X)$ increases with $X$ depends on two things: the slope $\beta$ and the noise variance $\sigma^2$. More precisely, it depends on the ratio $\frac{\beta}{\sigma}$. It is this (signal-to-noise) ratio which determines the (expected) coefficient you get from a logistic regression. In other words, you can think of the coefficients in a logistic regression as controlling how much each independent variable needs to change relative to the noise in the data in order to increase the probability of a certain outcome by some amount.
Now to come to your question: you're asking if it is possible to eliminate all randomness, i.e. to have no noise. This would mean that $\sigma$ equals $0$, and therefore $\frac{\beta}{\sigma}$ would be undefined (or "infinite"). This explains what you found, that you cannot estimate the coefficients when there is no noise. Indeed, you can think of the perfect separation you achieve without noise as corresponding to an infinite coefficient on your independent variable, since (for $X\beta$ near the threshold $\theta$) you only need to change $X$ an infinitesimal amount in order to go all the way from $p(y>\theta|X)=0$ to $p(y>\theta|X)=1$.
Edit: actually one thing you could do is instead of drawing samples from a binomial distribution to simulate your data, replace these samples by their expectation, i.e. the probability predicted by the simulated logistic function. That way, you're removing the randomness that derives from simulating a limited sample (i.e. the sampling variability), and thus your coefficient estimates should then equal the ground truth (since there is one logistic function that exactly fits these values). | Is it possible to simulate logistic regression without randomness?
I always like to think of logistic regression as what happens if you apply a binary decision to a linear model. That is, let's assume there is some underlying relationship that follows the linear mode |
35,108 | Why does reducing the learning rate quickly reduce the error | I think an intuitive answer goes along these lines:
Suppose you want to find a parameter that 'best explains' your data in only one dimension. 'Best explains' means to make an error function small (or a likelihood big, these are usually the same as error = -log(likelihood)). We forget for a moment that we want to talk about neural nets: our model is very simplistic: its just $f(x,\theta) = x + \theta$. $x$ is the input for the function and $\theta$ is the parameter of the model (in the case of NNs its the weights). We want to find the best parameter for explaining the single data point $(x,y) = (1,5)$. Also imagine that we do not use an L2-error but an L1-error, i.e. the error function is
$$l(\hat{y}, y) = |\hat{y} - y| = |x + \theta - y|$$
Of course, the absolute value is not differentiable at $0$ so we just define the differential of the absolute value at $0$ to be $0$ (if you are exactly at the minimal value of the function, then do not move at all). Otherwise the differential is $+1$ if $x + \theta < y$ and $-1$ if $x+\theta > y$. We start with some random $\theta$, for example, $\theta = -1.5$. Then $\hat{y} = x + \theta = 1 - 1.5 = -0.5$ so graphically, the error function looks like this:
Now the derivative is $+1$ so we move $\theta$ by $+1$ to the right which makes $\hat{y} = +0.5$:
After that the derivative is $-1$ which makes us set $\theta$ back to $-0.5$ and so on and so on. We always run around the minimal value but since we do not give any weight to our gradient, we circulate around it instead of finding our way inside. This is intuitively what could happens when you set your learning rate to be constantly $1$ instead of some lower value. Of course, in the real world we use an L2-error which already would take the distance to the minimal value into account and everything looks much more complicated... Also the reason is not that we are principally unable to find our way to the minimal value but rather that there are numerical instabilities which makes us over- or underestimate the 'perfect' gradient.
Question 2): The only explanation I can come up with is the following: Suppose we use a constant learning rate and the parameter search algorithm spirals around a local minimum for some time:
Sue to the fact that the learning rate stays constant it could happen that at some point the algorithm 'spiraled' into a suitable point so that in the next step it actually overshoots so much that it moves out of the complete region it was in all the time and 'accidentally' finds its way into a completely new valley and into the direction of another even lower local minimum that it can spiral around:
However, despite all of this I would not pay too much attention to question no. 2 in general: What the error graph does not tell you is that after so many epochs you are probably overfitting your data quite a lot, i.e. the best solution for your problem is mostly not the global minimum of the error function! Question no. 1 indeed is much more important. You will find realizations of the concept of an 'adaptive' learning rate in many different algorithms (for example in Gradient Boosting which is completely unrelated to NNs you have trees and you do not simply add the next tree but you add $\lambda*\text{next tree}$ where $0 < \lambda < 1$). | Why does reducing the learning rate quickly reduce the error | I think an intuitive answer goes along these lines:
Suppose you want to find a parameter that 'best explains' your data in only one dimension. 'Best explains' means to make an error function small (or | Why does reducing the learning rate quickly reduce the error
I think an intuitive answer goes along these lines:
Suppose you want to find a parameter that 'best explains' your data in only one dimension. 'Best explains' means to make an error function small (or a likelihood big, these are usually the same as error = -log(likelihood)). We forget for a moment that we want to talk about neural nets: our model is very simplistic: its just $f(x,\theta) = x + \theta$. $x$ is the input for the function and $\theta$ is the parameter of the model (in the case of NNs its the weights). We want to find the best parameter for explaining the single data point $(x,y) = (1,5)$. Also imagine that we do not use an L2-error but an L1-error, i.e. the error function is
$$l(\hat{y}, y) = |\hat{y} - y| = |x + \theta - y|$$
Of course, the absolute value is not differentiable at $0$ so we just define the differential of the absolute value at $0$ to be $0$ (if you are exactly at the minimal value of the function, then do not move at all). Otherwise the differential is $+1$ if $x + \theta < y$ and $-1$ if $x+\theta > y$. We start with some random $\theta$, for example, $\theta = -1.5$. Then $\hat{y} = x + \theta = 1 - 1.5 = -0.5$ so graphically, the error function looks like this:
Now the derivative is $+1$ so we move $\theta$ by $+1$ to the right which makes $\hat{y} = +0.5$:
After that the derivative is $-1$ which makes us set $\theta$ back to $-0.5$ and so on and so on. We always run around the minimal value but since we do not give any weight to our gradient, we circulate around it instead of finding our way inside. This is intuitively what could happens when you set your learning rate to be constantly $1$ instead of some lower value. Of course, in the real world we use an L2-error which already would take the distance to the minimal value into account and everything looks much more complicated... Also the reason is not that we are principally unable to find our way to the minimal value but rather that there are numerical instabilities which makes us over- or underestimate the 'perfect' gradient.
Question 2): The only explanation I can come up with is the following: Suppose we use a constant learning rate and the parameter search algorithm spirals around a local minimum for some time:
Sue to the fact that the learning rate stays constant it could happen that at some point the algorithm 'spiraled' into a suitable point so that in the next step it actually overshoots so much that it moves out of the complete region it was in all the time and 'accidentally' finds its way into a completely new valley and into the direction of another even lower local minimum that it can spiral around:
However, despite all of this I would not pay too much attention to question no. 2 in general: What the error graph does not tell you is that after so many epochs you are probably overfitting your data quite a lot, i.e. the best solution for your problem is mostly not the global minimum of the error function! Question no. 1 indeed is much more important. You will find realizations of the concept of an 'adaptive' learning rate in many different algorithms (for example in Gradient Boosting which is completely unrelated to NNs you have trees and you do not simply add the next tree but you add $\lambda*\text{next tree}$ where $0 < \lambda < 1$). | Why does reducing the learning rate quickly reduce the error
I think an intuitive answer goes along these lines:
Suppose you want to find a parameter that 'best explains' your data in only one dimension. 'Best explains' means to make an error function small (or |
35,109 | Does the Central Limit Theorem hold if you replace the true variance with the sample variance? | Yes it is a result of Slutsky's Theorem since $S_n \rightarrow_p \sigma$ | Does the Central Limit Theorem hold if you replace the true variance with the sample variance? | Yes it is a result of Slutsky's Theorem since $S_n \rightarrow_p \sigma$ | Does the Central Limit Theorem hold if you replace the true variance with the sample variance?
Yes it is a result of Slutsky's Theorem since $S_n \rightarrow_p \sigma$ | Does the Central Limit Theorem hold if you replace the true variance with the sample variance?
Yes it is a result of Slutsky's Theorem since $S_n \rightarrow_p \sigma$ |
35,110 | Does the Central Limit Theorem hold if you replace the true variance with the sample variance? | You appear to be interested in a quantity like
$$
\mathcal{T}=\frac{\sqrt T(\bar{y}-\mu)}{s},
$$
with $s$ the sample standard deviation of $y_t$, $t=1,\ldots,T$.
By the CLT, $\sqrt T(\bar{y}-\mu)\to_d \mathcal{N}(0,\sigma^2)$ when (e.g.) the $y_i$ are iid with mean $\mu$ and variance $\sigma^2$.
By the WLLN, $s^2\to_p\sigma^2$.
By the continuous mapping theorem, $s\to_p\sigma$.
By Slutzky's theorem, $\mathcal{T}\to_d \mathcal{N}(0,1)$. | Does the Central Limit Theorem hold if you replace the true variance with the sample variance? | You appear to be interested in a quantity like
$$
\mathcal{T}=\frac{\sqrt T(\bar{y}-\mu)}{s},
$$
with $s$ the sample standard deviation of $y_t$, $t=1,\ldots,T$.
By the CLT, $\sqrt T(\bar{y}-\mu)\to_ | Does the Central Limit Theorem hold if you replace the true variance with the sample variance?
You appear to be interested in a quantity like
$$
\mathcal{T}=\frac{\sqrt T(\bar{y}-\mu)}{s},
$$
with $s$ the sample standard deviation of $y_t$, $t=1,\ldots,T$.
By the CLT, $\sqrt T(\bar{y}-\mu)\to_d \mathcal{N}(0,\sigma^2)$ when (e.g.) the $y_i$ are iid with mean $\mu$ and variance $\sigma^2$.
By the WLLN, $s^2\to_p\sigma^2$.
By the continuous mapping theorem, $s\to_p\sigma$.
By Slutzky's theorem, $\mathcal{T}\to_d \mathcal{N}(0,1)$. | Does the Central Limit Theorem hold if you replace the true variance with the sample variance?
You appear to be interested in a quantity like
$$
\mathcal{T}=\frac{\sqrt T(\bar{y}-\mu)}{s},
$$
with $s$ the sample standard deviation of $y_t$, $t=1,\ldots,T$.
By the CLT, $\sqrt T(\bar{y}-\mu)\to_ |
35,111 | Interaction Terms (Categorical * Continuous) [duplicate] | Yes, it's possible. Suppose your categorical model has $k$ levels, you'll need $(k-1)$ binary indicators to represent them, and you'll need another $(k-1)$ interaction terms that interact with the continuous varaible to model the interaction correctly.
In essence, it's just a regression model that allow each level of the categorical variable to have its own slope and intercept (while when without interaction, each level can have their own intercept, but slopes are bound to be the same). Given the model:
$y = 50 + 100(Lv2) + 200(Lv3) + 2.5 x + 3.5(x\times Lv2) - 6.5(x \times Lv3)$
where $Lv2$ and $Lv3$ are binary dummy variables to represent attributes 2 and 3 of the categorical variable, respectively. Here, $k$ = 3 and we kept $Lv1$ as the reference group. It's easy to visualize them once we realized this is just a compact way to express three regression lines. If we substitute 1 and 0 into the regression model accordingly, we will find that the equations are:
for $Lv1$:
$y = 50 + 2.5 x$
for $Lv2$:
$y = (50 + 100) + (2.5+3.5) x$
for $Lv3$:
$y = (50 + 200) + (2.5-6.5) x$
If we plot the predicted y, $\hat{y}$, against the continuous variable and then assign different features by the categorical variable's levels, we'll get:
The red line is group 1, with slope 2.5 and intercept 50; the green line is group 2; the blue line is group 3.
There are more sophisticated ways (for example, it's possible to plot the 95%CI shading), this is just an overall gist.
R code I used:
set.seed(1520)
x <- rep(0:199, 3)
group <- as.factor(rep(1:3, rep(200,3)))
lv2 <- as.numeric(group==2)
lv3 <- as.numeric(group==3)
y <- 50 + 100 * lv2 + 200 * lv3 + 2.5 * x +
3.5 * (x * lv2) - 6.5 * (x * lv3) +
rnorm(600, 0, 15)
# Without interactions, lines will have to be parallel:
m01 <- lm(y ~ x + group)
summary(m01)
yhat <- m01$fit
plot(x, yhat, col=as.numeric(group)+1)
# With interactions, lines can have their own slope:
m02 <- lm(y ~ x + group + x:group)
summary(m02)
yhat <- m02$fit
plot(x, yhat, col=as.numeric(group)+1)
Just to clarify, what do you mean by 'Without interactions, lines will
have to be parallel?' Is that parallel vs reference group?
Correct, we can simulate the data again but this time we don't change the slopes for $Lv2$ and $Lv3$ (aka, we replace the slope adjustment 3.5 and -6.5 with 0):
set.seed(1520)
x <- rep(0:199, 3)
group <- as.factor(rep(1:3, rep(200,3)))
lv2 <- as.numeric(group==2)
lv3 <- as.numeric(group==3)
y <- 50 + 100 * lv2 + 200 * lv3 + 2.5 * x +
0 * (x * lv2) + 0 * (x * lv3) +
rnorm(600, 0, 15)
m03 <- lm(y ~ x + group + x:group)
summary(m03)
yhat <- m03$fit
plot(x, yhat, col=as.numeric(group)+1)
Here is the output:
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 4.980e+01 2.011e+00 24.761 <2e-16 ***
x 2.487e+00 1.748e-02 142.279 <2e-16 ***
group2 9.942e+01 2.844e+00 34.956 <2e-16 ***
group3 1.986e+02 2.844e+00 69.833 <2e-16 ***
x:group2 8.207e-03 2.472e-02 0.332 0.740
x:group3 1.398e-02 2.472e-02 0.566 0.572
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
And here is the predicted y:
As we can see, if we don't adjust the lines' slope, the interaction terms above (x:group2 and x:group3) will be close to 0, and because of that, the group predicted y will be close to parallel.
So in the graphical illustration you shown, no lines are parallel,
therefore there is no interaction?
No, the other way around. Interaction means that the association between an independent variable and the dependent actually depends on the value of another independent variable. In general case, a regression model like:
$$y = \beta_0 + \beta_1 x_1+ \beta_2 x_2$$
indicates that for one unit increase in $x_1$, mean $y$ differs by $\beta_1$ unit, regardless what value $x_2$ is. Applying to your situation, when there is no interaction, each unit increase in the continuous independent variable should be associated with the same amount of change in mean $y$, regardless of which group we are talking about. That scenario means that the lines have to be parallel.
When interaction exists, then each unit increase in the continuous independent variable will be associated with the amount of change in mean $y$ differently depends on which level of the categorical variable we're talking about. And that implies the lines are not parallel.
In the example I provided above, +3.5 adds an extra 3.5 to the slope 2.5 for $Lv2$ and -6.5 takes 6.5 away from the slope 2.5 for $Lv3$. If these two coefficients are different from zero, we have a significant interaction and the lines are not parallel; if they are close to zero, we don't have evidence of an interaction, and the lines are parallel.
Also how do I interpret the coefficients and p-value of the
interaction terms? Is it just the same as how coefficients and
p-values of categorical variables are interpreted?
First, to safeguard against multiple testing, we test if the whole set of interaction terms is significant or not using extra sum of squares F test:
m01 <- lm(y ~ x + group)
m02 <- lm(y ~ x + group + x:group)
anova(m01, m02)
If this test is significant, then at least one of the interaction terms in the model is significant. Then we can go on the look at each of their p-values and discuss where the difference might be coming from.
The coefficient (e.g. the 3.5 and -6.5 above in the model) are really just difference in slopes. So, given the reference group has a slope of 2.5, we can report that $Lv2$ has a significant increase in slope, which is 3.5, resulting in a final slope of 6.0. For the same reason the slope for $Lv3$ is (2.5 - 6.5) = -4.
To put this all into context, a unit increase in x is then associated with:
2.5 unit increase in mean $y$ in $Lv1$ of the categorical variable,
6.0 unit increase in mean $y$ in $Lv2$ of the categorical variable,
4.0 unit decrease in mean $y$ in $Lv3$ of the categorical variable. | Interaction Terms (Categorical * Continuous) [duplicate] | Yes, it's possible. Suppose your categorical model has $k$ levels, you'll need $(k-1)$ binary indicators to represent them, and you'll need another $(k-1)$ interaction terms that interact with the con | Interaction Terms (Categorical * Continuous) [duplicate]
Yes, it's possible. Suppose your categorical model has $k$ levels, you'll need $(k-1)$ binary indicators to represent them, and you'll need another $(k-1)$ interaction terms that interact with the continuous varaible to model the interaction correctly.
In essence, it's just a regression model that allow each level of the categorical variable to have its own slope and intercept (while when without interaction, each level can have their own intercept, but slopes are bound to be the same). Given the model:
$y = 50 + 100(Lv2) + 200(Lv3) + 2.5 x + 3.5(x\times Lv2) - 6.5(x \times Lv3)$
where $Lv2$ and $Lv3$ are binary dummy variables to represent attributes 2 and 3 of the categorical variable, respectively. Here, $k$ = 3 and we kept $Lv1$ as the reference group. It's easy to visualize them once we realized this is just a compact way to express three regression lines. If we substitute 1 and 0 into the regression model accordingly, we will find that the equations are:
for $Lv1$:
$y = 50 + 2.5 x$
for $Lv2$:
$y = (50 + 100) + (2.5+3.5) x$
for $Lv3$:
$y = (50 + 200) + (2.5-6.5) x$
If we plot the predicted y, $\hat{y}$, against the continuous variable and then assign different features by the categorical variable's levels, we'll get:
The red line is group 1, with slope 2.5 and intercept 50; the green line is group 2; the blue line is group 3.
There are more sophisticated ways (for example, it's possible to plot the 95%CI shading), this is just an overall gist.
R code I used:
set.seed(1520)
x <- rep(0:199, 3)
group <- as.factor(rep(1:3, rep(200,3)))
lv2 <- as.numeric(group==2)
lv3 <- as.numeric(group==3)
y <- 50 + 100 * lv2 + 200 * lv3 + 2.5 * x +
3.5 * (x * lv2) - 6.5 * (x * lv3) +
rnorm(600, 0, 15)
# Without interactions, lines will have to be parallel:
m01 <- lm(y ~ x + group)
summary(m01)
yhat <- m01$fit
plot(x, yhat, col=as.numeric(group)+1)
# With interactions, lines can have their own slope:
m02 <- lm(y ~ x + group + x:group)
summary(m02)
yhat <- m02$fit
plot(x, yhat, col=as.numeric(group)+1)
Just to clarify, what do you mean by 'Without interactions, lines will
have to be parallel?' Is that parallel vs reference group?
Correct, we can simulate the data again but this time we don't change the slopes for $Lv2$ and $Lv3$ (aka, we replace the slope adjustment 3.5 and -6.5 with 0):
set.seed(1520)
x <- rep(0:199, 3)
group <- as.factor(rep(1:3, rep(200,3)))
lv2 <- as.numeric(group==2)
lv3 <- as.numeric(group==3)
y <- 50 + 100 * lv2 + 200 * lv3 + 2.5 * x +
0 * (x * lv2) + 0 * (x * lv3) +
rnorm(600, 0, 15)
m03 <- lm(y ~ x + group + x:group)
summary(m03)
yhat <- m03$fit
plot(x, yhat, col=as.numeric(group)+1)
Here is the output:
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 4.980e+01 2.011e+00 24.761 <2e-16 ***
x 2.487e+00 1.748e-02 142.279 <2e-16 ***
group2 9.942e+01 2.844e+00 34.956 <2e-16 ***
group3 1.986e+02 2.844e+00 69.833 <2e-16 ***
x:group2 8.207e-03 2.472e-02 0.332 0.740
x:group3 1.398e-02 2.472e-02 0.566 0.572
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
And here is the predicted y:
As we can see, if we don't adjust the lines' slope, the interaction terms above (x:group2 and x:group3) will be close to 0, and because of that, the group predicted y will be close to parallel.
So in the graphical illustration you shown, no lines are parallel,
therefore there is no interaction?
No, the other way around. Interaction means that the association between an independent variable and the dependent actually depends on the value of another independent variable. In general case, a regression model like:
$$y = \beta_0 + \beta_1 x_1+ \beta_2 x_2$$
indicates that for one unit increase in $x_1$, mean $y$ differs by $\beta_1$ unit, regardless what value $x_2$ is. Applying to your situation, when there is no interaction, each unit increase in the continuous independent variable should be associated with the same amount of change in mean $y$, regardless of which group we are talking about. That scenario means that the lines have to be parallel.
When interaction exists, then each unit increase in the continuous independent variable will be associated with the amount of change in mean $y$ differently depends on which level of the categorical variable we're talking about. And that implies the lines are not parallel.
In the example I provided above, +3.5 adds an extra 3.5 to the slope 2.5 for $Lv2$ and -6.5 takes 6.5 away from the slope 2.5 for $Lv3$. If these two coefficients are different from zero, we have a significant interaction and the lines are not parallel; if they are close to zero, we don't have evidence of an interaction, and the lines are parallel.
Also how do I interpret the coefficients and p-value of the
interaction terms? Is it just the same as how coefficients and
p-values of categorical variables are interpreted?
First, to safeguard against multiple testing, we test if the whole set of interaction terms is significant or not using extra sum of squares F test:
m01 <- lm(y ~ x + group)
m02 <- lm(y ~ x + group + x:group)
anova(m01, m02)
If this test is significant, then at least one of the interaction terms in the model is significant. Then we can go on the look at each of their p-values and discuss where the difference might be coming from.
The coefficient (e.g. the 3.5 and -6.5 above in the model) are really just difference in slopes. So, given the reference group has a slope of 2.5, we can report that $Lv2$ has a significant increase in slope, which is 3.5, resulting in a final slope of 6.0. For the same reason the slope for $Lv3$ is (2.5 - 6.5) = -4.
To put this all into context, a unit increase in x is then associated with:
2.5 unit increase in mean $y$ in $Lv1$ of the categorical variable,
6.0 unit increase in mean $y$ in $Lv2$ of the categorical variable,
4.0 unit decrease in mean $y$ in $Lv3$ of the categorical variable. | Interaction Terms (Categorical * Continuous) [duplicate]
Yes, it's possible. Suppose your categorical model has $k$ levels, you'll need $(k-1)$ binary indicators to represent them, and you'll need another $(k-1)$ interaction terms that interact with the con |
35,112 | Interaction Terms (Categorical * Continuous) [duplicate] | I think you can do this. Say that you have k-1 categories then you can simply write the model as y = c + a$_0$ duration + a$_1$ category + a$_2$ duration(1) + a$_3$ duration(2) +...+ a$_k$ duration(k) where duration(i) is the duration for reason i and c is a constant/intercept term. If for a given y the duration corresponds to the ith reason then duration(i)=duration and all other duration(j)=0 for all j not equal to i. That means a$_i$ enters the equation only when the given y corresponds to reason i. | Interaction Terms (Categorical * Continuous) [duplicate] | I think you can do this. Say that you have k-1 categories then you can simply write the model as y = c + a$_0$ duration + a$_1$ category + a$_2$ duration(1) + a$_3$ duration(2) +...+ a$_k$ duration(k | Interaction Terms (Categorical * Continuous) [duplicate]
I think you can do this. Say that you have k-1 categories then you can simply write the model as y = c + a$_0$ duration + a$_1$ category + a$_2$ duration(1) + a$_3$ duration(2) +...+ a$_k$ duration(k) where duration(i) is the duration for reason i and c is a constant/intercept term. If for a given y the duration corresponds to the ith reason then duration(i)=duration and all other duration(j)=0 for all j not equal to i. That means a$_i$ enters the equation only when the given y corresponds to reason i. | Interaction Terms (Categorical * Continuous) [duplicate]
I think you can do this. Say that you have k-1 categories then you can simply write the model as y = c + a$_0$ duration + a$_1$ category + a$_2$ duration(1) + a$_3$ duration(2) +...+ a$_k$ duration(k |
35,113 | Does this NYT article incorrectly assume independent increments? | Sorry, I cannot agree with the independence assumption. Fertility in women, even without contraception is a function of age, such that, without contraception the
Chances of getting pregnant without IVF (in vitro fertilization)
Starting at about age 32, a woman’s chances of conceiving decrease gradually but significantly.
From age 35, the fertility decline speeds up.
By age 40, fertility has fallen by half.
At 30, the chance of conceiving each month is about 20%. At 40 it’s around 5%.
Note (mine) after age ~49 menopause occurs and when it does, women are infertile.
The rate of pregnancy is also a function of frequency of intercourse, which also changes with age:
About 5% of single women between the ages of 18 and 24 had sex 4 or more times per week, but 24% of married women did.
Like the men, just under half of the women between the ages of 25 and 59 had sex a few times per month to weekly, more than their single and partnered peers.
Sexual frequency did decrease with age for women, although almost a quarter of partnered women over age 70 had sex more than 4 times a week.
Relative time of ovulation, intercourse, and female age:
Finally, to consider the effectiveness of contraception on an annualized basis, one must consider not only decreasing fertility and variable but generally somewhat decreasing sexual frequency with age, but likely also myriad other factors. For example, the percentage of women who are postpartum increases with age, and postpartal women may have a different contraceptive usage effectiveness than the nulliparous, age of the partner at time of intercourse relative to ovulation, see image:
timing of intercourse relative to ovulation, having a huge impact on fertility, also reflects on the likelihood of pregnancy even when other factors, like contraception is considered. Thus, a woman who relies on the rhythm method, as well as one or more other methods of contraception, i.e., a woman who both knows her body functions, and uses that knowledge (and as knowledge is acquired) may eventually do an increasingly effective job of avoiding pregnancy, such that there is essentially no chance for independence of fertility with elapsed age. | Does this NYT article incorrectly assume independent increments? | Sorry, I cannot agree with the independence assumption. Fertility in women, even without contraception is a function of age, such that, without contraception the
Chances of getting pregnant without IV | Does this NYT article incorrectly assume independent increments?
Sorry, I cannot agree with the independence assumption. Fertility in women, even without contraception is a function of age, such that, without contraception the
Chances of getting pregnant without IVF (in vitro fertilization)
Starting at about age 32, a woman’s chances of conceiving decrease gradually but significantly.
From age 35, the fertility decline speeds up.
By age 40, fertility has fallen by half.
At 30, the chance of conceiving each month is about 20%. At 40 it’s around 5%.
Note (mine) after age ~49 menopause occurs and when it does, women are infertile.
The rate of pregnancy is also a function of frequency of intercourse, which also changes with age:
About 5% of single women between the ages of 18 and 24 had sex 4 or more times per week, but 24% of married women did.
Like the men, just under half of the women between the ages of 25 and 59 had sex a few times per month to weekly, more than their single and partnered peers.
Sexual frequency did decrease with age for women, although almost a quarter of partnered women over age 70 had sex more than 4 times a week.
Relative time of ovulation, intercourse, and female age:
Finally, to consider the effectiveness of contraception on an annualized basis, one must consider not only decreasing fertility and variable but generally somewhat decreasing sexual frequency with age, but likely also myriad other factors. For example, the percentage of women who are postpartum increases with age, and postpartal women may have a different contraceptive usage effectiveness than the nulliparous, age of the partner at time of intercourse relative to ovulation, see image:
timing of intercourse relative to ovulation, having a huge impact on fertility, also reflects on the likelihood of pregnancy even when other factors, like contraception is considered. Thus, a woman who relies on the rhythm method, as well as one or more other methods of contraception, i.e., a woman who both knows her body functions, and uses that knowledge (and as knowledge is acquired) may eventually do an increasingly effective job of avoiding pregnancy, such that there is essentially no chance for independence of fertility with elapsed age. | Does this NYT article incorrectly assume independent increments?
Sorry, I cannot agree with the independence assumption. Fertility in women, even without contraception is a function of age, such that, without contraception the
Chances of getting pregnant without IV |
35,114 | Does this NYT article incorrectly assume independent increments? | Here is an account of the probabilities relevant to the problem at hand.
Denote by $z_n$ the event 'no pregnancy after $n$ years' for a woman using some type of contraception. Then
$$
P(z_N) = P(z_N | z_{N-1}) P(z_{N-1} | z_{N-2})\cdots P(z_2 | z_1)P(z_1).
$$
The problem is that the NYT asumes $P(z_i | z_{i-1}) = P(z_1) = p$, for all $i$, while knowing $z_{i-1}$ may provide evidence that the woman makes good use of the contraception method and may be experienced with it. We should therefore expect that
$$
P(z_N | z_{N-1}) > P(z_{N-1} | z_{N-2}) > \cdots > P(z_1).
$$
This implies
$$
P(\text{'at least 1 pregnancy after $N$ years'}) < 1-p^n
$$
rather than the equality claimed by the NYT.
Addendum. (Alternative presentation of user385948's answer)
Every woman $w$ using a particular type of contraceptive, among $M$ other woman, has her own fixed probability $q_w$ of not getting an unwanted pregnancy in a year. The average success rate of the contraceptive over one year is $ p =\tfrac{1}{M}\sum_w q_w$. The average success rate after $N$ years, assuming year-to-year independence, is $\tfrac{1}{M}\sum_w q_w^N$. However,
$$
\tfrac{1}{M}\sum_w q_w^N \geq \left(\tfrac{1}{M}\sum_w q_w\right)^N = p^N,
$$
by Jensen's inequality, with equality if and only if $q_w$ is constant over $w$.
Therefore, in average, generally stricly less than $(1-p^{10})\times 100$ woman in a hundred will have an unwanted pregnancy over a period of 10 years. | Does this NYT article incorrectly assume independent increments? | Here is an account of the probabilities relevant to the problem at hand.
Denote by $z_n$ the event 'no pregnancy after $n$ years' for a woman using some type of contraception. Then
$$
P(z_N) = P(z_N | | Does this NYT article incorrectly assume independent increments?
Here is an account of the probabilities relevant to the problem at hand.
Denote by $z_n$ the event 'no pregnancy after $n$ years' for a woman using some type of contraception. Then
$$
P(z_N) = P(z_N | z_{N-1}) P(z_{N-1} | z_{N-2})\cdots P(z_2 | z_1)P(z_1).
$$
The problem is that the NYT asumes $P(z_i | z_{i-1}) = P(z_1) = p$, for all $i$, while knowing $z_{i-1}$ may provide evidence that the woman makes good use of the contraception method and may be experienced with it. We should therefore expect that
$$
P(z_N | z_{N-1}) > P(z_{N-1} | z_{N-2}) > \cdots > P(z_1).
$$
This implies
$$
P(\text{'at least 1 pregnancy after $N$ years'}) < 1-p^n
$$
rather than the equality claimed by the NYT.
Addendum. (Alternative presentation of user385948's answer)
Every woman $w$ using a particular type of contraceptive, among $M$ other woman, has her own fixed probability $q_w$ of not getting an unwanted pregnancy in a year. The average success rate of the contraceptive over one year is $ p =\tfrac{1}{M}\sum_w q_w$. The average success rate after $N$ years, assuming year-to-year independence, is $\tfrac{1}{M}\sum_w q_w^N$. However,
$$
\tfrac{1}{M}\sum_w q_w^N \geq \left(\tfrac{1}{M}\sum_w q_w\right)^N = p^N,
$$
by Jensen's inequality, with equality if and only if $q_w$ is constant over $w$.
Therefore, in average, generally stricly less than $(1-p^{10})\times 100$ woman in a hundred will have an unwanted pregnancy over a period of 10 years. | Does this NYT article incorrectly assume independent increments?
Here is an account of the probabilities relevant to the problem at hand.
Denote by $z_n$ the event 'no pregnancy after $n$ years' for a woman using some type of contraception. Then
$$
P(z_N) = P(z_N | |
35,115 | Does this NYT article incorrectly assume independent increments? | From a probabilist perspective I would expect that
$$ \mathbb P(\text{Not pregnant after year N}) \geq \mathbb P(\text{Not pregnant after year 1})^N.$$
This expectation is motivated as follows. Assume that at time $t=0$, every woman is assigned a (potentially different) number $p\in[0,1]$, the probability that she will get pregnant in the first year. If she did not get pregnant after $k$ years, then the probability that she gets pregnant in the $k+1$-th year is again $p$. Then $1-\mathbb{E}p$ is exactly
$$\mathbb P(\text{Not pregnant after year 1}).$$
We want to prove that
$$\mathbb P(\text{Not pregnant after year 1})^N$$
is a lower bound for
$$\mathbb P(\text{Not pregnant after year N}).$$
But, given the number of women and
$$1-\mathbb{E}p=\mathbb P(\text{Not pregnant after year 1}),$$
we can optimise the values for $p$ of the individual women to minimise
$$\mathbb P(\text{Not pregnant after year N}).$$
There is one global minimum, it is "assign $p' =\mathbb{E} p$ to any woman" (so $p'$ is deterministic), and for this minimum we have equality (because indeed everything is independent).
The inequality then follows.
To illustrate this with an example, suppose that we have two women,
having $p=0$ and $p=1$.
Then
$$\frac{1}{2}=\mathbb P(\text{Not pregnant after year N})>\mathbb P(\text{Not pregnant after year 1})^N =\frac{1}{2^N}$$
for $N>1$. | Does this NYT article incorrectly assume independent increments? | From a probabilist perspective I would expect that
$$ \mathbb P(\text{Not pregnant after year N}) \geq \mathbb P(\text{Not pregnant after year 1})^N.$$
This expectation is motivated as follows. Assume | Does this NYT article incorrectly assume independent increments?
From a probabilist perspective I would expect that
$$ \mathbb P(\text{Not pregnant after year N}) \geq \mathbb P(\text{Not pregnant after year 1})^N.$$
This expectation is motivated as follows. Assume that at time $t=0$, every woman is assigned a (potentially different) number $p\in[0,1]$, the probability that she will get pregnant in the first year. If she did not get pregnant after $k$ years, then the probability that she gets pregnant in the $k+1$-th year is again $p$. Then $1-\mathbb{E}p$ is exactly
$$\mathbb P(\text{Not pregnant after year 1}).$$
We want to prove that
$$\mathbb P(\text{Not pregnant after year 1})^N$$
is a lower bound for
$$\mathbb P(\text{Not pregnant after year N}).$$
But, given the number of women and
$$1-\mathbb{E}p=\mathbb P(\text{Not pregnant after year 1}),$$
we can optimise the values for $p$ of the individual women to minimise
$$\mathbb P(\text{Not pregnant after year N}).$$
There is one global minimum, it is "assign $p' =\mathbb{E} p$ to any woman" (so $p'$ is deterministic), and for this minimum we have equality (because indeed everything is independent).
The inequality then follows.
To illustrate this with an example, suppose that we have two women,
having $p=0$ and $p=1$.
Then
$$\frac{1}{2}=\mathbb P(\text{Not pregnant after year N})>\mathbb P(\text{Not pregnant after year 1})^N =\frac{1}{2^N}$$
for $N>1$. | Does this NYT article incorrectly assume independent increments?
From a probabilist perspective I would expect that
$$ \mathbb P(\text{Not pregnant after year N}) \geq \mathbb P(\text{Not pregnant after year 1})^N.$$
This expectation is motivated as follows. Assume |
35,116 | Meaning of Epsilon in SVM regression | You have it backwards.
Traditional $\epsilon$-SVR works with the epsilon-insensitive hinge loss. The value of $\epsilon$ defines a margin of tolerance where no penalty is given to errors.
Remember the support vectors are the instances across the margin, i.e. the samples being penalized, which slack variables are non-zero.
The larger $\epsilon$ is, the larger errors you admit in your solution. By contrast, if $\epsilon \rightarrow 0_+$, every error is penalized: you end with many (tending to the total number of instances) support vectors to sustain that. | Meaning of Epsilon in SVM regression | You have it backwards.
Traditional $\epsilon$-SVR works with the epsilon-insensitive hinge loss. The value of $\epsilon$ defines a margin of tolerance where no penalty is given to errors.
Remember th | Meaning of Epsilon in SVM regression
You have it backwards.
Traditional $\epsilon$-SVR works with the epsilon-insensitive hinge loss. The value of $\epsilon$ defines a margin of tolerance where no penalty is given to errors.
Remember the support vectors are the instances across the margin, i.e. the samples being penalized, which slack variables are non-zero.
The larger $\epsilon$ is, the larger errors you admit in your solution. By contrast, if $\epsilon \rightarrow 0_+$, every error is penalized: you end with many (tending to the total number of instances) support vectors to sustain that. | Meaning of Epsilon in SVM regression
You have it backwards.
Traditional $\epsilon$-SVR works with the epsilon-insensitive hinge loss. The value of $\epsilon$ defines a margin of tolerance where no penalty is given to errors.
Remember th |
35,117 | Correlation between an original variable and a principal component | Correlation coefficient between variable $X_i$ and principal component $Y_j$ is given by $$r=v_{ij}\cdot \mathrm{std}(Y_j) / \mathrm{std}(X_i)=v_{ij}\cdot \sqrt{e_{j}} / \mathrm{std}(X_i),$$
where $v_{ij}$ is an $i$-th element of the $j$-th unit-length eigenvector of the covariance matrix, $e_j=\mathrm{var}(Y_j)$ is the corresponding eigenvalue which gives variance of this PC, and $\mathrm{std}(X_i)$ is standard deviation of $X_i$.
Please see my answer to How to find which variables are most correlated with the first principal component? for the derivation and additional explanations. Note that $v_{ij}\cdot \sqrt{e_{j}}$ are called "loadings" $L_{ij}$.
I think the formula in your quote says the same thing: $a_{ij}$ are the elements of the eigenvectors, $\mathrm{var}(Y_i)$ are the respective eigenvalues, and $s_{ii}$ stands for the diagonal elements of the original covariance matrix, i.e. for the variances of $\mathrm{var}(X_i)$.
Regarding terminology, please see What exactly is called "principal component" in PCA? and Loadings vs eigenvectors in PCA: when to use one or another? | Correlation between an original variable and a principal component | Correlation coefficient between variable $X_i$ and principal component $Y_j$ is given by $$r=v_{ij}\cdot \mathrm{std}(Y_j) / \mathrm{std}(X_i)=v_{ij}\cdot \sqrt{e_{j}} / \mathrm{std}(X_i),$$
where $v_ | Correlation between an original variable and a principal component
Correlation coefficient between variable $X_i$ and principal component $Y_j$ is given by $$r=v_{ij}\cdot \mathrm{std}(Y_j) / \mathrm{std}(X_i)=v_{ij}\cdot \sqrt{e_{j}} / \mathrm{std}(X_i),$$
where $v_{ij}$ is an $i$-th element of the $j$-th unit-length eigenvector of the covariance matrix, $e_j=\mathrm{var}(Y_j)$ is the corresponding eigenvalue which gives variance of this PC, and $\mathrm{std}(X_i)$ is standard deviation of $X_i$.
Please see my answer to How to find which variables are most correlated with the first principal component? for the derivation and additional explanations. Note that $v_{ij}\cdot \sqrt{e_{j}}$ are called "loadings" $L_{ij}$.
I think the formula in your quote says the same thing: $a_{ij}$ are the elements of the eigenvectors, $\mathrm{var}(Y_i)$ are the respective eigenvalues, and $s_{ii}$ stands for the diagonal elements of the original covariance matrix, i.e. for the variances of $\mathrm{var}(X_i)$.
Regarding terminology, please see What exactly is called "principal component" in PCA? and Loadings vs eigenvectors in PCA: when to use one or another? | Correlation between an original variable and a principal component
Correlation coefficient between variable $X_i$ and principal component $Y_j$ is given by $$r=v_{ij}\cdot \mathrm{std}(Y_j) / \mathrm{std}(X_i)=v_{ij}\cdot \sqrt{e_{j}} / \mathrm{std}(X_i),$$
where $v_ |
35,118 | Correlation between an original variable and a principal component | Correlations with factors are called loadings. In PCA, eigenvectors can be scaled differently but if normalized to their eigenvalues, they are loadings (if memory serves). For other types of factor analysis, loadings and factors can differ but loadings are always refer to correlations. | Correlation between an original variable and a principal component | Correlations with factors are called loadings. In PCA, eigenvectors can be scaled differently but if normalized to their eigenvalues, they are loadings (if memory serves). For other types of factor an | Correlation between an original variable and a principal component
Correlations with factors are called loadings. In PCA, eigenvectors can be scaled differently but if normalized to their eigenvalues, they are loadings (if memory serves). For other types of factor analysis, loadings and factors can differ but loadings are always refer to correlations. | Correlation between an original variable and a principal component
Correlations with factors are called loadings. In PCA, eigenvectors can be scaled differently but if normalized to their eigenvalues, they are loadings (if memory serves). For other types of factor an |
35,119 | Mathematical statistics (moments vs. central moments) | Two salient properties of real numbers $x, y,$ and $\mu$ are
The triangle inequalities $$|x-\mu| \le |x|+|\mu|$$ and $$|x| \le |x-\mu| + |\mu|.$$
Raising to the $r$ power for $r \gt 0$ preserves order: $$|x| \le |y| \text{ implies } |x|^r \le |y|^r$$ and (therefore) $$\max(|x|^r, |y|^r) = \max(|x|,|y|)^r.$$
Note, too, the simple relationship $$|x| + |y| \le 2\max(|x|, |y|).$$
Consequently for any random variable $X$ and real number $\mu$,
$$|X-\mu|^r \le \left(|X| + |\mu|\right)^r \le \left(2\max\left(|X|, |\mu|\right)\right)^r = 2^r\max\left(|X|^r, |\mu|^r\right)$$
and
$$|X|^r \le \left(|X-\mu| + |\mu|\right)^r \le \cdots \le 2^r\max\left(|X-\mu|^r, |\mu|^r\right).$$
Letting $\mu = \mathbb{E}(X)$ and taking expectations establishes the inequalities you need. | Mathematical statistics (moments vs. central moments) | Two salient properties of real numbers $x, y,$ and $\mu$ are
The triangle inequalities $$|x-\mu| \le |x|+|\mu|$$ and $$|x| \le |x-\mu| + |\mu|.$$
Raising to the $r$ power for $r \gt 0$ preserves orde | Mathematical statistics (moments vs. central moments)
Two salient properties of real numbers $x, y,$ and $\mu$ are
The triangle inequalities $$|x-\mu| \le |x|+|\mu|$$ and $$|x| \le |x-\mu| + |\mu|.$$
Raising to the $r$ power for $r \gt 0$ preserves order: $$|x| \le |y| \text{ implies } |x|^r \le |y|^r$$ and (therefore) $$\max(|x|^r, |y|^r) = \max(|x|,|y|)^r.$$
Note, too, the simple relationship $$|x| + |y| \le 2\max(|x|, |y|).$$
Consequently for any random variable $X$ and real number $\mu$,
$$|X-\mu|^r \le \left(|X| + |\mu|\right)^r \le \left(2\max\left(|X|, |\mu|\right)\right)^r = 2^r\max\left(|X|^r, |\mu|^r\right)$$
and
$$|X|^r \le \left(|X-\mu| + |\mu|\right)^r \le \cdots \le 2^r\max\left(|X-\mu|^r, |\mu|^r\right).$$
Letting $\mu = \mathbb{E}(X)$ and taking expectations establishes the inequalities you need. | Mathematical statistics (moments vs. central moments)
Two salient properties of real numbers $x, y,$ and $\mu$ are
The triangle inequalities $$|x-\mu| \le |x|+|\mu|$$ and $$|x| \le |x-\mu| + |\mu|.$$
Raising to the $r$ power for $r \gt 0$ preserves orde |
35,120 | The issue of quantile curves crossing each other | In general case, the problem of non-crossing linear quantile regresion has no solutions.
Indeed, either your quantile lines are parallel (and trivial), or they do cross somewhere.
By placing restrictions, you could ensure that the lines do not cross in the training sample, but it will in no way guarantee that crossing will not occur at the next observation you see after training the model. And if the quantile lines intersect within the training sample, it most probably means that your model is specified incorrectly: either mean or standard deviation change nonlinearly, or you apply a wrong cost function when fitting the model.
If you still want to estimate such a model, I would propose fitting it as a neural network.
Your model should take input $X$, multiply it by matrix(!) $\beta$ to get a matrix of forecasts $f=X\beta$ with size $n \times k$, where $n$ is number of observations and $k$ is number of estimated quantiles. I assume that quantile percentages $q$ are in increasing order. You should minimize the function
$$
L = \sum_{i=1}^n \left(\sum_{j=1}^k \max(q_j(y_i-f_{ij}), (q_j-1)(y_i-f_{ij})) + \sum_{j=1}^{k-1} \alpha \max(0, \delta - (f_{i,j+1}-f_{ij})) \right)
$$
The first term in the inner sum is just the ordinary quantile regression loss. The second term is the penalty that is applied if two consecutive quantile predictions differ by less then $\delta$.
Minimizing this function by gradient descent will give you your non-crossing quantile lines (if $\alpha$ is large enough). But I still warn you that if "natural" quantile lines intersect, then ther might be problems with the functional form of your model. Maybe you would prefer quantile estimates of Random Forest (like quantregForest in R), which are always consistent.
There is a Python example. As for me, both restricted and unrestricted versions look ugly.
# import everything
import keras
from keras import backend as K
from keras import Sequential
from keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt
# create the dataset
n = 200
np.random.seed(1)
X = np.sort(np.random.normal(size=n))[:, np.newaxis] + 4
y = 5 + X.ravel()*(1 + np.random.normal(size=n)*0.2)
quantiles = np.array([0.1, 0.25, 0.5, 0.75, 0.9])
# define loss function
def quantile_ensemble_loss(q, y, f, alpha=100, margin=0.1):
error = (y - f)
quantile_loss = K.mean(K.maximum(q*error, (q-1)*error))
diff = f[:, 1:] - f[:, :-1]
penalty = K.mean(K.maximum(0.0, margin - diff)) * alpha
return quantile_loss + penalty
# fit two models
for i, alpha, name in [(1, 0, 'w/o penalty'), (2, 10, 'with_penalty')]:
model = Sequential()
model.add(Dense(len(quantiles), input_dim=X.shape[1]))
model.compile(loss=lambda y,f: quantile_ensemble_loss(quantiles,y,f,alpha), optimizer=keras.optimizers.RMSprop(lr=0.003))
model.fit(X, y, epochs=3000, verbose=0, batch_size=100);
plt.subplot(1,2,i)
plt.scatter(X.ravel(), y, s=1)
plt.plot(X.ravel(), model.predict(X))
plt.title(name)
plt.show() | The issue of quantile curves crossing each other | In general case, the problem of non-crossing linear quantile regresion has no solutions.
Indeed, either your quantile lines are parallel (and trivial), or they do cross somewhere.
By placing restric | The issue of quantile curves crossing each other
In general case, the problem of non-crossing linear quantile regresion has no solutions.
Indeed, either your quantile lines are parallel (and trivial), or they do cross somewhere.
By placing restrictions, you could ensure that the lines do not cross in the training sample, but it will in no way guarantee that crossing will not occur at the next observation you see after training the model. And if the quantile lines intersect within the training sample, it most probably means that your model is specified incorrectly: either mean or standard deviation change nonlinearly, or you apply a wrong cost function when fitting the model.
If you still want to estimate such a model, I would propose fitting it as a neural network.
Your model should take input $X$, multiply it by matrix(!) $\beta$ to get a matrix of forecasts $f=X\beta$ with size $n \times k$, where $n$ is number of observations and $k$ is number of estimated quantiles. I assume that quantile percentages $q$ are in increasing order. You should minimize the function
$$
L = \sum_{i=1}^n \left(\sum_{j=1}^k \max(q_j(y_i-f_{ij}), (q_j-1)(y_i-f_{ij})) + \sum_{j=1}^{k-1} \alpha \max(0, \delta - (f_{i,j+1}-f_{ij})) \right)
$$
The first term in the inner sum is just the ordinary quantile regression loss. The second term is the penalty that is applied if two consecutive quantile predictions differ by less then $\delta$.
Minimizing this function by gradient descent will give you your non-crossing quantile lines (if $\alpha$ is large enough). But I still warn you that if "natural" quantile lines intersect, then ther might be problems with the functional form of your model. Maybe you would prefer quantile estimates of Random Forest (like quantregForest in R), which are always consistent.
There is a Python example. As for me, both restricted and unrestricted versions look ugly.
# import everything
import keras
from keras import backend as K
from keras import Sequential
from keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt
# create the dataset
n = 200
np.random.seed(1)
X = np.sort(np.random.normal(size=n))[:, np.newaxis] + 4
y = 5 + X.ravel()*(1 + np.random.normal(size=n)*0.2)
quantiles = np.array([0.1, 0.25, 0.5, 0.75, 0.9])
# define loss function
def quantile_ensemble_loss(q, y, f, alpha=100, margin=0.1):
error = (y - f)
quantile_loss = K.mean(K.maximum(q*error, (q-1)*error))
diff = f[:, 1:] - f[:, :-1]
penalty = K.mean(K.maximum(0.0, margin - diff)) * alpha
return quantile_loss + penalty
# fit two models
for i, alpha, name in [(1, 0, 'w/o penalty'), (2, 10, 'with_penalty')]:
model = Sequential()
model.add(Dense(len(quantiles), input_dim=X.shape[1]))
model.compile(loss=lambda y,f: quantile_ensemble_loss(quantiles,y,f,alpha), optimizer=keras.optimizers.RMSprop(lr=0.003))
model.fit(X, y, epochs=3000, verbose=0, batch_size=100);
plt.subplot(1,2,i)
plt.scatter(X.ravel(), y, s=1)
plt.plot(X.ravel(), model.predict(X))
plt.title(name)
plt.show() | The issue of quantile curves crossing each other
In general case, the problem of non-crossing linear quantile regresion has no solutions.
Indeed, either your quantile lines are parallel (and trivial), or they do cross somewhere.
By placing restric |
35,121 | The issue of quantile curves crossing each other | Placing a regularizing restriction sometimes help prevent crossing.
https://ieeexplore.ieee.org/document/9548806 | The issue of quantile curves crossing each other | Placing a regularizing restriction sometimes help prevent crossing.
https://ieeexplore.ieee.org/document/9548806 | The issue of quantile curves crossing each other
Placing a regularizing restriction sometimes help prevent crossing.
https://ieeexplore.ieee.org/document/9548806 | The issue of quantile curves crossing each other
Placing a regularizing restriction sometimes help prevent crossing.
https://ieeexplore.ieee.org/document/9548806 |
35,122 | Regression when the dependent variable is between 0 and 1 | Beta regressions are used for continuous proportions (like the proportion of land with a particular soil type).
For count proportions, the most common models would be binomial regression models, a particular type of generalized linear model (GLM).
Of those, logistic regression is the most widely used though there's a number of other link functions that are used.
The estimated fit is automatically constrained to lie within the bounds.
It doesn't transform the response; it relies on fitting a function that stays inside the limits.
[Numerous questions on site discuss logistic regression. A few discuss other models - probit regression and complementary log-log regression, for example] | Regression when the dependent variable is between 0 and 1 | Beta regressions are used for continuous proportions (like the proportion of land with a particular soil type).
For count proportions, the most common models would be binomial regression models, a par | Regression when the dependent variable is between 0 and 1
Beta regressions are used for continuous proportions (like the proportion of land with a particular soil type).
For count proportions, the most common models would be binomial regression models, a particular type of generalized linear model (GLM).
Of those, logistic regression is the most widely used though there's a number of other link functions that are used.
The estimated fit is automatically constrained to lie within the bounds.
It doesn't transform the response; it relies on fitting a function that stays inside the limits.
[Numerous questions on site discuss logistic regression. A few discuss other models - probit regression and complementary log-log regression, for example] | Regression when the dependent variable is between 0 and 1
Beta regressions are used for continuous proportions (like the proportion of land with a particular soil type).
For count proportions, the most common models would be binomial regression models, a par |
35,123 | Use of Metropolis & Rejection & Inverse Transform sampling methods | It's not entirely correct to say that inverse methods are impossible to compute. There are perfectly good numerical approximations to the inverse Gaussian CDF. As far as I'm aware, plenty of methods use it to generate gaussian random variables. There are of course plenty of other, possibly simpler methods of generating Gaussians.
Concerning rejection sampling, this is a mixed bag. If $f(x)$ is the Gaussian pdf, then in rejection sampling, you need to find a PDF $g(x)$ which dominates $f(x)$: $f(x)\leq Mg(x)$, for some $M>0$. One interpretation for $M$ here is the expected number of rejections you need to make before accepting a sample, so the smaller $M$ is the better. This issue can make rejection sampling a huge pain because sometimes $M$ is huge. The rule here is, if you can't find a $g$ that makes $M$ tractable, you'll need to look at other methods, for example, the inverse transform method.
For example, the exponential distribution works for the normal distribution (actually the one sided normal, after which you can flip a coin to decide on the sign). In this case, you can work out $M=\sqrt{2\pi/e}=1.32$, which is great because the exponential is very easy to generate using the inverse cdf method and you only need to throw out roughly 2 samples on average. The nice thing about rejection sampling combined with MCMC is, when used in a clever way, you can simulate rare events without actually having to wait the lifetime of the universe for the event to occur. | Use of Metropolis & Rejection & Inverse Transform sampling methods | It's not entirely correct to say that inverse methods are impossible to compute. There are perfectly good numerical approximations to the inverse Gaussian CDF. As far as I'm aware, plenty of methods u | Use of Metropolis & Rejection & Inverse Transform sampling methods
It's not entirely correct to say that inverse methods are impossible to compute. There are perfectly good numerical approximations to the inverse Gaussian CDF. As far as I'm aware, plenty of methods use it to generate gaussian random variables. There are of course plenty of other, possibly simpler methods of generating Gaussians.
Concerning rejection sampling, this is a mixed bag. If $f(x)$ is the Gaussian pdf, then in rejection sampling, you need to find a PDF $g(x)$ which dominates $f(x)$: $f(x)\leq Mg(x)$, for some $M>0$. One interpretation for $M$ here is the expected number of rejections you need to make before accepting a sample, so the smaller $M$ is the better. This issue can make rejection sampling a huge pain because sometimes $M$ is huge. The rule here is, if you can't find a $g$ that makes $M$ tractable, you'll need to look at other methods, for example, the inverse transform method.
For example, the exponential distribution works for the normal distribution (actually the one sided normal, after which you can flip a coin to decide on the sign). In this case, you can work out $M=\sqrt{2\pi/e}=1.32$, which is great because the exponential is very easy to generate using the inverse cdf method and you only need to throw out roughly 2 samples on average. The nice thing about rejection sampling combined with MCMC is, when used in a clever way, you can simulate rare events without actually having to wait the lifetime of the universe for the event to occur. | Use of Metropolis & Rejection & Inverse Transform sampling methods
It's not entirely correct to say that inverse methods are impossible to compute. There are perfectly good numerical approximations to the inverse Gaussian CDF. As far as I'm aware, plenty of methods u |
35,124 | Use of Metropolis & Rejection & Inverse Transform sampling methods | Comparisons between simulation methods are only about efficiency as they all produce an output that is supposed to be from the same target distribution. Hence, you cannot expect one simulation method (like MCMC) to produce more rare events than another one, as those rare events are supposed to occur at the correct (and rare) rate.
The inverse cdf transform approach, namely to return $F^{-}(U)$ when $U$ is $\mathscr{U}(0,1)$, as distributed from $F$. is mathematically correct. It may become inefficient when computing $F^{-1}$ is too demanding. If the software of your choice includes a code for this inverse, there is no need to seek further, unless you are worried at the precision of the inversion (but then need to find another method with a higher numerical precision!). If the inverse cdf is not coded and requires a heavy coding investment, it is more efficient to seek generic methods like Markov chain Monte Carlo methods, which suffer from the drawback of not guaranteeing simulations that come exactly from the target. These are asymptotic methods in that the distribution of the simulation only converges to the target distribution when the number of Markov steps grows to infinity (except in special cases where convergence can be validated after a finite number of steps). But these also are generic methods that require less coding and planning, hence more efficient methods in the sense that computer time is rather cheap, when compared with the coder's own time. | Use of Metropolis & Rejection & Inverse Transform sampling methods | Comparisons between simulation methods are only about efficiency as they all produce an output that is supposed to be from the same target distribution. Hence, you cannot expect one simulation method | Use of Metropolis & Rejection & Inverse Transform sampling methods
Comparisons between simulation methods are only about efficiency as they all produce an output that is supposed to be from the same target distribution. Hence, you cannot expect one simulation method (like MCMC) to produce more rare events than another one, as those rare events are supposed to occur at the correct (and rare) rate.
The inverse cdf transform approach, namely to return $F^{-}(U)$ when $U$ is $\mathscr{U}(0,1)$, as distributed from $F$. is mathematically correct. It may become inefficient when computing $F^{-1}$ is too demanding. If the software of your choice includes a code for this inverse, there is no need to seek further, unless you are worried at the precision of the inversion (but then need to find another method with a higher numerical precision!). If the inverse cdf is not coded and requires a heavy coding investment, it is more efficient to seek generic methods like Markov chain Monte Carlo methods, which suffer from the drawback of not guaranteeing simulations that come exactly from the target. These are asymptotic methods in that the distribution of the simulation only converges to the target distribution when the number of Markov steps grows to infinity (except in special cases where convergence can be validated after a finite number of steps). But these also are generic methods that require less coding and planning, hence more efficient methods in the sense that computer time is rather cheap, when compared with the coder's own time. | Use of Metropolis & Rejection & Inverse Transform sampling methods
Comparisons between simulation methods are only about efficiency as they all produce an output that is supposed to be from the same target distribution. Hence, you cannot expect one simulation method |
35,125 | What metric should I use for assessing Implicit matrix factorization recommender with ALS? | Evaluating implicit feedback based recommendations is tricky. Here are couple of approaches that I'd recommend.
Approach 1
You can use modified precision and recall metrics. Overall the procedure would be as follows,
Divide your data into train and test set by users.
For a user in test set, given their history, get the top N recommendations using implicit feedback based model.
Precision can be calculated using # of recommendations given by model which actually matched by what user had acted upon (for example read in case of articles).
Recall can be calculated using # of user actions (articles read by user) that were captured by top N recommendations.
You can calculate these for all users in test set and average them.
Approach 2
The approach is similar to approach 1, but rather than splitting train and test data by users, you use something called as "leave one out" strategy. We use a simple accuracy metric in this case. The steps to calculate the accuracy will be as follows,
For each user (or a subset of users), hide one of the articles read/browsed and move it to test set (leave one out).
Using user history, get top N recommendations for each user.
Calculate the number of times the left out article was captured by the top N recommendations.
Note that in both cases, the N in top N recommendations will become your hyper-parameter which can be tuned further. | What metric should I use for assessing Implicit matrix factorization recommender with ALS? | Evaluating implicit feedback based recommendations is tricky. Here are couple of approaches that I'd recommend.
Approach 1
You can use modified precision and recall metrics. Overall the procedure woul | What metric should I use for assessing Implicit matrix factorization recommender with ALS?
Evaluating implicit feedback based recommendations is tricky. Here are couple of approaches that I'd recommend.
Approach 1
You can use modified precision and recall metrics. Overall the procedure would be as follows,
Divide your data into train and test set by users.
For a user in test set, given their history, get the top N recommendations using implicit feedback based model.
Precision can be calculated using # of recommendations given by model which actually matched by what user had acted upon (for example read in case of articles).
Recall can be calculated using # of user actions (articles read by user) that were captured by top N recommendations.
You can calculate these for all users in test set and average them.
Approach 2
The approach is similar to approach 1, but rather than splitting train and test data by users, you use something called as "leave one out" strategy. We use a simple accuracy metric in this case. The steps to calculate the accuracy will be as follows,
For each user (or a subset of users), hide one of the articles read/browsed and move it to test set (leave one out).
Using user history, get top N recommendations for each user.
Calculate the number of times the left out article was captured by the top N recommendations.
Note that in both cases, the N in top N recommendations will become your hyper-parameter which can be tuned further. | What metric should I use for assessing Implicit matrix factorization recommender with ALS?
Evaluating implicit feedback based recommendations is tricky. Here are couple of approaches that I'd recommend.
Approach 1
You can use modified precision and recall metrics. Overall the procedure woul |
35,126 | What is the difference between VAR, Dynamic Regressive, and ARMAX models? | I will focus on ARMAX versus VAR. I am not quite sure what a dynamic regression is. (I have seen a few different interpretations. Funnily, there are textbooks and lecture notes with chapters called "Dynamic regression" that do not really delimit this class of models. Also, Rob J. Hyndman notes in his blog post "The ARIMAX model muddle" that different books use that term for different models).
An ARMAX model has the form
$$ y_t = \beta x_t + \varphi_1 y_{t-1} + \dotsc + \varphi_p y_{t-p} + \varepsilon_t + \theta_1 \varepsilon_{t-1} + \dotsc + \theta_q \varepsilon_{t-q} $$
(one could also have more than one exogenous variable and/or lags of exogenous variables in the above equation.)
The dependent variable is a univariate time series.
The model cannot be used for forecasting $y_{t+h}$ unless one has the future values of the independent variable $x_{t+h}$ available, or has a separate model for predicting $x_{t+h}$.
The model is estimated using maximum likelihood (slow), often using a state space representation.
Allowing for both AR and MA terms offers a parsimonious representation of the process.
A VAR model has the form
$$ z_t = \varphi_1 z_{t-1} + \dotsc + \varphi_p z_{t-p} + \varepsilon_t $$
where $z$ is a vector; for example, $z=(y,x)'$.
The dependent variable is a multivariate time series.
The model can be used for forecasting all components of $z_{t+h}$, e.g. for $z=(y,x)'$. Given data up to and including time $t$, forecasts for time $t+1$ are straightforward to obtain; forecasts for $t+h$ where $h>1$ can be obtained iteratively.
The model can be estimated using OLS or GLS (fast).
Lack of MA terms may (or may not) require large AR order to approximate the process well, and large AR order means a large number of parameters to be estimated and thus high estimation variance. Fortunately, regularization (shrinkage) applies pretty straightforwardly to VAR models (unlike ARMAX), so the variance can be tamed.
[H]ow do we decide when to use which[?]
It depends on your intentions and the data at hand.
If you need fast estimation and direct applicability to forecasting, try a VAR.
If you need a parsimonious representation, try ARMAX.
Also, ARMAX and VAR could be combined to obtain the VARIMAX model that has a multivariate dependent variable, does allow for forecasting of all of its components but also takes a long time to estimate, is prone to convergence problems and is difficult to regularize. | What is the difference between VAR, Dynamic Regressive, and ARMAX models? | I will focus on ARMAX versus VAR. I am not quite sure what a dynamic regression is. (I have seen a few different interpretations. Funnily, there are textbooks and lecture notes with chapters called "D | What is the difference between VAR, Dynamic Regressive, and ARMAX models?
I will focus on ARMAX versus VAR. I am not quite sure what a dynamic regression is. (I have seen a few different interpretations. Funnily, there are textbooks and lecture notes with chapters called "Dynamic regression" that do not really delimit this class of models. Also, Rob J. Hyndman notes in his blog post "The ARIMAX model muddle" that different books use that term for different models).
An ARMAX model has the form
$$ y_t = \beta x_t + \varphi_1 y_{t-1} + \dotsc + \varphi_p y_{t-p} + \varepsilon_t + \theta_1 \varepsilon_{t-1} + \dotsc + \theta_q \varepsilon_{t-q} $$
(one could also have more than one exogenous variable and/or lags of exogenous variables in the above equation.)
The dependent variable is a univariate time series.
The model cannot be used for forecasting $y_{t+h}$ unless one has the future values of the independent variable $x_{t+h}$ available, or has a separate model for predicting $x_{t+h}$.
The model is estimated using maximum likelihood (slow), often using a state space representation.
Allowing for both AR and MA terms offers a parsimonious representation of the process.
A VAR model has the form
$$ z_t = \varphi_1 z_{t-1} + \dotsc + \varphi_p z_{t-p} + \varepsilon_t $$
where $z$ is a vector; for example, $z=(y,x)'$.
The dependent variable is a multivariate time series.
The model can be used for forecasting all components of $z_{t+h}$, e.g. for $z=(y,x)'$. Given data up to and including time $t$, forecasts for time $t+1$ are straightforward to obtain; forecasts for $t+h$ where $h>1$ can be obtained iteratively.
The model can be estimated using OLS or GLS (fast).
Lack of MA terms may (or may not) require large AR order to approximate the process well, and large AR order means a large number of parameters to be estimated and thus high estimation variance. Fortunately, regularization (shrinkage) applies pretty straightforwardly to VAR models (unlike ARMAX), so the variance can be tamed.
[H]ow do we decide when to use which[?]
It depends on your intentions and the data at hand.
If you need fast estimation and direct applicability to forecasting, try a VAR.
If you need a parsimonious representation, try ARMAX.
Also, ARMAX and VAR could be combined to obtain the VARIMAX model that has a multivariate dependent variable, does allow for forecasting of all of its components but also takes a long time to estimate, is prone to convergence problems and is difficult to regularize. | What is the difference between VAR, Dynamic Regressive, and ARMAX models?
I will focus on ARMAX versus VAR. I am not quite sure what a dynamic regression is. (I have seen a few different interpretations. Funnily, there are textbooks and lecture notes with chapters called "D |
35,127 | What is the difference between VAR, Dynamic Regressive, and ARMAX models? | ARMAX models are more general that VAR and Dynamic Regressive . You can see ARMAX in action here https://twitter.com/tomdireill/status/717694028104474625 where the GASX/GASY example from the Box-Jenkins text is analyzed/ | What is the difference between VAR, Dynamic Regressive, and ARMAX models? | ARMAX models are more general that VAR and Dynamic Regressive . You can see ARMAX in action here https://twitter.com/tomdireill/status/717694028104474625 where the GASX/GASY example from the Box-Jenki | What is the difference between VAR, Dynamic Regressive, and ARMAX models?
ARMAX models are more general that VAR and Dynamic Regressive . You can see ARMAX in action here https://twitter.com/tomdireill/status/717694028104474625 where the GASX/GASY example from the Box-Jenkins text is analyzed/ | What is the difference between VAR, Dynamic Regressive, and ARMAX models?
ARMAX models are more general that VAR and Dynamic Regressive . You can see ARMAX in action here https://twitter.com/tomdireill/status/717694028104474625 where the GASX/GASY example from the Box-Jenki |
35,128 | The Number of Exponential Summands in a Fixed Interval is Poisson | I propose taking, as a point of departure, the concept of a homogeneous Poisson process. This is a point process on the line (often thought of, and referred to, as a "time" line). The realizations are sets of points. Almost surely, any bounded set of real numbers will contain only finitely many points.
The fundamental properties enjoyed by this process, the ones I will use repeatedly in the analysis, are
(Independence) The outcomes in any two disjoint sets are independent.
(Homogeneity) The expected number of points in any measurable set $\mathcal{A}$ with finite measure $|\mathcal A|$ is directly proportional to $|\mathcal{A}|$. The constant of proportionality, $\lambda$, is nonzero.
Everything flows from these properties, as we will see.
Waiting times
Let's study the "waiting times" of this process. Given a start time $s$ and elapsed duration $t \ge 0$, let $S(s, t)$ be the chance that no points occur between $s$ and $s+t$: that is, within the interval $(s, s+t]$. Consider two adjacent intervals, one from $r$ to $r+s$ and another from $r+s$ to $r+s+t$. By independence, that chance of no point being in their union is the product of the chance that no point is in the first and the chance that no point is in the second:
$$S(r, s+t) = S(r,s) S(r+s,t).\tag{1}$$
By homogeneity, these chances remain the same when we slide the intervals around. That is, for any $s$, $S(r, t) = S(r+s, t)$. In particular, we may always take $r=-s$ to obtain
$$S(r, t) = S(0,t) = S(t)$$
for all $r$, allowing us to drop the explicit dependence on $r$ in the notation. Plugging this into $(1)$ gives
$$S(s+t) = S(s)S(t).\tag{2}$$
Homogeneity makes it obvious $S$ must be continuous (actually, differentiable). It is well known that the only solutions to $(2)$ are exponential. One simple way to see this is to consider that the logarithm of $S$ is linear and, since $S(0)=1$, there consequently must be some number $\kappa$ for which
$$\log(S(t)) = \kappa t.$$
Since $S$ must decrease as time goes on, $\kappa \lt 0$. Ergo, all solutions are of the form
$$S(t) = e^{-\kappa t}.$$
It is the chance that no points occur within any specified interval of length $t$.
Exponential summands
Fix an interval; by virtue of homogeneity, we may assume it starts at $0$ and ends (say) at $b$. Almost surely there are only finitely many points of the process in the interval $(0,b]$, allowing us to order them $0 \lt t_1 \lt t_2 \lt \cdots \lt t_n$. $t_1$ is a realization of a random variable $T_1$ governed by $S$: that is,
$$\Pr(T_1 \le t) = 1 - \Pr(T_1 \gt t) = 1 - S(t) = 1 - e^{-\kappa t}.$$
$T_2$ similarly is an independent random variable, where $T_2 - T_1$ also is governed by $S$, whence
$$\Pr(T_2 \le T_1 + t) = 1 - S(t) = 1 - e^{-\kappa t},$$
and likewise for the remaining $T_i$. This demonstrates that $n$ is exactly as described in the question: it is the largest number of "exponential summands" that fit within the interval $(0, b]$. It is a realization of the random variable
$$N(0,b) = \max\{i\,|\,T_1+T_2+\cdots+T_i \le b\}.$$
Poisson distribution
Let $k\ge 0$ be an integer. What is the chance, $p_k$, that there are exactly $k$ points in the interval $[0,1]$? I am going to deduce the answer from the ergodic property of the Poisson process, which I take to be intuitive: because the process within the unit interval $[0,1]$ is the same as (and independent of) the process within any unit interval $[t-1, t]$, we may deduce properties of the process by varying $t$ for a single realization and studying the point patterns that show up. In particular, $p_k$ must equal the limiting proportion of time that the number of points $N(t)=N(t-1,t)$ in the interval $[t-1,t]$ equals $k$. We may express this formally using the indicator function $I$ which is equal to $1$ when its argument is true and is $0$ otherwise:
$$p_k = \lim_{x\to\infty}\frac{1}{x-1}\int_1^x I(N(t)=k) dt.$$
The integral is the total duration between $1$ and $x$ when interval $[t-1,t]$ contains exactly $k$ points, while the denominator of the fraction of course is the total elapsed time from $1$ to $x$.
This is a plot of $N(t)$ for one realization of a Poisson process with rate $\lambda=2.5$. White horizontal lines mark the values $k=1,2,3$ on the vertical axis, which extends from $0$ to $4$. The gray vertical lines show the times at which points occur in this realization. The dotted blue vertical lines show the same points shifted one unit to the right. The solid red curve plots $N(t)$ beginning at $t=1$. (It extends infinitely far to the right but not all of it could be drawn!)
$N(1)=4$ because four points (gray lines) appear in the first unit of time, $[0,1]$. The plot of $N(t)$ then rises by one unit every time $t$ another gray line is encountered moving left to right, because this is when the interval $[t-1,t]$ picks up that point. It falls by one unit every time $t$ a blue line is encountered, because this is the same thing as losing the value $t-1$ from the interval $[t-1,t]$.
The proportion of time spent at each height $k$ estimates $p_k$, the chance that any unit interval contains exactly $k$ points.
Suppose the interval $[t-1, t]$ contains $k$ points. As we slide it to the right, let's keep track of the new points it picks up and the old points that drop off. Two simple relations determine everything:
Between $t$ and $t+dt$ (for $dt \ge 0$), the expected number of new points is $\lambda\, dt$. (That's homogeneity.)
However, the expected number of points that are lost is $k\, dt$ because there are $k$ points randomly located within the interval. (This, too, is due to homogeneity.)
Almost surely at most one point is added or lost at any instant. (If not, there would be a positive lower bound to the chance of two or more points appearing in arbitrarily small intervals $[t, t+dt]$, but since the expected number of points in such intervals is only $\lambda dt$--which grows vanishingly small with small $dt$--this is impossible.) Accordingly, there are only two transitions that have nonzero chance of occurring: from $k$ points to $k+1$ points and from $k$ points to $k-1$ points. Their instantaneous rates are
$$\tau(k\to k+1) =\lim_{dt\to 0^{+}} \frac{\lambda\, dt}{dt} = \lambda$$
and, if $k \ge 1$,
$$\tau(k\to k-1) = \lim_{dt\to 0^{+}} \frac{k\, dt}{dt} = k.$$
This might look complicated, since it establishes a system of differential equations for the infinitely many probabilities $p_k$. However, because the process is homogeneous these probabilities are unchanging.
Look first at the case $k=0$. The expected rate at which $p_0$ changes (namely, zero) is the expected rate of transitions $1\to 0$ from states with $k=1$ minus the expected rate of transitions $0\to 1$ to states with $k=1$. Thus, by virtue of the simple relations (1) and (2),
$$(1)p_1 - (\lambda)p_0 = 0.$$
This enables us to find $p_1$ in terms of $p_0$:
$$p_1 = \lambda p_0.\tag{3}$$
Now consider the general situation $k\gt 0$. There are four transitions potentially changing $p_k$, all of which must balance out in expectation: $k\to k+1$ and $k\to k-1$ make it decrease, while $k+1\to k$ and $k-1\to k$ increase it. Thus, again using the simple relations (1) and (2) to compute the instantaneous rates,
$$[(\lambda)p_{k-1} - (k) p_k] + [(k+1)p_{k+1} - (\lambda)p_k] = 0.$$
We may assume inductively that the first term in brackets balances out (something we just showed for the case $k=0$), thereby automatically balancing out the second term in brackets and easily giving the solution
$$p_{k+1} = \frac{\lambda}{k+1}p_k.\tag{4}$$
Formulas $(3)$ and $(4)$ determine all the $p_k$ in terms of $p_0$: the solution is
$$p_k = p_0\frac{\lambda^k}{k!}.\tag{5}$$
(Proof: this formula satisfies the initial condition $(3)$ as well as the recursion $(4)$.)
The connection between the Exponential and Poisson parameters
There are two ways to find $p_0$. First, we may exploit what we learned previously about exponential waiting times: $p_0$ is the chance that an Exponential variable of parameter $\kappa$ exceeds $1$. This is
$$p_0 = e^{-\kappa}.\tag{6}$$
The second is the fact that the probabilities sum to unity, whence
$$1 = \sum_{k=0}^\infty p_0\frac{\lambda^k}{k!} = p_0\sum_{k=0}^\infty \frac{\lambda^k}{k!} = p_0 e^{\lambda}.$$
Therefore
$$p_0 = e^{-\lambda}\tag{7}$$
is the unique value that works. Consequently $(5)$ is now fully explicit:
$$p_k = e^{-\lambda} \frac{\lambda^k}{k!}.$$
This is the Poisson distribution.
Equating $(6)$ and $(7)$ reveals that
$$\kappa = \lambda.$$
This explicitly relates the parameter of the Exponential waiting times to the parameter of the Poisson distribution.
Simulation for greater understanding
The first figure did not show a sufficiently long time span to estimate the $p_k$ accurately. Consider, though, a portion another realization of $N(t)$ that is a hundred times longer:
(The vertical lines are no longer drawn, because they are so numerous.)
Here are the proportions of time spent for each $k$. Beneath them are the proportions for the Poisson$(2.5)$ distribution:
0 1 2 3 4 5 6 7 8 9
y 0.0745 0.2068 0.2637 0.2215 0.1290 0.0660 0.0235 0.0128 0.0016 6e-04
fit 0.0821 0.2052 0.2565 0.2138 0.1336 0.0668 0.0278 0.0099 0.0031 9e-04
The agreement is apparent--although still imperfect, because this is still just a short initial segment of the realization.
Here is the R code used to produce the figures. Experiment with lambda and n to get a feel for this analysis.
lambda <- 2.5 # Poisson intensity
n <- 1000 # Number of points to realize
x <- cumsum(rexp(n, lambda))# Accumulate the waiting times
# Compute the proportion of times for each `k` and compare to the Poisson distribution.
f <- ecdf(x) # The ECDF does the work of computing N(t)
b <- max(x)
u <- seq(1, b, length.out=10*n)
y <- table(round(n*(f(u) - f(u-1)), 4))
y <- y / sum(y)
fit <- dpois(as.numeric(names(y)), lambda)
round(rbind(y, fit), 4)
# Plot N(t)
y.max <- max(as.numeric(names(y)))
curve(ifelse(x >= 1 & x <= b, n*(f(x) - f(x-1)), NA), 0,b, ylim=c(0, y.max*1.01),
n=max(10001, 10*n), xlab="t", ylab="", col="#00000080",
yaxp=c(0, y.max, y.max), bty="n", yaxt="n", yaxs="i")
rect(0, 0, b, y.max, col="#f4f4f4", border=NA)
abline(h=0:y.max, col="White")
if (n < 1000) {
abline(v=x, lty=1, col="Gray")
abline(v=x[x <= b-1]+1, lty=3, col="Blue")
}
curve(ifelse(x >= 1 & x <= b, n*(f(x) - f(x-1)), NA), add=TRUE,
n=max(10001, 10*n), lwd=2, col="#802020") | The Number of Exponential Summands in a Fixed Interval is Poisson | I propose taking, as a point of departure, the concept of a homogeneous Poisson process. This is a point process on the line (often thought of, and referred to, as a "time" line). The realizations a | The Number of Exponential Summands in a Fixed Interval is Poisson
I propose taking, as a point of departure, the concept of a homogeneous Poisson process. This is a point process on the line (often thought of, and referred to, as a "time" line). The realizations are sets of points. Almost surely, any bounded set of real numbers will contain only finitely many points.
The fundamental properties enjoyed by this process, the ones I will use repeatedly in the analysis, are
(Independence) The outcomes in any two disjoint sets are independent.
(Homogeneity) The expected number of points in any measurable set $\mathcal{A}$ with finite measure $|\mathcal A|$ is directly proportional to $|\mathcal{A}|$. The constant of proportionality, $\lambda$, is nonzero.
Everything flows from these properties, as we will see.
Waiting times
Let's study the "waiting times" of this process. Given a start time $s$ and elapsed duration $t \ge 0$, let $S(s, t)$ be the chance that no points occur between $s$ and $s+t$: that is, within the interval $(s, s+t]$. Consider two adjacent intervals, one from $r$ to $r+s$ and another from $r+s$ to $r+s+t$. By independence, that chance of no point being in their union is the product of the chance that no point is in the first and the chance that no point is in the second:
$$S(r, s+t) = S(r,s) S(r+s,t).\tag{1}$$
By homogeneity, these chances remain the same when we slide the intervals around. That is, for any $s$, $S(r, t) = S(r+s, t)$. In particular, we may always take $r=-s$ to obtain
$$S(r, t) = S(0,t) = S(t)$$
for all $r$, allowing us to drop the explicit dependence on $r$ in the notation. Plugging this into $(1)$ gives
$$S(s+t) = S(s)S(t).\tag{2}$$
Homogeneity makes it obvious $S$ must be continuous (actually, differentiable). It is well known that the only solutions to $(2)$ are exponential. One simple way to see this is to consider that the logarithm of $S$ is linear and, since $S(0)=1$, there consequently must be some number $\kappa$ for which
$$\log(S(t)) = \kappa t.$$
Since $S$ must decrease as time goes on, $\kappa \lt 0$. Ergo, all solutions are of the form
$$S(t) = e^{-\kappa t}.$$
It is the chance that no points occur within any specified interval of length $t$.
Exponential summands
Fix an interval; by virtue of homogeneity, we may assume it starts at $0$ and ends (say) at $b$. Almost surely there are only finitely many points of the process in the interval $(0,b]$, allowing us to order them $0 \lt t_1 \lt t_2 \lt \cdots \lt t_n$. $t_1$ is a realization of a random variable $T_1$ governed by $S$: that is,
$$\Pr(T_1 \le t) = 1 - \Pr(T_1 \gt t) = 1 - S(t) = 1 - e^{-\kappa t}.$$
$T_2$ similarly is an independent random variable, where $T_2 - T_1$ also is governed by $S$, whence
$$\Pr(T_2 \le T_1 + t) = 1 - S(t) = 1 - e^{-\kappa t},$$
and likewise for the remaining $T_i$. This demonstrates that $n$ is exactly as described in the question: it is the largest number of "exponential summands" that fit within the interval $(0, b]$. It is a realization of the random variable
$$N(0,b) = \max\{i\,|\,T_1+T_2+\cdots+T_i \le b\}.$$
Poisson distribution
Let $k\ge 0$ be an integer. What is the chance, $p_k$, that there are exactly $k$ points in the interval $[0,1]$? I am going to deduce the answer from the ergodic property of the Poisson process, which I take to be intuitive: because the process within the unit interval $[0,1]$ is the same as (and independent of) the process within any unit interval $[t-1, t]$, we may deduce properties of the process by varying $t$ for a single realization and studying the point patterns that show up. In particular, $p_k$ must equal the limiting proportion of time that the number of points $N(t)=N(t-1,t)$ in the interval $[t-1,t]$ equals $k$. We may express this formally using the indicator function $I$ which is equal to $1$ when its argument is true and is $0$ otherwise:
$$p_k = \lim_{x\to\infty}\frac{1}{x-1}\int_1^x I(N(t)=k) dt.$$
The integral is the total duration between $1$ and $x$ when interval $[t-1,t]$ contains exactly $k$ points, while the denominator of the fraction of course is the total elapsed time from $1$ to $x$.
This is a plot of $N(t)$ for one realization of a Poisson process with rate $\lambda=2.5$. White horizontal lines mark the values $k=1,2,3$ on the vertical axis, which extends from $0$ to $4$. The gray vertical lines show the times at which points occur in this realization. The dotted blue vertical lines show the same points shifted one unit to the right. The solid red curve plots $N(t)$ beginning at $t=1$. (It extends infinitely far to the right but not all of it could be drawn!)
$N(1)=4$ because four points (gray lines) appear in the first unit of time, $[0,1]$. The plot of $N(t)$ then rises by one unit every time $t$ another gray line is encountered moving left to right, because this is when the interval $[t-1,t]$ picks up that point. It falls by one unit every time $t$ a blue line is encountered, because this is the same thing as losing the value $t-1$ from the interval $[t-1,t]$.
The proportion of time spent at each height $k$ estimates $p_k$, the chance that any unit interval contains exactly $k$ points.
Suppose the interval $[t-1, t]$ contains $k$ points. As we slide it to the right, let's keep track of the new points it picks up and the old points that drop off. Two simple relations determine everything:
Between $t$ and $t+dt$ (for $dt \ge 0$), the expected number of new points is $\lambda\, dt$. (That's homogeneity.)
However, the expected number of points that are lost is $k\, dt$ because there are $k$ points randomly located within the interval. (This, too, is due to homogeneity.)
Almost surely at most one point is added or lost at any instant. (If not, there would be a positive lower bound to the chance of two or more points appearing in arbitrarily small intervals $[t, t+dt]$, but since the expected number of points in such intervals is only $\lambda dt$--which grows vanishingly small with small $dt$--this is impossible.) Accordingly, there are only two transitions that have nonzero chance of occurring: from $k$ points to $k+1$ points and from $k$ points to $k-1$ points. Their instantaneous rates are
$$\tau(k\to k+1) =\lim_{dt\to 0^{+}} \frac{\lambda\, dt}{dt} = \lambda$$
and, if $k \ge 1$,
$$\tau(k\to k-1) = \lim_{dt\to 0^{+}} \frac{k\, dt}{dt} = k.$$
This might look complicated, since it establishes a system of differential equations for the infinitely many probabilities $p_k$. However, because the process is homogeneous these probabilities are unchanging.
Look first at the case $k=0$. The expected rate at which $p_0$ changes (namely, zero) is the expected rate of transitions $1\to 0$ from states with $k=1$ minus the expected rate of transitions $0\to 1$ to states with $k=1$. Thus, by virtue of the simple relations (1) and (2),
$$(1)p_1 - (\lambda)p_0 = 0.$$
This enables us to find $p_1$ in terms of $p_0$:
$$p_1 = \lambda p_0.\tag{3}$$
Now consider the general situation $k\gt 0$. There are four transitions potentially changing $p_k$, all of which must balance out in expectation: $k\to k+1$ and $k\to k-1$ make it decrease, while $k+1\to k$ and $k-1\to k$ increase it. Thus, again using the simple relations (1) and (2) to compute the instantaneous rates,
$$[(\lambda)p_{k-1} - (k) p_k] + [(k+1)p_{k+1} - (\lambda)p_k] = 0.$$
We may assume inductively that the first term in brackets balances out (something we just showed for the case $k=0$), thereby automatically balancing out the second term in brackets and easily giving the solution
$$p_{k+1} = \frac{\lambda}{k+1}p_k.\tag{4}$$
Formulas $(3)$ and $(4)$ determine all the $p_k$ in terms of $p_0$: the solution is
$$p_k = p_0\frac{\lambda^k}{k!}.\tag{5}$$
(Proof: this formula satisfies the initial condition $(3)$ as well as the recursion $(4)$.)
The connection between the Exponential and Poisson parameters
There are two ways to find $p_0$. First, we may exploit what we learned previously about exponential waiting times: $p_0$ is the chance that an Exponential variable of parameter $\kappa$ exceeds $1$. This is
$$p_0 = e^{-\kappa}.\tag{6}$$
The second is the fact that the probabilities sum to unity, whence
$$1 = \sum_{k=0}^\infty p_0\frac{\lambda^k}{k!} = p_0\sum_{k=0}^\infty \frac{\lambda^k}{k!} = p_0 e^{\lambda}.$$
Therefore
$$p_0 = e^{-\lambda}\tag{7}$$
is the unique value that works. Consequently $(5)$ is now fully explicit:
$$p_k = e^{-\lambda} \frac{\lambda^k}{k!}.$$
This is the Poisson distribution.
Equating $(6)$ and $(7)$ reveals that
$$\kappa = \lambda.$$
This explicitly relates the parameter of the Exponential waiting times to the parameter of the Poisson distribution.
Simulation for greater understanding
The first figure did not show a sufficiently long time span to estimate the $p_k$ accurately. Consider, though, a portion another realization of $N(t)$ that is a hundred times longer:
(The vertical lines are no longer drawn, because they are so numerous.)
Here are the proportions of time spent for each $k$. Beneath them are the proportions for the Poisson$(2.5)$ distribution:
0 1 2 3 4 5 6 7 8 9
y 0.0745 0.2068 0.2637 0.2215 0.1290 0.0660 0.0235 0.0128 0.0016 6e-04
fit 0.0821 0.2052 0.2565 0.2138 0.1336 0.0668 0.0278 0.0099 0.0031 9e-04
The agreement is apparent--although still imperfect, because this is still just a short initial segment of the realization.
Here is the R code used to produce the figures. Experiment with lambda and n to get a feel for this analysis.
lambda <- 2.5 # Poisson intensity
n <- 1000 # Number of points to realize
x <- cumsum(rexp(n, lambda))# Accumulate the waiting times
# Compute the proportion of times for each `k` and compare to the Poisson distribution.
f <- ecdf(x) # The ECDF does the work of computing N(t)
b <- max(x)
u <- seq(1, b, length.out=10*n)
y <- table(round(n*(f(u) - f(u-1)), 4))
y <- y / sum(y)
fit <- dpois(as.numeric(names(y)), lambda)
round(rbind(y, fit), 4)
# Plot N(t)
y.max <- max(as.numeric(names(y)))
curve(ifelse(x >= 1 & x <= b, n*(f(x) - f(x-1)), NA), 0,b, ylim=c(0, y.max*1.01),
n=max(10001, 10*n), xlab="t", ylab="", col="#00000080",
yaxp=c(0, y.max, y.max), bty="n", yaxt="n", yaxs="i")
rect(0, 0, b, y.max, col="#f4f4f4", border=NA)
abline(h=0:y.max, col="White")
if (n < 1000) {
abline(v=x, lty=1, col="Gray")
abline(v=x[x <= b-1]+1, lty=3, col="Blue")
}
curve(ifelse(x >= 1 & x <= b, n*(f(x) - f(x-1)), NA), add=TRUE,
n=max(10001, 10*n), lwd=2, col="#802020") | The Number of Exponential Summands in a Fixed Interval is Poisson
I propose taking, as a point of departure, the concept of a homogeneous Poisson process. This is a point process on the line (often thought of, and referred to, as a "time" line). The realizations a |
35,129 | Forecasting Poisson, accuracy and prediction intervals | You have what is called intermittent demand, that is, a demand time series characterized by "many" zeros. (If your time series is not demand per se, most of what follows will still apply.) So a web search for "forecasting intermittent demand" would already be helpful. Teunter and Duncan (2009, JORS) give an overview of intermittent demand forecasting methods.
The standard method of forecasting intermittent demands is Croston's method. Use exponential smoothing on inter-demand intervals and on nonzero demand sizes separately. The point forecast then is the ratio of the smoothed nonzero demand to the smoothed inter-demand interval. Syntetos and Boylan (2001, IJPE) note that Croston is slightly biased and propose a modification, but this usually doesn't make all that much of a difference in practice.
An alternative is integer autoregressive moving average models (INARMA), which modify the standard ARIMA time series models. Maryam Mohammadipour wrote a thesis on these.
I personally have major doubts about the usefulness of such an expectation point forecast. A time series of 1 demand every other time period has an expectation of 0.5... as does a time series of 2 demands every fourth time period... and so forth - although these are, of course, less and less Poisson-y. I'd argue that it's much more useful to understand the entire future (and predictive) distribution of demands. So I applaud your looking for prediction intervals!
However, the $\alpha(n-2)$ formula you found applies only to single exponential smoothing on continuous data, via the ARIMA model SES is optimal for. So it is inapplicable to count data. I'd much rather propose that you take your point prediction $\hat{y}$ and use quantiles of the Poisson distribution with parameter $\lambda=\hat{y}$. This still disregards parameter estimation uncertainty (along with model selection uncertainty etc.), but it's a simple possibility and likely better than the formula you have.
Shenstone and Hyndman (2005, JoF) note that there is no consistent stochastic model for which Croston's method would be optimal - all candidate models are (1) continuous, not discrete, and (2) can yield negative values. However, for those candidate models, Shenstone and Hyndman provide prediction intervals.
Finally, a word of caution: don't use the MAD for assessing the accuracy of count data forecasts, especially not for intermittent demands. The expected MAD is minimized by the median of your future distribution, not its mean, and if you write that 65% of your data are zeros, then the median is zero... implying that you will probably get the lowest MAD by a flat zero forecast, which is badly biased and likely useless. Here is a presentation I gave at last year's International Symposium on Forecasting on this issue. Or look at Morlidge (2015, Foresight).
Final piece of shameless self-promotion: I have an article in the IJF (Kolassa, 2016) which looks at forecasting low volume count data (mostly intermittent), at different accuracy measures and different forecasting methods, including various flavors of Poisson models. This may be useful to you. | Forecasting Poisson, accuracy and prediction intervals | You have what is called intermittent demand, that is, a demand time series characterized by "many" zeros. (If your time series is not demand per se, most of what follows will still apply.) So a web se | Forecasting Poisson, accuracy and prediction intervals
You have what is called intermittent demand, that is, a demand time series characterized by "many" zeros. (If your time series is not demand per se, most of what follows will still apply.) So a web search for "forecasting intermittent demand" would already be helpful. Teunter and Duncan (2009, JORS) give an overview of intermittent demand forecasting methods.
The standard method of forecasting intermittent demands is Croston's method. Use exponential smoothing on inter-demand intervals and on nonzero demand sizes separately. The point forecast then is the ratio of the smoothed nonzero demand to the smoothed inter-demand interval. Syntetos and Boylan (2001, IJPE) note that Croston is slightly biased and propose a modification, but this usually doesn't make all that much of a difference in practice.
An alternative is integer autoregressive moving average models (INARMA), which modify the standard ARIMA time series models. Maryam Mohammadipour wrote a thesis on these.
I personally have major doubts about the usefulness of such an expectation point forecast. A time series of 1 demand every other time period has an expectation of 0.5... as does a time series of 2 demands every fourth time period... and so forth - although these are, of course, less and less Poisson-y. I'd argue that it's much more useful to understand the entire future (and predictive) distribution of demands. So I applaud your looking for prediction intervals!
However, the $\alpha(n-2)$ formula you found applies only to single exponential smoothing on continuous data, via the ARIMA model SES is optimal for. So it is inapplicable to count data. I'd much rather propose that you take your point prediction $\hat{y}$ and use quantiles of the Poisson distribution with parameter $\lambda=\hat{y}$. This still disregards parameter estimation uncertainty (along with model selection uncertainty etc.), but it's a simple possibility and likely better than the formula you have.
Shenstone and Hyndman (2005, JoF) note that there is no consistent stochastic model for which Croston's method would be optimal - all candidate models are (1) continuous, not discrete, and (2) can yield negative values. However, for those candidate models, Shenstone and Hyndman provide prediction intervals.
Finally, a word of caution: don't use the MAD for assessing the accuracy of count data forecasts, especially not for intermittent demands. The expected MAD is minimized by the median of your future distribution, not its mean, and if you write that 65% of your data are zeros, then the median is zero... implying that you will probably get the lowest MAD by a flat zero forecast, which is badly biased and likely useless. Here is a presentation I gave at last year's International Symposium on Forecasting on this issue. Or look at Morlidge (2015, Foresight).
Final piece of shameless self-promotion: I have an article in the IJF (Kolassa, 2016) which looks at forecasting low volume count data (mostly intermittent), at different accuracy measures and different forecasting methods, including various flavors of Poisson models. This may be useful to you. | Forecasting Poisson, accuracy and prediction intervals
You have what is called intermittent demand, that is, a demand time series characterized by "many" zeros. (If your time series is not demand per se, most of what follows will still apply.) So a web se |
35,130 | Is Principal Component Analysis a parametric method? | We do not have to make any distributional assumptions in order to extract the Principal Component directions from a covariance or correlation matrix. To see this, recall the problem PCA solves. For a $p\times p $ covariance matrix $\mathbf{\Sigma}$ and all vectors $\mathbf{x} \in \mathbb{R}^p$ we would like to maximize
$$\mathbf{x}^{\prime} \mathbf{\Sigma} \mathbf{x} \tag{1}$$
subject to the condition that $\mathbf{x}$ is a unit vector, i.e. $\mathbf{x}^\prime \mathbf{x} = 1$. The solution is the eigenvector of the covariance (or correlation) matrix corresponding to the largest eigenvalue. The second principal component is the vector that maximizes $(1)$ subject to the additional condition that is perpendicular to the first direction and likewise for the third, forth and millionth principal component (always $\leq p$) . All we require is that the maximizers are unit vectors and perpendicular to the previous directions.
We do not need normality for the extraction but we definitely need the normality for hypothesis testing, e.g. to see how many directions are significant. It's worth noting, however, that with normality we have a pretty neat interpretation of PCA as the axes in ellipsoids of constant density (recall the exponent of a multivariate Normal distribution). | Is Principal Component Analysis a parametric method? | We do not have to make any distributional assumptions in order to extract the Principal Component directions from a covariance or correlation matrix. To see this, recall the problem PCA solves. For a | Is Principal Component Analysis a parametric method?
We do not have to make any distributional assumptions in order to extract the Principal Component directions from a covariance or correlation matrix. To see this, recall the problem PCA solves. For a $p\times p $ covariance matrix $\mathbf{\Sigma}$ and all vectors $\mathbf{x} \in \mathbb{R}^p$ we would like to maximize
$$\mathbf{x}^{\prime} \mathbf{\Sigma} \mathbf{x} \tag{1}$$
subject to the condition that $\mathbf{x}$ is a unit vector, i.e. $\mathbf{x}^\prime \mathbf{x} = 1$. The solution is the eigenvector of the covariance (or correlation) matrix corresponding to the largest eigenvalue. The second principal component is the vector that maximizes $(1)$ subject to the additional condition that is perpendicular to the first direction and likewise for the third, forth and millionth principal component (always $\leq p$) . All we require is that the maximizers are unit vectors and perpendicular to the previous directions.
We do not need normality for the extraction but we definitely need the normality for hypothesis testing, e.g. to see how many directions are significant. It's worth noting, however, that with normality we have a pretty neat interpretation of PCA as the axes in ellipsoids of constant density (recall the exponent of a multivariate Normal distribution). | Is Principal Component Analysis a parametric method?
We do not have to make any distributional assumptions in order to extract the Principal Component directions from a covariance or correlation matrix. To see this, recall the problem PCA solves. For a |
35,131 | Is Principal Component Analysis a parametric method? | PCA has nothing to do with the normality of your data. The principle is that you have a bunch of data points in a (high-dimensional) space and you want to see which directions or principal vectors can describe your data in an optimal way. It is virtually the same as the singular value decomposition and can be applied to any matrix (here the matrix of your data points). | Is Principal Component Analysis a parametric method? | PCA has nothing to do with the normality of your data. The principle is that you have a bunch of data points in a (high-dimensional) space and you want to see which directions or principal vectors can | Is Principal Component Analysis a parametric method?
PCA has nothing to do with the normality of your data. The principle is that you have a bunch of data points in a (high-dimensional) space and you want to see which directions or principal vectors can describe your data in an optimal way. It is virtually the same as the singular value decomposition and can be applied to any matrix (here the matrix of your data points). | Is Principal Component Analysis a parametric method?
PCA has nothing to do with the normality of your data. The principle is that you have a bunch of data points in a (high-dimensional) space and you want to see which directions or principal vectors can |
35,132 | High level overview of `auto.arima` with `xreg` predictors | I think the real question is not about auto.arima but rather about regression with ARMA errors as implemented in arima with exogenous regressors.
So how does forecasting auto.arima with xreg work? Do you create a forecast for a time series based on past data and regression model based on the input time series and input xreg, and then forecast each data point in the time series and for each forecasted data point use the regression model you built and future xreg values to adjust the forecasted values?
No, this is not how it works. It is simpler than that. Let us call the time series of interest $y$ and the exogenous regressors $X$. In a regression with ARMA errors as implemented in arima (and auto.arima) with xreg, the model equations are
$$
\begin{align}
y_t &= \beta' X_t + u_t \\
u_t &= \varphi_1 u_{t-1} + \dotsc + \varphi_p u_{t-p} + \varepsilon_t + \theta_1\varepsilon_{t-1} + \dotsc + \theta_q\varepsilon_{t-q}
\end{align}
$$
where $u_t$ is not $i.i.d.$ but $\varepsilon_t$ is.
The "main" equation is the upper one which specifies a linear relationship between $y_t$ and $X_t$ and looks very much like a regular regression model. The difference from a regular regression is made by the second equation that specifies the error term $u_t$ to follow an ARMA($p,q$) process (instead of $u_t$ being uncorrelated as would be the case in a regular regression). The second equation serves to "fix the problem with the first equation's errors". I like to think of this model as basically the good old regression but with unpleasant error pattern that needs to be accounted for.
How does auto.arima differ from arima in this case? auto.arima selects the optimal autoregressive and moving-average orders $p$ and $q$ based on a chosen information criterion (AICc by default, alternatively AIC or BIC) from a local search over a few regions of values. Meanwhile, arima requires the user to specify $p$ and $q$ manually.
How are these models fit? Generally, by maximum likelihood estimation. Refering to your three-step example algorithm, arima can be done in one step where all the parameters ($\beta$s, $\varphi$s and $\theta$s) are estimated at once together producing the fitted values $\hat y_t$ and the residuals $\hat\varepsilon_t$. auto.arima would do that multiple times as it tries out different values of $p$ and $q$.
See more in the Hyndman & Khandakar "Automatic time series forecasting: the forecast package for R" (2008). Also, try Rob J. Hyndman's blog post "The ARIMAX model muddle". | High level overview of `auto.arima` with `xreg` predictors | I think the real question is not about auto.arima but rather about regression with ARMA errors as implemented in arima with exogenous regressors.
So how does forecasting auto.arima with xreg work? D | High level overview of `auto.arima` with `xreg` predictors
I think the real question is not about auto.arima but rather about regression with ARMA errors as implemented in arima with exogenous regressors.
So how does forecasting auto.arima with xreg work? Do you create a forecast for a time series based on past data and regression model based on the input time series and input xreg, and then forecast each data point in the time series and for each forecasted data point use the regression model you built and future xreg values to adjust the forecasted values?
No, this is not how it works. It is simpler than that. Let us call the time series of interest $y$ and the exogenous regressors $X$. In a regression with ARMA errors as implemented in arima (and auto.arima) with xreg, the model equations are
$$
\begin{align}
y_t &= \beta' X_t + u_t \\
u_t &= \varphi_1 u_{t-1} + \dotsc + \varphi_p u_{t-p} + \varepsilon_t + \theta_1\varepsilon_{t-1} + \dotsc + \theta_q\varepsilon_{t-q}
\end{align}
$$
where $u_t$ is not $i.i.d.$ but $\varepsilon_t$ is.
The "main" equation is the upper one which specifies a linear relationship between $y_t$ and $X_t$ and looks very much like a regular regression model. The difference from a regular regression is made by the second equation that specifies the error term $u_t$ to follow an ARMA($p,q$) process (instead of $u_t$ being uncorrelated as would be the case in a regular regression). The second equation serves to "fix the problem with the first equation's errors". I like to think of this model as basically the good old regression but with unpleasant error pattern that needs to be accounted for.
How does auto.arima differ from arima in this case? auto.arima selects the optimal autoregressive and moving-average orders $p$ and $q$ based on a chosen information criterion (AICc by default, alternatively AIC or BIC) from a local search over a few regions of values. Meanwhile, arima requires the user to specify $p$ and $q$ manually.
How are these models fit? Generally, by maximum likelihood estimation. Refering to your three-step example algorithm, arima can be done in one step where all the parameters ($\beta$s, $\varphi$s and $\theta$s) are estimated at once together producing the fitted values $\hat y_t$ and the residuals $\hat\varepsilon_t$. auto.arima would do that multiple times as it tries out different values of $p$ and $q$.
See more in the Hyndman & Khandakar "Automatic time series forecasting: the forecast package for R" (2008). Also, try Rob J. Hyndman's blog post "The ARIMAX model muddle". | High level overview of `auto.arima` with `xreg` predictors
I think the real question is not about auto.arima but rather about regression with ARMA errors as implemented in arima with exogenous regressors.
So how does forecasting auto.arima with xreg work? D |
35,133 | Does the intercept in a logistic regression capture the unobserved effects? | Theoretically, does the intercept term in a logistic regression model capture all unobserved effects?
This is an interesting question, and I can see how with some simple experiments, one might think that this is the case. In fact, in my first attempt to set this up, I actually created a demonstration would only incorrectly estimate the intercept when I mis-specified the model -- otherwise, all coefficient estimates were fine!
In an OLS regression, the error term is where we would like for all of the effects for which we have not accounted to go... but if there are effects for which we have not accounted (i.e., the model is mis-specified) then they will tend to rear their heads in other features of the model, particularly if there are confounding relationships among variables. This is also true of all other conventional regression methods -- if the model is mis-specified, the coefficient estimates are not trustworthy (but perhaps the predictions will be helpful or the model serves some other useful purpose).
For example, here is a binomial model where there are just two features, and some dependence between them. I've rigged it such that the coefficients should be $\beta_0=10, \beta_1=-5, \beta_2=5.$ But if we omit $x_2$ from the model estimation, all of our coefficients are estimated incorrectly -- and wildly so!
set.seed(13)
N <- 100
inv_logit <- function(x){
ifelse(x< -20, -20, x)
out <- 1/(1+exp(-x))
return(out)
}
x0 <- rep(1, N)
x1 <- rnorm(N)
x2 <- rnorm(N, mean=10+3*x1-0.5*x1^2)
zTransform <- cbind(x0, x1, x2)%*%c(-10,-5,1)
summary(zTransform)
yObs <- rbinom(N, size=1, prob=inv_logit(zTransform))
badModel <- glm(yObs~x1, family=binomial(link="logit"))
summary(badModel)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -0.1404 0.2327 -0.604 0.546
x1 -1.3417 0.3041 -4.412 1.02e-05 ***
But if we correctly-specify the model, we get our coefficients back, but with some estimate error.
goodModel <- glm(yObs~x1+x2, family=binomial(link="logit"))
summary(goodModel)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -9.9512 2.9331 -3.393 0.000692 ***
x1 -4.8657 1.1918 -4.083 4.45e-05 ***
x2 0.9970 0.2948 3.382 0.000720 ***
In other words, in a logistic regression model with a perfect fit (i.e. all relevant variables are included), the intercept term should be zero right?
Why would this be the case? Suppose you're performing a logistic regression and you have no covariates -- for example, your experiment is rolling a die and every 6 is a "success", and every other outcome is a failure (perhaps you're doing quality assurance for a casino). If we assume that the dice are fair, you'd estimate the coefficient at some nonzero value purely because there are more unfavorable outcomes than favorable outcomes in your data.
It's important to understand that you've asked two different questions in your post. The first asks whether the intercept captures un-modeled effects (it doesn't! All coefficient estimates are wrong when the model is mis-specified!) The second question asks whether the intercept should be zero -- and the answer is also no, because the intercept term is fixed by the ratio of "successes" to "failures". | Does the intercept in a logistic regression capture the unobserved effects? | Theoretically, does the intercept term in a logistic regression model capture all unobserved effects?
This is an interesting question, and I can see how with some simple experiments, one might think | Does the intercept in a logistic regression capture the unobserved effects?
Theoretically, does the intercept term in a logistic regression model capture all unobserved effects?
This is an interesting question, and I can see how with some simple experiments, one might think that this is the case. In fact, in my first attempt to set this up, I actually created a demonstration would only incorrectly estimate the intercept when I mis-specified the model -- otherwise, all coefficient estimates were fine!
In an OLS regression, the error term is where we would like for all of the effects for which we have not accounted to go... but if there are effects for which we have not accounted (i.e., the model is mis-specified) then they will tend to rear their heads in other features of the model, particularly if there are confounding relationships among variables. This is also true of all other conventional regression methods -- if the model is mis-specified, the coefficient estimates are not trustworthy (but perhaps the predictions will be helpful or the model serves some other useful purpose).
For example, here is a binomial model where there are just two features, and some dependence between them. I've rigged it such that the coefficients should be $\beta_0=10, \beta_1=-5, \beta_2=5.$ But if we omit $x_2$ from the model estimation, all of our coefficients are estimated incorrectly -- and wildly so!
set.seed(13)
N <- 100
inv_logit <- function(x){
ifelse(x< -20, -20, x)
out <- 1/(1+exp(-x))
return(out)
}
x0 <- rep(1, N)
x1 <- rnorm(N)
x2 <- rnorm(N, mean=10+3*x1-0.5*x1^2)
zTransform <- cbind(x0, x1, x2)%*%c(-10,-5,1)
summary(zTransform)
yObs <- rbinom(N, size=1, prob=inv_logit(zTransform))
badModel <- glm(yObs~x1, family=binomial(link="logit"))
summary(badModel)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -0.1404 0.2327 -0.604 0.546
x1 -1.3417 0.3041 -4.412 1.02e-05 ***
But if we correctly-specify the model, we get our coefficients back, but with some estimate error.
goodModel <- glm(yObs~x1+x2, family=binomial(link="logit"))
summary(goodModel)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -9.9512 2.9331 -3.393 0.000692 ***
x1 -4.8657 1.1918 -4.083 4.45e-05 ***
x2 0.9970 0.2948 3.382 0.000720 ***
In other words, in a logistic regression model with a perfect fit (i.e. all relevant variables are included), the intercept term should be zero right?
Why would this be the case? Suppose you're performing a logistic regression and you have no covariates -- for example, your experiment is rolling a die and every 6 is a "success", and every other outcome is a failure (perhaps you're doing quality assurance for a casino). If we assume that the dice are fair, you'd estimate the coefficient at some nonzero value purely because there are more unfavorable outcomes than favorable outcomes in your data.
It's important to understand that you've asked two different questions in your post. The first asks whether the intercept captures un-modeled effects (it doesn't! All coefficient estimates are wrong when the model is mis-specified!) The second question asks whether the intercept should be zero -- and the answer is also no, because the intercept term is fixed by the ratio of "successes" to "failures". | Does the intercept in a logistic regression capture the unobserved effects?
Theoretically, does the intercept term in a logistic regression model capture all unobserved effects?
This is an interesting question, and I can see how with some simple experiments, one might think |
35,134 | Does the intercept in a logistic regression capture the unobserved effects? | I am not sure if any model, even a linear one, with a 'perfect' fit implies that the intercept term should be 0. It helps in these cases to think of a simple linear regression.
The way I understand the intercept is that it fixes some reasonable value for the y-variable. It just shows what value the y-variable takes even if all the x's are 0. There must be a good reason to think why this should be 0. I dont think it has anything to do with unobservables. In a linear model, it allows a) a better fit and b) ensures that the residuals sum to 1. | Does the intercept in a logistic regression capture the unobserved effects? | I am not sure if any model, even a linear one, with a 'perfect' fit implies that the intercept term should be 0. It helps in these cases to think of a simple linear regression.
The way I understand th | Does the intercept in a logistic regression capture the unobserved effects?
I am not sure if any model, even a linear one, with a 'perfect' fit implies that the intercept term should be 0. It helps in these cases to think of a simple linear regression.
The way I understand the intercept is that it fixes some reasonable value for the y-variable. It just shows what value the y-variable takes even if all the x's are 0. There must be a good reason to think why this should be 0. I dont think it has anything to do with unobservables. In a linear model, it allows a) a better fit and b) ensures that the residuals sum to 1. | Does the intercept in a logistic regression capture the unobserved effects?
I am not sure if any model, even a linear one, with a 'perfect' fit implies that the intercept term should be 0. It helps in these cases to think of a simple linear regression.
The way I understand th |
35,135 | Does the intercept in a logistic regression capture the unobserved effects? | in a logistic regression model with a perfect fit (i.e. all relevant variables are included), the intercept term should be zero right?
No. The intercept captures the constant part of the hazard. | Does the intercept in a logistic regression capture the unobserved effects? | in a logistic regression model with a perfect fit (i.e. all relevant variables are included), the intercept term should be zero right?
No. The intercept captures the constant part of the hazard. | Does the intercept in a logistic regression capture the unobserved effects?
in a logistic regression model with a perfect fit (i.e. all relevant variables are included), the intercept term should be zero right?
No. The intercept captures the constant part of the hazard. | Does the intercept in a logistic regression capture the unobserved effects?
in a logistic regression model with a perfect fit (i.e. all relevant variables are included), the intercept term should be zero right?
No. The intercept captures the constant part of the hazard. |
35,136 | Does the intercept in a logistic regression capture the unobserved effects? | The intercept allows the linear hyperplane to move "sideways". For instance, in one dimension it moves the sigmoid left and right, effectively changing the place the regression activates. | Does the intercept in a logistic regression capture the unobserved effects? | The intercept allows the linear hyperplane to move "sideways". For instance, in one dimension it moves the sigmoid left and right, effectively changing the place the regression activates. | Does the intercept in a logistic regression capture the unobserved effects?
The intercept allows the linear hyperplane to move "sideways". For instance, in one dimension it moves the sigmoid left and right, effectively changing the place the regression activates. | Does the intercept in a logistic regression capture the unobserved effects?
The intercept allows the linear hyperplane to move "sideways". For instance, in one dimension it moves the sigmoid left and right, effectively changing the place the regression activates. |
35,137 | Best modeling technique for predicting waiting times? | Waiting times can often be modelled by the exponential distribution, but this better describes the time between two events of the same type, e.g. it would probably nicely model the time between two subsequent questions.
The time to answer has some more complex properties:
There is a real chance of it never being answered
There will be some delay before an answer can realistically appear
Complex questions take longer (maybe approximately captured by #characters in question?)
For these reasons the exponential distribution won't be a perfect fit. The point about the delay is the most serious defect.
Survival analysis might be another option, but also hasn't got the "waiting" time for people to read and understand the question, before they can answer.
Other concerns include dependence on time of day and day of week. There could be spam bots that answers the question very quickly.
Since this is exploratory anyway, I would start by plotting the data. Start with some histograms of the time until an answer, look at how many never get answered. Go the same plots by time of day and day of week. See if there are differences. Then plan from there. | Best modeling technique for predicting waiting times? | Waiting times can often be modelled by the exponential distribution, but this better describes the time between two events of the same type, e.g. it would probably nicely model the time between two su | Best modeling technique for predicting waiting times?
Waiting times can often be modelled by the exponential distribution, but this better describes the time between two events of the same type, e.g. it would probably nicely model the time between two subsequent questions.
The time to answer has some more complex properties:
There is a real chance of it never being answered
There will be some delay before an answer can realistically appear
Complex questions take longer (maybe approximately captured by #characters in question?)
For these reasons the exponential distribution won't be a perfect fit. The point about the delay is the most serious defect.
Survival analysis might be another option, but also hasn't got the "waiting" time for people to read and understand the question, before they can answer.
Other concerns include dependence on time of day and day of week. There could be spam bots that answers the question very quickly.
Since this is exploratory anyway, I would start by plotting the data. Start with some histograms of the time until an answer, look at how many never get answered. Go the same plots by time of day and day of week. See if there are differences. Then plan from there. | Best modeling technique for predicting waiting times?
Waiting times can often be modelled by the exponential distribution, but this better describes the time between two events of the same type, e.g. it would probably nicely model the time between two su |
35,138 | Best modeling technique for predicting waiting times? | I have accepted an answer above and am only writing this as an answer because I think my research could be beneficial to other Python users.
The comments and answers above helpfully directed me towards Survival Analysis. After exploring the modelling options in StatsModels, I then discovered the library Lifelines by Cameron Davidson Pilon (@Cam.Davidson.Pilon).
I can thoroughly recommend Lifelines to anyone looking to do duration-based analysis in Python. It's excellent in many ways. I particularly like the way it addresses - both theoretically and practically - the concept of Censorship. Given how elegant and effective the library is, and how broad the applications of Survival Analysis are, I'm somewhat surprised Lifelines isn't better known.
I can also recommend watching this introductory talk. It got me up and running with Lifelines in no time. | Best modeling technique for predicting waiting times? | I have accepted an answer above and am only writing this as an answer because I think my research could be beneficial to other Python users.
The comments and answers above helpfully directed me towar | Best modeling technique for predicting waiting times?
I have accepted an answer above and am only writing this as an answer because I think my research could be beneficial to other Python users.
The comments and answers above helpfully directed me towards Survival Analysis. After exploring the modelling options in StatsModels, I then discovered the library Lifelines by Cameron Davidson Pilon (@Cam.Davidson.Pilon).
I can thoroughly recommend Lifelines to anyone looking to do duration-based analysis in Python. It's excellent in many ways. I particularly like the way it addresses - both theoretically and practically - the concept of Censorship. Given how elegant and effective the library is, and how broad the applications of Survival Analysis are, I'm somewhat surprised Lifelines isn't better known.
I can also recommend watching this introductory talk. It got me up and running with Lifelines in no time. | Best modeling technique for predicting waiting times?
I have accepted an answer above and am only writing this as an answer because I think my research could be beneficial to other Python users.
The comments and answers above helpfully directed me towar |
35,139 | Fisher's tea tasting, binomial exact test | This is a good idea, but the lady knows that there are 4 cup of tea for each type. This is a valuable information for the lady, which makes things wrong if we model the process via a binomial distribution. The problem is that the variables (successes at each trial) you want to consider are not independent and identically distributed.
I think you have thought to model the process by at least one of these cases:
Case 1: You study the number of success among the 4 selected cups.
Under this representation the statistic is 4 success over 4 trials. Under the null, each one would have a probability of 0.5 to be milk-first. This is mathematically right, but these probabilities are not independents.
Illustration: If the cup A,B and C are mistakes, there are good chances that the last one is a good one because among the 5 remaining cups, there are 4 milk-first cups remaining and only one milk-after cup.
Case 2: You study the number of success among the 8 presented cups.
Under this representation the statistic is 8 successes over 8 trials. This is the same problem of non independence.
Illustration: If she judged well the first 7 cups, the probability that she also judge well the last cup is 1. Because, relatively to the experimental setting, by elimination, there is no possibility that the lady is right about 7 cups and wrong about one.
In more mathematical term, for both cases, $\newcommand{\success}{\rm success}P(\success_i)$ is not independent with $P(\success_j)$.
Fisher avoided this problem by considering the selection process as a whole, enumerating the number of successful selections (well, only one) divided by the number of possible selections (4 amongst 8 = 70).
Still, there is a simple raw formula which takes into account non independence, less beautiful than Fisher solution though:
\begin{align}
P(\success) &= P(X_1=1)\times P(X_2=1|X_1=1)\times \\
&\quad\ \ P(X_3=1|X_1=1 \cap X_2=1)\times \\
&\quad\ \ P(X_4=1|X_1=1 \cap X_2=1 \cap X_3=1) \\
&= 4/8\times 3/7\times 2/6\times 1/5 \\
&= 1/70
\end{align}
A binomial test would be the correct answer to another kind of setting like this one I just made up.
The judge toss a fair coin, if tails he prepares a milk-first tea, if head a milk-after tea. Obviously the lady does not know the result of the coin toss.
The lady knows the process and will have to judge which kind of cup of tea was served.
With this setting, a binomial test, as you described it, with $H_0$: success rate = 0.5, would be undeniably a good approach. | Fisher's tea tasting, binomial exact test | This is a good idea, but the lady knows that there are 4 cup of tea for each type. This is a valuable information for the lady, which makes things wrong if we model the process via a binomial distribu | Fisher's tea tasting, binomial exact test
This is a good idea, but the lady knows that there are 4 cup of tea for each type. This is a valuable information for the lady, which makes things wrong if we model the process via a binomial distribution. The problem is that the variables (successes at each trial) you want to consider are not independent and identically distributed.
I think you have thought to model the process by at least one of these cases:
Case 1: You study the number of success among the 4 selected cups.
Under this representation the statistic is 4 success over 4 trials. Under the null, each one would have a probability of 0.5 to be milk-first. This is mathematically right, but these probabilities are not independents.
Illustration: If the cup A,B and C are mistakes, there are good chances that the last one is a good one because among the 5 remaining cups, there are 4 milk-first cups remaining and only one milk-after cup.
Case 2: You study the number of success among the 8 presented cups.
Under this representation the statistic is 8 successes over 8 trials. This is the same problem of non independence.
Illustration: If she judged well the first 7 cups, the probability that she also judge well the last cup is 1. Because, relatively to the experimental setting, by elimination, there is no possibility that the lady is right about 7 cups and wrong about one.
In more mathematical term, for both cases, $\newcommand{\success}{\rm success}P(\success_i)$ is not independent with $P(\success_j)$.
Fisher avoided this problem by considering the selection process as a whole, enumerating the number of successful selections (well, only one) divided by the number of possible selections (4 amongst 8 = 70).
Still, there is a simple raw formula which takes into account non independence, less beautiful than Fisher solution though:
\begin{align}
P(\success) &= P(X_1=1)\times P(X_2=1|X_1=1)\times \\
&\quad\ \ P(X_3=1|X_1=1 \cap X_2=1)\times \\
&\quad\ \ P(X_4=1|X_1=1 \cap X_2=1 \cap X_3=1) \\
&= 4/8\times 3/7\times 2/6\times 1/5 \\
&= 1/70
\end{align}
A binomial test would be the correct answer to another kind of setting like this one I just made up.
The judge toss a fair coin, if tails he prepares a milk-first tea, if head a milk-after tea. Obviously the lady does not know the result of the coin toss.
The lady knows the process and will have to judge which kind of cup of tea was served.
With this setting, a binomial test, as you described it, with $H_0$: success rate = 0.5, would be undeniably a good approach. | Fisher's tea tasting, binomial exact test
This is a good idea, but the lady knows that there are 4 cup of tea for each type. This is a valuable information for the lady, which makes things wrong if we model the process via a binomial distribu |
35,140 | How large does a Poisson distribution's mean need to be to use normal distribution statistics? | Update: As @whuber has pointed out with his comments, a better way to look at this is by computing the true coverage probabilities for the Poisson. The simulation, while also with its uses, does not reveal the interesting pattern seen in the plot below.
This was based on @whuber's code (see his first comment on this answer):
f <- function(mu) ppois(mu + sqrt(mu), mu) - ppois(mu - sqrt(mu), mu) ## computing coverage probabilities as a function of the true mean
curve(f, from = 1, to = 2000, n = 300, main = "True Coverage Probabilities for Poisson", xlab = expression(lambda), ylab = "Probability")
abline(h = 0.6827, col = "red") ## coverage prob. for a Normal RV
What this does:
If $X \sim \textrm{Pois}(\lambda)$ then $E(X) = \lambda$ and $V(X) = \lambda$. This means that the interval in question is $I := (\lambda - \sqrt \lambda, \lambda + \sqrt \lambda)$. The function f computes
$$
\mathbb P_\lambda(X \in I) = F_X(\lambda + \sqrt \lambda; \lambda) - F_X(\lambda - \sqrt \lambda; \lambda)
$$
where in R $F_X(t; \lambda)$ is obtained via the ppois function.
Original answer:
This is in no way a categorical answer but I thought you might like to see a simulation. Note that I'm using samples of size $n = 20000$ because you didn't mention that you cared about the sample size, so I wanted each sample to reflect asymptotic properties.
The simulation shows that the Poisson random variables (RVs) do not behave indistinguishably from the Normal RVs until around $\lambda \approx 1000$ with respect to the coverage rate and this choice of $n$. We can also see the variation in the coverage of random samples of Normal RVs even though they all exactly have the property that we are investigating at the population level. Note that in this simulation I compared a random sample to its sample mean and sample standard deviation rather than the population mean and population standard deviation. I chose to do so because I felt this to be more interesting for a discussion about the distribution of a statistic calculated from a sample.
Here's the code to make the plot.
set.seed(1)
lambda.seq <- round(seq(10, 2000, length = 300)) ## lambdas to try
res.norm <- res.pois <- numeric(length(lambda.seq)) ## these get the results
nsim <- 20000 ## number of observations at each iteration
for(i in 1:length(lambda.seq))
{
sims <- rpois(nsim, lambda.seq[i]) ## simulating Poissons
res.pois[i] <- mean(sims > mean(sims) - sd(sims) & sims < mean(sims) + sd(sims)) ## computing proportion of Poisson RVs within 1 SE of the mean
sims <- rnorm(nsim, lambda.seq[i], lambda.seq[i]) ## simulating normals
res.norm[i] <- mean(sims > mean(sims) - sd(sims) & sims < mean(sims) + sd(sims))
}
plot(res.pois ~ lambda.seq, pch = 19, col = "red", main = "1 SD Coverage Convergence of Poisson to Normal", xlab = expression(lambda), ylab = expression(paste("Proportion within ", mu, " \u00b1 ", sigma, sep = "")))
points(res.norm ~ lambda.seq, pch = 19, col = "blue")
abline(h = .6827) ## this is the true coverage for a normal distribution
legend("topright", c("Poisson", "Normal"), pch = 19, col = c("red", "blue"), bty = "n") | How large does a Poisson distribution's mean need to be to use normal distribution statistics? | Update: As @whuber has pointed out with his comments, a better way to look at this is by computing the true coverage probabilities for the Poisson. The simulation, while also with its uses, does not r | How large does a Poisson distribution's mean need to be to use normal distribution statistics?
Update: As @whuber has pointed out with his comments, a better way to look at this is by computing the true coverage probabilities for the Poisson. The simulation, while also with its uses, does not reveal the interesting pattern seen in the plot below.
This was based on @whuber's code (see his first comment on this answer):
f <- function(mu) ppois(mu + sqrt(mu), mu) - ppois(mu - sqrt(mu), mu) ## computing coverage probabilities as a function of the true mean
curve(f, from = 1, to = 2000, n = 300, main = "True Coverage Probabilities for Poisson", xlab = expression(lambda), ylab = "Probability")
abline(h = 0.6827, col = "red") ## coverage prob. for a Normal RV
What this does:
If $X \sim \textrm{Pois}(\lambda)$ then $E(X) = \lambda$ and $V(X) = \lambda$. This means that the interval in question is $I := (\lambda - \sqrt \lambda, \lambda + \sqrt \lambda)$. The function f computes
$$
\mathbb P_\lambda(X \in I) = F_X(\lambda + \sqrt \lambda; \lambda) - F_X(\lambda - \sqrt \lambda; \lambda)
$$
where in R $F_X(t; \lambda)$ is obtained via the ppois function.
Original answer:
This is in no way a categorical answer but I thought you might like to see a simulation. Note that I'm using samples of size $n = 20000$ because you didn't mention that you cared about the sample size, so I wanted each sample to reflect asymptotic properties.
The simulation shows that the Poisson random variables (RVs) do not behave indistinguishably from the Normal RVs until around $\lambda \approx 1000$ with respect to the coverage rate and this choice of $n$. We can also see the variation in the coverage of random samples of Normal RVs even though they all exactly have the property that we are investigating at the population level. Note that in this simulation I compared a random sample to its sample mean and sample standard deviation rather than the population mean and population standard deviation. I chose to do so because I felt this to be more interesting for a discussion about the distribution of a statistic calculated from a sample.
Here's the code to make the plot.
set.seed(1)
lambda.seq <- round(seq(10, 2000, length = 300)) ## lambdas to try
res.norm <- res.pois <- numeric(length(lambda.seq)) ## these get the results
nsim <- 20000 ## number of observations at each iteration
for(i in 1:length(lambda.seq))
{
sims <- rpois(nsim, lambda.seq[i]) ## simulating Poissons
res.pois[i] <- mean(sims > mean(sims) - sd(sims) & sims < mean(sims) + sd(sims)) ## computing proportion of Poisson RVs within 1 SE of the mean
sims <- rnorm(nsim, lambda.seq[i], lambda.seq[i]) ## simulating normals
res.norm[i] <- mean(sims > mean(sims) - sd(sims) & sims < mean(sims) + sd(sims))
}
plot(res.pois ~ lambda.seq, pch = 19, col = "red", main = "1 SD Coverage Convergence of Poisson to Normal", xlab = expression(lambda), ylab = expression(paste("Proportion within ", mu, " \u00b1 ", sigma, sep = "")))
points(res.norm ~ lambda.seq, pch = 19, col = "blue")
abline(h = .6827) ## this is the true coverage for a normal distribution
legend("topright", c("Poisson", "Normal"), pch = 19, col = c("red", "blue"), bty = "n") | How large does a Poisson distribution's mean need to be to use normal distribution statistics?
Update: As @whuber has pointed out with his comments, a better way to look at this is by computing the true coverage probabilities for the Poisson. The simulation, while also with its uses, does not r |
35,141 | How large does a Poisson distribution's mean need to be to use normal distribution statistics? | Here's another perspective. Let's say you want to approximate cdf values of a Poisson with a normal fit. You didn't specify a desired accuracy, so I'll just give an example. Suppose you want to be within 0.01 of the true cdf at all points.
Empirically, if $\lambda$ is the mean of the Poisson, I observe that $\lambda \geq 44$ is enough to get the stated accuracy by matching the mean and variance of the normal to the Poisson and using a continuity correction. | How large does a Poisson distribution's mean need to be to use normal distribution statistics? | Here's another perspective. Let's say you want to approximate cdf values of a Poisson with a normal fit. You didn't specify a desired accuracy, so I'll just give an example. Suppose you want to be wit | How large does a Poisson distribution's mean need to be to use normal distribution statistics?
Here's another perspective. Let's say you want to approximate cdf values of a Poisson with a normal fit. You didn't specify a desired accuracy, so I'll just give an example. Suppose you want to be within 0.01 of the true cdf at all points.
Empirically, if $\lambda$ is the mean of the Poisson, I observe that $\lambda \geq 44$ is enough to get the stated accuracy by matching the mean and variance of the normal to the Poisson and using a continuity correction. | How large does a Poisson distribution's mean need to be to use normal distribution statistics?
Here's another perspective. Let's say you want to approximate cdf values of a Poisson with a normal fit. You didn't specify a desired accuracy, so I'll just give an example. Suppose you want to be wit |
35,142 | How large does a Poisson distribution's mean need to be to use normal distribution statistics? | To really answer we need to know what you want to do! If you want a confidence interval, say, more might be needed than for standard errors. But why do you want a normal approximation? You can construct confidence intervals directly from the likelihood function, which probably is better.
And, note that for the poisson distribution, the variance is equal to the expectation. So with increasing $\lambda$ (the expectation) the variance is increasing as well. For confidence intervals you really want a pivotal quantity ( a pivot is a function of data and parameters with a distribution not depending on the parameters), or, if that is impossible (as in most discrete distribution cases), at least with constant expectation and variance.
One way to obtain that is to use a variance-stabilizing transformation, which in the Poisson case is the square root transformation. So, if $X$ is Poisson ($\lambda$) then $\sqrt{X}$ have variance approximately 1/4. A normal approximation for the transformed variable usually works better, as it is closer to pivotal.
Also have a look at the post GLM vs square root data transformation | How large does a Poisson distribution's mean need to be to use normal distribution statistics? | To really answer we need to know what you want to do! If you want a confidence interval, say, more might be needed than for standard errors. But why do you want a normal approximation? You can constr | How large does a Poisson distribution's mean need to be to use normal distribution statistics?
To really answer we need to know what you want to do! If you want a confidence interval, say, more might be needed than for standard errors. But why do you want a normal approximation? You can construct confidence intervals directly from the likelihood function, which probably is better.
And, note that for the poisson distribution, the variance is equal to the expectation. So with increasing $\lambda$ (the expectation) the variance is increasing as well. For confidence intervals you really want a pivotal quantity ( a pivot is a function of data and parameters with a distribution not depending on the parameters), or, if that is impossible (as in most discrete distribution cases), at least with constant expectation and variance.
One way to obtain that is to use a variance-stabilizing transformation, which in the Poisson case is the square root transformation. So, if $X$ is Poisson ($\lambda$) then $\sqrt{X}$ have variance approximately 1/4. A normal approximation for the transformed variable usually works better, as it is closer to pivotal.
Also have a look at the post GLM vs square root data transformation | How large does a Poisson distribution's mean need to be to use normal distribution statistics?
To really answer we need to know what you want to do! If you want a confidence interval, say, more might be needed than for standard errors. But why do you want a normal approximation? You can constr |
35,143 | How to interpret modification indices output of structural equation models? | In most CFA analyses, the chi sq value will not reach p>.05, especially if you have a large N. Most people look for CMIN, i.e., chisq/df, of <3, or the change in chi sq between nested models, i.e., two models with a minor change in structure, the chi sq for this being (diff in chisq) with (diff in df) df.
The Modification Indices suggest links to change in your structure. Do this incrementally, checking the change in chi sq after each one, to see if it has really helped. You should only make changes that are theoretically sensible, in terms of your model. Start with the largest sensible modofication.
The MIs with the =~ operator are most use, as these are between latent (endogenous) and observed (exogenous) variables.
Once you have exhausted these, the ~~ operators indicate additional links between factors, or error variances. Be careful here. Most analysts accept adding links between error variances for observed variables that form the same latent variable, or for observed variables that have some relationship not captured by the latent variables in the model (e.g., measurement method, perhaps). | How to interpret modification indices output of structural equation models? | In most CFA analyses, the chi sq value will not reach p>.05, especially if you have a large N. Most people look for CMIN, i.e., chisq/df, of <3, or the change in chi sq between nested models, i.e., tw | How to interpret modification indices output of structural equation models?
In most CFA analyses, the chi sq value will not reach p>.05, especially if you have a large N. Most people look for CMIN, i.e., chisq/df, of <3, or the change in chi sq between nested models, i.e., two models with a minor change in structure, the chi sq for this being (diff in chisq) with (diff in df) df.
The Modification Indices suggest links to change in your structure. Do this incrementally, checking the change in chi sq after each one, to see if it has really helped. You should only make changes that are theoretically sensible, in terms of your model. Start with the largest sensible modofication.
The MIs with the =~ operator are most use, as these are between latent (endogenous) and observed (exogenous) variables.
Once you have exhausted these, the ~~ operators indicate additional links between factors, or error variances. Be careful here. Most analysts accept adding links between error variances for observed variables that form the same latent variable, or for observed variables that have some relationship not captured by the latent variables in the model (e.g., measurement method, perhaps). | How to interpret modification indices output of structural equation models?
In most CFA analyses, the chi sq value will not reach p>.05, especially if you have a large N. Most people look for CMIN, i.e., chisq/df, of <3, or the change in chi sq between nested models, i.e., tw |
35,144 | How to interpret modification indices output of structural equation models? | The model is actually not that good. See, you have a chi-square of 85.306 with p-value of 0.000. You want it to be not statistically significant instead. Also, the other fit indices are easier to interpret when comparing two different models. By themselves they mean little to nothing. Some authors have suggested that RMSEA below .08 can be used to argue for good fit, but that is not agreed upon in the field and your RMSEA is above that threshold.
Improving your model by fiddling with MI
Some authors do not recommend trying to improve your model by fiddling with MI scores. However, AFAIK the bigger the mi value, the most influential is the variable.
You can spot those variables by running:
mod_ind <- modificationindices(fit)
Spoting the top 10:
head(mod_ind[order(mod_ind$mi, decreasing=TRUE), ], 10)
And the bigger than 5:
subset(mod_ind[order(mod_ind$mi, decreasing=TRUE), ], mi > 5)
Again, this should only be done if you have a hypothesis for what might be going on in the data.
Here is the reference to the code: http://jeromyanglim.tumblr.com/post/33556941601/lavaan-cheat-sheet | How to interpret modification indices output of structural equation models? | The model is actually not that good. See, you have a chi-square of 85.306 with p-value of 0.000. You want it to be not statistically significant instead. Also, the other fit indices are easier to inte | How to interpret modification indices output of structural equation models?
The model is actually not that good. See, you have a chi-square of 85.306 with p-value of 0.000. You want it to be not statistically significant instead. Also, the other fit indices are easier to interpret when comparing two different models. By themselves they mean little to nothing. Some authors have suggested that RMSEA below .08 can be used to argue for good fit, but that is not agreed upon in the field and your RMSEA is above that threshold.
Improving your model by fiddling with MI
Some authors do not recommend trying to improve your model by fiddling with MI scores. However, AFAIK the bigger the mi value, the most influential is the variable.
You can spot those variables by running:
mod_ind <- modificationindices(fit)
Spoting the top 10:
head(mod_ind[order(mod_ind$mi, decreasing=TRUE), ], 10)
And the bigger than 5:
subset(mod_ind[order(mod_ind$mi, decreasing=TRUE), ], mi > 5)
Again, this should only be done if you have a hypothesis for what might be going on in the data.
Here is the reference to the code: http://jeromyanglim.tumblr.com/post/33556941601/lavaan-cheat-sheet | How to interpret modification indices output of structural equation models?
The model is actually not that good. See, you have a chi-square of 85.306 with p-value of 0.000. You want it to be not statistically significant instead. Also, the other fit indices are easier to inte |
35,145 | Regularization and projection onto the $l_*$ ball | Regularization and vector projections are connected through the idea of constrained optimization and the Karush-Kuhn (no relation)-Tucker conditions.
What are the KKT conditions?
Briefly, these state that, if $x$ is a solution to the problem "minimize $f(x)$ subject to $g(x) \le 0$", then $x$ is also a solution to the problem $\nabla f(x) = \lambda \nabla g(x)$ for some scalar $\lambda$. But this is equivalent to saying $\nabla f(x) - \lambda \nabla g(x) = 0$, which means that $x$ minimizes the unconstrained optimization problem "minimize $f(x) - \lambda g(x)$".
The intuition is that either:
$g(x) < 0$. In this case, $x$ is an "interior solution" so the gradient of $f$ must be zero at that point. (If it weren't zero, we could move a little bit in that direction from $x$, while maintaining $g(x) < 0$, and have a higher value for $f(x)$. Then we set $\lambda = 0$ and we're done.
Or, $g(x) = 0$. In this case, $x$ is on the edge of the possible solution space. Locally, this edge looks like a hyperplane orthogonal to the gradient $\nabla g(x)$, because the way you maintain the $g(x) = 0$ constraint is to not move up or down the gradient at all. But that means that the only direction the gradient $\nabla f$ could possibly point is the exact same direction as $\nabla g$--if it had any component that was orthogonal to $\nabla g$, we could move $x$ a little bit in that direction, stay on the orthogonal hyperplane $g(x) = 0$, and increase $f(x)$.
How the KKT conditions explain the relationship between constrained minimization and regularization
If $g(x) = |x| - c$ for some norm and some constant $c$, then the constraint $g(x) \le 0$ means that $x$ lies on a sphere of radius $c$ under that norm. And in the unconstrained formulation, subtracting $\lambda g(x)$ from the function you want to maximize is what ends up applying the regularization penalty: you're really subtracting $\lambda |x| + \lambda c$ (and the constant $\lambda c$ doesn't matter for optimization).
People often take advantage of this "duality" between unconstrained and constrained optimization. For an example that I could find quickly by Googling see On the LASSO and its dual.
Why are projections important here?
OK, so why is someone writing a paper on fast projections, though?
Basically, one way you can do general constrained optimization--"maximize $f(x)$ subject to $x \in X$"-- is to do the following:
Take any iterative algorithm for unconstrained maximization of $f(x)$
Start with a guess $x_0$
Take one step of the algorithm: $x_0^\prime \leftarrow step(x_0)$
Then project back onto the set $X$: $x_1 \leftarrow P_X(x_0^\prime)$.
And repeat until convergence.
For instance, this is how projected gradient descent is derived from ordinary gradient descent. Of course, optimizing your projection function $P_X$ is vitally important here.
Putting it all together
So, suppose that you want to solve the LASSO: $$\arg\min_\beta (\mathbf{y} - \beta^\prime \mathbf{X})^2 + \lambda ||\beta||_1$$
That's the unconstrained version. By the KKT conditions, adding the regularization term is equivalent to constraining the solution to lie in $||\beta||_1 \le c$ for some constant $c$. But that's just the $\ell_1$-ball with radius $c$!
So you could imagine solving this with projected (sub)gradient descent.* If you did, your $P_X$ function would be a projection onto the unit ball, and you want to make that fast.
*I don't think people actually do this, because there are more efficient ways. But those might use projections also. EDIT: as @Dougal points out, a more sophisticated variant of projected subgradient descent was good enough to write a paper about in 2008. | Regularization and projection onto the $l_*$ ball | Regularization and vector projections are connected through the idea of constrained optimization and the Karush-Kuhn (no relation)-Tucker conditions.
What are the KKT conditions?
Briefly, these state | Regularization and projection onto the $l_*$ ball
Regularization and vector projections are connected through the idea of constrained optimization and the Karush-Kuhn (no relation)-Tucker conditions.
What are the KKT conditions?
Briefly, these state that, if $x$ is a solution to the problem "minimize $f(x)$ subject to $g(x) \le 0$", then $x$ is also a solution to the problem $\nabla f(x) = \lambda \nabla g(x)$ for some scalar $\lambda$. But this is equivalent to saying $\nabla f(x) - \lambda \nabla g(x) = 0$, which means that $x$ minimizes the unconstrained optimization problem "minimize $f(x) - \lambda g(x)$".
The intuition is that either:
$g(x) < 0$. In this case, $x$ is an "interior solution" so the gradient of $f$ must be zero at that point. (If it weren't zero, we could move a little bit in that direction from $x$, while maintaining $g(x) < 0$, and have a higher value for $f(x)$. Then we set $\lambda = 0$ and we're done.
Or, $g(x) = 0$. In this case, $x$ is on the edge of the possible solution space. Locally, this edge looks like a hyperplane orthogonal to the gradient $\nabla g(x)$, because the way you maintain the $g(x) = 0$ constraint is to not move up or down the gradient at all. But that means that the only direction the gradient $\nabla f$ could possibly point is the exact same direction as $\nabla g$--if it had any component that was orthogonal to $\nabla g$, we could move $x$ a little bit in that direction, stay on the orthogonal hyperplane $g(x) = 0$, and increase $f(x)$.
How the KKT conditions explain the relationship between constrained minimization and regularization
If $g(x) = |x| - c$ for some norm and some constant $c$, then the constraint $g(x) \le 0$ means that $x$ lies on a sphere of radius $c$ under that norm. And in the unconstrained formulation, subtracting $\lambda g(x)$ from the function you want to maximize is what ends up applying the regularization penalty: you're really subtracting $\lambda |x| + \lambda c$ (and the constant $\lambda c$ doesn't matter for optimization).
People often take advantage of this "duality" between unconstrained and constrained optimization. For an example that I could find quickly by Googling see On the LASSO and its dual.
Why are projections important here?
OK, so why is someone writing a paper on fast projections, though?
Basically, one way you can do general constrained optimization--"maximize $f(x)$ subject to $x \in X$"-- is to do the following:
Take any iterative algorithm for unconstrained maximization of $f(x)$
Start with a guess $x_0$
Take one step of the algorithm: $x_0^\prime \leftarrow step(x_0)$
Then project back onto the set $X$: $x_1 \leftarrow P_X(x_0^\prime)$.
And repeat until convergence.
For instance, this is how projected gradient descent is derived from ordinary gradient descent. Of course, optimizing your projection function $P_X$ is vitally important here.
Putting it all together
So, suppose that you want to solve the LASSO: $$\arg\min_\beta (\mathbf{y} - \beta^\prime \mathbf{X})^2 + \lambda ||\beta||_1$$
That's the unconstrained version. By the KKT conditions, adding the regularization term is equivalent to constraining the solution to lie in $||\beta||_1 \le c$ for some constant $c$. But that's just the $\ell_1$-ball with radius $c$!
So you could imagine solving this with projected (sub)gradient descent.* If you did, your $P_X$ function would be a projection onto the unit ball, and you want to make that fast.
*I don't think people actually do this, because there are more efficient ways. But those might use projections also. EDIT: as @Dougal points out, a more sophisticated variant of projected subgradient descent was good enough to write a paper about in 2008. | Regularization and projection onto the $l_*$ ball
Regularization and vector projections are connected through the idea of constrained optimization and the Karush-Kuhn (no relation)-Tucker conditions.
What are the KKT conditions?
Briefly, these state |
35,146 | Stopping conditions in coin flipping sequence | The probability of "success" (heads, making a basket, etc.) is the limiting ratio of the number of successes to the number of trials, $p$.
One way to run your simulation is to generate a very long sequence of independent binary trials with underlying success probability $p$. Scan across the sequence, looking for the stopping sequence $S$ (where $S$ is one success, in the case of the birth problem, or three failures in a row, in the basketball problem, for example). Immediately after the end of each appearance of $S$ declare the beginning of a new experiment.
For example, here is the beginning of such a sequence with $p=1/3$, 1 designating success and 0 failure, with $S$ set to 010:
10010 010 0010 1010 10000011010 11110
| | | | |
The ticks mark the endpoints of each experiment. The last five results (11110) would be thrown away in this short simulation because the experiment of which they are part did not end, leaving $27$ independent random values comprising five full experiments. Out of these $27$ values, $10$ were successes, in proportion $10/27$ (which is consistent with $p=1/3 = 9/27$ but varies from it due to chance).
Notice that the stopping rule changes the sequence not one whit: it merely marks the boundaries between successive experiments.
In a finite simulation you will have to throw away all the results after the last appearance of $S$, but as the simulation grows ever longer the chance that these abandoned results constitute any appreciable proportion of all the results shrinks to zero.
Consequently, the proportion of successes in your simulation cannot be any different (in the limit as the number of trials grows large) than the proportion of successes in a long independent sequence of results: it will not deviate from $p$ by any more than chance permits. | Stopping conditions in coin flipping sequence | The probability of "success" (heads, making a basket, etc.) is the limiting ratio of the number of successes to the number of trials, $p$.
One way to run your simulation is to generate a very long seq | Stopping conditions in coin flipping sequence
The probability of "success" (heads, making a basket, etc.) is the limiting ratio of the number of successes to the number of trials, $p$.
One way to run your simulation is to generate a very long sequence of independent binary trials with underlying success probability $p$. Scan across the sequence, looking for the stopping sequence $S$ (where $S$ is one success, in the case of the birth problem, or three failures in a row, in the basketball problem, for example). Immediately after the end of each appearance of $S$ declare the beginning of a new experiment.
For example, here is the beginning of such a sequence with $p=1/3$, 1 designating success and 0 failure, with $S$ set to 010:
10010 010 0010 1010 10000011010 11110
| | | | |
The ticks mark the endpoints of each experiment. The last five results (11110) would be thrown away in this short simulation because the experiment of which they are part did not end, leaving $27$ independent random values comprising five full experiments. Out of these $27$ values, $10$ were successes, in proportion $10/27$ (which is consistent with $p=1/3 = 9/27$ but varies from it due to chance).
Notice that the stopping rule changes the sequence not one whit: it merely marks the boundaries between successive experiments.
In a finite simulation you will have to throw away all the results after the last appearance of $S$, but as the simulation grows ever longer the chance that these abandoned results constitute any appreciable proportion of all the results shrinks to zero.
Consequently, the proportion of successes in your simulation cannot be any different (in the limit as the number of trials grows large) than the proportion of successes in a long independent sequence of results: it will not deviate from $p$ by any more than chance permits. | Stopping conditions in coin flipping sequence
The probability of "success" (heads, making a basket, etc.) is the limiting ratio of the number of successes to the number of trials, $p$.
One way to run your simulation is to generate a very long seq |
35,147 | Stopping conditions in coin flipping sequence | I thought of an intuitive way to explain this (and answer my own question). It turns out that if you just ignore the stopping and see this problem as a sum of concatenated sequences, it becomes clear that it doesn't matter.
Imagine we get the following sequences stopping after 3 successive misses:
1 0 1 0 0 0
1 0 1 1 0 1 0 0 0
0 0 0
1 0 0 0
Now, you can see if you simply concatenate these sequences, the overall proportion of 1's and 0's is the same as if you flipped all in the same sequence. The "stopping" doesn't matter at all. It's just a mental break in the sequence.
1 0 1 0 0 0 1 0 1 1 0 1 0 0 0 0 0 0 1 0 0 0
There you have the same number of 1's and 0's. The stopping condition is a red herring. | Stopping conditions in coin flipping sequence | I thought of an intuitive way to explain this (and answer my own question). It turns out that if you just ignore the stopping and see this problem as a sum of concatenated sequences, it becomes clear | Stopping conditions in coin flipping sequence
I thought of an intuitive way to explain this (and answer my own question). It turns out that if you just ignore the stopping and see this problem as a sum of concatenated sequences, it becomes clear that it doesn't matter.
Imagine we get the following sequences stopping after 3 successive misses:
1 0 1 0 0 0
1 0 1 1 0 1 0 0 0
0 0 0
1 0 0 0
Now, you can see if you simply concatenate these sequences, the overall proportion of 1's and 0's is the same as if you flipped all in the same sequence. The "stopping" doesn't matter at all. It's just a mental break in the sequence.
1 0 1 0 0 0 1 0 1 1 0 1 0 0 0 0 0 0 1 0 0 0
There you have the same number of 1's and 0's. The stopping condition is a red herring. | Stopping conditions in coin flipping sequence
I thought of an intuitive way to explain this (and answer my own question). It turns out that if you just ignore the stopping and see this problem as a sum of concatenated sequences, it becomes clear |
35,148 | Null distribution of subspaces similarity, or what is the distribution of $\mathrm{tr}(AA'BB')$? | I have once asked a question that is essentially a special case of yours when $k=1$: Distribution of a scalar product of two random unit vectors in $\mathbb{R}^D$. @whuber gave an excellent answer, where he explains that a dot product equals $t=2u-1$, where $$u\sim \mathrm{Beta}((d-1)/2,(d-1)/2)$$ and $d$ is the dimensionality of the space. It follows that $\mathrm{Var}[t]=1/d$ (one can also show this directly, see the answer by @Student001 in the linked thread).
Your question is about a random variable $$w=\mathrm{tr}(AA^\top BB^\top) = \|A^\top B\|^2,$$ where $A$ and $B$ are $d\times k$ matrices with orthonormal columns. Note that $A^\top B$ is a $k \times k$ square matrix, where each element is a dot product between two random unit vectors in $d$ dimensions. Different vectors are not independent (because they have to be orthogonal), but with $d=2000 \gg k$ I hope this can be ignored. Then we can consider $A^\top B$ as a matrix of $k^2$ independent draws of $t$, and its squared norm is a random variable $$w=\sum_{i=1}^{k^2} t^2_i = \sum_{i=1}^{k^2} (2u_i-1)^2.$$
I think it would be difficult to obtain an analytical expression for the PDF of a sum of $k^2$ beta distributed random variables, but thanks to the central limit theorem, it will rapidly approach a normal distribution (see a related thread on math.SE). To specify this normal distribution, we need to compute its mean and variance. The mean is easy: mean of $t$ is zero, so mean of $t^2$ is equal to the variance of $t$, which is $1/d$. This means that $\mathbb E[w]=k^2/d$.
Computing the variance is a huge mess that I started but cannot finish that embarrassingly enough took me hours. Here are some auxiliary formulas that I derived by looking up the formula for the raw moments of beta distribution $$\mathbb E[X^q] = \prod_{r=0}^{q-1}\frac{\alpha+r}{\alpha+\beta+r}, \;\;\; X \sim \mathrm{Beta}(\alpha,\beta),$$ and plugging in $\alpha=\beta=(d-1)/2$:
\begin{align}
\mathbb E[u]&=1/2, \\
\mathbb E[u^2] &= \frac{d+1}{4d}, \\
\mathbb E[u^3] &= \frac{d+3}{8d}, \\
\mathbb E[u^4] &= \frac{(d+3)(d+5)}{16d(d+2)}.
\end{align}
Using this, one can derive the variance of $w$ starting from
$$\mathrm{Var}[w] = k^2 \mathrm{Var}[(2u-1)^2] = k^2 \mathbb E[(2u-1)^4]-k^2(\mathbb E[(2u-1)^2])^2.$$ I omit the tedious arithmetics, and skip directly to the answer: $$\mathrm{Var}[w] = k^2 \frac{2(d-1)}{d^2(d+2)}.$$ The conclusion is that asymptotically $$w \mathrel{\dot\sim} \mathcal N\left(k^2\frac{1}{d}, \; k^2 \frac{2(d-1)}{d^2(d+2)}\right) \mathrel{\dot\sim} \mathcal N\left(\frac{k^2}{d}, \; \frac{2k^2}{d^2}\right).$$
A quick simulation in Matlab confirms this result:
Here is the code I used to produce this figure ($d=2000$, $k=50$, number of Monte Carlo repetitions is $n=1000$; this runs for 17 seconds on my computer):
d = 2000;
k = 50;
n_iter = 1000;
tic
for rep = 1:n_iter
A = randn(d,k);
[A,~,~] = svd(A,0); %// orthogonalizing
B = randn(d,k);
[B,~,~] = svd(B,0); %// orthogonalizing
w(rep) = sum(sum((transpose(A)*B).^2)); %// = trace(A*A'*B*B'), but faster!
end
toc
figure
[f, xi] = ksdensity(w);
h1 = plot(xi, f, 'LineWidth', 2);
hold on
x = min(w):(max(w)-min(w))/100:max(w);
mu = k^2/d;
sigma2 = k^2 * 2*(d-1)/d^2/(d+2);
h2 = plot(x, 1/(sqrt(2*pi*sigma2)) * exp(-(x-mu).^2/2/sigma2), 'r', 'LineWidth', 2);
title(['d = ' num2str(d) ', k = ', num2str(k)])
hh = legend({['Observed density (n = ' num2str(niter) ')'], 'Predicted density'});
legend('boxoff')
Interpretation of $w$
Cosines of principal angles between subspaces spanned by columns of $A$ and $B$ are given by singular values of $A^\top B$. Then the squares of these cosines are given by the eigenvalues of $A^\top BB^\top A$ or also of $AA^\top BB^\top$. So, geometrically, your trace is the sum of squared cosines of principal angles. If $A=B$, then all angles are zero and sum of squared cosines equals $k$. If $A \perp B$, then all angles are $90^\circ$ and sum of squared cosines is zero.
I like your approach of normalizing $w$ by $k$, i.e. of taking $w/k$ as the main measure of similarity. It obviously cannot exceed $1$, will be equal to $1$ when the subspaces coincide, and will be close to zero if they are randomly chosen. Indeed, $\mathbb E[w]=k^2/d$, which means that $\mathbb E[w/k] = k/d$. When $k \ll d$, this is close to zero. | Null distribution of subspaces similarity, or what is the distribution of $\mathrm{tr}(AA'BB')$? | I have once asked a question that is essentially a special case of yours when $k=1$: Distribution of a scalar product of two random unit vectors in $\mathbb{R}^D$. @whuber gave an excellent answer, wh | Null distribution of subspaces similarity, or what is the distribution of $\mathrm{tr}(AA'BB')$?
I have once asked a question that is essentially a special case of yours when $k=1$: Distribution of a scalar product of two random unit vectors in $\mathbb{R}^D$. @whuber gave an excellent answer, where he explains that a dot product equals $t=2u-1$, where $$u\sim \mathrm{Beta}((d-1)/2,(d-1)/2)$$ and $d$ is the dimensionality of the space. It follows that $\mathrm{Var}[t]=1/d$ (one can also show this directly, see the answer by @Student001 in the linked thread).
Your question is about a random variable $$w=\mathrm{tr}(AA^\top BB^\top) = \|A^\top B\|^2,$$ where $A$ and $B$ are $d\times k$ matrices with orthonormal columns. Note that $A^\top B$ is a $k \times k$ square matrix, where each element is a dot product between two random unit vectors in $d$ dimensions. Different vectors are not independent (because they have to be orthogonal), but with $d=2000 \gg k$ I hope this can be ignored. Then we can consider $A^\top B$ as a matrix of $k^2$ independent draws of $t$, and its squared norm is a random variable $$w=\sum_{i=1}^{k^2} t^2_i = \sum_{i=1}^{k^2} (2u_i-1)^2.$$
I think it would be difficult to obtain an analytical expression for the PDF of a sum of $k^2$ beta distributed random variables, but thanks to the central limit theorem, it will rapidly approach a normal distribution (see a related thread on math.SE). To specify this normal distribution, we need to compute its mean and variance. The mean is easy: mean of $t$ is zero, so mean of $t^2$ is equal to the variance of $t$, which is $1/d$. This means that $\mathbb E[w]=k^2/d$.
Computing the variance is a huge mess that I started but cannot finish that embarrassingly enough took me hours. Here are some auxiliary formulas that I derived by looking up the formula for the raw moments of beta distribution $$\mathbb E[X^q] = \prod_{r=0}^{q-1}\frac{\alpha+r}{\alpha+\beta+r}, \;\;\; X \sim \mathrm{Beta}(\alpha,\beta),$$ and plugging in $\alpha=\beta=(d-1)/2$:
\begin{align}
\mathbb E[u]&=1/2, \\
\mathbb E[u^2] &= \frac{d+1}{4d}, \\
\mathbb E[u^3] &= \frac{d+3}{8d}, \\
\mathbb E[u^4] &= \frac{(d+3)(d+5)}{16d(d+2)}.
\end{align}
Using this, one can derive the variance of $w$ starting from
$$\mathrm{Var}[w] = k^2 \mathrm{Var}[(2u-1)^2] = k^2 \mathbb E[(2u-1)^4]-k^2(\mathbb E[(2u-1)^2])^2.$$ I omit the tedious arithmetics, and skip directly to the answer: $$\mathrm{Var}[w] = k^2 \frac{2(d-1)}{d^2(d+2)}.$$ The conclusion is that asymptotically $$w \mathrel{\dot\sim} \mathcal N\left(k^2\frac{1}{d}, \; k^2 \frac{2(d-1)}{d^2(d+2)}\right) \mathrel{\dot\sim} \mathcal N\left(\frac{k^2}{d}, \; \frac{2k^2}{d^2}\right).$$
A quick simulation in Matlab confirms this result:
Here is the code I used to produce this figure ($d=2000$, $k=50$, number of Monte Carlo repetitions is $n=1000$; this runs for 17 seconds on my computer):
d = 2000;
k = 50;
n_iter = 1000;
tic
for rep = 1:n_iter
A = randn(d,k);
[A,~,~] = svd(A,0); %// orthogonalizing
B = randn(d,k);
[B,~,~] = svd(B,0); %// orthogonalizing
w(rep) = sum(sum((transpose(A)*B).^2)); %// = trace(A*A'*B*B'), but faster!
end
toc
figure
[f, xi] = ksdensity(w);
h1 = plot(xi, f, 'LineWidth', 2);
hold on
x = min(w):(max(w)-min(w))/100:max(w);
mu = k^2/d;
sigma2 = k^2 * 2*(d-1)/d^2/(d+2);
h2 = plot(x, 1/(sqrt(2*pi*sigma2)) * exp(-(x-mu).^2/2/sigma2), 'r', 'LineWidth', 2);
title(['d = ' num2str(d) ', k = ', num2str(k)])
hh = legend({['Observed density (n = ' num2str(niter) ')'], 'Predicted density'});
legend('boxoff')
Interpretation of $w$
Cosines of principal angles between subspaces spanned by columns of $A$ and $B$ are given by singular values of $A^\top B$. Then the squares of these cosines are given by the eigenvalues of $A^\top BB^\top A$ or also of $AA^\top BB^\top$. So, geometrically, your trace is the sum of squared cosines of principal angles. If $A=B$, then all angles are zero and sum of squared cosines equals $k$. If $A \perp B$, then all angles are $90^\circ$ and sum of squared cosines is zero.
I like your approach of normalizing $w$ by $k$, i.e. of taking $w/k$ as the main measure of similarity. It obviously cannot exceed $1$, will be equal to $1$ when the subspaces coincide, and will be close to zero if they are randomly chosen. Indeed, $\mathbb E[w]=k^2/d$, which means that $\mathbb E[w/k] = k/d$. When $k \ll d$, this is close to zero. | Null distribution of subspaces similarity, or what is the distribution of $\mathrm{tr}(AA'BB')$?
I have once asked a question that is essentially a special case of yours when $k=1$: Distribution of a scalar product of two random unit vectors in $\mathbb{R}^D$. @whuber gave an excellent answer, wh |
35,149 | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value? | You might want to consider an approach outside of the traditional regression approach. This is comparable to the types of problems that psychometrics is designed to resolve (well, actually your first example is precisely that, since it is a test).
In Classical Test Theory, one of the most common metrics is the item-total score correlation, which is essentially the correlation between the item score and the total score. It tells you the item's discrimination - it's ability to discriminate between high and low scoring respondents. This is comparable to explaining the variance, like what you are asking about above with $R^2$. There are two ways to calculate this score, either by using the total test score including the item of interest, or excluding it. When you have a lot of items, these two methods are almost the same, but when you have few items, then they can make a big difference.
Another approach from Item Response Theory (IRT) is to estimate, either via a 2-parameter item response model or via a confirmatory factor analysis (which statistically are the same, but interpretation-wise are different). A 2-parameter model includes a parameter for the item difficulty (the relative difficulty of the item) and one for item discrimination, which is interpreted very similar to the item-total score correlation. High discrimination=the item differentiates between high and low scorers well. If you use confirmatory factor analysis (CFA), you have item loadings, which are essentially your discrimination parameters. They tell you how much of the total score is driven by a particular item.
Using IRT or CFA assumes you have a latent score, not an observed score, that you are trying to estimate. In the examples you give above, you are concerned with an observed score, that isn't latent. So these models wouldn't be what you are after, since they are probabilistic and you kind of have a tautological relationship (your total is by definition made up of the parts, with no error). But I point them out as examples of ways statistics gets at similar answers.
Last thing I want to point out, and this is probably something others would argue with, but while an assumption is that regressors are independent, when we have a categorical variable, and we enter dummies into the model, those dummy variables are, by definition, correlated. So this would seemingly violate assumptions of independence and bring in multicollinearity. If you think of it this way, it would make sense to run your regression of say the elements in urine, and exclude one, the coefficients would be valid just as if it was a single categorical variable. In that sense, you are getting a comparable number to the item-total correlation from Classical Test Theory I pointed out above. | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value? | You might want to consider an approach outside of the traditional regression approach. This is comparable to the types of problems that psychometrics is designed to resolve (well, actually your first | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value?
You might want to consider an approach outside of the traditional regression approach. This is comparable to the types of problems that psychometrics is designed to resolve (well, actually your first example is precisely that, since it is a test).
In Classical Test Theory, one of the most common metrics is the item-total score correlation, which is essentially the correlation between the item score and the total score. It tells you the item's discrimination - it's ability to discriminate between high and low scoring respondents. This is comparable to explaining the variance, like what you are asking about above with $R^2$. There are two ways to calculate this score, either by using the total test score including the item of interest, or excluding it. When you have a lot of items, these two methods are almost the same, but when you have few items, then they can make a big difference.
Another approach from Item Response Theory (IRT) is to estimate, either via a 2-parameter item response model or via a confirmatory factor analysis (which statistically are the same, but interpretation-wise are different). A 2-parameter model includes a parameter for the item difficulty (the relative difficulty of the item) and one for item discrimination, which is interpreted very similar to the item-total score correlation. High discrimination=the item differentiates between high and low scorers well. If you use confirmatory factor analysis (CFA), you have item loadings, which are essentially your discrimination parameters. They tell you how much of the total score is driven by a particular item.
Using IRT or CFA assumes you have a latent score, not an observed score, that you are trying to estimate. In the examples you give above, you are concerned with an observed score, that isn't latent. So these models wouldn't be what you are after, since they are probabilistic and you kind of have a tautological relationship (your total is by definition made up of the parts, with no error). But I point them out as examples of ways statistics gets at similar answers.
Last thing I want to point out, and this is probably something others would argue with, but while an assumption is that regressors are independent, when we have a categorical variable, and we enter dummies into the model, those dummy variables are, by definition, correlated. So this would seemingly violate assumptions of independence and bring in multicollinearity. If you think of it this way, it would make sense to run your regression of say the elements in urine, and exclude one, the coefficients would be valid just as if it was a single categorical variable. In that sense, you are getting a comparable number to the item-total correlation from Classical Test Theory I pointed out above. | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value?
You might want to consider an approach outside of the traditional regression approach. This is comparable to the types of problems that psychometrics is designed to resolve (well, actually your first |
35,150 | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value? | A quick mathematial way of looking at it is to expand out the formulas. Let $Z=X+Y+W$.
$$ R^2 =\left(\frac{Cov(X,Z)}{\sigma_X \sigma_Z}\right)^2 =\left(\frac{Var(X)+Cov(X,Y)+Cov(X,W)}{\sigma_X \sigma_Z}\right)^2 $$
So in a nutshell You're going to get the variance of $X$ plus its relationship with your other two variables, divided by a scaling factor. The scaling factor itself could be expanded, but the numerator is telling the story. In general, things that will affect that number are a) the relative scale of X compared to Y and W, b) the relative variance of X, c) X's "contribution" to the variance of Y and W.
As for whether that's useful or not, that kind of depends on what you're after. It's probably best to think of it as a "percentage of total variation" or something like that, even though the same for Y and W may not all sum to 1 (or maybe it does...not sure). | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value? | A quick mathematial way of looking at it is to expand out the formulas. Let $Z=X+Y+W$.
$$ R^2 =\left(\frac{Cov(X,Z)}{\sigma_X \sigma_Z}\right)^2 =\left(\frac{Var(X)+Cov(X,Y)+Cov(X,W)}{\sigma_X \sigma_ | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value?
A quick mathematial way of looking at it is to expand out the formulas. Let $Z=X+Y+W$.
$$ R^2 =\left(\frac{Cov(X,Z)}{\sigma_X \sigma_Z}\right)^2 =\left(\frac{Var(X)+Cov(X,Y)+Cov(X,W)}{\sigma_X \sigma_Z}\right)^2 $$
So in a nutshell You're going to get the variance of $X$ plus its relationship with your other two variables, divided by a scaling factor. The scaling factor itself could be expanded, but the numerator is telling the story. In general, things that will affect that number are a) the relative scale of X compared to Y and W, b) the relative variance of X, c) X's "contribution" to the variance of Y and W.
As for whether that's useful or not, that kind of depends on what you're after. It's probably best to think of it as a "percentage of total variation" or something like that, even though the same for Y and W may not all sum to 1 (or maybe it does...not sure). | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value?
A quick mathematial way of looking at it is to expand out the formulas. Let $Z=X+Y+W$.
$$ R^2 =\left(\frac{Cov(X,Z)}{\sigma_X \sigma_Z}\right)^2 =\left(\frac{Var(X)+Cov(X,Y)+Cov(X,W)}{\sigma_X \sigma_ |
35,151 | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value? | If X is one of several variables that sum to define Y, then clearly the assumptions of linear regression are broken. The P values won't be useful. The slopes and their confidence intervals can't be interpreted in the usual way. But is $R^2$ still useful? I suppose it is as a descriptive statistics. If you have three $R^2$ values quantifying correlation between Y and each of its three components, I suppose you'd learn something interesting by seeing the relative values of $R^2$. | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value? | If X is one of several variables that sum to define Y, then clearly the assumptions of linear regression are broken. The P values won't be useful. The slopes and their confidence intervals can't be in | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value?
If X is one of several variables that sum to define Y, then clearly the assumptions of linear regression are broken. The P values won't be useful. The slopes and their confidence intervals can't be interpreted in the usual way. But is $R^2$ still useful? I suppose it is as a descriptive statistics. If you have three $R^2$ values quantifying correlation between Y and each of its three components, I suppose you'd learn something interesting by seeing the relative values of $R^2$. | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value?
If X is one of several variables that sum to define Y, then clearly the assumptions of linear regression are broken. The P values won't be useful. The slopes and their confidence intervals can't be in |
35,152 | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value? | One assumption for regression analysis is that $X$ and $Y$ are not intertwined.
This is incorrect. One assumption for regression analysis is that the ERRORS are uncorrelated. See the wikipedia entry for the Gauss-Markov theorem.
If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value?
About the only use I can think of for the $R^2$ between $X$ and $Y$ is to show how much better your model performs when you include other predictors. There's other values that would be much informative. The values of the estimated coefficients and their standard errors in particular. | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value? | One assumption for regression analysis is that $X$ and $Y$ are not intertwined.
This is incorrect. One assumption for regression analysis is that the ERRORS are uncorrelated. See the wikipedia entry | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value?
One assumption for regression analysis is that $X$ and $Y$ are not intertwined.
This is incorrect. One assumption for regression analysis is that the ERRORS are uncorrelated. See the wikipedia entry for the Gauss-Markov theorem.
If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value?
About the only use I can think of for the $R^2$ between $X$ and $Y$ is to show how much better your model performs when you include other predictors. There's other values that would be much informative. The values of the estimated coefficients and their standard errors in particular. | If $X$ is one of several variables that sum to $Y$, is the $R^2$ between $X$ and $Y$ a useful value?
One assumption for regression analysis is that $X$ and $Y$ are not intertwined.
This is incorrect. One assumption for regression analysis is that the ERRORS are uncorrelated. See the wikipedia entry |
35,153 | Is there a way to define a statistic similar to the z-score for the Poisson distribution? | Assuming that the typical number of spikes is large, I would suggest to use a Variance stabilizing transformation. For Poisson distribution, it goes as follows: let $X \sim \mathcal P(\lambda)$, and let $Y \sim 2 \sqrt X$. A first order approximation gives
$$Y \simeq 2 \sqrt\lambda + {1\over \sqrt\lambda}(X-\lambda),$$
from which we get $\text{var}(Y) \simeq {1\over \lambda} \times \lambda = 1$. Moreover for $\lambda$ large $Y$ is approximately normal $Y \sim \mathcal N(2\sqrt\lambda,1)$.
You can use $Y - 2\sqrt\lambda = 2(\sqrt X - \sqrt\lambda)$ as $z$-score. | Is there a way to define a statistic similar to the z-score for the Poisson distribution? | Assuming that the typical number of spikes is large, I would suggest to use a Variance stabilizing transformation. For Poisson distribution, it goes as follows: let $X \sim \mathcal P(\lambda)$, and l | Is there a way to define a statistic similar to the z-score for the Poisson distribution?
Assuming that the typical number of spikes is large, I would suggest to use a Variance stabilizing transformation. For Poisson distribution, it goes as follows: let $X \sim \mathcal P(\lambda)$, and let $Y \sim 2 \sqrt X$. A first order approximation gives
$$Y \simeq 2 \sqrt\lambda + {1\over \sqrt\lambda}(X-\lambda),$$
from which we get $\text{var}(Y) \simeq {1\over \lambda} \times \lambda = 1$. Moreover for $\lambda$ large $Y$ is approximately normal $Y \sim \mathcal N(2\sqrt\lambda,1)$.
You can use $Y - 2\sqrt\lambda = 2(\sqrt X - \sqrt\lambda)$ as $z$-score. | Is there a way to define a statistic similar to the z-score for the Poisson distribution?
Assuming that the typical number of spikes is large, I would suggest to use a Variance stabilizing transformation. For Poisson distribution, it goes as follows: let $X \sim \mathcal P(\lambda)$, and l |
35,154 | Is there a way to define a statistic similar to the z-score for the Poisson distribution? | Is the reason that you want to test for Poisson distribution, that you think the spikes are generated by a Poisson process (that is, the instantaneous probability of seeing a spike is constant over time)? If so, and you know the length between each spike, consider testing for a Poisson process instead. This amounts to testing that the gaps between spikes follow an exponential distribution, with a fixed rate parameter at each location. This allows you to aggregate all the different events at each location, which hopefully gives you a large enough sample to have a reasonably powerful test. (Of course, few processes are actually Poisson, so it might be more informative to look at how much the distribution deviates from exponential and in what way, but that's a separate question.)
If you don't have between-spike timings, you may have to do something more complicated. You could, for instance, find the maximum-likelihood Poisson rate for a location, and compare your real data to a simulation from the resulting model in various ways to see how different it looks. As far as I know there are no off-the-shelf tests for this case though. | Is there a way to define a statistic similar to the z-score for the Poisson distribution? | Is the reason that you want to test for Poisson distribution, that you think the spikes are generated by a Poisson process (that is, the instantaneous probability of seeing a spike is constant over ti | Is there a way to define a statistic similar to the z-score for the Poisson distribution?
Is the reason that you want to test for Poisson distribution, that you think the spikes are generated by a Poisson process (that is, the instantaneous probability of seeing a spike is constant over time)? If so, and you know the length between each spike, consider testing for a Poisson process instead. This amounts to testing that the gaps between spikes follow an exponential distribution, with a fixed rate parameter at each location. This allows you to aggregate all the different events at each location, which hopefully gives you a large enough sample to have a reasonably powerful test. (Of course, few processes are actually Poisson, so it might be more informative to look at how much the distribution deviates from exponential and in what way, but that's a separate question.)
If you don't have between-spike timings, you may have to do something more complicated. You could, for instance, find the maximum-likelihood Poisson rate for a location, and compare your real data to a simulation from the resulting model in various ways to see how different it looks. As far as I know there are no off-the-shelf tests for this case though. | Is there a way to define a statistic similar to the z-score for the Poisson distribution?
Is the reason that you want to test for Poisson distribution, that you think the spikes are generated by a Poisson process (that is, the instantaneous probability of seeing a spike is constant over ti |
35,155 | Is there a way to define a statistic similar to the z-score for the Poisson distribution? | This is similar to Ben's question, but are you just trying to test whether a multi-variate Poisson distribution fits this data? Your major problem here is that you're having to estimate the poisson mean for each cell from the data that you're trying to get a p-value/likelihood score/whatever for. Now strictly speaking this may not be a problem, but if you don't have enough data for any of these individually, you're not going to have enough data for them collectively without some additional restriction on your hypothesis (which could come in a variety of forms).
Here's an example of the model you're vaguely describing. Let $i$ be each cell and $Y_i$ be the count within each cell.
$$
Y_i\sim Poisson(\lambda_i)\\
\lambda_i=\mu+\alpha_i
$$
This is a general Poisson regression where the number of parameters is equal to the number of observations. Unless the ratio of those two approaches 0, your estimates for the number of parameters are not statistically consistent and your likelihood ratio won't tell you very much.
Now the model Ben Describes is a little better if you have the time interval data: here let $Y_ij$ by the time between $(j-1)th$ and $j$th observations:
$$
Y_{ij}\sim Exp(\lambda_i)\\
\lambda_i=\mu+\alpha_i
$$
This is a little bit better, and if the ratio is small enough you may be able to test this via something like a Q-Q Plot on the probabilities of each time (which again, credit to Ben, is roughly what he's describing). If the number of locations is roughly the log of the number of observations, you may be in business there, but that QQ-Plot is still going to have some real bias, especially toward making the big outliers look more normal.
Some real improvements would be if there is any kind of additional knowledge you could impose on the problem. Like for example if you could say that sensors in nearby locations should have similar rates of firing, then you could leverage that knowledge by imposing a linear model on lat/long or maybe a thin-plate spline if you're not sure how the spatial relationship should look. Or maybe if the sensors of a certain "type" and you could say that sensors of the same "type" should have similar rates, and you could again make it linear and do an Anova test, or make a random effects model or something like that.
Anyway, there are a lot of ways to go with this if you have some kind of additional knowledge, or if your # of locations is $O(\log n)$. HTH | Is there a way to define a statistic similar to the z-score for the Poisson distribution? | This is similar to Ben's question, but are you just trying to test whether a multi-variate Poisson distribution fits this data? Your major problem here is that you're having to estimate the poisson me | Is there a way to define a statistic similar to the z-score for the Poisson distribution?
This is similar to Ben's question, but are you just trying to test whether a multi-variate Poisson distribution fits this data? Your major problem here is that you're having to estimate the poisson mean for each cell from the data that you're trying to get a p-value/likelihood score/whatever for. Now strictly speaking this may not be a problem, but if you don't have enough data for any of these individually, you're not going to have enough data for them collectively without some additional restriction on your hypothesis (which could come in a variety of forms).
Here's an example of the model you're vaguely describing. Let $i$ be each cell and $Y_i$ be the count within each cell.
$$
Y_i\sim Poisson(\lambda_i)\\
\lambda_i=\mu+\alpha_i
$$
This is a general Poisson regression where the number of parameters is equal to the number of observations. Unless the ratio of those two approaches 0, your estimates for the number of parameters are not statistically consistent and your likelihood ratio won't tell you very much.
Now the model Ben Describes is a little better if you have the time interval data: here let $Y_ij$ by the time between $(j-1)th$ and $j$th observations:
$$
Y_{ij}\sim Exp(\lambda_i)\\
\lambda_i=\mu+\alpha_i
$$
This is a little bit better, and if the ratio is small enough you may be able to test this via something like a Q-Q Plot on the probabilities of each time (which again, credit to Ben, is roughly what he's describing). If the number of locations is roughly the log of the number of observations, you may be in business there, but that QQ-Plot is still going to have some real bias, especially toward making the big outliers look more normal.
Some real improvements would be if there is any kind of additional knowledge you could impose on the problem. Like for example if you could say that sensors in nearby locations should have similar rates of firing, then you could leverage that knowledge by imposing a linear model on lat/long or maybe a thin-plate spline if you're not sure how the spatial relationship should look. Or maybe if the sensors of a certain "type" and you could say that sensors of the same "type" should have similar rates, and you could again make it linear and do an Anova test, or make a random effects model or something like that.
Anyway, there are a lot of ways to go with this if you have some kind of additional knowledge, or if your # of locations is $O(\log n)$. HTH | Is there a way to define a statistic similar to the z-score for the Poisson distribution?
This is similar to Ben's question, but are you just trying to test whether a multi-variate Poisson distribution fits this data? Your major problem here is that you're having to estimate the poisson me |
35,156 | R binomial family with identity link | See Wikipedia on the linear probability model, & CV posts here & here for the statistical background. Though not "wrong", you'd want a good reason for using an identity link to model a Bernoulli probability.
According to the family manual
the binomial family [accepts] the links logit, probit, cauchit,
(corresponding to logistic, normal and Cauchy CDFs respectively) log
and cloglog (complementary log-log)
But
The link and variance arguments have rather awkward semantics for
back-compatibility. The recommended way is to supply them is as quoted
character strings, but they can also be supplied unquoted (as names or
expressions). In addition, they can also be supplied as a length-one
character vector giving the name of one of the options, or as a list
(for link, of class "link-glm"). The restrictions apply only to links
given as names: when given as a character string all the links known
to make.link are accepted.
So family=binomial(link="identity") works but family=binomial(link=identity) doesn't. (If you find differently it might be to do with the R version.) To allow for over-dispersion, then usefamily=quasi(link="identity", variance = "mu(1-mu)"). | R binomial family with identity link | See Wikipedia on the linear probability model, & CV posts here & here for the statistical background. Though not "wrong", you'd want a good reason for using an identity link to model a Bernoulli proba | R binomial family with identity link
See Wikipedia on the linear probability model, & CV posts here & here for the statistical background. Though not "wrong", you'd want a good reason for using an identity link to model a Bernoulli probability.
According to the family manual
the binomial family [accepts] the links logit, probit, cauchit,
(corresponding to logistic, normal and Cauchy CDFs respectively) log
and cloglog (complementary log-log)
But
The link and variance arguments have rather awkward semantics for
back-compatibility. The recommended way is to supply them is as quoted
character strings, but they can also be supplied unquoted (as names or
expressions). In addition, they can also be supplied as a length-one
character vector giving the name of one of the options, or as a list
(for link, of class "link-glm"). The restrictions apply only to links
given as names: when given as a character string all the links known
to make.link are accepted.
So family=binomial(link="identity") works but family=binomial(link=identity) doesn't. (If you find differently it might be to do with the R version.) To allow for over-dispersion, then usefamily=quasi(link="identity", variance = "mu(1-mu)"). | R binomial family with identity link
See Wikipedia on the linear probability model, & CV posts here & here for the statistical background. Though not "wrong", you'd want a good reason for using an identity link to model a Bernoulli proba |
35,157 | completing the square for Gaussian multivariate estimation | The essential step is along these lines:
$$(x-a)^TA(x-a) + (x-b)^TB(x-b)$$
$$=x^TAx -2a^TAx + a^TAa+ x^TBx -2b^TBx + b^TBb$$
$$=x^T(A+B)x -2(a^TA+b^TB)x + (a^TAa+ b^TBb)$$
$$=x^T(A+B)x -2(a^TA+b^TB)x + (a^TAa+ b^TBb)$$
Let $M=A+B$, let $m=(M^{-1})^T(B^Tb+A^Ta)$ and let $C=a^TAa+ b^TBb-m^TMm$
(I hope I got $m$ right there. You just need to pick $m$ so that $a^TA+b^TB=m^TM$ given the definition of $M$ we had already. And feel free to work with $-2x^T(Aa+Bb)$ if that's easier.)
$$=x^TMx-2m^TMx+(m^TMm+C)$$
$$=(x-m)^TM(x-m)+C$$
Taking your expression, putting it all in one exponent, then focusing on what's in the exponent, and dropping off constants not in $\beta$ (like the factor of $\frac{1}{2}$, we get something of the above form). | completing the square for Gaussian multivariate estimation | The essential step is along these lines:
$$(x-a)^TA(x-a) + (x-b)^TB(x-b)$$
$$=x^TAx -2a^TAx + a^TAa+ x^TBx -2b^TBx + b^TBb$$
$$=x^T(A+B)x -2(a^TA+b^TB)x + (a^TAa+ b^TBb)$$
$$=x^T(A+B)x -2(a^TA+b^TB)x | completing the square for Gaussian multivariate estimation
The essential step is along these lines:
$$(x-a)^TA(x-a) + (x-b)^TB(x-b)$$
$$=x^TAx -2a^TAx + a^TAa+ x^TBx -2b^TBx + b^TBb$$
$$=x^T(A+B)x -2(a^TA+b^TB)x + (a^TAa+ b^TBb)$$
$$=x^T(A+B)x -2(a^TA+b^TB)x + (a^TAa+ b^TBb)$$
Let $M=A+B$, let $m=(M^{-1})^T(B^Tb+A^Ta)$ and let $C=a^TAa+ b^TBb-m^TMm$
(I hope I got $m$ right there. You just need to pick $m$ so that $a^TA+b^TB=m^TM$ given the definition of $M$ we had already. And feel free to work with $-2x^T(Aa+Bb)$ if that's easier.)
$$=x^TMx-2m^TMx+(m^TMm+C)$$
$$=(x-m)^TM(x-m)+C$$
Taking your expression, putting it all in one exponent, then focusing on what's in the exponent, and dropping off constants not in $\beta$ (like the factor of $\frac{1}{2}$, we get something of the above form). | completing the square for Gaussian multivariate estimation
The essential step is along these lines:
$$(x-a)^TA(x-a) + (x-b)^TB(x-b)$$
$$=x^TAx -2a^TAx + a^TAa+ x^TBx -2b^TBx + b^TBb$$
$$=x^T(A+B)x -2(a^TA+b^TB)x + (a^TAa+ b^TBb)$$
$$=x^T(A+B)x -2(a^TA+b^TB)x |
35,158 | If $X$ takes on a Gamma Distribution, how can I find $X^2$, $X^3$, etc? | Your strategy will fail. Powers of $X$ follow Generalized Gamma distributions. Their densities are given by
$$f(x; k, \gamma, 1) = \frac{1}{\Gamma (k)} x^{\gamma k} e^{-x^{\gamma }} \left(\gamma \frac{dx}{x} \right).$$
(The third parameter, here set to a unit value $\sigma=1$, is a scale parameter.) For the power $m$ of $X \sim \Gamma(k)$, the shape parameter is $\gamma = 1/m$. This all becomes obvious when you think of $x^\gamma$ as being another variable, say $u$, and note that
$$\frac{du}{u} = \frac{d(x^\gamma)}{x^\gamma} = \gamma \frac{d x}{x}.$$
The remaining factors, $u^k e^{-u}/\Gamma(k)$, give the PDF of a Gamma distribution (with respect to the measure $du/u$).
The issue before us is whether for any given $k$ it is possible to find other parameters $k^\prime$ and $\sigma^\prime$ such that $f(x,k, \gamma, \sigma)=f(x;k^\prime, 1, \sigma^\prime)$, where $\gamma = 1/m$ for some integral $m \gt 1$: that is what it would mean for $X^m$ to have an (ordinary) Gamma distribution.
We can settle this by looking at moments. Integration shows that the (non-central) moments of the generalized Gamma distribution are
$$\mu_i = \sigma^i\frac{\Gamma(k+m i)}{\Gamma(k)}.$$
For integral values of $m$ their successive ratios are
$$\frac{\mu_{i+1}}{\mu_i} = \frac{\sigma^{i+1}\Gamma(k + mi + m)}{\sigma^i\Gamma(k + m i)} = \sigma(k + mi)(k+mi+1)\cdots (k+mi+m-1).$$
Trying to solve equations (or rather, prove they have no solutions) involving these formulas looks messy. Instead, consider the limiting values
$$\lim_{i\to \infty}\frac{\mu_{i+1}}{i\mu_i}.$$
For $m=1$ (a true Gamma distribution) this is the limiting value of $\sigma(k+i)/i$, obviously equal to $\sigma$, whereas for $m\gt 1$ this is the limiting value of $\sigma(k+mi)\cdots(k+mi+m-1)/i$, which (being of order $i^{m-1}$) diverges. Therefore the distribution of $X^m$ for $m\gt 1$ (and integral) cannot have the same moments as any possible Gamma function, proving it is not a Gamma function.
It should be clear that the generalized Gamma distribution family is indeed closed under taking (positive) powers. | If $X$ takes on a Gamma Distribution, how can I find $X^2$, $X^3$, etc? | Your strategy will fail. Powers of $X$ follow Generalized Gamma distributions. Their densities are given by
$$f(x; k, \gamma, 1) = \frac{1}{\Gamma (k)} x^{\gamma k} e^{-x^{\gamma }} \left(\gamma \ | If $X$ takes on a Gamma Distribution, how can I find $X^2$, $X^3$, etc?
Your strategy will fail. Powers of $X$ follow Generalized Gamma distributions. Their densities are given by
$$f(x; k, \gamma, 1) = \frac{1}{\Gamma (k)} x^{\gamma k} e^{-x^{\gamma }} \left(\gamma \frac{dx}{x} \right).$$
(The third parameter, here set to a unit value $\sigma=1$, is a scale parameter.) For the power $m$ of $X \sim \Gamma(k)$, the shape parameter is $\gamma = 1/m$. This all becomes obvious when you think of $x^\gamma$ as being another variable, say $u$, and note that
$$\frac{du}{u} = \frac{d(x^\gamma)}{x^\gamma} = \gamma \frac{d x}{x}.$$
The remaining factors, $u^k e^{-u}/\Gamma(k)$, give the PDF of a Gamma distribution (with respect to the measure $du/u$).
The issue before us is whether for any given $k$ it is possible to find other parameters $k^\prime$ and $\sigma^\prime$ such that $f(x,k, \gamma, \sigma)=f(x;k^\prime, 1, \sigma^\prime)$, where $\gamma = 1/m$ for some integral $m \gt 1$: that is what it would mean for $X^m$ to have an (ordinary) Gamma distribution.
We can settle this by looking at moments. Integration shows that the (non-central) moments of the generalized Gamma distribution are
$$\mu_i = \sigma^i\frac{\Gamma(k+m i)}{\Gamma(k)}.$$
For integral values of $m$ their successive ratios are
$$\frac{\mu_{i+1}}{\mu_i} = \frac{\sigma^{i+1}\Gamma(k + mi + m)}{\sigma^i\Gamma(k + m i)} = \sigma(k + mi)(k+mi+1)\cdots (k+mi+m-1).$$
Trying to solve equations (or rather, prove they have no solutions) involving these formulas looks messy. Instead, consider the limiting values
$$\lim_{i\to \infty}\frac{\mu_{i+1}}{i\mu_i}.$$
For $m=1$ (a true Gamma distribution) this is the limiting value of $\sigma(k+i)/i$, obviously equal to $\sigma$, whereas for $m\gt 1$ this is the limiting value of $\sigma(k+mi)\cdots(k+mi+m-1)/i$, which (being of order $i^{m-1}$) diverges. Therefore the distribution of $X^m$ for $m\gt 1$ (and integral) cannot have the same moments as any possible Gamma function, proving it is not a Gamma function.
It should be clear that the generalized Gamma distribution family is indeed closed under taking (positive) powers. | If $X$ takes on a Gamma Distribution, how can I find $X^2$, $X^3$, etc?
Your strategy will fail. Powers of $X$ follow Generalized Gamma distributions. Their densities are given by
$$f(x; k, \gamma, 1) = \frac{1}{\Gamma (k)} x^{\gamma k} e^{-x^{\gamma }} \left(\gamma \ |
35,159 | Is using error bars for means in a within-subjects study wrong? | It isn't "wrong" necessarily, and it isn't "completely uninformative". But it provides information that pertains to a largely unrelated question, and so is likely to be misleading. When you run a paired samples $t$-test, you are really conducting a one-sample $t$-test of whether the mean of the differences is equal to $0$. Because this is a one-sample test, a corresponding figure would have one bar showing the mean difference (with error bars).
To see how this could be misleading, consider these data (coded with R):
set.seed(4868) # this makes the example exactly reproducible (if you use R)
b = c(2, 4, 6, 8)
a = b + rnorm(4, mean=.5, sd=.1)
a = round(a, digits=3)
d = data.frame(before=b, after=a, differences=a-b)
d
# before after differences
# 1 2 2.679 0.679
# 2 4 4.597 0.597
# 3 6 6.592 0.592
# 4 8 8.366 0.366
t.test(a, b, paired=T)
# Paired t-test
#
# data: a and b
# t = 8.3117, df = 3, p-value = 0.003649
# alternative hypothesis: true difference in means is not equal to 0
# 95 percent confidence interval:
# 0.3446575 0.7723425
# sample estimates:
# mean of the differences
# 0.5585
The $t$-test is highly significant. However, what impression would people get if you plotted the bars on the left vs. the bar on the right? | Is using error bars for means in a within-subjects study wrong? | It isn't "wrong" necessarily, and it isn't "completely uninformative". But it provides information that pertains to a largely unrelated question, and so is likely to be misleading. When you run a pa | Is using error bars for means in a within-subjects study wrong?
It isn't "wrong" necessarily, and it isn't "completely uninformative". But it provides information that pertains to a largely unrelated question, and so is likely to be misleading. When you run a paired samples $t$-test, you are really conducting a one-sample $t$-test of whether the mean of the differences is equal to $0$. Because this is a one-sample test, a corresponding figure would have one bar showing the mean difference (with error bars).
To see how this could be misleading, consider these data (coded with R):
set.seed(4868) # this makes the example exactly reproducible (if you use R)
b = c(2, 4, 6, 8)
a = b + rnorm(4, mean=.5, sd=.1)
a = round(a, digits=3)
d = data.frame(before=b, after=a, differences=a-b)
d
# before after differences
# 1 2 2.679 0.679
# 2 4 4.597 0.597
# 3 6 6.592 0.592
# 4 8 8.366 0.366
t.test(a, b, paired=T)
# Paired t-test
#
# data: a and b
# t = 8.3117, df = 3, p-value = 0.003649
# alternative hypothesis: true difference in means is not equal to 0
# 95 percent confidence interval:
# 0.3446575 0.7723425
# sample estimates:
# mean of the differences
# 0.5585
The $t$-test is highly significant. However, what impression would people get if you plotted the bars on the left vs. the bar on the right? | Is using error bars for means in a within-subjects study wrong?
It isn't "wrong" necessarily, and it isn't "completely uninformative". But it provides information that pertains to a largely unrelated question, and so is likely to be misleading. When you run a pa |
35,160 | Neural network over-fitting | Overfitting is not only when test error increases with iterations. We say that there is overfitting when the performance on test set is much lower than the performance on train set (because the model fits too much to seen data, and do not generalize well).
In your second plot we can see that performances on test sets are almost 10 times lower than performances on train sets, which can be considered as overfitting.
It's almost always the case that a model performs better on the training set than on test set, since the model has already seen the data. However, a good model should be able to generalize well on unseen data, and then to reduce the gap between performances on train and test sets.
Your first example of overfitting can be solved by early stopping for example. Your second example can be solved by regularization, by corrupting input, etc. | Neural network over-fitting | Overfitting is not only when test error increases with iterations. We say that there is overfitting when the performance on test set is much lower than the performance on train set (because the model | Neural network over-fitting
Overfitting is not only when test error increases with iterations. We say that there is overfitting when the performance on test set is much lower than the performance on train set (because the model fits too much to seen data, and do not generalize well).
In your second plot we can see that performances on test sets are almost 10 times lower than performances on train sets, which can be considered as overfitting.
It's almost always the case that a model performs better on the training set than on test set, since the model has already seen the data. However, a good model should be able to generalize well on unseen data, and then to reduce the gap between performances on train and test sets.
Your first example of overfitting can be solved by early stopping for example. Your second example can be solved by regularization, by corrupting input, etc. | Neural network over-fitting
Overfitting is not only when test error increases with iterations. We say that there is overfitting when the performance on test set is much lower than the performance on train set (because the model |
35,161 | How to "undifference" a time series variable | I'm afraid you've already hit upon the easiest solution, which is to pick a xi, aka the constant of integration. The alternative is to phrase any question you ask about your "undifferenced" sequence such that the constant of integration doesn't matter.
The underlying problem is that "differencing" maps many sequences of values to the same sequence of differences. If $x_n$ is your sequence, then for any constant $C$, the sequence $x_n+ C$ will have the same differences. | How to "undifference" a time series variable | I'm afraid you've already hit upon the easiest solution, which is to pick a xi, aka the constant of integration. The alternative is to phrase any question you ask about your "undifferenced" sequence s | How to "undifference" a time series variable
I'm afraid you've already hit upon the easiest solution, which is to pick a xi, aka the constant of integration. The alternative is to phrase any question you ask about your "undifferenced" sequence such that the constant of integration doesn't matter.
The underlying problem is that "differencing" maps many sequences of values to the same sequence of differences. If $x_n$ is your sequence, then for any constant $C$, the sequence $x_n+ C$ will have the same differences. | How to "undifference" a time series variable
I'm afraid you've already hit upon the easiest solution, which is to pick a xi, aka the constant of integration. The alternative is to phrase any question you ask about your "undifferenced" sequence s |
35,162 | How to "undifference" a time series variable | Instead of doing diff() with the actual time series data, use instead the d parameter in auto.arima function to define it. lets say your data series is val.ts and you want to do differencing only until first order to make your series stationary, then instead of using auto.arima(diff(val.ts)), do auto.arima(val.ts,d=1). I have answered it here to my actual question here
Convert double differenced forecast into actual value | How to "undifference" a time series variable | Instead of doing diff() with the actual time series data, use instead the d parameter in auto.arima function to define it. lets say your data series is val.ts and you want to do differencing only unti | How to "undifference" a time series variable
Instead of doing diff() with the actual time series data, use instead the d parameter in auto.arima function to define it. lets say your data series is val.ts and you want to do differencing only until first order to make your series stationary, then instead of using auto.arima(diff(val.ts)), do auto.arima(val.ts,d=1). I have answered it here to my actual question here
Convert double differenced forecast into actual value | How to "undifference" a time series variable
Instead of doing diff() with the actual time series data, use instead the d parameter in auto.arima function to define it. lets say your data series is val.ts and you want to do differencing only unti |
35,163 | How to "undifference" a time series variable | Since the series was twice-differenced, you need the first two values of the original source data.
You mention that it is a money market, cash return proxy variable. Shouldn't it be possible to get the source data?
In your simulation, I'm assuming you are generating 100,000 series that have similar characteristics (using the fitted copula) as the twice-differenced data? You just need to choose your xi values to "re-calibrate" your differencing series back to be similar to the original.
In your example, the 0.5 is the initial value to start at when adding each differencing step back.
If I generated 100,000 differencing series, I would set xi to 0.5 to have the same starting point as the original. | How to "undifference" a time series variable | Since the series was twice-differenced, you need the first two values of the original source data.
You mention that it is a money market, cash return proxy variable. Shouldn't it be possible to get th | How to "undifference" a time series variable
Since the series was twice-differenced, you need the first two values of the original source data.
You mention that it is a money market, cash return proxy variable. Shouldn't it be possible to get the source data?
In your simulation, I'm assuming you are generating 100,000 series that have similar characteristics (using the fitted copula) as the twice-differenced data? You just need to choose your xi values to "re-calibrate" your differencing series back to be similar to the original.
In your example, the 0.5 is the initial value to start at when adding each differencing step back.
If I generated 100,000 differencing series, I would set xi to 0.5 to have the same starting point as the original. | How to "undifference" a time series variable
Since the series was twice-differenced, you need the first two values of the original source data.
You mention that it is a money market, cash return proxy variable. Shouldn't it be possible to get th |
35,164 | Determine the limiting distribution of Uniform Order Statistic | If you look at the cdf of $Y_n$, $$F_n(\delta)=\mathbb{P}(Y_n\le\delta)=(\delta/\theta)^n\qquad0\le\delta\le\theta\,,$$ you get that $F_n(\delta)$ converges to zero when $0\le\delta<\theta$, which means that $Y_n$ converges in probability to $\theta$:
$$Y_n\stackrel{\text{prob}}{\longrightarrow} \theta\,.$$ This implies that $Y_n$ also converges in distribution to the constant value random variable $\theta$:
$$Y_n\stackrel{\text{dist}}{\longrightarrow} \theta\,.$$ To get a more precise description of the asymptotic behaviour of $Y_n$, you need to zoom around $\theta$, i.e., to consider $(\theta-Y_n)$ scaled by a power of $n$, $n^\alpha$, so that, while $(\theta-Y_n)$ converges to zero in distribution and $n^\alpha$ goes to infinity, the product $$n^\alpha(\theta-Y_n)$$ converges to a standard distribution (in distribution).
This is e.g. the case for the Central Limit theorem: if the mean of $X$ is well-defined, $\bar{X}_n-\mathbb{E}[X]$ converges to zero in distribution, while $$\sqrt{n}(\bar{X}_n-\mathbb{E}[X])=n^{1/2}(\bar{X}_n-\mathbb{E}[X])$$ converges to a Normal distribution (in distribution).
To answer your question you thus have to find the right scale $n^\alpha$ (there is only one!) and then deduce the associated limiting distribution. Hint: Remember that
$$\lim_{n\to\infty} \left\{1-\frac{\beta}{n} \right\}^n = \exp\{-\beta\}\,.$$ | Determine the limiting distribution of Uniform Order Statistic | If you look at the cdf of $Y_n$, $$F_n(\delta)=\mathbb{P}(Y_n\le\delta)=(\delta/\theta)^n\qquad0\le\delta\le\theta\,,$$ you get that $F_n(\delta)$ converges to zero when $0\le\delta<\theta$, which mea | Determine the limiting distribution of Uniform Order Statistic
If you look at the cdf of $Y_n$, $$F_n(\delta)=\mathbb{P}(Y_n\le\delta)=(\delta/\theta)^n\qquad0\le\delta\le\theta\,,$$ you get that $F_n(\delta)$ converges to zero when $0\le\delta<\theta$, which means that $Y_n$ converges in probability to $\theta$:
$$Y_n\stackrel{\text{prob}}{\longrightarrow} \theta\,.$$ This implies that $Y_n$ also converges in distribution to the constant value random variable $\theta$:
$$Y_n\stackrel{\text{dist}}{\longrightarrow} \theta\,.$$ To get a more precise description of the asymptotic behaviour of $Y_n$, you need to zoom around $\theta$, i.e., to consider $(\theta-Y_n)$ scaled by a power of $n$, $n^\alpha$, so that, while $(\theta-Y_n)$ converges to zero in distribution and $n^\alpha$ goes to infinity, the product $$n^\alpha(\theta-Y_n)$$ converges to a standard distribution (in distribution).
This is e.g. the case for the Central Limit theorem: if the mean of $X$ is well-defined, $\bar{X}_n-\mathbb{E}[X]$ converges to zero in distribution, while $$\sqrt{n}(\bar{X}_n-\mathbb{E}[X])=n^{1/2}(\bar{X}_n-\mathbb{E}[X])$$ converges to a Normal distribution (in distribution).
To answer your question you thus have to find the right scale $n^\alpha$ (there is only one!) and then deduce the associated limiting distribution. Hint: Remember that
$$\lim_{n\to\infty} \left\{1-\frac{\beta}{n} \right\}^n = \exp\{-\beta\}\,.$$ | Determine the limiting distribution of Uniform Order Statistic
If you look at the cdf of $Y_n$, $$F_n(\delta)=\mathbb{P}(Y_n\le\delta)=(\delta/\theta)^n\qquad0\le\delta\le\theta\,,$$ you get that $F_n(\delta)$ converges to zero when $0\le\delta<\theta$, which mea |
35,165 | Determine the limiting distribution of Uniform Order Statistic | As suggested by Xi'an, work with the CDF
$$
F_n(t) = \Pr(Y_n\leq t)=\bigcap_{i=1}^n \Pr(X_i\leq t) = \prod_{i=1}^n \Pr(X_1\leq t) \, .
$$
Hence,
$$
F_n(t) = \begin{cases}
0 &,& t<0\,; \\
\left(t/\theta\right)^n &,& 0\leq t<\theta\,; \\
1 &,& t\geq\theta \, .
\end{cases}
$$
Plot a graph of this $F_n$.
For $t<0$ and $t\geq\theta$ you're done. Now, what is $\lim_{n\to\infty}F_n(t)$ for $0\leq t<\theta$?
Put everything together to find $F(t)$ such that $F_n(t)\to F(t)$ for every $t$ when $n\to\infty$.
Graph this $F$. What is the interpretation of $F$?
Is this result intuitive? Imagine yourself drawing huge samples from a $U[0,\theta]$ distribution and computing the sample maximum every time.
Can you code a short simulation in R which confirms your results? | Determine the limiting distribution of Uniform Order Statistic | As suggested by Xi'an, work with the CDF
$$
F_n(t) = \Pr(Y_n\leq t)=\bigcap_{i=1}^n \Pr(X_i\leq t) = \prod_{i=1}^n \Pr(X_1\leq t) \, .
$$
Hence,
$$
F_n(t) = \begin{cases}
0 &,& t<0\,; \\
\left(t/ | Determine the limiting distribution of Uniform Order Statistic
As suggested by Xi'an, work with the CDF
$$
F_n(t) = \Pr(Y_n\leq t)=\bigcap_{i=1}^n \Pr(X_i\leq t) = \prod_{i=1}^n \Pr(X_1\leq t) \, .
$$
Hence,
$$
F_n(t) = \begin{cases}
0 &,& t<0\,; \\
\left(t/\theta\right)^n &,& 0\leq t<\theta\,; \\
1 &,& t\geq\theta \, .
\end{cases}
$$
Plot a graph of this $F_n$.
For $t<0$ and $t\geq\theta$ you're done. Now, what is $\lim_{n\to\infty}F_n(t)$ for $0\leq t<\theta$?
Put everything together to find $F(t)$ such that $F_n(t)\to F(t)$ for every $t$ when $n\to\infty$.
Graph this $F$. What is the interpretation of $F$?
Is this result intuitive? Imagine yourself drawing huge samples from a $U[0,\theta]$ distribution and computing the sample maximum every time.
Can you code a short simulation in R which confirms your results? | Determine the limiting distribution of Uniform Order Statistic
As suggested by Xi'an, work with the CDF
$$
F_n(t) = \Pr(Y_n\leq t)=\bigcap_{i=1}^n \Pr(X_i\leq t) = \prod_{i=1}^n \Pr(X_1\leq t) \, .
$$
Hence,
$$
F_n(t) = \begin{cases}
0 &,& t<0\,; \\
\left(t/ |
35,166 | Hourly predictions using time series | Well, the difference is... that they are different methods. ("Can any one explain the difference between apples and oranges?")
ARIMA models are explained in any introductory time series book. (I'll never tire of recommending this free open source online forecasting textbook.) If you want to include weather info, you'd need ARIMA models with eXplanatory or eXternal information, or ARIMAX models. These are also standard.
Trees/CARTs/Random Forests are explained in any Data Science textbook, or even the Wikipedia pages. These will, of course, model explanatory variables "as-is". Your idea of using days, hours and months as features does make sense in this context. However, simply feeding independent dummies for "9-10am", "10-11am" and so forth into your model may or may not account for the fact that your observations in the 9-10am and the 10-11am time buckets will be more highly correlated than the ones in the 9-10am and the 1-2pm buckets.
A couple of random thoughts:
ARIMA(X) will have a hard time dealing with the multiple seasonalities involved (year-over-year, intra-week with people commuting to work Mon-Fri but not Sat/Sun, intra-day with more people biking during the day). You could in principle model these seasonalities using dummies in your ML models. Alternatively, there are a couple of approaches to multiple seasonalities in the context of Exponential Smoothing/State Space models.
Weather is of course highly correlated with time-of-year and time-of-day: it's hotter in summer and during the day than in winter and during the night. If you already model seasonality as above, you may find that adding weather information does not improve the forecasts very much beyond what seasonality already does.
If you want to forecast something using the weather, remember that you will need weather forecasts, too! Don't assess your out-of-sample forecasts based on how they work with actual weather - you won't know tomorrow's actual weather when you do "production" forecasting. The uncertainty in weather forecasts adds an additional source of uncertainty in your bicycling forecasts. In particular, weather forecasts are not very reliable for more than 15 days out, so they won't be very helpful for forecasting bike rides that far out. (Incidentally, getting historical weather data is far easier and cheaper than getting historical weather forecasts.)
You may want to look at the electricity price or load forecasting literature - that use case deals with many of your challenges (high frequency data, multiple seasonalities, weather influence). I haven't read this review yet, but it may be helpful. | Hourly predictions using time series | Well, the difference is... that they are different methods. ("Can any one explain the difference between apples and oranges?")
ARIMA models are explained in any introductory time series book. (I'll n | Hourly predictions using time series
Well, the difference is... that they are different methods. ("Can any one explain the difference between apples and oranges?")
ARIMA models are explained in any introductory time series book. (I'll never tire of recommending this free open source online forecasting textbook.) If you want to include weather info, you'd need ARIMA models with eXplanatory or eXternal information, or ARIMAX models. These are also standard.
Trees/CARTs/Random Forests are explained in any Data Science textbook, or even the Wikipedia pages. These will, of course, model explanatory variables "as-is". Your idea of using days, hours and months as features does make sense in this context. However, simply feeding independent dummies for "9-10am", "10-11am" and so forth into your model may or may not account for the fact that your observations in the 9-10am and the 10-11am time buckets will be more highly correlated than the ones in the 9-10am and the 1-2pm buckets.
A couple of random thoughts:
ARIMA(X) will have a hard time dealing with the multiple seasonalities involved (year-over-year, intra-week with people commuting to work Mon-Fri but not Sat/Sun, intra-day with more people biking during the day). You could in principle model these seasonalities using dummies in your ML models. Alternatively, there are a couple of approaches to multiple seasonalities in the context of Exponential Smoothing/State Space models.
Weather is of course highly correlated with time-of-year and time-of-day: it's hotter in summer and during the day than in winter and during the night. If you already model seasonality as above, you may find that adding weather information does not improve the forecasts very much beyond what seasonality already does.
If you want to forecast something using the weather, remember that you will need weather forecasts, too! Don't assess your out-of-sample forecasts based on how they work with actual weather - you won't know tomorrow's actual weather when you do "production" forecasting. The uncertainty in weather forecasts adds an additional source of uncertainty in your bicycling forecasts. In particular, weather forecasts are not very reliable for more than 15 days out, so they won't be very helpful for forecasting bike rides that far out. (Incidentally, getting historical weather data is far easier and cheaper than getting historical weather forecasts.)
You may want to look at the electricity price or load forecasting literature - that use case deals with many of your challenges (high frequency data, multiple seasonalities, weather influence). I haven't read this review yet, but it may be helpful. | Hourly predictions using time series
Well, the difference is... that they are different methods. ("Can any one explain the difference between apples and oranges?")
ARIMA models are explained in any introductory time series book. (I'll n |
35,167 | How to use the Hausman test for gender discrimination? | I see the reasoning behind this advice but i) this person should have explained it better to you and ii) they should have also mentioned the restrictive assumptions underlying this idea.
In the Hausman test you generally ask whether there is a difference between a consistent but inefficient model and a potential inconsistent model which is more efficient. In the standard case where you compare fixed and random effects the fixed effects estimator is consistent whether or not the individual effects are correlated with the other explanatory variables but it is less efficient than the random effects estimator which is only consistent for uncorrelated fixed effects with the explanatory variables.
Either of the two groups (male or female) will have fewer observations. A priori I would guess that this is the female group. So if you run the same regression specification
$$y_{it} = \alpha + X‘_{it}\beta + c_i + \epsilon_{it}$$
where $y$ is earnings, $X$ are the same time-variant explantory variables, $c_i$ are the individual fixed effects and $\epsilon$ is a stochastic error, then a difference between the male and female models would imply that there is a different treatment of men and women in terms of wages. The test statistics in this case would be
$$H = (\beta_{fem} - \beta_{male})'(Var(\beta_{fem}) - Var(\beta_{male}))(\beta_{fem} - \beta_{male})$$
However, and this is an important point, this whole reasoning is only true if the two models are correctly specified. It should be easy to come up with omitted gender-specific variables that are time-variant and that affect wages, e.g. child birth. This immediately breaks the main assumption of this idea so I would be careful with that. | How to use the Hausman test for gender discrimination? | I see the reasoning behind this advice but i) this person should have explained it better to you and ii) they should have also mentioned the restrictive assumptions underlying this idea.
In the Hausma | How to use the Hausman test for gender discrimination?
I see the reasoning behind this advice but i) this person should have explained it better to you and ii) they should have also mentioned the restrictive assumptions underlying this idea.
In the Hausman test you generally ask whether there is a difference between a consistent but inefficient model and a potential inconsistent model which is more efficient. In the standard case where you compare fixed and random effects the fixed effects estimator is consistent whether or not the individual effects are correlated with the other explanatory variables but it is less efficient than the random effects estimator which is only consistent for uncorrelated fixed effects with the explanatory variables.
Either of the two groups (male or female) will have fewer observations. A priori I would guess that this is the female group. So if you run the same regression specification
$$y_{it} = \alpha + X‘_{it}\beta + c_i + \epsilon_{it}$$
where $y$ is earnings, $X$ are the same time-variant explantory variables, $c_i$ are the individual fixed effects and $\epsilon$ is a stochastic error, then a difference between the male and female models would imply that there is a different treatment of men and women in terms of wages. The test statistics in this case would be
$$H = (\beta_{fem} - \beta_{male})'(Var(\beta_{fem}) - Var(\beta_{male}))(\beta_{fem} - \beta_{male})$$
However, and this is an important point, this whole reasoning is only true if the two models are correctly specified. It should be easy to come up with omitted gender-specific variables that are time-variant and that affect wages, e.g. child birth. This immediately breaks the main assumption of this idea so I would be careful with that. | How to use the Hausman test for gender discrimination?
I see the reasoning behind this advice but i) this person should have explained it better to you and ii) they should have also mentioned the restrictive assumptions underlying this idea.
In the Hausma |
35,168 | Efficient convolution (in R) | Have you taken a look at dedicated R packages for that? Like convolve, https://stat.ethz.ch/R-manual/R-devel/library/stats/html/convolve.html | Efficient convolution (in R) | Have you taken a look at dedicated R packages for that? Like convolve, https://stat.ethz.ch/R-manual/R-devel/library/stats/html/convolve.html | Efficient convolution (in R)
Have you taken a look at dedicated R packages for that? Like convolve, https://stat.ethz.ch/R-manual/R-devel/library/stats/html/convolve.html | Efficient convolution (in R)
Have you taken a look at dedicated R packages for that? Like convolve, https://stat.ethz.ch/R-manual/R-devel/library/stats/html/convolve.html |
35,169 | How to fit regression to custom model in R | You could fit a nonlinear regression. This would be suitable if - aside from the nonlinear relationship between $E(Y)$ and $x$ - your model assumptions were similar to ordinary regression (independence and constant variance, for example).
In R, see ?nls.
The difficulty with this particular model is finding suitable starting values. With a reparameterization, however, you might be able to get it into the form of one of the available self-start functions and save some trouble there (specifically, I believe SSasymp is the self start function for the reparameterized model you need). However, I managed to find reasonable enough start values and got convergence:
nlsfit <- nls(D.weight ~ a - b * exp(-c*N) ,P0,start=list(a=10,b=-20,c=.05))
summary(nlsfit)
Formula: D.weight ~ a - b * exp(-c * N)
Parameters:
Estimate Std. Error t value Pr(>|t|)
a 16.208572 6.222312 2.605 0.01617 *
b -22.000400 7.552922 -2.913 0.00806 **
c 0.011082 0.009454 1.172 0.25364
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 12.63 on 22 degrees of freedom
Number of iterations to convergence: 11
Achieved convergence tolerance: 8.554e-06
It seems to fit tolerably well, though the constant variance assumption may be suspect:
There's also some suggestion of the possibility of right skewness.
If you search for "nonlinear least squares" or "nls" you should turn up a number of posts, some with useful advice. I agree with the comments you've already received about seeking advice. | How to fit regression to custom model in R | You could fit a nonlinear regression. This would be suitable if - aside from the nonlinear relationship between $E(Y)$ and $x$ - your model assumptions were similar to ordinary regression (independenc | How to fit regression to custom model in R
You could fit a nonlinear regression. This would be suitable if - aside from the nonlinear relationship between $E(Y)$ and $x$ - your model assumptions were similar to ordinary regression (independence and constant variance, for example).
In R, see ?nls.
The difficulty with this particular model is finding suitable starting values. With a reparameterization, however, you might be able to get it into the form of one of the available self-start functions and save some trouble there (specifically, I believe SSasymp is the self start function for the reparameterized model you need). However, I managed to find reasonable enough start values and got convergence:
nlsfit <- nls(D.weight ~ a - b * exp(-c*N) ,P0,start=list(a=10,b=-20,c=.05))
summary(nlsfit)
Formula: D.weight ~ a - b * exp(-c * N)
Parameters:
Estimate Std. Error t value Pr(>|t|)
a 16.208572 6.222312 2.605 0.01617 *
b -22.000400 7.552922 -2.913 0.00806 **
c 0.011082 0.009454 1.172 0.25364
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 12.63 on 22 degrees of freedom
Number of iterations to convergence: 11
Achieved convergence tolerance: 8.554e-06
It seems to fit tolerably well, though the constant variance assumption may be suspect:
There's also some suggestion of the possibility of right skewness.
If you search for "nonlinear least squares" or "nls" you should turn up a number of posts, some with useful advice. I agree with the comments you've already received about seeking advice. | How to fit regression to custom model in R
You could fit a nonlinear regression. This would be suitable if - aside from the nonlinear relationship between $E(Y)$ and $x$ - your model assumptions were similar to ordinary regression (independenc |
35,170 | How to fit regression to custom model in R | @Glen_b provides the right path you should pursue. Here are some issues I would like to point out for this nonlinear modeling scenario.
First, the nonlinear fit @Glen_b showed has an underlying assumption that each observation, either at the same N or not, are independent. I noticed that you have a variable "R" which is the rep. I am not sure what it means, but it seems to me that there are 5 R's, i.e., r1, r2, r3,r4, and r5. So I am concerned that the data from each rep might be correlated (you might want to provide more information about your variables). If they're correlated, you might want to use the pooled mean at each nitrogen level N to fit the nonlinear least squares regression model. Otherwise, you should get similar point estimates, but the estimates of the standard errors are different.
Second, as for the initial values, here are the tricks you can use. Note that $a$ is the weight value when $x$ goes to positive infinity. So you can use the pooled mean of weight data from the largest $x$ (i.e., nitrogen level) at hand for $a$, since this would be the closest guess. Similarly, when $x=0, y = a - b$, thus you can then use the pooled mean of weight at $x=0$ to obtain the initial estimate for $a-b$. Thus you can figure out the initial guess for $b$. After that, you can choose data at an arbitrary $x$, and substitute $a, b$ to solve for the initial estimate $c$.
Third, if the data from each rep are truly correlated. You might want to first build a nonlinear random-effects model, assuming that at different level of R, the nonlinear curves are different, i.e., the $a, b, c$ are different. After you build the model, you can test whether each of the three random coefficients are significant or not. For example, random $a$ is essentially random intercept. If there is just random intercept, then that means all the nonlinear curves are the same shape, but just shift up and down by random $a$. I've not used R to do nonlinear mixed-effects model in R. But in SAS, the PROC NLMIXED exactly does this. | How to fit regression to custom model in R | @Glen_b provides the right path you should pursue. Here are some issues I would like to point out for this nonlinear modeling scenario.
First, the nonlinear fit @Glen_b showed has an underlying assump | How to fit regression to custom model in R
@Glen_b provides the right path you should pursue. Here are some issues I would like to point out for this nonlinear modeling scenario.
First, the nonlinear fit @Glen_b showed has an underlying assumption that each observation, either at the same N or not, are independent. I noticed that you have a variable "R" which is the rep. I am not sure what it means, but it seems to me that there are 5 R's, i.e., r1, r2, r3,r4, and r5. So I am concerned that the data from each rep might be correlated (you might want to provide more information about your variables). If they're correlated, you might want to use the pooled mean at each nitrogen level N to fit the nonlinear least squares regression model. Otherwise, you should get similar point estimates, but the estimates of the standard errors are different.
Second, as for the initial values, here are the tricks you can use. Note that $a$ is the weight value when $x$ goes to positive infinity. So you can use the pooled mean of weight data from the largest $x$ (i.e., nitrogen level) at hand for $a$, since this would be the closest guess. Similarly, when $x=0, y = a - b$, thus you can then use the pooled mean of weight at $x=0$ to obtain the initial estimate for $a-b$. Thus you can figure out the initial guess for $b$. After that, you can choose data at an arbitrary $x$, and substitute $a, b$ to solve for the initial estimate $c$.
Third, if the data from each rep are truly correlated. You might want to first build a nonlinear random-effects model, assuming that at different level of R, the nonlinear curves are different, i.e., the $a, b, c$ are different. After you build the model, you can test whether each of the three random coefficients are significant or not. For example, random $a$ is essentially random intercept. If there is just random intercept, then that means all the nonlinear curves are the same shape, but just shift up and down by random $a$. I've not used R to do nonlinear mixed-effects model in R. But in SAS, the PROC NLMIXED exactly does this. | How to fit regression to custom model in R
@Glen_b provides the right path you should pursue. Here are some issues I would like to point out for this nonlinear modeling scenario.
First, the nonlinear fit @Glen_b showed has an underlying assump |
35,171 | How to fit regression to custom model in R | I assumed that since you are not statistician I will give you a simple solution.
Install SPSS and go to regression >> non linear | How to fit regression to custom model in R | I assumed that since you are not statistician I will give you a simple solution.
Install SPSS and go to regression >> non linear | How to fit regression to custom model in R
I assumed that since you are not statistician I will give you a simple solution.
Install SPSS and go to regression >> non linear | How to fit regression to custom model in R
I assumed that since you are not statistician I will give you a simple solution.
Install SPSS and go to regression >> non linear |
35,172 | What is the meaning of $\oplus$ and $\otimes$? | In statistics, $$A\oplus B:=\left[\begin{array}{cc}A & 0 \\ 0 & B \end{array} \right]$$ and (e.g. for a $2\times 2$-matrix $A$)
$$A\otimes B:=\left[\begin{array}{cc}a_{11}B & a_{12}B \\ a_{21}B & a_{22}B \end{array} \right].$$
This focuses on matrices for their use in statistics as design or hypothesis matrices etc., where these notations simplify the frequent block structure of such matrices. One can find the name Kronecker sum for $\oplus$ and Kronecker product for $\otimes$, especially in the manuals of statistical software. (Also very handy is the component wise matrix multiplication $A\#B=[a_{ij}b_{ij}]_{i,j}$ for equally shaped matrices. It's sometimes called Hadamard product.)
In mathematics, $\oplus$ and $\otimes$ have their slightly different typical meaning as direct sum or tensor product of vector spaces or even more general algebraic structures. | What is the meaning of $\oplus$ and $\otimes$? | In statistics, $$A\oplus B:=\left[\begin{array}{cc}A & 0 \\ 0 & B \end{array} \right]$$ and (e.g. for a $2\times 2$-matrix $A$)
$$A\otimes B:=\left[\begin{array}{cc}a_{11}B & a_{12}B \\ a_{21}B & a_{2 | What is the meaning of $\oplus$ and $\otimes$?
In statistics, $$A\oplus B:=\left[\begin{array}{cc}A & 0 \\ 0 & B \end{array} \right]$$ and (e.g. for a $2\times 2$-matrix $A$)
$$A\otimes B:=\left[\begin{array}{cc}a_{11}B & a_{12}B \\ a_{21}B & a_{22}B \end{array} \right].$$
This focuses on matrices for their use in statistics as design or hypothesis matrices etc., where these notations simplify the frequent block structure of such matrices. One can find the name Kronecker sum for $\oplus$ and Kronecker product for $\otimes$, especially in the manuals of statistical software. (Also very handy is the component wise matrix multiplication $A\#B=[a_{ij}b_{ij}]_{i,j}$ for equally shaped matrices. It's sometimes called Hadamard product.)
In mathematics, $\oplus$ and $\otimes$ have their slightly different typical meaning as direct sum or tensor product of vector spaces or even more general algebraic structures. | What is the meaning of $\oplus$ and $\otimes$?
In statistics, $$A\oplus B:=\left[\begin{array}{cc}A & 0 \\ 0 & B \end{array} \right]$$ and (e.g. for a $2\times 2$-matrix $A$)
$$A\otimes B:=\left[\begin{array}{cc}a_{11}B & a_{12}B \\ a_{21}B & a_{2 |
35,173 | What is the meaning of $\oplus$ and $\otimes$? | Suppose $A=\begin{pmatrix}a&b\\c&d\end{pmatrix}$ and $B=\begin{pmatrix}e&f\\g&h\end{pmatrix}$
Then,
A$\otimes$B=$\begin{pmatrix}a&b\\c&d\end{pmatrix}$ $\otimes$ $\begin{pmatrix}e&f\\g&h\end{pmatrix}$=\begin{pmatrix} a {\begin{pmatrix}e&f\\g&h\end{pmatrix}}&b{\begin{pmatrix}e&f\\g&h\end{pmatrix}}\\c{\begin{pmatrix}e&f\\g&h\end{pmatrix}}&d{\begin{pmatrix}e&f\\g&h\end{pmatrix}}\end{pmatrix}
And
A$\oplus B=\begin{bmatrix}A&0\\0&B\end{bmatrix}$ | What is the meaning of $\oplus$ and $\otimes$? | Suppose $A=\begin{pmatrix}a&b\\c&d\end{pmatrix}$ and $B=\begin{pmatrix}e&f\\g&h\end{pmatrix}$
Then,
A$\otimes$B=$\begin{pmatrix}a&b\\c&d\end{pmatrix}$ $\otimes$ $\begin{pmatrix}e&f\\g&h\end{pmatrix}$= | What is the meaning of $\oplus$ and $\otimes$?
Suppose $A=\begin{pmatrix}a&b\\c&d\end{pmatrix}$ and $B=\begin{pmatrix}e&f\\g&h\end{pmatrix}$
Then,
A$\otimes$B=$\begin{pmatrix}a&b\\c&d\end{pmatrix}$ $\otimes$ $\begin{pmatrix}e&f\\g&h\end{pmatrix}$=\begin{pmatrix} a {\begin{pmatrix}e&f\\g&h\end{pmatrix}}&b{\begin{pmatrix}e&f\\g&h\end{pmatrix}}\\c{\begin{pmatrix}e&f\\g&h\end{pmatrix}}&d{\begin{pmatrix}e&f\\g&h\end{pmatrix}}\end{pmatrix}
And
A$\oplus B=\begin{bmatrix}A&0\\0&B\end{bmatrix}$ | What is the meaning of $\oplus$ and $\otimes$?
Suppose $A=\begin{pmatrix}a&b\\c&d\end{pmatrix}$ and $B=\begin{pmatrix}e&f\\g&h\end{pmatrix}$
Then,
A$\otimes$B=$\begin{pmatrix}a&b\\c&d\end{pmatrix}$ $\otimes$ $\begin{pmatrix}e&f\\g&h\end{pmatrix}$= |
35,174 | Oddly large R squared values in meta regression (metafor) | The pseudo-$R^2$ value that is reported is computed with: $$R^2 = \frac{\hat{\tau}^2_{RE} - \hat{\tau}^2_{ME}}{\hat{\tau}^2_{RE}},$$ where $\hat{\tau}^2_{RE}$ is the (total) amount of heterogeneity as estimated based on a random-effects model and $\hat{\tau}^2_{ME}$ is the amount of (residual) heterogeneity as estimated based on the mixed-effects meta-regression model. Note that this isn't anything specific to the metafor package -- it's how this value is typically computed in mixed-effects meta-regression models.
This value estimates the amount of heterogeneity that is accounted for by the moderators/covariates included in the meta-regression model (i.e., it is the proportional reduction in the amount of heterogeneity after including moderators/covariates in the model). Note that it does not involve sampling variability at all. Hence, it is quite possible to get very large $R^2$ values, even when there are still discrepancies between the regression line and the observed effect sizes (when those discrepancies are not much larger than what one would expect based on sampling variability alone). In fact, when $\hat{\tau}^2_{ME} = 0$ (which can certainly happen), then $R^2 = 1$ -- but this doesn't imply that the points all fall on the regression line (the residuals are just not larger than expected based on sampling variability).
Regardless, it is important to realize that this pseudo-$R^2$ statistic is not very trustworthy unless the number of studies is large. See, for example, this article:
López-López, J. A., Marín-Martínez, F., Sánchez-Meca, J., Van den Noortgate, W., & Viechtbauer, W. (2014). Estimation of the predictive power of the model in mixed-effects meta-regression: A simulation study. British Journal of Mathematical and Statistical Psychology, 67(1), 30–48.
In essence, I wouldn't place too much trust in the actual value unless you have at least 30 studies (but don't quote me exactly on that figure). For a nice exercise, you could use bootstrapping to obtain an approximate CI for $R^2$. Pretty much all you need to know to do this is explained here:
http://www.metafor-project.org/doku.php/tips:bootstrapping_with_ma
Just change the value that is returned by the boot.func() function to res$R2 (and since there is no variance estimate for $R^2$, you cannot get the studentized intervals). In your case, you will probably end up with a very wide CI (possibly extending pretty much from 0 to 100%). | Oddly large R squared values in meta regression (metafor) | The pseudo-$R^2$ value that is reported is computed with: $$R^2 = \frac{\hat{\tau}^2_{RE} - \hat{\tau}^2_{ME}}{\hat{\tau}^2_{RE}},$$ where $\hat{\tau}^2_{RE}$ is the (total) amount of heterogeneity as | Oddly large R squared values in meta regression (metafor)
The pseudo-$R^2$ value that is reported is computed with: $$R^2 = \frac{\hat{\tau}^2_{RE} - \hat{\tau}^2_{ME}}{\hat{\tau}^2_{RE}},$$ where $\hat{\tau}^2_{RE}$ is the (total) amount of heterogeneity as estimated based on a random-effects model and $\hat{\tau}^2_{ME}$ is the amount of (residual) heterogeneity as estimated based on the mixed-effects meta-regression model. Note that this isn't anything specific to the metafor package -- it's how this value is typically computed in mixed-effects meta-regression models.
This value estimates the amount of heterogeneity that is accounted for by the moderators/covariates included in the meta-regression model (i.e., it is the proportional reduction in the amount of heterogeneity after including moderators/covariates in the model). Note that it does not involve sampling variability at all. Hence, it is quite possible to get very large $R^2$ values, even when there are still discrepancies between the regression line and the observed effect sizes (when those discrepancies are not much larger than what one would expect based on sampling variability alone). In fact, when $\hat{\tau}^2_{ME} = 0$ (which can certainly happen), then $R^2 = 1$ -- but this doesn't imply that the points all fall on the regression line (the residuals are just not larger than expected based on sampling variability).
Regardless, it is important to realize that this pseudo-$R^2$ statistic is not very trustworthy unless the number of studies is large. See, for example, this article:
López-López, J. A., Marín-Martínez, F., Sánchez-Meca, J., Van den Noortgate, W., & Viechtbauer, W. (2014). Estimation of the predictive power of the model in mixed-effects meta-regression: A simulation study. British Journal of Mathematical and Statistical Psychology, 67(1), 30–48.
In essence, I wouldn't place too much trust in the actual value unless you have at least 30 studies (but don't quote me exactly on that figure). For a nice exercise, you could use bootstrapping to obtain an approximate CI for $R^2$. Pretty much all you need to know to do this is explained here:
http://www.metafor-project.org/doku.php/tips:bootstrapping_with_ma
Just change the value that is returned by the boot.func() function to res$R2 (and since there is no variance estimate for $R^2$, you cannot get the studentized intervals). In your case, you will probably end up with a very wide CI (possibly extending pretty much from 0 to 100%). | Oddly large R squared values in meta regression (metafor)
The pseudo-$R^2$ value that is reported is computed with: $$R^2 = \frac{\hat{\tau}^2_{RE} - \hat{\tau}^2_{ME}}{\hat{\tau}^2_{RE}},$$ where $\hat{\tau}^2_{RE}$ is the (total) amount of heterogeneity as |
35,175 | Predict observation using Hidden Markov Models | From your question, I understood (hopefully correctly) that you want to estimate the next observation, given the observations up to now. Let $y_{1:N} = Y$ the N observations you have seen until now and let $\Theta$ be the parameters of the HMM. Then you want to infer the probability of the next observation given the already observed data, which can be expressed as:
$$ P(y_{N+1}|y_{1:N}=Y,\Theta)$$
If this is what you want, the above conditional expression is equal to :
$$ P(y_{N+1}|y_{1:N}=Y,\Theta) = \dfrac{P(y_{1:N}=Y, y_{N+1}|\Theta)}{P(y_{1:N}=Y|\Theta)}$$
Note that the denominator is independent from $y_{N+1}$. So, it is:
$$ P(y_{N+1}|y_{1:N}=Y,\Theta) \propto P(y_{1:N}=Y, y_{N+1}|\Theta)$$
A brute force approach is the following:
For each of your possible observations, $y_{N+1}=Click, y_{N+1}=Scroll$ etc, calculate the likelihood of the sequences $y_{1:N+1}$. So what you need to calculate is $P(y_{N+1}=Click,y_{1:N}=Y|\Theta)$ , $P(y_{N+1}=Scroll,y_{1:N}=Y|\Theta)$, etc. for each of your possible observation sequences. Then the $y_{N+1}$ which gives the maximum likelihood can be estimated as the best guess for the next observation. Note that each of these likelihood calculations is a straightforward application of the forward pass algorithm, which corresponds to one of the three problems of HMMs: The calculation of the likelihood of a observation sequence. You have stated this in b) in your question.
Hope this helps. | Predict observation using Hidden Markov Models | From your question, I understood (hopefully correctly) that you want to estimate the next observation, given the observations up to now. Let $y_{1:N} = Y$ the N observations you have seen until now an | Predict observation using Hidden Markov Models
From your question, I understood (hopefully correctly) that you want to estimate the next observation, given the observations up to now. Let $y_{1:N} = Y$ the N observations you have seen until now and let $\Theta$ be the parameters of the HMM. Then you want to infer the probability of the next observation given the already observed data, which can be expressed as:
$$ P(y_{N+1}|y_{1:N}=Y,\Theta)$$
If this is what you want, the above conditional expression is equal to :
$$ P(y_{N+1}|y_{1:N}=Y,\Theta) = \dfrac{P(y_{1:N}=Y, y_{N+1}|\Theta)}{P(y_{1:N}=Y|\Theta)}$$
Note that the denominator is independent from $y_{N+1}$. So, it is:
$$ P(y_{N+1}|y_{1:N}=Y,\Theta) \propto P(y_{1:N}=Y, y_{N+1}|\Theta)$$
A brute force approach is the following:
For each of your possible observations, $y_{N+1}=Click, y_{N+1}=Scroll$ etc, calculate the likelihood of the sequences $y_{1:N+1}$. So what you need to calculate is $P(y_{N+1}=Click,y_{1:N}=Y|\Theta)$ , $P(y_{N+1}=Scroll,y_{1:N}=Y|\Theta)$, etc. for each of your possible observation sequences. Then the $y_{N+1}$ which gives the maximum likelihood can be estimated as the best guess for the next observation. Note that each of these likelihood calculations is a straightforward application of the forward pass algorithm, which corresponds to one of the three problems of HMMs: The calculation of the likelihood of a observation sequence. You have stated this in b) in your question.
Hope this helps. | Predict observation using Hidden Markov Models
From your question, I understood (hopefully correctly) that you want to estimate the next observation, given the observations up to now. Let $y_{1:N} = Y$ the N observations you have seen until now an |
35,176 | Predict observation using Hidden Markov Models | You can solve this problem with 2 way.
You can set new observations to your HMM model and run forward probabilities.Once you have you should focus on last column of probabilities because the forward algorithm efficiently sums over all the probabilities of all possible paths to each state for each observation in each sequence. The end result is that the log-likelihood values in the final observation columns represent the likelihood over all possible paths through the HMM.Once you find most likely state then just need to find new observation from emission matrix. And for the second observation you should look transition matrix for next state and once you sample next state you should calculate 2nd observation from emission matrix...
Second option to find max likelihood of new observations from all possible observations in forward probabilities. As you mentioned you need to run all observations and same as first method you just need to calculate likelihood for last column.(I mentioned the reason already).Once you find the maximum likely observation you can set it and can calculate for the 2nd observation with same way.
for the seqHMM package
1st option
model$transition_probs[,apply(fb$forward_probs[, , 1], 2, which.max)[column_number]]
2nd option
fb_<-forward_backward(model_,forward_only = TRUE)
fb_<-data.frame(fb_$forward_probs)
last_probs<-fb_[,ncol(fb_)]
print(logSumExp(last_probs)) | Predict observation using Hidden Markov Models | You can solve this problem with 2 way.
You can set new observations to your HMM model and run forward probabilities.Once you have you should focus on last column of probabilities because the forward | Predict observation using Hidden Markov Models
You can solve this problem with 2 way.
You can set new observations to your HMM model and run forward probabilities.Once you have you should focus on last column of probabilities because the forward algorithm efficiently sums over all the probabilities of all possible paths to each state for each observation in each sequence. The end result is that the log-likelihood values in the final observation columns represent the likelihood over all possible paths through the HMM.Once you find most likely state then just need to find new observation from emission matrix. And for the second observation you should look transition matrix for next state and once you sample next state you should calculate 2nd observation from emission matrix...
Second option to find max likelihood of new observations from all possible observations in forward probabilities. As you mentioned you need to run all observations and same as first method you just need to calculate likelihood for last column.(I mentioned the reason already).Once you find the maximum likely observation you can set it and can calculate for the 2nd observation with same way.
for the seqHMM package
1st option
model$transition_probs[,apply(fb$forward_probs[, , 1], 2, which.max)[column_number]]
2nd option
fb_<-forward_backward(model_,forward_only = TRUE)
fb_<-data.frame(fb_$forward_probs)
last_probs<-fb_[,ncol(fb_)]
print(logSumExp(last_probs)) | Predict observation using Hidden Markov Models
You can solve this problem with 2 way.
You can set new observations to your HMM model and run forward probabilities.Once you have you should focus on last column of probabilities because the forward |
35,177 | Question about standard deviation and central limit theorem | Yes, the sample standard deviation is asymptotically normal. Let the sample standard deviation be $\hat{\sigma} = \sqrt{\frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2}$, and let $\sigma$ be the population standard deviation. Let's use the central limit theorem to show that
$$ \sqrt{n}(\hat{\sigma} - \sigma) \xrightarrow{d} N(0, V). $$
First write things as
$$ \sqrt{n}(\hat{\sigma} - \sigma) = \sqrt{n}\left(\sqrt{ \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2} - \sqrt{\sigma^2} \right)$$
The central limit theorem tells is about how sample moments minus population moments behave. If we didn't have square roots above, we'd just have something like sample moments minus population ones, and we could use the central limit theorem. To get rid of the square roots, let's take a Taylor expansion of the first square root around $\sigma^2$.
$$ \sqrt{ \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2} = \sqrt{\sigma^2} + \frac{1}{2\sigma} \left( \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right) + O\left(\left( \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right)^2\right)
$$
Plugging this into the above, we have
$$\sqrt{n}(\hat{\sigma} - \sigma) = \frac{\sqrt{n}}{2 \sigma} \left( \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right) + O\left(\frac{1}{n^{3/2}} \left(\sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right)^2\right)$$
Rearranging the first term on the right gives
$$\frac{\sqrt{n}}{2 \sigma} \left( \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right) = \frac{1}{2\sigma \sqrt{n}} \sum_{i=1}^n ((x_i - E[X])^2 - \sigma^2) - \frac{\sqrt{n}}{2\sigma}(\bar{x} - E[x])^2 $$
The central limit theorem tells us that under some conditions $\frac{1}{\sqrt{n}} \sum_{i=1}^n (y_i - E[y]) \xrightarrow{d} N(0, \sigma_y^2)$. With $y_i = (x_i - E[x])^2$ and $E[y] = \sigma^2$, then the first term on the right converges in distribution to a normal.
The second term we can write as $\sqrt{n}(\bar{x} - E[x]) (\bar{x} - E[x])$, and since $\sqrt{n}(\bar{x} - E[x]) \xrightarrow{d} N$ and $(\bar{x} - E[x]) \xrightarrow{p} 0$, by Slutsky's lemma, the product converges in probability to 0.
Similarly, we could show that, $\frac{1}{n^{3/2}} \left(\sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right)^2 \xrightarrow{p} 0$, so the remainder from the Taylor expansion vanishes.
This Taylor expansion trick comes up often, so it has a name. It's called the delta method. | Question about standard deviation and central limit theorem | Yes, the sample standard deviation is asymptotically normal. Let the sample standard deviation be $\hat{\sigma} = \sqrt{\frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2}$, and let $\sigma$ be the population | Question about standard deviation and central limit theorem
Yes, the sample standard deviation is asymptotically normal. Let the sample standard deviation be $\hat{\sigma} = \sqrt{\frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2}$, and let $\sigma$ be the population standard deviation. Let's use the central limit theorem to show that
$$ \sqrt{n}(\hat{\sigma} - \sigma) \xrightarrow{d} N(0, V). $$
First write things as
$$ \sqrt{n}(\hat{\sigma} - \sigma) = \sqrt{n}\left(\sqrt{ \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2} - \sqrt{\sigma^2} \right)$$
The central limit theorem tells is about how sample moments minus population moments behave. If we didn't have square roots above, we'd just have something like sample moments minus population ones, and we could use the central limit theorem. To get rid of the square roots, let's take a Taylor expansion of the first square root around $\sigma^2$.
$$ \sqrt{ \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2} = \sqrt{\sigma^2} + \frac{1}{2\sigma} \left( \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right) + O\left(\left( \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right)^2\right)
$$
Plugging this into the above, we have
$$\sqrt{n}(\hat{\sigma} - \sigma) = \frac{\sqrt{n}}{2 \sigma} \left( \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right) + O\left(\frac{1}{n^{3/2}} \left(\sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right)^2\right)$$
Rearranging the first term on the right gives
$$\frac{\sqrt{n}}{2 \sigma} \left( \frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right) = \frac{1}{2\sigma \sqrt{n}} \sum_{i=1}^n ((x_i - E[X])^2 - \sigma^2) - \frac{\sqrt{n}}{2\sigma}(\bar{x} - E[x])^2 $$
The central limit theorem tells us that under some conditions $\frac{1}{\sqrt{n}} \sum_{i=1}^n (y_i - E[y]) \xrightarrow{d} N(0, \sigma_y^2)$. With $y_i = (x_i - E[x])^2$ and $E[y] = \sigma^2$, then the first term on the right converges in distribution to a normal.
The second term we can write as $\sqrt{n}(\bar{x} - E[x]) (\bar{x} - E[x])$, and since $\sqrt{n}(\bar{x} - E[x]) \xrightarrow{d} N$ and $(\bar{x} - E[x]) \xrightarrow{p} 0$, by Slutsky's lemma, the product converges in probability to 0.
Similarly, we could show that, $\frac{1}{n^{3/2}} \left(\sum_{i=1}^n (x_i - \bar{x})^2 - \sigma^2\right)^2 \xrightarrow{p} 0$, so the remainder from the Taylor expansion vanishes.
This Taylor expansion trick comes up often, so it has a name. It's called the delta method. | Question about standard deviation and central limit theorem
Yes, the sample standard deviation is asymptotically normal. Let the sample standard deviation be $\hat{\sigma} = \sqrt{\frac{1}{n} \sum_{i=1}^n (x_i - \bar{x})^2}$, and let $\sigma$ be the population |
35,178 | Question about standard deviation and central limit theorem | In the comments on Paul's answer Whuber commented that the case of a Bernoulli variable with $p=1/2$ contradicts with his argument. In this question we look further into the Delta method with a graphic. This will provide some intuition and explanation about the (multivariate) Delta method and it explains why the Bernoulli variable is an exception (the only exception along with a degenerate variable).
Graphical description and intuition
The standard deviation of a sample equals $\hat\sigma = \sqrt{\hat\mu_2-{\hat\mu_1}^2}$ with $\hat\mu_1 = \frac{1}{n} \sum {x_i}$ and $\hat\mu_2 = \frac{1}{n} \sum {x_i}^2$. We can consider the sample joint distribution of $\mu_1,\mu_2$. The deviation of this sample distribution (scaled by $\sqrt{n}$) should approach a multivariate normal distribution with covariance equal to the covariance of the population distribution of a single point.
On top of the distribution of $\hat\mu_1$ and $\hat\mu_2$ we can consider isolines for $\hat\sigma = \sqrt{\hat\mu_2-{\hat\mu_1}^2} = constant$.
The $\hat\sigma$ is a non-linear function $\hat\mu_1$ and $\hat\mu_2$ but when we consider a small region then the non-linear function can be approximated with a linear function (the delta method does not only require that that a distribution approximates a normal distribution, but also that the variance becomes small).
If the mean $E(\hat\mu_1) = 0$ (which we can choose without loss of generality by translation of the variable) then $\hat\sigma^2 = \hat\mu_2-{\hat\mu_1}^2$ becomes approximately a normal distributed variable with mean equal to the second moment of the variable and variance equal to the difference of the fourth and second moment $$\sqrt{n}( \hat\sigma^2 - E(\hat\sigma^2)) \xrightarrow[]{P} N(0, E(X^4)-E(X^2)^2)$$
The distribution of $\hat\sigma = \sqrt{\hat\sigma^2}$ can be related to this by the series expansion around $\hat\sigma^2 = E(\hat\sigma^2)$ which is $$\sqrt{\hat\sigma^2} = \sqrt{E(\hat\sigma^2)} + \frac{\hat\sigma^2 - E(\hat\sigma^2)}{2\sqrt{E(\hat\sigma^2)}} + O\left((\hat\sigma^2 - E(\hat\sigma^2))^2\right)$$ and for the limit distribution
$$\sqrt{n}( \hat\sigma - \sqrt{E(\hat\sigma^2)}) \xrightarrow[]{P} N\left(0,\frac{ E(X^4)-E(X^2)^2}{4 E(\hat\sigma^2)}\right)$$
This is the limiting distribution. It might not be optimal for approximations of intermediate steps. For instance the mean $\sqrt{E(\hat\sigma^2)}$ is biased and not the same as $E(\hat\sigma)$ (but the bias shrinks to 0 for increasing sample size and that's why it still works as a limit distribution). A similar situation is when you take the logarithm of an approximately normal distributed variable, and you can do better than the Delta method.
The issue with the Bernoulli variable is that the limiting sample distribution of $\hat\mu_1,\hat\mu_2$ is a fully correlated multivariate normal distribution (the population distribution of the $x_i,{x_i}^2$ are just two points and the distribution of the sample mean will be on a straight line between those two points).
In the case of $p=1/2$ (and $x_i = \pm 1$ such that the mean of $x_i$ is zero) the orientation is horizontal; the variance of $\hat\mu_2$ (which is in the vertical direction) is zero, and the first order Delta method does not work (similar question/situation is here). Instead one needs to use the second order Delta method and the distribution becomes related to a chi squared distribution instead of a normal distribution. | Question about standard deviation and central limit theorem | In the comments on Paul's answer Whuber commented that the case of a Bernoulli variable with $p=1/2$ contradicts with his argument. In this question we look further into the Delta method with a graphi | Question about standard deviation and central limit theorem
In the comments on Paul's answer Whuber commented that the case of a Bernoulli variable with $p=1/2$ contradicts with his argument. In this question we look further into the Delta method with a graphic. This will provide some intuition and explanation about the (multivariate) Delta method and it explains why the Bernoulli variable is an exception (the only exception along with a degenerate variable).
Graphical description and intuition
The standard deviation of a sample equals $\hat\sigma = \sqrt{\hat\mu_2-{\hat\mu_1}^2}$ with $\hat\mu_1 = \frac{1}{n} \sum {x_i}$ and $\hat\mu_2 = \frac{1}{n} \sum {x_i}^2$. We can consider the sample joint distribution of $\mu_1,\mu_2$. The deviation of this sample distribution (scaled by $\sqrt{n}$) should approach a multivariate normal distribution with covariance equal to the covariance of the population distribution of a single point.
On top of the distribution of $\hat\mu_1$ and $\hat\mu_2$ we can consider isolines for $\hat\sigma = \sqrt{\hat\mu_2-{\hat\mu_1}^2} = constant$.
The $\hat\sigma$ is a non-linear function $\hat\mu_1$ and $\hat\mu_2$ but when we consider a small region then the non-linear function can be approximated with a linear function (the delta method does not only require that that a distribution approximates a normal distribution, but also that the variance becomes small).
If the mean $E(\hat\mu_1) = 0$ (which we can choose without loss of generality by translation of the variable) then $\hat\sigma^2 = \hat\mu_2-{\hat\mu_1}^2$ becomes approximately a normal distributed variable with mean equal to the second moment of the variable and variance equal to the difference of the fourth and second moment $$\sqrt{n}( \hat\sigma^2 - E(\hat\sigma^2)) \xrightarrow[]{P} N(0, E(X^4)-E(X^2)^2)$$
The distribution of $\hat\sigma = \sqrt{\hat\sigma^2}$ can be related to this by the series expansion around $\hat\sigma^2 = E(\hat\sigma^2)$ which is $$\sqrt{\hat\sigma^2} = \sqrt{E(\hat\sigma^2)} + \frac{\hat\sigma^2 - E(\hat\sigma^2)}{2\sqrt{E(\hat\sigma^2)}} + O\left((\hat\sigma^2 - E(\hat\sigma^2))^2\right)$$ and for the limit distribution
$$\sqrt{n}( \hat\sigma - \sqrt{E(\hat\sigma^2)}) \xrightarrow[]{P} N\left(0,\frac{ E(X^4)-E(X^2)^2}{4 E(\hat\sigma^2)}\right)$$
This is the limiting distribution. It might not be optimal for approximations of intermediate steps. For instance the mean $\sqrt{E(\hat\sigma^2)}$ is biased and not the same as $E(\hat\sigma)$ (but the bias shrinks to 0 for increasing sample size and that's why it still works as a limit distribution). A similar situation is when you take the logarithm of an approximately normal distributed variable, and you can do better than the Delta method.
The issue with the Bernoulli variable is that the limiting sample distribution of $\hat\mu_1,\hat\mu_2$ is a fully correlated multivariate normal distribution (the population distribution of the $x_i,{x_i}^2$ are just two points and the distribution of the sample mean will be on a straight line between those two points).
In the case of $p=1/2$ (and $x_i = \pm 1$ such that the mean of $x_i$ is zero) the orientation is horizontal; the variance of $\hat\mu_2$ (which is in the vertical direction) is zero, and the first order Delta method does not work (similar question/situation is here). Instead one needs to use the second order Delta method and the distribution becomes related to a chi squared distribution instead of a normal distribution. | Question about standard deviation and central limit theorem
In the comments on Paul's answer Whuber commented that the case of a Bernoulli variable with $p=1/2$ contradicts with his argument. In this question we look further into the Delta method with a graphi |
35,179 | Do kernel methods "scale" with the amount of data? | It's not necessary to hold the whole kernel matrix in memory at all times, but ofcourse you pay a price of recomputing entries if you don't. Kernel methods are very efficient in dealing with high input dimensionality thanks to the kernel trick, but as you correctly note they don't scale up that easily to large numbers of training instances.
Nonlinear SVM, for example, has a $\Omega(n^2)$ training complexity ($n$ number of instances). This is no problem for data sets up to a few million instances, but after that it is no longer feasible. At that point, approximations can be used such as fixed-size kernels or ensemble of smaller SVM base models. | Do kernel methods "scale" with the amount of data? | It's not necessary to hold the whole kernel matrix in memory at all times, but ofcourse you pay a price of recomputing entries if you don't. Kernel methods are very efficient in dealing with high inpu | Do kernel methods "scale" with the amount of data?
It's not necessary to hold the whole kernel matrix in memory at all times, but ofcourse you pay a price of recomputing entries if you don't. Kernel methods are very efficient in dealing with high input dimensionality thanks to the kernel trick, but as you correctly note they don't scale up that easily to large numbers of training instances.
Nonlinear SVM, for example, has a $\Omega(n^2)$ training complexity ($n$ number of instances). This is no problem for data sets up to a few million instances, but after that it is no longer feasible. At that point, approximations can be used such as fixed-size kernels or ensemble of smaller SVM base models. | Do kernel methods "scale" with the amount of data?
It's not necessary to hold the whole kernel matrix in memory at all times, but ofcourse you pay a price of recomputing entries if you don't. Kernel methods are very efficient in dealing with high inpu |
35,180 | Do kernel methods "scale" with the amount of data? | There is a rich history of literature about dealing with large kernels.
"Random features for large-scale kernel machines" by Rahimi and Recht is an important milestone. They embed the input in a lower dimension in a randomized fashion to achieve scalability. This work has spawned further interesting works in dealing with different types of kernels etc.
The Nystrom method based approach is another way to deal with large kernels. Again, this approach has been addressed by several works.
Recently, Divide-and-conquer kernel SVM has addressed this problem in distributed setting. Check out: www.cs.utexas.edu/~cjhsieh/dcsvm/ | Do kernel methods "scale" with the amount of data? | There is a rich history of literature about dealing with large kernels.
"Random features for large-scale kernel machines" by Rahimi and Recht is an important milestone. They embed the input in a lower | Do kernel methods "scale" with the amount of data?
There is a rich history of literature about dealing with large kernels.
"Random features for large-scale kernel machines" by Rahimi and Recht is an important milestone. They embed the input in a lower dimension in a randomized fashion to achieve scalability. This work has spawned further interesting works in dealing with different types of kernels etc.
The Nystrom method based approach is another way to deal with large kernels. Again, this approach has been addressed by several works.
Recently, Divide-and-conquer kernel SVM has addressed this problem in distributed setting. Check out: www.cs.utexas.edu/~cjhsieh/dcsvm/ | Do kernel methods "scale" with the amount of data?
There is a rich history of literature about dealing with large kernels.
"Random features for large-scale kernel machines" by Rahimi and Recht is an important milestone. They embed the input in a lower |
35,181 | Do kernel methods "scale" with the amount of data? | I think some kernel computation can be distributed to the cluster. Then this algorithm could be regarded as scalable, since there are huge amount of memory and cpu in the computing cluster. | Do kernel methods "scale" with the amount of data? | I think some kernel computation can be distributed to the cluster. Then this algorithm could be regarded as scalable, since there are huge amount of memory and cpu in the computing cluster. | Do kernel methods "scale" with the amount of data?
I think some kernel computation can be distributed to the cluster. Then this algorithm could be regarded as scalable, since there are huge amount of memory and cpu in the computing cluster. | Do kernel methods "scale" with the amount of data?
I think some kernel computation can be distributed to the cluster. Then this algorithm could be regarded as scalable, since there are huge amount of memory and cpu in the computing cluster. |
35,182 | How to calculate the covariance between two observations of the same variable? | @AndyW has provided a nice answer. Let me throw out one small additional point relative to the "[w]hat does this mean" part of your question.
It does seem incomprehensible that there can be a covariance between two single points. What you need to bear in mind is that the two points you have are just realizations from two error distributions at two $X$ values. The assumption that ${\rm Cov}[\varepsilon_i,\varepsilon_j] = 0$ pertains to the error distributions of the data generating process, not actually to the realized data.
In theory, it is possible that the error distribution for March is correlated with the error distribution for February, but that all other pairings of error distributions would be perfectly uncorrelated. With just one data point each from February and March, this cannot be checked (it is also a very bizarre possibility). Instead, what we do, in effect, is test the residuals at lags. That is, we would check, e.g., the covariance of every data point with the point before it. Now you have two sets of data such that you can check the covariance. | How to calculate the covariance between two observations of the same variable? | @AndyW has provided a nice answer. Let me throw out one small additional point relative to the "[w]hat does this mean" part of your question.
It does seem incomprehensible that there can be a covar | How to calculate the covariance between two observations of the same variable?
@AndyW has provided a nice answer. Let me throw out one small additional point relative to the "[w]hat does this mean" part of your question.
It does seem incomprehensible that there can be a covariance between two single points. What you need to bear in mind is that the two points you have are just realizations from two error distributions at two $X$ values. The assumption that ${\rm Cov}[\varepsilon_i,\varepsilon_j] = 0$ pertains to the error distributions of the data generating process, not actually to the realized data.
In theory, it is possible that the error distribution for March is correlated with the error distribution for February, but that all other pairings of error distributions would be perfectly uncorrelated. With just one data point each from February and March, this cannot be checked (it is also a very bizarre possibility). Instead, what we do, in effect, is test the residuals at lags. That is, we would check, e.g., the covariance of every data point with the point before it. Now you have two sets of data such that you can check the covariance. | How to calculate the covariance between two observations of the same variable?
@AndyW has provided a nice answer. Let me throw out one small additional point relative to the "[w]hat does this mean" part of your question.
It does seem incomprehensible that there can be a covar |
35,183 | How to calculate the covariance between two observations of the same variable? | One useful way to rewrite the variance instead of square deviations from the mean is in terms of squared deviations from every other observation (via Wikipedia):
$${\rm Var}(X) = \frac{1}{n^2}\sum_{i=1}^{n}\sum_{j=1}^{n}\frac{1}{2}(x_i - x_j)^2$$
You can imagine making a figure where $x_i$ are the rows and $x_j$ are the columns (where $i$ and $j$ both index the same observations in the same order), and the matrix is filled with the values of $\frac{1}{2}(x_i - x_j)^2$. You should not be able to shuffle the order of the observations to provide patterns in this matrix in the case of independent data.
When we are interested in auto-correlation of the series we need to define pairs of data in which to examine whether the variance within the pairs contributes a greater/lesser amount to the overall variance. That is pairs within this grouping are more similar than pairs outside of this groupings (for positive auto-correlation).
Some examples of this are:
The intraclass correlation for grouped data (which in simple cases is available from the output of an ANOVA table).
For time series or spatial data the auto-correlation of points near by in time and/or space.
For the suggested matrices above, if you have grouped data with positive auto-correlation and you placed the groups in order, the matrix would appear block like, with smaller values within the blocks are larger values between the blocks. For time series data if you order the observations by time, the matrix would appear diagonal, with smaller values on the diagonal and larger values off the diagonal for positive auto-correlation. | How to calculate the covariance between two observations of the same variable? | One useful way to rewrite the variance instead of square deviations from the mean is in terms of squared deviations from every other observation (via Wikipedia):
$${\rm Var}(X) = \frac{1}{n^2}\sum_{i= | How to calculate the covariance between two observations of the same variable?
One useful way to rewrite the variance instead of square deviations from the mean is in terms of squared deviations from every other observation (via Wikipedia):
$${\rm Var}(X) = \frac{1}{n^2}\sum_{i=1}^{n}\sum_{j=1}^{n}\frac{1}{2}(x_i - x_j)^2$$
You can imagine making a figure where $x_i$ are the rows and $x_j$ are the columns (where $i$ and $j$ both index the same observations in the same order), and the matrix is filled with the values of $\frac{1}{2}(x_i - x_j)^2$. You should not be able to shuffle the order of the observations to provide patterns in this matrix in the case of independent data.
When we are interested in auto-correlation of the series we need to define pairs of data in which to examine whether the variance within the pairs contributes a greater/lesser amount to the overall variance. That is pairs within this grouping are more similar than pairs outside of this groupings (for positive auto-correlation).
Some examples of this are:
The intraclass correlation for grouped data (which in simple cases is available from the output of an ANOVA table).
For time series or spatial data the auto-correlation of points near by in time and/or space.
For the suggested matrices above, if you have grouped data with positive auto-correlation and you placed the groups in order, the matrix would appear block like, with smaller values within the blocks are larger values between the blocks. For time series data if you order the observations by time, the matrix would appear diagonal, with smaller values on the diagonal and larger values off the diagonal for positive auto-correlation. | How to calculate the covariance between two observations of the same variable?
One useful way to rewrite the variance instead of square deviations from the mean is in terms of squared deviations from every other observation (via Wikipedia):
$${\rm Var}(X) = \frac{1}{n^2}\sum_{i= |
35,184 | Choosing a regression model | You can look at AIC, BIC or any of the other similar measures.
You could use your eyes and sense of the field.
Or you could avoid some of the problem by using splines. | Choosing a regression model | You can look at AIC, BIC or any of the other similar measures.
You could use your eyes and sense of the field.
Or you could avoid some of the problem by using splines. | Choosing a regression model
You can look at AIC, BIC or any of the other similar measures.
You could use your eyes and sense of the field.
Or you could avoid some of the problem by using splines. | Choosing a regression model
You can look at AIC, BIC or any of the other similar measures.
You could use your eyes and sense of the field.
Or you could avoid some of the problem by using splines. |
35,185 | Choosing a regression model | It's likely to be the case that you are not going to be able to find a polynomial that constitutes a correct description of the relationship no matter how much data you have.
This problem may extend to almost any class of models.
However, usually we're interested in getting a good description that suffices for some purpose (a model), rather than discovering the (possibly over-complicated) actual process driving the observations.
Indeed, even where the true process is from some hypothesized class of potential models, it may be counterproductive to discover the true model (which might be of high order, for example, but the high order terms might be very very small). It may be that a simpler (i.e. wrong) model is much better for our purposes.
For example, imagine we were trying to predict the next few values in a somewhat noisy series. Any model we fit has some error in the parameter estimates, and that error will be magnified by the forecasting. It doesn't take much to have a low-order model (which is necessarily biased) with much better mean square prediction error (say) performance than the 'true' model order.
One common tool for evaluating model performance is at out-of-sample prediction (not necessarily over time). Cross-validation is one common way to choose models or compare model performance.
Rob Hyndman wrote a nice little introduction here. | Choosing a regression model | It's likely to be the case that you are not going to be able to find a polynomial that constitutes a correct description of the relationship no matter how much data you have.
This problem may extend t | Choosing a regression model
It's likely to be the case that you are not going to be able to find a polynomial that constitutes a correct description of the relationship no matter how much data you have.
This problem may extend to almost any class of models.
However, usually we're interested in getting a good description that suffices for some purpose (a model), rather than discovering the (possibly over-complicated) actual process driving the observations.
Indeed, even where the true process is from some hypothesized class of potential models, it may be counterproductive to discover the true model (which might be of high order, for example, but the high order terms might be very very small). It may be that a simpler (i.e. wrong) model is much better for our purposes.
For example, imagine we were trying to predict the next few values in a somewhat noisy series. Any model we fit has some error in the parameter estimates, and that error will be magnified by the forecasting. It doesn't take much to have a low-order model (which is necessarily biased) with much better mean square prediction error (say) performance than the 'true' model order.
One common tool for evaluating model performance is at out-of-sample prediction (not necessarily over time). Cross-validation is one common way to choose models or compare model performance.
Rob Hyndman wrote a nice little introduction here. | Choosing a regression model
It's likely to be the case that you are not going to be able to find a polynomial that constitutes a correct description of the relationship no matter how much data you have.
This problem may extend t |
35,186 | Choosing a regression model | I would say very often people align themselves with one of three different approaches:
frequentists, which make use of tests such as the F-test
bayesians, which make use of bayesian inference
information theory guys, which use the BIC and AIC, just like other examples cited above.
Frequentist analysis is probably both the most straightforward and the most criticized for its shortcomings. Information theory on the other hand, underwent a boom recently, drawing the attention of more and more people as time goes by.
I think you should try to understand a bit and draw some ideas from each of the three approaches.
If you have no idea about what the data should contain, then the frequentist approach is a good way to start; on the other hand If you have some information on the underlying model, take a look at bayesian inference. And I would always keep the number of free parameters low, and that's what AIC and BIC try to balancing information with parameters. | Choosing a regression model | I would say very often people align themselves with one of three different approaches:
frequentists, which make use of tests such as the F-test
bayesians, which make use of bayesian inference
informa | Choosing a regression model
I would say very often people align themselves with one of three different approaches:
frequentists, which make use of tests such as the F-test
bayesians, which make use of bayesian inference
information theory guys, which use the BIC and AIC, just like other examples cited above.
Frequentist analysis is probably both the most straightforward and the most criticized for its shortcomings. Information theory on the other hand, underwent a boom recently, drawing the attention of more and more people as time goes by.
I think you should try to understand a bit and draw some ideas from each of the three approaches.
If you have no idea about what the data should contain, then the frequentist approach is a good way to start; on the other hand If you have some information on the underlying model, take a look at bayesian inference. And I would always keep the number of free parameters low, and that's what AIC and BIC try to balancing information with parameters. | Choosing a regression model
I would say very often people align themselves with one of three different approaches:
frequentists, which make use of tests such as the F-test
bayesians, which make use of bayesian inference
informa |
35,187 | Choosing a regression model | I would use restricted cubic splines which allow you to better approximate the curve. As an added refinement, may use AICc (or BIC) to chose the number of knots. | Choosing a regression model | I would use restricted cubic splines which allow you to better approximate the curve. As an added refinement, may use AICc (or BIC) to chose the number of knots. | Choosing a regression model
I would use restricted cubic splines which allow you to better approximate the curve. As an added refinement, may use AICc (or BIC) to chose the number of knots. | Choosing a regression model
I would use restricted cubic splines which allow you to better approximate the curve. As an added refinement, may use AICc (or BIC) to chose the number of knots. |
35,188 | Can a multivariate distribution with a singular covariance matrix have a density function? | A singular covariance matrix means that there exists a linear combination
$Y = \sum_{i=1}^n a_i X_i$ of the $n$ random variables such that $E[Y] = a_0$
and $\operatorname{var}(Y) = 0$. Thus,
all the probability mass lies in a hyperplane of $\mathbb R^n$ defined by
$\sum_{i=1}^n a_i x_i = a_0$ and so
the $n$ random variables cannot have a $n$-variate density function. | Can a multivariate distribution with a singular covariance matrix have a density function? | A singular covariance matrix means that there exists a linear combination
$Y = \sum_{i=1}^n a_i X_i$ of the $n$ random variables such that $E[Y] = a_0$
and $\operatorname{var}(Y) = 0$. Thus,
all the | Can a multivariate distribution with a singular covariance matrix have a density function?
A singular covariance matrix means that there exists a linear combination
$Y = \sum_{i=1}^n a_i X_i$ of the $n$ random variables such that $E[Y] = a_0$
and $\operatorname{var}(Y) = 0$. Thus,
all the probability mass lies in a hyperplane of $\mathbb R^n$ defined by
$\sum_{i=1}^n a_i x_i = a_0$ and so
the $n$ random variables cannot have a $n$-variate density function. | Can a multivariate distribution with a singular covariance matrix have a density function?
A singular covariance matrix means that there exists a linear combination
$Y = \sum_{i=1}^n a_i X_i$ of the $n$ random variables such that $E[Y] = a_0$
and $\operatorname{var}(Y) = 0$. Thus,
all the |
35,189 | Can a multivariate distribution with a singular covariance matrix have a density function? | Yes, but it will be a probability distribution over a lower dimensional subspace. You could argue that it is a probability distribution in R^N if you allow things like dirac delta functions. That's a subtle mathematical issue but physicists, for example, do it all the time. | Can a multivariate distribution with a singular covariance matrix have a density function? | Yes, but it will be a probability distribution over a lower dimensional subspace. You could argue that it is a probability distribution in R^N if you allow things like dirac delta functions. That's a | Can a multivariate distribution with a singular covariance matrix have a density function?
Yes, but it will be a probability distribution over a lower dimensional subspace. You could argue that it is a probability distribution in R^N if you allow things like dirac delta functions. That's a subtle mathematical issue but physicists, for example, do it all the time. | Can a multivariate distribution with a singular covariance matrix have a density function?
Yes, but it will be a probability distribution over a lower dimensional subspace. You could argue that it is a probability distribution in R^N if you allow things like dirac delta functions. That's a |
35,190 | Can a multivariate distribution with a singular covariance matrix have a density function? | Although this is alluded to above, I want to make it clearer that whilst it may not have a meaningful density on $\mathbb{R}^{n}$ you can define the density on a Rank($\Sigma$)-dimensional subspace, where $\Sigma$ denotes the covariance matrix. | Can a multivariate distribution with a singular covariance matrix have a density function? | Although this is alluded to above, I want to make it clearer that whilst it may not have a meaningful density on $\mathbb{R}^{n}$ you can define the density on a Rank($\Sigma$)-dimensional subspace, w | Can a multivariate distribution with a singular covariance matrix have a density function?
Although this is alluded to above, I want to make it clearer that whilst it may not have a meaningful density on $\mathbb{R}^{n}$ you can define the density on a Rank($\Sigma$)-dimensional subspace, where $\Sigma$ denotes the covariance matrix. | Can a multivariate distribution with a singular covariance matrix have a density function?
Although this is alluded to above, I want to make it clearer that whilst it may not have a meaningful density on $\mathbb{R}^{n}$ you can define the density on a Rank($\Sigma$)-dimensional subspace, w |
35,191 | Why use rejection sampling if it still uses the distribution? | Therefore we still use the distribution of p for the randomly generated values x.
Computing the density, $p$, isn't the same as sampling random variables from the distribution $p$ is the density for.
Why don't we sample directly from p?
I'm uncertain what you mean by "sample directly". How do you propose to sample directly from $p$ in general?
Consider the following density, for example: $f_X(x) = c.\exp(-\sqrt{1+x^2})$ (to my recollection, $c$ can be computed in terms of Bessel functions, but its value is unimportant right now). Maybe you can figure out how to sample from that "directly" (whatever you mean by that) if you're sufficiently clever ... but personally, I'm usually not quite that clever -- and generally I'd just use (a variant of) rejection sampling for something like that.
[One additional advantage of rejection sampling in this example is that I don't even need to know $c$ to use it; it affects the rejection rate, but not the progress of the algorithm. There are some simple proposal densities that will work nicely for this case.]
In other words, what makes a distribution difficult to sample from?
That depends on what tools you have for generating random variables. If you know many tools, some distributions are not difficult. If you only have a few tools, many more things become difficult to sample from.
(For example, if you only know how to generate random numbers by use of the probability integral transform, then any density whose inverse cdf is difficult to evaluate will be difficult to sample from. Any distribution whose inverse cdf is expensive to evaluate will be expensive to sample from.
You might like to consider a Tweedie distribution with $p$ between 1.7 and 1.8, say (where you only need a few observations at any one value of $p$). It has some point mass at 0, but that can be dealt with. Nevertheless, the inverse cdf for the continuous part is problematic, to say the least. Even the density involves an infinite sum (which, nonetheless, can be evaluated, though it's expensive to calculate). Rejection sampling - with some tweaks to reduce function evaluations to a minimum - is possible here. Inverse cdf? I don't know that it would be practical, even if it were possible. You might figure out a way to do it using the inverse cdf if you're really clever - I think it might be beyond me, but even if you do, it's going to take a while to get your numbers.)
Rejection sampling is a very important tool in that collection (or rather, rejection sampling is itself a class of tools, because there are many clever variations on the idea), perhaps one of the most important tools. Variations on it are very widely used. | Why use rejection sampling if it still uses the distribution? | Therefore we still use the distribution of p for the randomly generated values x.
Computing the density, $p$, isn't the same as sampling random variables from the distribution $p$ is the density for. | Why use rejection sampling if it still uses the distribution?
Therefore we still use the distribution of p for the randomly generated values x.
Computing the density, $p$, isn't the same as sampling random variables from the distribution $p$ is the density for.
Why don't we sample directly from p?
I'm uncertain what you mean by "sample directly". How do you propose to sample directly from $p$ in general?
Consider the following density, for example: $f_X(x) = c.\exp(-\sqrt{1+x^2})$ (to my recollection, $c$ can be computed in terms of Bessel functions, but its value is unimportant right now). Maybe you can figure out how to sample from that "directly" (whatever you mean by that) if you're sufficiently clever ... but personally, I'm usually not quite that clever -- and generally I'd just use (a variant of) rejection sampling for something like that.
[One additional advantage of rejection sampling in this example is that I don't even need to know $c$ to use it; it affects the rejection rate, but not the progress of the algorithm. There are some simple proposal densities that will work nicely for this case.]
In other words, what makes a distribution difficult to sample from?
That depends on what tools you have for generating random variables. If you know many tools, some distributions are not difficult. If you only have a few tools, many more things become difficult to sample from.
(For example, if you only know how to generate random numbers by use of the probability integral transform, then any density whose inverse cdf is difficult to evaluate will be difficult to sample from. Any distribution whose inverse cdf is expensive to evaluate will be expensive to sample from.
You might like to consider a Tweedie distribution with $p$ between 1.7 and 1.8, say (where you only need a few observations at any one value of $p$). It has some point mass at 0, but that can be dealt with. Nevertheless, the inverse cdf for the continuous part is problematic, to say the least. Even the density involves an infinite sum (which, nonetheless, can be evaluated, though it's expensive to calculate). Rejection sampling - with some tweaks to reduce function evaluations to a minimum - is possible here. Inverse cdf? I don't know that it would be practical, even if it were possible. You might figure out a way to do it using the inverse cdf if you're really clever - I think it might be beyond me, but even if you do, it's going to take a while to get your numbers.)
Rejection sampling is a very important tool in that collection (or rather, rejection sampling is itself a class of tools, because there are many clever variations on the idea), perhaps one of the most important tools. Variations on it are very widely used. | Why use rejection sampling if it still uses the distribution?
Therefore we still use the distribution of p for the randomly generated values x.
Computing the density, $p$, isn't the same as sampling random variables from the distribution $p$ is the density for. |
35,192 | Why use rejection sampling if it still uses the distribution? | Sampling from a distribution means getting a sample with its probability matching the pdf of that distribution. In rejection sampling, we take random samples and select such that the pdf of these samples donot exceed the pdf of given distribution. This is the rejection criteria.
This way we have appropriate samples and by getting large number of random sample under this criteria will represent the total picture of distribution. | Why use rejection sampling if it still uses the distribution? | Sampling from a distribution means getting a sample with its probability matching the pdf of that distribution. In rejection sampling, we take random samples and select such that the pdf of these sam | Why use rejection sampling if it still uses the distribution?
Sampling from a distribution means getting a sample with its probability matching the pdf of that distribution. In rejection sampling, we take random samples and select such that the pdf of these samples donot exceed the pdf of given distribution. This is the rejection criteria.
This way we have appropriate samples and by getting large number of random sample under this criteria will represent the total picture of distribution. | Why use rejection sampling if it still uses the distribution?
Sampling from a distribution means getting a sample with its probability matching the pdf of that distribution. In rejection sampling, we take random samples and select such that the pdf of these sam |
35,193 | Why use rejection sampling if it still uses the distribution? | So why do we use rejection sampling exactly?
There are a few reasons to use rejection sampling.
Historically, computation was the bottleneck in random variate generation. Calculation of functions like $log(\cdot)$, $exp(\cdot)$ and $sin(\cdot$) were time consuming. Some rejection techniques enabled avoiding the computation of these functions entirely.
Presently (as of 2022), one common reason is that sampling from a distribution (say ($p(\cdot)$) itself is difficult, whereas sampling from $q(\cdot)$ is easier. Let's call sampling from $p(\cdot)$ by the inverse CDF method the iCDF method for brevity. This reason is perhaps less likely to change with time.
Another reason to use rejection sampling is efficiency. For example an iCDF method could be $\mathcal{O}(\theta)$ where $\theta$ is a parameter of the distribution $p(\cdot)$ whereas a rejection method might be $\mathcal{O}(1)$ so that-in theory anyway-the rejection method can be used by default in a sampling library. We'd use it as a default because you wouldn't know in advance which of the particular values of $\theta$ a user of the library would need for a particular bit of code. In practice you'd usually find some cutoff or threshold-if one exists-in the $\theta$ space and use rejection sampling in the $\theta$ region where more efficient and iCDF where the latter is more efficient.
Why don't we sample directly from $p(\cdot)$?
Some times it may not be possible to use the iCDF method to sample directly (this is how I'm interpreting the word 'directly'). An example is the Kolmogorov-Smirnov distribution. As far as I'm aware the only methods to sample this distribution either use numerical approximations or they use a variant of rejection sampling known as the Series method. This is an example where it isn't possible to sample directly unless you want to accept numerical tradeoffs which add a lot to library maintenance and implementation overhead. Also see my comment about efficiency in the answer to the first question which also applies to this question, that is another reason to use rejection sampling.
In addition there are many variants on rejection sampling, like Vaduva's method, the series method, and the Ratio-of-Uniforms method. You can read about each of them in Luc Devroye's wonderful book Non-uniform Random Variate Generation.
In other words, what makes a distribution difficult to sample from?
This is perhaps too broad of a question to answer. To paraphrase Tolstoy,
All easy distributions are alike, but every difficult distribution is unhappy in its own way.
What makes a distribution easy to sample from is light tails and a finite mode. Light tails and a finite mode imply that rejection sampling can be used with a suitably dominating distribution. Various tricks and techniques may be required to recognize an easy form but they all seem to follow this pattern. | Why use rejection sampling if it still uses the distribution? | So why do we use rejection sampling exactly?
There are a few reasons to use rejection sampling.
Historically, computation was the bottleneck in random variate generation. Calculation of functions lik | Why use rejection sampling if it still uses the distribution?
So why do we use rejection sampling exactly?
There are a few reasons to use rejection sampling.
Historically, computation was the bottleneck in random variate generation. Calculation of functions like $log(\cdot)$, $exp(\cdot)$ and $sin(\cdot$) were time consuming. Some rejection techniques enabled avoiding the computation of these functions entirely.
Presently (as of 2022), one common reason is that sampling from a distribution (say ($p(\cdot)$) itself is difficult, whereas sampling from $q(\cdot)$ is easier. Let's call sampling from $p(\cdot)$ by the inverse CDF method the iCDF method for brevity. This reason is perhaps less likely to change with time.
Another reason to use rejection sampling is efficiency. For example an iCDF method could be $\mathcal{O}(\theta)$ where $\theta$ is a parameter of the distribution $p(\cdot)$ whereas a rejection method might be $\mathcal{O}(1)$ so that-in theory anyway-the rejection method can be used by default in a sampling library. We'd use it as a default because you wouldn't know in advance which of the particular values of $\theta$ a user of the library would need for a particular bit of code. In practice you'd usually find some cutoff or threshold-if one exists-in the $\theta$ space and use rejection sampling in the $\theta$ region where more efficient and iCDF where the latter is more efficient.
Why don't we sample directly from $p(\cdot)$?
Some times it may not be possible to use the iCDF method to sample directly (this is how I'm interpreting the word 'directly'). An example is the Kolmogorov-Smirnov distribution. As far as I'm aware the only methods to sample this distribution either use numerical approximations or they use a variant of rejection sampling known as the Series method. This is an example where it isn't possible to sample directly unless you want to accept numerical tradeoffs which add a lot to library maintenance and implementation overhead. Also see my comment about efficiency in the answer to the first question which also applies to this question, that is another reason to use rejection sampling.
In addition there are many variants on rejection sampling, like Vaduva's method, the series method, and the Ratio-of-Uniforms method. You can read about each of them in Luc Devroye's wonderful book Non-uniform Random Variate Generation.
In other words, what makes a distribution difficult to sample from?
This is perhaps too broad of a question to answer. To paraphrase Tolstoy,
All easy distributions are alike, but every difficult distribution is unhappy in its own way.
What makes a distribution easy to sample from is light tails and a finite mode. Light tails and a finite mode imply that rejection sampling can be used with a suitably dominating distribution. Various tricks and techniques may be required to recognize an easy form but they all seem to follow this pattern. | Why use rejection sampling if it still uses the distribution?
So why do we use rejection sampling exactly?
There are a few reasons to use rejection sampling.
Historically, computation was the bottleneck in random variate generation. Calculation of functions lik |
35,194 | When correlation turns too high? | Some correlation is not a problem. Actually, it is the very reason why we add control variables. Consider what would happen when all explanatory variables are not correlated with one another. In that case there would be no added value to adding them all in one model: you could just look at a series of bivariate regressions and get the same results. So, the idea of adding control variables to your model only makes sense if the variables are correlated with one another.
An extremely high correlation may cause problems with the way computers handle numbers. However, algorithms for computing linear regression have improved that much that that is in most cases not a problem. A correlation of .4 is no where near that mark (think .99 or .999).
Moderate correlation means that there is less information which your model could use to disentangle the effects of two correlated explanatory variables than you would have expected based on the sample size alone. As a concequence the standard error will be high and confidence intervals will be wide. That is an unfortunate but accurate representation of the amount of information you have available. So if you are not collecting the data yourself there is nothing you can do and there is nothing you should do about that.
However, if your variables are moderately correlated you might want to consider the possibility that they are actually measuring the same thing. In that case you would either want to use that to get a better estimate of that one thing (a measurement model in a SEM for example) or choose just one of these variables. Imagine how you would interpret your results when you add both: the effect of a unit change in one measurement of a concept while keeping the other measurement of that same concept constant... | When correlation turns too high? | Some correlation is not a problem. Actually, it is the very reason why we add control variables. Consider what would happen when all explanatory variables are not correlated with one another. In that | When correlation turns too high?
Some correlation is not a problem. Actually, it is the very reason why we add control variables. Consider what would happen when all explanatory variables are not correlated with one another. In that case there would be no added value to adding them all in one model: you could just look at a series of bivariate regressions and get the same results. So, the idea of adding control variables to your model only makes sense if the variables are correlated with one another.
An extremely high correlation may cause problems with the way computers handle numbers. However, algorithms for computing linear regression have improved that much that that is in most cases not a problem. A correlation of .4 is no where near that mark (think .99 or .999).
Moderate correlation means that there is less information which your model could use to disentangle the effects of two correlated explanatory variables than you would have expected based on the sample size alone. As a concequence the standard error will be high and confidence intervals will be wide. That is an unfortunate but accurate representation of the amount of information you have available. So if you are not collecting the data yourself there is nothing you can do and there is nothing you should do about that.
However, if your variables are moderately correlated you might want to consider the possibility that they are actually measuring the same thing. In that case you would either want to use that to get a better estimate of that one thing (a measurement model in a SEM for example) or choose just one of these variables. Imagine how you would interpret your results when you add both: the effect of a unit change in one measurement of a concept while keeping the other measurement of that same concept constant... | When correlation turns too high?
Some correlation is not a problem. Actually, it is the very reason why we add control variables. Consider what would happen when all explanatory variables are not correlated with one another. In that |
35,195 | What does "$\sim$" mean and $A | B \sim C$? | Usually ~ means "has the distribution...", so you are correct.
A ~ B, means that the random variable A has the distribution B (or is distributed equal to B).
In the article you mentioned DP is described as a distribution (see page 05, Dirichlet Processes):
A Dirichlet process DP($\alpha_0$;$G_0$) is defined to be the distribution of a random
probability measure G over ($\theta$;$\beta$) such that...
The symbol "|" means "given" what comes next. It is used to express condition.
For example $\theta_i$ given G, has the distribution G.
On page 7, Equation 9, the text says:
where $F(\theta_i)$ denotes the distribution of the observation $x_i$ given $i$. | What does "$\sim$" mean and $A | B \sim C$? | Usually ~ means "has the distribution...", so you are correct.
A ~ B, means that the random variable A has the distribution B (or is distributed equal to B).
In the article you mentioned DP is describ | What does "$\sim$" mean and $A | B \sim C$?
Usually ~ means "has the distribution...", so you are correct.
A ~ B, means that the random variable A has the distribution B (or is distributed equal to B).
In the article you mentioned DP is described as a distribution (see page 05, Dirichlet Processes):
A Dirichlet process DP($\alpha_0$;$G_0$) is defined to be the distribution of a random
probability measure G over ($\theta$;$\beta$) such that...
The symbol "|" means "given" what comes next. It is used to express condition.
For example $\theta_i$ given G, has the distribution G.
On page 7, Equation 9, the text says:
where $F(\theta_i)$ denotes the distribution of the observation $x_i$ given $i$. | What does "$\sim$" mean and $A | B \sim C$?
Usually ~ means "has the distribution...", so you are correct.
A ~ B, means that the random variable A has the distribution B (or is distributed equal to B).
In the article you mentioned DP is describ |
35,196 | What does "$\sim$" mean and $A | B \sim C$? | The ~ symbol means 'distributed according to'. So $a \sim G$ means the random variable $a$ is distributed according to the distribution $G$.
The bar symbol, as in $x_i|\theta_i \sim F(\theta_i)$, means "given". You shouldn't let it confuse you. It's often used in hierarchical models to emphasize that the lower stage of the model depends on the stage above it. | What does "$\sim$" mean and $A | B \sim C$? | The ~ symbol means 'distributed according to'. So $a \sim G$ means the random variable $a$ is distributed according to the distribution $G$.
The bar symbol, as in $x_i|\theta_i \sim F(\theta_i)$, mea | What does "$\sim$" mean and $A | B \sim C$?
The ~ symbol means 'distributed according to'. So $a \sim G$ means the random variable $a$ is distributed according to the distribution $G$.
The bar symbol, as in $x_i|\theta_i \sim F(\theta_i)$, means "given". You shouldn't let it confuse you. It's often used in hierarchical models to emphasize that the lower stage of the model depends on the stage above it. | What does "$\sim$" mean and $A | B \sim C$?
The ~ symbol means 'distributed according to'. So $a \sim G$ means the random variable $a$ is distributed according to the distribution $G$.
The bar symbol, as in $x_i|\theta_i \sim F(\theta_i)$, mea |
35,197 | How to calculate ratings/rankings from Paired comparison / Pairwise comparison of large data-sets? | Hopefully this isn't too late, but your data is still valuable using the Bradley-Terry model. This paper is a nice reference MM Algorithms for generalized Bradley-Terry models. Equation 4 is the one you want.
Brief explanation as I guess you are not a mathematition, and I'm being nice as I'd really like a copy of your data to test my implementation of this algorithm!
Explanation of Bradley-Terry Model
Basically Bradley-Terry assigns a value to each object, which is the answer you want - e.g. if you are asking "Which of these cars looks sexier", the value would measure sexiness. Then it says if you have two cars with sexinesses $s_i$ and $s_j$, the probability of someone choosing car $i$ over car $j$ is:
$$P(o_i\succ o_j)=\frac{e^{s_i}}{e^{s_i}-e^{s_j}}$$
That actually only depends on $s_j-s_i$ as follows:
So if they have the same sexiness the chances are 50-50 (random guessing), and if one has a higher sexiness it is more likely to be chosen.
This model is mostly plucked out of the air for its plausibility and nice mathematical properties. I don't know how realistic it really is. It is widely use though.
Maximum Likelihood
BT then uses something called Maximum Likelihood to estimate the values of $s_i$. Put in words, it finds the sexinesses of all the cars that would make the choices that you measured ("Dave says car A is sexier than car B" etc.) as likely as possible, according to our choice model above. So if people choose car A over car B a lot, then giving $s_A$ a lower sexiness than $s_B$ would mean that their choices (A > B) are very unlikely. So those sexiness values are not a maximum likelihood estimate.
To actually find all the $s_i$'s you can use a generic optimisation method (e.g. fminsearch in matlab). Or there is an iterative algorithm that they claim is guaranteed to converge on a "unique maximum" (which I assume means global?).
That algorithm is equation 4 in the linked paper (plus normalisation).
Algorithm.
Basically you count the number of times each object is beaten by every other. Store that in $w_{ij}$. The total number of comparisons between any two objects is $N_{ij}=w_{ij}+w_{ji}$. Define new numbers $\gamma_i=e^{s_i}$. Then start with all $\gamma_i=0$ and iteratively update, looping repeatedly through the $i$'s.
$$\gamma_i\leftarrow W_{i}\left[\sum_{j\neq i}\frac{N_{ij}}{\gamma_{i}+\gamma_{j}}\right]^{-1}$$
You don't need to complete a whole loop before updating each $i$. By which I mean you don't need to store old values of $\gamma_i$. As soon as a new value is calculated you can use it in subsequent updates.
$W_i$ is the total number of wins by $i$: $\sum_{j}w_{ij}=W_{i}$
You also need to normalise $\gamma$ after each loop over it:
$$\gamma \leftarrow \frac{\gamma}{\mathrm{mean}(\gamma)}$$
Regularisation.
You probably won't need this since your data set is so large and dense. In some cases you need to regularise by adding "phantom" comparisons of every object with an extra virtual one. Apparently the standard method is to count $\lambda$ wins for the real objects vs virtual, and $\lambda$ losses. I've found $\lambda$=0.1 to work fine.
Please can you send me your data and expected results if you still have it? :-) | How to calculate ratings/rankings from Paired comparison / Pairwise comparison of large data-sets? | Hopefully this isn't too late, but your data is still valuable using the Bradley-Terry model. This paper is a nice reference MM Algorithms for generalized Bradley-Terry models. Equation 4 is the one y | How to calculate ratings/rankings from Paired comparison / Pairwise comparison of large data-sets?
Hopefully this isn't too late, but your data is still valuable using the Bradley-Terry model. This paper is a nice reference MM Algorithms for generalized Bradley-Terry models. Equation 4 is the one you want.
Brief explanation as I guess you are not a mathematition, and I'm being nice as I'd really like a copy of your data to test my implementation of this algorithm!
Explanation of Bradley-Terry Model
Basically Bradley-Terry assigns a value to each object, which is the answer you want - e.g. if you are asking "Which of these cars looks sexier", the value would measure sexiness. Then it says if you have two cars with sexinesses $s_i$ and $s_j$, the probability of someone choosing car $i$ over car $j$ is:
$$P(o_i\succ o_j)=\frac{e^{s_i}}{e^{s_i}-e^{s_j}}$$
That actually only depends on $s_j-s_i$ as follows:
So if they have the same sexiness the chances are 50-50 (random guessing), and if one has a higher sexiness it is more likely to be chosen.
This model is mostly plucked out of the air for its plausibility and nice mathematical properties. I don't know how realistic it really is. It is widely use though.
Maximum Likelihood
BT then uses something called Maximum Likelihood to estimate the values of $s_i$. Put in words, it finds the sexinesses of all the cars that would make the choices that you measured ("Dave says car A is sexier than car B" etc.) as likely as possible, according to our choice model above. So if people choose car A over car B a lot, then giving $s_A$ a lower sexiness than $s_B$ would mean that their choices (A > B) are very unlikely. So those sexiness values are not a maximum likelihood estimate.
To actually find all the $s_i$'s you can use a generic optimisation method (e.g. fminsearch in matlab). Or there is an iterative algorithm that they claim is guaranteed to converge on a "unique maximum" (which I assume means global?).
That algorithm is equation 4 in the linked paper (plus normalisation).
Algorithm.
Basically you count the number of times each object is beaten by every other. Store that in $w_{ij}$. The total number of comparisons between any two objects is $N_{ij}=w_{ij}+w_{ji}$. Define new numbers $\gamma_i=e^{s_i}$. Then start with all $\gamma_i=0$ and iteratively update, looping repeatedly through the $i$'s.
$$\gamma_i\leftarrow W_{i}\left[\sum_{j\neq i}\frac{N_{ij}}{\gamma_{i}+\gamma_{j}}\right]^{-1}$$
You don't need to complete a whole loop before updating each $i$. By which I mean you don't need to store old values of $\gamma_i$. As soon as a new value is calculated you can use it in subsequent updates.
$W_i$ is the total number of wins by $i$: $\sum_{j}w_{ij}=W_{i}$
You also need to normalise $\gamma$ after each loop over it:
$$\gamma \leftarrow \frac{\gamma}{\mathrm{mean}(\gamma)}$$
Regularisation.
You probably won't need this since your data set is so large and dense. In some cases you need to regularise by adding "phantom" comparisons of every object with an extra virtual one. Apparently the standard method is to count $\lambda$ wins for the real objects vs virtual, and $\lambda$ losses. I've found $\lambda$=0.1 to work fine.
Please can you send me your data and expected results if you still have it? :-) | How to calculate ratings/rankings from Paired comparison / Pairwise comparison of large data-sets?
Hopefully this isn't too late, but your data is still valuable using the Bradley-Terry model. This paper is a nice reference MM Algorithms for generalized Bradley-Terry models. Equation 4 is the one y |
35,198 | Translate R's glm command into mathematical notation | For a binary logistic regression, the usual use case for the binomial GLM with a logit link, you're modeling the probability that your dependent variable is a "success" (or "yes"), conventionally coded as $1$. The way that you're doing this is by modeling the log odds. So rather than modeling the mean of the response as in OLS, you're modeling the change in the log odds: $$\Pr(y=1)=\theta=\text{logit}^{-1}(\beta_0+\beta_1x_1+\beta_2x_2+...+\beta_7x_7)$$
Where $\text{logit}(x)=\log(\frac{x}{1-x})$ and $\text{logit}^{-1}(x)=\frac{\exp(x)}{1+\exp(x)}$.
A more thorough, very approachable explanation of this can be found in Agresti, An Introduction to Categorical Data Analysis.
But to your particular question, you state that you're modeling the proportion of successes. This is not actually what a binomial GLM is used to do. However, what you're really after is what a binomial GLM does, and is still possible in R. It just requires a slight tweak to what you're doing. In the case where you have a finite number of trials $n$ which may have $y \in \{0...n\}$ successes, you can still use the same model, which has density
$$\Pr(y) \sim \binom{n}{y}\theta^y(1-\theta)^{n-y}$$
Because your values $n$ are fixed by experimental design, and $y$ is your observed successes, you're performing inference on the parameter $\theta$ in the same way as the more typical binary response case (above), in which $n$ is fixed at 1, $y$ takes the value 1 with probability $\theta$, and $\theta$ is a function of your parameters. For the case of the logit link, then we model $$\text{logit}(\theta)=\beta_0+\beta_1x_1+...+\beta_ix_i$$, chiefly because this transformed $\theta$ exists on the whole real line, rather than the unit interval. (Other desirable properties of the logit link are described in Agresti, including validity of the coefficients even in settings where nonrandom samples like case-control designs are used; this is not the case for, e.g., probit link functions.)
In terms of R, simply create an object (which you term glmDV) that is a 2-column matrix, the first column the number of successes $y$ and the second the total number of failures $n-y$. The rest of the statement remains the same! | Translate R's glm command into mathematical notation | For a binary logistic regression, the usual use case for the binomial GLM with a logit link, you're modeling the probability that your dependent variable is a "success" (or "yes"), conventionally code | Translate R's glm command into mathematical notation
For a binary logistic regression, the usual use case for the binomial GLM with a logit link, you're modeling the probability that your dependent variable is a "success" (or "yes"), conventionally coded as $1$. The way that you're doing this is by modeling the log odds. So rather than modeling the mean of the response as in OLS, you're modeling the change in the log odds: $$\Pr(y=1)=\theta=\text{logit}^{-1}(\beta_0+\beta_1x_1+\beta_2x_2+...+\beta_7x_7)$$
Where $\text{logit}(x)=\log(\frac{x}{1-x})$ and $\text{logit}^{-1}(x)=\frac{\exp(x)}{1+\exp(x)}$.
A more thorough, very approachable explanation of this can be found in Agresti, An Introduction to Categorical Data Analysis.
But to your particular question, you state that you're modeling the proportion of successes. This is not actually what a binomial GLM is used to do. However, what you're really after is what a binomial GLM does, and is still possible in R. It just requires a slight tweak to what you're doing. In the case where you have a finite number of trials $n$ which may have $y \in \{0...n\}$ successes, you can still use the same model, which has density
$$\Pr(y) \sim \binom{n}{y}\theta^y(1-\theta)^{n-y}$$
Because your values $n$ are fixed by experimental design, and $y$ is your observed successes, you're performing inference on the parameter $\theta$ in the same way as the more typical binary response case (above), in which $n$ is fixed at 1, $y$ takes the value 1 with probability $\theta$, and $\theta$ is a function of your parameters. For the case of the logit link, then we model $$\text{logit}(\theta)=\beta_0+\beta_1x_1+...+\beta_ix_i$$, chiefly because this transformed $\theta$ exists on the whole real line, rather than the unit interval. (Other desirable properties of the logit link are described in Agresti, including validity of the coefficients even in settings where nonrandom samples like case-control designs are used; this is not the case for, e.g., probit link functions.)
In terms of R, simply create an object (which you term glmDV) that is a 2-column matrix, the first column the number of successes $y$ and the second the total number of failures $n-y$. The rest of the statement remains the same! | Translate R's glm command into mathematical notation
For a binary logistic regression, the usual use case for the binomial GLM with a logit link, you're modeling the probability that your dependent variable is a "success" (or "yes"), conventionally code |
35,199 | Does ARIMA require normally distributed errors or normally distributed input data? | First, having normally distributed errors is equivalent to having normally distributed observations for any linear time series model.
Second, it is not necessary to assume normality of errors. Often, maximum likelihood is used to estimate the parameters of the model, and then a Gaussian likelihood is used, but it gives good results even with non-normal data. Where normality of errors is often assumed is in using the AIC for order selection, and in computing prediction intervals.
There are several specifications of ARIMA models with exogenous variables, and more than one such specification has been called an ARIMAX model, so it is not possible to precisely answer your second question without you specifying the model more accurately. For discussion of some of the models, see http://robjhyndman.com/hyndsight/arimax/ | Does ARIMA require normally distributed errors or normally distributed input data? | First, having normally distributed errors is equivalent to having normally distributed observations for any linear time series model.
Second, it is not necessary to assume normality of errors. Often, | Does ARIMA require normally distributed errors or normally distributed input data?
First, having normally distributed errors is equivalent to having normally distributed observations for any linear time series model.
Second, it is not necessary to assume normality of errors. Often, maximum likelihood is used to estimate the parameters of the model, and then a Gaussian likelihood is used, but it gives good results even with non-normal data. Where normality of errors is often assumed is in using the AIC for order selection, and in computing prediction intervals.
There are several specifications of ARIMA models with exogenous variables, and more than one such specification has been called an ARIMAX model, so it is not possible to precisely answer your second question without you specifying the model more accurately. For discussion of some of the models, see http://robjhyndman.com/hyndsight/arimax/ | Does ARIMA require normally distributed errors or normally distributed input data?
First, having normally distributed errors is equivalent to having normally distributed observations for any linear time series model.
Second, it is not necessary to assume normality of errors. Often, |
35,200 | Does ARIMA require normally distributed errors or normally distributed input data? | No -- the paper Maximum Likelihood Estimates of Non-Gaussian ARMA Models studies ARMA models with Student-t and Laplace distributed errors. Here is the abstract:
"We consider an approximate maximum likelihood algorithm for estimating parameters of possibly non-causal and non-invertible autoregressive moving average processes driven by independent identically distributed non-Gaussian noise. The normalized approximate maximum likelihood estimate has a global maximum which is consistent and ecient. The estimates and their associated asymptotic covariance matrix are calculated with a subroutine
implemented in FORTRAN 77." | Does ARIMA require normally distributed errors or normally distributed input data? | No -- the paper Maximum Likelihood Estimates of Non-Gaussian ARMA Models studies ARMA models with Student-t and Laplace distributed errors. Here is the abstract:
"We consider an approximate maximum li | Does ARIMA require normally distributed errors or normally distributed input data?
No -- the paper Maximum Likelihood Estimates of Non-Gaussian ARMA Models studies ARMA models with Student-t and Laplace distributed errors. Here is the abstract:
"We consider an approximate maximum likelihood algorithm for estimating parameters of possibly non-causal and non-invertible autoregressive moving average processes driven by independent identically distributed non-Gaussian noise. The normalized approximate maximum likelihood estimate has a global maximum which is consistent and ecient. The estimates and their associated asymptotic covariance matrix are calculated with a subroutine
implemented in FORTRAN 77." | Does ARIMA require normally distributed errors or normally distributed input data?
No -- the paper Maximum Likelihood Estimates of Non-Gaussian ARMA Models studies ARMA models with Student-t and Laplace distributed errors. Here is the abstract:
"We consider an approximate maximum li |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.