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 |
|---|---|---|---|---|---|---|
17,501 | Difference between one-way and two-way fixed effects, and their estimation | From this paper on reliability and intra-class correlation coefficient: https://www.sciencedirect.com/science/article/pii/S1556370716000158
One-Way Random-Effects Model
In this model, each subject is rated by a different set of raters who were randomly chosen from a larger population of possible raters. Practically, this model is rarely used in clinical reliability analysis because majority of the reliability studies typically involve the same set of raters to measure all subjects. An exception would be multicenter studies for which the physical distance between centers prohibits the same set of raters to rate all subjects. Under such circumstance, one set of raters may assess a subgroup of subjects in one center and another set of raters may assess a subgroup of subjects in another center, and hence, 1-way random-effects model should be used in this case.
Two-Way Random-Effects Model
If we randomly select our raters from a larger population of raters with similar characteristics, 2-way random-effects model is the model of choice. In other words, we choose 2-way random-effects model if we plan to generalize our reliability results to any raters who possess the same characteristics as the selected raters in the reliability study. This model is appropriate for evaluating rater-based clinical assessment methods (eg, passive range of motion) that are designed for routine clinical use by any clinicians with specific characteristics (eg, years of experience) as stated in the reliability study.
Two-Way Mixed-Effects Model
We should use the 2-way mixed-effects model if the selected raters are the only raters of interest. With this model, the results only represent the reliability of the specific raters involved in the reliability experiment. They cannot be generalized to other raters even if those raters have similar characteristics as the selected raters in the reliability experiment. As a result, 2-way mixed-effects model is less commonly used in interrater reliability analysis. | Difference between one-way and two-way fixed effects, and their estimation | From this paper on reliability and intra-class correlation coefficient: https://www.sciencedirect.com/science/article/pii/S1556370716000158
One-Way Random-Effects Model
In this model, each subject is | Difference between one-way and two-way fixed effects, and their estimation
From this paper on reliability and intra-class correlation coefficient: https://www.sciencedirect.com/science/article/pii/S1556370716000158
One-Way Random-Effects Model
In this model, each subject is rated by a different set of raters who were randomly chosen from a larger population of possible raters. Practically, this model is rarely used in clinical reliability analysis because majority of the reliability studies typically involve the same set of raters to measure all subjects. An exception would be multicenter studies for which the physical distance between centers prohibits the same set of raters to rate all subjects. Under such circumstance, one set of raters may assess a subgroup of subjects in one center and another set of raters may assess a subgroup of subjects in another center, and hence, 1-way random-effects model should be used in this case.
Two-Way Random-Effects Model
If we randomly select our raters from a larger population of raters with similar characteristics, 2-way random-effects model is the model of choice. In other words, we choose 2-way random-effects model if we plan to generalize our reliability results to any raters who possess the same characteristics as the selected raters in the reliability study. This model is appropriate for evaluating rater-based clinical assessment methods (eg, passive range of motion) that are designed for routine clinical use by any clinicians with specific characteristics (eg, years of experience) as stated in the reliability study.
Two-Way Mixed-Effects Model
We should use the 2-way mixed-effects model if the selected raters are the only raters of interest. With this model, the results only represent the reliability of the specific raters involved in the reliability experiment. They cannot be generalized to other raters even if those raters have similar characteristics as the selected raters in the reliability experiment. As a result, 2-way mixed-effects model is less commonly used in interrater reliability analysis. | Difference between one-way and two-way fixed effects, and their estimation
From this paper on reliability and intra-class correlation coefficient: https://www.sciencedirect.com/science/article/pii/S1556370716000158
One-Way Random-Effects Model
In this model, each subject is |
17,502 | What is the intuition behind an Indicator Function? | I do not think that you can go more intuitive about it then saying once again what it does: it returns $1$ for something that interests you, and $0$ for all the other cases.
So if you want to count blue-eyed people, you can use indicator function that returns ones for each blue-eyed person and zero otherwise, and sum the outcomes of the function.
As about probability defined in terms of expectation and indicator function: if you divide the count (or sum of ones) by total number of cases, you get probability. Peter Whittle in his books Probability and Probability via Expectation writes a lot about defining probability like this and even considers such usage of expected value and indicator function as one of the most basic aspects of probability theory.
As about your question in the comment
isn't the Random Variable there to serve the same purpose? Like $H=1$
and $T=0$?
Well, yes it is! In fact, in statistics we use indicator function to create new random variables, e.g. imagine that you have normally distributed random variable $X$, then you may create new random variable using indicator function, say
$$ I_{2<X<3} = \begin{cases} 1 & \text{if} \quad 2 < X < 3 \\
0 & \text{otherwise} \end{cases} $$
or you may create new random variable using two Bernoulli distributed random variables $A,B$:
$$ I_{A\ne B} = \begin{cases} 0 & \text{if } & A=B, \\
1 & \text{if } & A \ne B
\end{cases} $$
...of course, you could use as well any other function to create new random variable. Indicator function is helpful if you want to focus on some specific event and signalize when it happens.
For a physical indicator function imagine that you marked one of the walls of six-sided dice using red paint, so you can now count red and non-red outcomes. It is not less random them the dice itself, while it's a new random variable that defines outcomes differently.
You may also be interested in reading about Dirac delta that is used in probability and statistics like a continuous counterpart to indicator function.
See also: Why 0 for failure and 1 for success in a Bernoulli distribution? | What is the intuition behind an Indicator Function? | I do not think that you can go more intuitive about it then saying once again what it does: it returns $1$ for something that interests you, and $0$ for all the other cases.
So if you want to count bl | What is the intuition behind an Indicator Function?
I do not think that you can go more intuitive about it then saying once again what it does: it returns $1$ for something that interests you, and $0$ for all the other cases.
So if you want to count blue-eyed people, you can use indicator function that returns ones for each blue-eyed person and zero otherwise, and sum the outcomes of the function.
As about probability defined in terms of expectation and indicator function: if you divide the count (or sum of ones) by total number of cases, you get probability. Peter Whittle in his books Probability and Probability via Expectation writes a lot about defining probability like this and even considers such usage of expected value and indicator function as one of the most basic aspects of probability theory.
As about your question in the comment
isn't the Random Variable there to serve the same purpose? Like $H=1$
and $T=0$?
Well, yes it is! In fact, in statistics we use indicator function to create new random variables, e.g. imagine that you have normally distributed random variable $X$, then you may create new random variable using indicator function, say
$$ I_{2<X<3} = \begin{cases} 1 & \text{if} \quad 2 < X < 3 \\
0 & \text{otherwise} \end{cases} $$
or you may create new random variable using two Bernoulli distributed random variables $A,B$:
$$ I_{A\ne B} = \begin{cases} 0 & \text{if } & A=B, \\
1 & \text{if } & A \ne B
\end{cases} $$
...of course, you could use as well any other function to create new random variable. Indicator function is helpful if you want to focus on some specific event and signalize when it happens.
For a physical indicator function imagine that you marked one of the walls of six-sided dice using red paint, so you can now count red and non-red outcomes. It is not less random them the dice itself, while it's a new random variable that defines outcomes differently.
You may also be interested in reading about Dirac delta that is used in probability and statistics like a continuous counterpart to indicator function.
See also: Why 0 for failure and 1 for success in a Bernoulli distribution? | What is the intuition behind an Indicator Function?
I do not think that you can go more intuitive about it then saying once again what it does: it returns $1$ for something that interests you, and $0$ for all the other cases.
So if you want to count bl |
17,503 | What is the intuition behind an Indicator Function? | Indicator random variables are useful in that they provide a seamless connection between probability and expectation. Consider how easy it is to prove Markov's inequality with the help of indicator random variables: let $X$ be a nonnegative random variable, $\alpha > 0$ and then note the trivial inequality $\alpha I_{\{ X \geq \alpha \}} \leq X$. We can then just take an expectation of both sides and do some algebra to get $P(X \geq \alpha) \leq \text{E}(X) / \alpha$. Other proofs, like that of the inclusion-exclusion formula, also make use of this connection. In fact, the whole theory of conditional probability can be developed from the theory of conditional expectation because of this.
They're also nice in that they're idempotent meaning $I_A^2 = I_A$, and this makes calculating variances easy. Also, products of indicator random variables are themselves indicator random variables whose expectation is the probability of the intersection.
Finally, while not really a probabilistic thing, indicator functions are a nice way of translating Boolean operations into arithmetic ones, which is helpful for general programming purposes. For instance, $I_{A \cup B} = \max(I_A, I_B)$ and $I_{A \cap B} = \min(I_A, I_B)$. | What is the intuition behind an Indicator Function? | Indicator random variables are useful in that they provide a seamless connection between probability and expectation. Consider how easy it is to prove Markov's inequality with the help of indicator r | What is the intuition behind an Indicator Function?
Indicator random variables are useful in that they provide a seamless connection between probability and expectation. Consider how easy it is to prove Markov's inequality with the help of indicator random variables: let $X$ be a nonnegative random variable, $\alpha > 0$ and then note the trivial inequality $\alpha I_{\{ X \geq \alpha \}} \leq X$. We can then just take an expectation of both sides and do some algebra to get $P(X \geq \alpha) \leq \text{E}(X) / \alpha$. Other proofs, like that of the inclusion-exclusion formula, also make use of this connection. In fact, the whole theory of conditional probability can be developed from the theory of conditional expectation because of this.
They're also nice in that they're idempotent meaning $I_A^2 = I_A$, and this makes calculating variances easy. Also, products of indicator random variables are themselves indicator random variables whose expectation is the probability of the intersection.
Finally, while not really a probabilistic thing, indicator functions are a nice way of translating Boolean operations into arithmetic ones, which is helpful for general programming purposes. For instance, $I_{A \cup B} = \max(I_A, I_B)$ and $I_{A \cap B} = \min(I_A, I_B)$. | What is the intuition behind an Indicator Function?
Indicator random variables are useful in that they provide a seamless connection between probability and expectation. Consider how easy it is to prove Markov's inequality with the help of indicator r |
17,504 | What is the intuition behind an Indicator Function? | I also struggled with the topic and the most intuitive reflection I've found is truncation. Indicator function effectively truncates the density.
An example from (Train, 2009) can illustrate the point (e.g. some $v = 2$):
$$
\text{P}(\varepsilon>-v)
= \int_{-\infty}^{\infty}1_{\{\varepsilon \:>\: -v\}} \cdot f(\varepsilon)d\varepsilon \\
= \int_{-v}^{\infty} f(\varepsilon)d\varepsilon = F(\varepsilon)|_{-v}^{\infty}
= F(\infty) - F(-v)
= 1 -F(-v)
$$
The last statement in OP is also by no means intuitive. The easiest way to get it, in my opinion, is using LOTUS.
$$
\mathbb{E}[\: g(x) \: ] = \int_X g(x)\cdot f(x)dx
$$
Indicator function is a function, so we may put it directly instead of $g(x)$.
Let us take a simple case, say $A = \{x| x > a\}$.
$$
\mathbb{E}[1_A] = \int_{-\infty}^{\infty}1_{\{x>a\}}\cdot f(x)dx =
\int_{a}^{\infty} f(x)dx = P(x>a)= P(A)
$$
Hope this may help. | What is the intuition behind an Indicator Function? | I also struggled with the topic and the most intuitive reflection I've found is truncation. Indicator function effectively truncates the density.
An example from (Train, 2009) can illustrate the poin | What is the intuition behind an Indicator Function?
I also struggled with the topic and the most intuitive reflection I've found is truncation. Indicator function effectively truncates the density.
An example from (Train, 2009) can illustrate the point (e.g. some $v = 2$):
$$
\text{P}(\varepsilon>-v)
= \int_{-\infty}^{\infty}1_{\{\varepsilon \:>\: -v\}} \cdot f(\varepsilon)d\varepsilon \\
= \int_{-v}^{\infty} f(\varepsilon)d\varepsilon = F(\varepsilon)|_{-v}^{\infty}
= F(\infty) - F(-v)
= 1 -F(-v)
$$
The last statement in OP is also by no means intuitive. The easiest way to get it, in my opinion, is using LOTUS.
$$
\mathbb{E}[\: g(x) \: ] = \int_X g(x)\cdot f(x)dx
$$
Indicator function is a function, so we may put it directly instead of $g(x)$.
Let us take a simple case, say $A = \{x| x > a\}$.
$$
\mathbb{E}[1_A] = \int_{-\infty}^{\infty}1_{\{x>a\}}\cdot f(x)dx =
\int_{a}^{\infty} f(x)dx = P(x>a)= P(A)
$$
Hope this may help. | What is the intuition behind an Indicator Function?
I also struggled with the topic and the most intuitive reflection I've found is truncation. Indicator function effectively truncates the density.
An example from (Train, 2009) can illustrate the poin |
17,505 | What does it mean to say that an event "happens eventually"? | How would you demonstrate an event "eventually happens"? You would conduct a thought experiment with a hypothetical opponent. Your opponent may challenge you with any positive number $p$. If you can find an $n$ (which most likely depends on $p$) for which the chance of the event happening by time $n$ is at least $1-p$, then you win.
In the example, "$S_n$" is misleading notation because you use it both to refer to one state of a random walk as well as to the entire random walk itself. Let's take care to recognize the distinction. "Reaches $1$ eventually" is meant to refer to a subset $\mathcal{S}$ of the set of all random walks $\Omega$. Each walk $S\in\Omega$ has infinitely many steps. The value of $S$ at time $n$ is $S_n$. "$S$ reaches $1$ by time $n$" refers to the subset of $\Omega$ of walks that have reached the state $1$ by time $n$. Rigorously, it is the set
$$\Omega_{1,n} = \{S\in\Omega \mid S_1=1\text{ or }S_2=1\text{ or }\cdots\text{ or }S_n=1\}.$$
In your response to the imaginary opponent, you are exhibiting some $\Omega_{1,n}$ with the property that
$$\mathbb{P}_\xi(\Omega_{1,n}) \ge 1-p.$$
Because $n$ is arbitrary, you have available all elements of the set
$$\Omega_{1,\infty} = \bigcup_{n=1}^\infty \Omega_{1,n}.$$
(Recall that $S \in \bigcup_{n=1}^\infty \Omega_{1,n}$ if and only if there exists a finite $n$ for which $S \in \Omega_{1,n}$, so there aren't any infinite numbers involved in this union.)
Your ability to win the game shows this union has a probability exceeding all values of the form $1-p$, no matter how small $p\gt 0$ may be. Consequently, that probability is at least $1$--and therefore equals $1$. You will have demonstrated, then, that
$$\mathbb{P}_\xi(\Omega_{1,\infty}) = 1.$$
One simple way to appreciate the distinction between "happening eventually" and having an infinite expected first passage time is to contemplate a simpler situation. For $n$ any natural number, let $\omega^{(n)}$ be the sequence
$$\omega^{(n)} = (\underbrace{0, 0,\ldots,0}_{n},1,1,\ldots)$$
in which $n$ zeros are followed by an endless string of ones. In other words, these are the walks that stay at the origin and at some (finite) time step over to the point $1$, then stay there forever.
Let $\Omega$ be the set of all these $\omega^{(n)}, n=0, 1, 2, \ldots$ with the discrete sigma algebra. Assign a probability measure via
$$\mathbb{P}(\omega^{(n)}) = \frac{1}{n+1} - \frac{1}{n+2} = \frac{1}{(n+1)(n+2)}.$$
This was designed to make the chance of jumping to $1$ by the time $n$ equal to $1-1/(n+1)$, which obviously approaches arbitrarily closely to $1$. You will win the game. The jump eventually happens and when it does, it will be at some finite time. However, the expected time when it happens is the sum of the survival function (which gives the chances of not having jumped at time $n$),
$$\mathbb{E}(\tau) = \frac{1}{1} + \frac{1}{2} + \frac{1}{3} + \cdots,$$
which diverges. That is because a relatively large probability is given to waiting a long time before jumping. | What does it mean to say that an event "happens eventually"? | How would you demonstrate an event "eventually happens"? You would conduct a thought experiment with a hypothetical opponent. Your opponent may challenge you with any positive number $p$. If you ca | What does it mean to say that an event "happens eventually"?
How would you demonstrate an event "eventually happens"? You would conduct a thought experiment with a hypothetical opponent. Your opponent may challenge you with any positive number $p$. If you can find an $n$ (which most likely depends on $p$) for which the chance of the event happening by time $n$ is at least $1-p$, then you win.
In the example, "$S_n$" is misleading notation because you use it both to refer to one state of a random walk as well as to the entire random walk itself. Let's take care to recognize the distinction. "Reaches $1$ eventually" is meant to refer to a subset $\mathcal{S}$ of the set of all random walks $\Omega$. Each walk $S\in\Omega$ has infinitely many steps. The value of $S$ at time $n$ is $S_n$. "$S$ reaches $1$ by time $n$" refers to the subset of $\Omega$ of walks that have reached the state $1$ by time $n$. Rigorously, it is the set
$$\Omega_{1,n} = \{S\in\Omega \mid S_1=1\text{ or }S_2=1\text{ or }\cdots\text{ or }S_n=1\}.$$
In your response to the imaginary opponent, you are exhibiting some $\Omega_{1,n}$ with the property that
$$\mathbb{P}_\xi(\Omega_{1,n}) \ge 1-p.$$
Because $n$ is arbitrary, you have available all elements of the set
$$\Omega_{1,\infty} = \bigcup_{n=1}^\infty \Omega_{1,n}.$$
(Recall that $S \in \bigcup_{n=1}^\infty \Omega_{1,n}$ if and only if there exists a finite $n$ for which $S \in \Omega_{1,n}$, so there aren't any infinite numbers involved in this union.)
Your ability to win the game shows this union has a probability exceeding all values of the form $1-p$, no matter how small $p\gt 0$ may be. Consequently, that probability is at least $1$--and therefore equals $1$. You will have demonstrated, then, that
$$\mathbb{P}_\xi(\Omega_{1,\infty}) = 1.$$
One simple way to appreciate the distinction between "happening eventually" and having an infinite expected first passage time is to contemplate a simpler situation. For $n$ any natural number, let $\omega^{(n)}$ be the sequence
$$\omega^{(n)} = (\underbrace{0, 0,\ldots,0}_{n},1,1,\ldots)$$
in which $n$ zeros are followed by an endless string of ones. In other words, these are the walks that stay at the origin and at some (finite) time step over to the point $1$, then stay there forever.
Let $\Omega$ be the set of all these $\omega^{(n)}, n=0, 1, 2, \ldots$ with the discrete sigma algebra. Assign a probability measure via
$$\mathbb{P}(\omega^{(n)}) = \frac{1}{n+1} - \frac{1}{n+2} = \frac{1}{(n+1)(n+2)}.$$
This was designed to make the chance of jumping to $1$ by the time $n$ equal to $1-1/(n+1)$, which obviously approaches arbitrarily closely to $1$. You will win the game. The jump eventually happens and when it does, it will be at some finite time. However, the expected time when it happens is the sum of the survival function (which gives the chances of not having jumped at time $n$),
$$\mathbb{E}(\tau) = \frac{1}{1} + \frac{1}{2} + \frac{1}{3} + \cdots,$$
which diverges. That is because a relatively large probability is given to waiting a long time before jumping. | What does it mean to say that an event "happens eventually"?
How would you demonstrate an event "eventually happens"? You would conduct a thought experiment with a hypothetical opponent. Your opponent may challenge you with any positive number $p$. If you ca |
17,506 | What does it mean to say that an event "happens eventually"? | That something happens eventually means that there is some point in time at which it happens, but there is a connotation that one is not referring to any particular specified time before which it happens. If you say something will happen within three weeks, that is a stronger statement than that it will happen eventually. That it will happen eventually does not specify a time, such as "three weeks" or "thirty-billion years" or "one minute". | What does it mean to say that an event "happens eventually"? | That something happens eventually means that there is some point in time at which it happens, but there is a connotation that one is not referring to any particular specified time before which it happ | What does it mean to say that an event "happens eventually"?
That something happens eventually means that there is some point in time at which it happens, but there is a connotation that one is not referring to any particular specified time before which it happens. If you say something will happen within three weeks, that is a stronger statement than that it will happen eventually. That it will happen eventually does not specify a time, such as "three weeks" or "thirty-billion years" or "one minute". | What does it mean to say that an event "happens eventually"?
That something happens eventually means that there is some point in time at which it happens, but there is a connotation that one is not referring to any particular specified time before which it happ |
17,507 | GAM vs LOESS vs splines | What matters the most is the number of effective degrees of freedom that you give to each approach. For nonparametric smoothers such as loess this is controlled by the bandwidth whereas for regression splines the d.f. are more obvious and one d.f. is spent for each knot added. Both loess and splines are estimating relationships between $X$ and $Y$. Splines are more general in the sense that they can be used in a greater variety of contexts. | GAM vs LOESS vs splines | What matters the most is the number of effective degrees of freedom that you give to each approach. For nonparametric smoothers such as loess this is controlled by the bandwidth whereas for regressio | GAM vs LOESS vs splines
What matters the most is the number of effective degrees of freedom that you give to each approach. For nonparametric smoothers such as loess this is controlled by the bandwidth whereas for regression splines the d.f. are more obvious and one d.f. is spent for each knot added. Both loess and splines are estimating relationships between $X$ and $Y$. Splines are more general in the sense that they can be used in a greater variety of contexts. | GAM vs LOESS vs splines
What matters the most is the number of effective degrees of freedom that you give to each approach. For nonparametric smoothers such as loess this is controlled by the bandwidth whereas for regressio |
17,508 | The difference between average and marginal treatment effect | As some of the information you provided states, the two are not the same. I like better the terminology of conditional (on covariates) and unconditional (marginal) estimates. There is a very subtle language problem that clouds the issue greatly. Analysts who tend to love "population average effects" have a dangerous tendency to try to estimate such effects from a sample with no reference to any population distribution of subject characteristics. In this sense the estimates should not be called population average estimates but instead should be called sample average estimates. It is very important to note that sample average estimates have a low chance of being transportable to the population from which the sample came or in fact to any population. One reason for this is the somewhat arbitrary selection criteria for how subjects get into studies.
As an example, if one compared treatment A and treatment B in a binary logistic model adjusted for sex, one obtains a treatment effect that is specific to both males and females. If the sex variable is omitted from the model, a sample average odds ratio effect for treatment is obtained. This in effect is a comparison of some of the males on treatment A with some of the females on treatment B, due to non-collapsibility of the odds ratio. If one had a population with a different female:male frequency, this average treatment effect coming from a marginal odds ratio for treatment, will no longer apply.
So if one wants a quantity that pertains to individual subjects, full conditioning on covariates is required. And these conditional estimates are the ones that transport to populations, not the so-called "population average" estimates.
Another way to think about it: think of an ideal study for comparing treatment to no treatment. This would be a multi-period randomized crossover study. Then think about the next best study: a randomized trial on identical twins where one of the twins in each pair is randomly selected to get treatment A and the other is selected to get treatment B. Both of these ideal studies are mimicked by full conditioning, i.e., full covariate adjustment to get conditional and not marginal effects from the more usual parallel group randomized controlled trial. | The difference between average and marginal treatment effect | As some of the information you provided states, the two are not the same. I like better the terminology of conditional (on covariates) and unconditional (marginal) estimates. There is a very subtle | The difference between average and marginal treatment effect
As some of the information you provided states, the two are not the same. I like better the terminology of conditional (on covariates) and unconditional (marginal) estimates. There is a very subtle language problem that clouds the issue greatly. Analysts who tend to love "population average effects" have a dangerous tendency to try to estimate such effects from a sample with no reference to any population distribution of subject characteristics. In this sense the estimates should not be called population average estimates but instead should be called sample average estimates. It is very important to note that sample average estimates have a low chance of being transportable to the population from which the sample came or in fact to any population. One reason for this is the somewhat arbitrary selection criteria for how subjects get into studies.
As an example, if one compared treatment A and treatment B in a binary logistic model adjusted for sex, one obtains a treatment effect that is specific to both males and females. If the sex variable is omitted from the model, a sample average odds ratio effect for treatment is obtained. This in effect is a comparison of some of the males on treatment A with some of the females on treatment B, due to non-collapsibility of the odds ratio. If one had a population with a different female:male frequency, this average treatment effect coming from a marginal odds ratio for treatment, will no longer apply.
So if one wants a quantity that pertains to individual subjects, full conditioning on covariates is required. And these conditional estimates are the ones that transport to populations, not the so-called "population average" estimates.
Another way to think about it: think of an ideal study for comparing treatment to no treatment. This would be a multi-period randomized crossover study. Then think about the next best study: a randomized trial on identical twins where one of the twins in each pair is randomly selected to get treatment A and the other is selected to get treatment B. Both of these ideal studies are mimicked by full conditioning, i.e., full covariate adjustment to get conditional and not marginal effects from the more usual parallel group randomized controlled trial. | The difference between average and marginal treatment effect
As some of the information you provided states, the two are not the same. I like better the terminology of conditional (on covariates) and unconditional (marginal) estimates. There is a very subtle |
17,509 | How is cross validation different from data snooping? | I wondered whether using cross-validation to find the best tuning parameters for various machine learning techniques is different from data snooping?
Your concern is right spot on, and there is a whole lot of literature on this topic, e.g.
Cawley, G. C. & Talbot, N. L. C.: On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation, Journal of Machine Learning Research, 11, 2079-2107 (2010).
Boulesteix, A.-L.: Over-optimism in bioinformatics research., Bioinformatics, 26, 437-439 (2010). DOI: 10.1093/bioinformatics/btp648
Jelizarow, M.; Guillemot, V.; Tenenhaus, A.; Strimmer, K. & Boulesteix, A.-L.: Over-optimism in bioinformatics: an illustration., Bioinformatics, 26, 1990-1998 (2010). DOI: 10.1093/bioinformatics/btq323
The problem is that hyperparameter tuning with cross validation is a data-driven optimization process, and will still tend to overfit to yor data set (less than tuning by resubstitution error, but still). Trying to use the tuning cross validation results as "independent" performance measure is in a way like eating the pie (= tuning) and keeping (= measure final model performance) it.
This does not mean that you shouldn't use cross-validation for hyperparameter tuning. It just means that you can use it only for one purpose. Either optimize or measure model performance for validation purposes.
The solution is that you need to do an independent validation for measuring the quality of the model obtained with the tuned hyperparameters. This is called nested or double validation. You'll find a number of questions and answers here on these topics
Filzmoser, P.; Liebmann, B. & Varmuza, K.: Repeated double cross validation, J Chemom, 23, 160-171 (2009). DOI: 10.1002/cem.1225
Brereton, R.: Chemometrics for pattern recognition, Wiley, (2009).
Conceptually, I like to say that training includes all kinds of fancy steps to fit not only the "usual" model parameters but also to fit (auto-tune) the hyperparameters. So data-driven optimization of λ is clearly part of the model training.
As a rule of thumb you can also say that model training is everything that needs to be done before you have a ready-to-use final black-box function that is able to produce predictions for new cases.
PS: I find the testing vs. validation terminology very confusing because in my field "validation" means proving that the final model is fit for purpose, and is therefore what other people call testing rather than validation. I prefer to call the inner test set "tuning test set" and the outer "final validation test set" or the like.
Update:
So if my model (i.e. my tuning parameter in this case) fails the outer validation, what should I do then?
Typically, this is nothing that just happens: there are typical situations that can cause such a failure. And all such situations that I'm aware of are overfitting situations. You need to be aware that while regularization helps to reduce the necessary number of training cases, data-driven optimization needs large amounts of data.
My recommendations:
Typically, you (should) already have rough expectations, e.g. what performance should be achievable, what performance you'd consider suspiciously good looking. Or have specs what performance you need to achieve and a baseline performance. From that and the number of availabe training cases (for the splitting scheme you decided for), calculate the expected uncertainty for the inner (tuning) tests. If that uncertainty indicates that you would not be able to get meaningful comparisons, don't do data-driven optimization.
You should check how stable both the obtained predictions with the chosen λ and the optimal λ found by the auto-tuning procedure are. If λ isn't reasonably stable with respect to different splits of your data, the optimization didn't work.
If you find that either you won't be able to do the data-driven optimization or that it didn't work after all, you may choose the λ by your expert knowledge, e.g. from experience with similar data. Or by the knowledge that if you find out that the optimization failed, you'll need a stronger regularization: the overfitting that leads to the failure works towards too complex models. | How is cross validation different from data snooping? | I wondered whether using cross-validation to find the best tuning parameters for various machine learning techniques is different from data snooping?
Your concern is right spot on, and there is a wh | How is cross validation different from data snooping?
I wondered whether using cross-validation to find the best tuning parameters for various machine learning techniques is different from data snooping?
Your concern is right spot on, and there is a whole lot of literature on this topic, e.g.
Cawley, G. C. & Talbot, N. L. C.: On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation, Journal of Machine Learning Research, 11, 2079-2107 (2010).
Boulesteix, A.-L.: Over-optimism in bioinformatics research., Bioinformatics, 26, 437-439 (2010). DOI: 10.1093/bioinformatics/btp648
Jelizarow, M.; Guillemot, V.; Tenenhaus, A.; Strimmer, K. & Boulesteix, A.-L.: Over-optimism in bioinformatics: an illustration., Bioinformatics, 26, 1990-1998 (2010). DOI: 10.1093/bioinformatics/btq323
The problem is that hyperparameter tuning with cross validation is a data-driven optimization process, and will still tend to overfit to yor data set (less than tuning by resubstitution error, but still). Trying to use the tuning cross validation results as "independent" performance measure is in a way like eating the pie (= tuning) and keeping (= measure final model performance) it.
This does not mean that you shouldn't use cross-validation for hyperparameter tuning. It just means that you can use it only for one purpose. Either optimize or measure model performance for validation purposes.
The solution is that you need to do an independent validation for measuring the quality of the model obtained with the tuned hyperparameters. This is called nested or double validation. You'll find a number of questions and answers here on these topics
Filzmoser, P.; Liebmann, B. & Varmuza, K.: Repeated double cross validation, J Chemom, 23, 160-171 (2009). DOI: 10.1002/cem.1225
Brereton, R.: Chemometrics for pattern recognition, Wiley, (2009).
Conceptually, I like to say that training includes all kinds of fancy steps to fit not only the "usual" model parameters but also to fit (auto-tune) the hyperparameters. So data-driven optimization of λ is clearly part of the model training.
As a rule of thumb you can also say that model training is everything that needs to be done before you have a ready-to-use final black-box function that is able to produce predictions for new cases.
PS: I find the testing vs. validation terminology very confusing because in my field "validation" means proving that the final model is fit for purpose, and is therefore what other people call testing rather than validation. I prefer to call the inner test set "tuning test set" and the outer "final validation test set" or the like.
Update:
So if my model (i.e. my tuning parameter in this case) fails the outer validation, what should I do then?
Typically, this is nothing that just happens: there are typical situations that can cause such a failure. And all such situations that I'm aware of are overfitting situations. You need to be aware that while regularization helps to reduce the necessary number of training cases, data-driven optimization needs large amounts of data.
My recommendations:
Typically, you (should) already have rough expectations, e.g. what performance should be achievable, what performance you'd consider suspiciously good looking. Or have specs what performance you need to achieve and a baseline performance. From that and the number of availabe training cases (for the splitting scheme you decided for), calculate the expected uncertainty for the inner (tuning) tests. If that uncertainty indicates that you would not be able to get meaningful comparisons, don't do data-driven optimization.
You should check how stable both the obtained predictions with the chosen λ and the optimal λ found by the auto-tuning procedure are. If λ isn't reasonably stable with respect to different splits of your data, the optimization didn't work.
If you find that either you won't be able to do the data-driven optimization or that it didn't work after all, you may choose the λ by your expert knowledge, e.g. from experience with similar data. Or by the knowledge that if you find out that the optimization failed, you'll need a stronger regularization: the overfitting that leads to the failure works towards too complex models. | How is cross validation different from data snooping?
I wondered whether using cross-validation to find the best tuning parameters for various machine learning techniques is different from data snooping?
Your concern is right spot on, and there is a wh |
17,510 | How is cross validation different from data snooping? | Cross validation is used to assess the validity of a particular finding, usually tangibly related to a prediction model. These kinds of findings can include results from cluster analyses, classification, or prediction models. In any case, the nature of the analysis is part of a pre-specified question of scientific interest such as "which frequencies of mRNA expression most likely originated from breast cancer biopsies versus healthy controls?". Cross validation is a very robust way to assess the validity of a prespecified prediction model that serves a specific purpose. I suspect that $k$-fold cross validation, which involves repeated model fitting, may be the origin of your confusion.
When using CV to identify an "optimal" tuning parameter, as is needed with penalized likelihood methods, there is usually a prespecified criterion that the process is set to meet. This might be minimal MSE, or maximal AUC, or minimal BIC. If you cherry pick a $\lambda$ which gives you results you are after, then you have done something worse than data dredging, I think. So, using a microarray example, if you are interested in which proteins are more expressed in cancer cases versus controls, you might prespecify a GLM LASSO to have $\lambda$ give the best BIC and markers selected in the final model are chosen as candidate proteins for further investigation. This is an example of feature selection.
"Data snooping" or, as I could call it, "Exploratory data analysis" does not deal with a pre-specified question. You kind of enumerate a number of possible, plausibly interesting results and evaluate them individually. You can perform any number of exploratory analyses and, usually, you don't worry about multiple testing. You can assess each exploratory analysis individually using cross-validation, but it does not inherently account for multiple testing when you have more than 1 exploratory analysis. Hypotheses in this setting can be quite wide and far reaching, "which factors are associated with prostate cancer?" (from which coffee drinking, vasectomy usage, etc. etc. were measured in a cohort). Significant results are seen as "hypothesis generating" and provide no confirmatory evidence.
So while both approaches are somewhat "iterative" in nature, they are entirely independent procedures. $k$-fold cross-validation is a tool for assessing uncertainty and validity of a particular set of findings which are part of a "modular" hypothesis. Data dredging, data snooping, or exploratory data analysis is meant to generate hypotheses based on a large set of possibly interesting questions addressed by a comprehensive and large dataset. | How is cross validation different from data snooping? | Cross validation is used to assess the validity of a particular finding, usually tangibly related to a prediction model. These kinds of findings can include results from cluster analyses, classificati | How is cross validation different from data snooping?
Cross validation is used to assess the validity of a particular finding, usually tangibly related to a prediction model. These kinds of findings can include results from cluster analyses, classification, or prediction models. In any case, the nature of the analysis is part of a pre-specified question of scientific interest such as "which frequencies of mRNA expression most likely originated from breast cancer biopsies versus healthy controls?". Cross validation is a very robust way to assess the validity of a prespecified prediction model that serves a specific purpose. I suspect that $k$-fold cross validation, which involves repeated model fitting, may be the origin of your confusion.
When using CV to identify an "optimal" tuning parameter, as is needed with penalized likelihood methods, there is usually a prespecified criterion that the process is set to meet. This might be minimal MSE, or maximal AUC, or minimal BIC. If you cherry pick a $\lambda$ which gives you results you are after, then you have done something worse than data dredging, I think. So, using a microarray example, if you are interested in which proteins are more expressed in cancer cases versus controls, you might prespecify a GLM LASSO to have $\lambda$ give the best BIC and markers selected in the final model are chosen as candidate proteins for further investigation. This is an example of feature selection.
"Data snooping" or, as I could call it, "Exploratory data analysis" does not deal with a pre-specified question. You kind of enumerate a number of possible, plausibly interesting results and evaluate them individually. You can perform any number of exploratory analyses and, usually, you don't worry about multiple testing. You can assess each exploratory analysis individually using cross-validation, but it does not inherently account for multiple testing when you have more than 1 exploratory analysis. Hypotheses in this setting can be quite wide and far reaching, "which factors are associated with prostate cancer?" (from which coffee drinking, vasectomy usage, etc. etc. were measured in a cohort). Significant results are seen as "hypothesis generating" and provide no confirmatory evidence.
So while both approaches are somewhat "iterative" in nature, they are entirely independent procedures. $k$-fold cross-validation is a tool for assessing uncertainty and validity of a particular set of findings which are part of a "modular" hypothesis. Data dredging, data snooping, or exploratory data analysis is meant to generate hypotheses based on a large set of possibly interesting questions addressed by a comprehensive and large dataset. | How is cross validation different from data snooping?
Cross validation is used to assess the validity of a particular finding, usually tangibly related to a prediction model. These kinds of findings can include results from cluster analyses, classificati |
17,511 | How is cross validation different from data snooping? | Actually, during CV you try to find the best parameters on a validation set, which is distinct from the test set. You split your entire data into three sets : training set, validation set, and test set. When you do cross-validation properly, you never look at the test end until the end, so there is no snooping at all. Doing cross-validation on the test set is a serious (yet frequent) methodological error. | How is cross validation different from data snooping? | Actually, during CV you try to find the best parameters on a validation set, which is distinct from the test set. You split your entire data into three sets : training set, validation set, and test se | How is cross validation different from data snooping?
Actually, during CV you try to find the best parameters on a validation set, which is distinct from the test set. You split your entire data into three sets : training set, validation set, and test set. When you do cross-validation properly, you never look at the test end until the end, so there is no snooping at all. Doing cross-validation on the test set is a serious (yet frequent) methodological error. | How is cross validation different from data snooping?
Actually, during CV you try to find the best parameters on a validation set, which is distinct from the test set. You split your entire data into three sets : training set, validation set, and test se |
17,512 | How is cross validation different from data snooping? | If you look for example at page 225 of "An Introduction to Statistical Learning" with Lasso example, you see that they actually do nested cross-validation. I.e. the model selection is done in cv.glmnet on a train set, which is split by the cv.glmnet package into train-test pairs. The model validation is done on validation ("test") set, so it is independent validation. | How is cross validation different from data snooping? | If you look for example at page 225 of "An Introduction to Statistical Learning" with Lasso example, you see that they actually do nested cross-validation. I.e. the model selection is done in cv.glmn | How is cross validation different from data snooping?
If you look for example at page 225 of "An Introduction to Statistical Learning" with Lasso example, you see that they actually do nested cross-validation. I.e. the model selection is done in cv.glmnet on a train set, which is split by the cv.glmnet package into train-test pairs. The model validation is done on validation ("test") set, so it is independent validation. | How is cross validation different from data snooping?
If you look for example at page 225 of "An Introduction to Statistical Learning" with Lasso example, you see that they actually do nested cross-validation. I.e. the model selection is done in cv.glmn |
17,513 | Marginal model versus random-effects model – how to choose between them? An advice for a layman | Thank you for linking my answer! I will try to give an explicit explanation. This question has been discussed many times at this site (see the related questions on the right side), but it is really confusing and important for a "layman".
First of all, for linear models (continuous response), the estimates of marginal and conditional (random-effects) models coincide. So I will focus on nonlinear models, especially logistic regression for binary data.
Scientific questions
The mostly used example to distinguish marginal and conditional models is:
If you are a doctor and you want an estimate of how much a statin
drug will lower your patient’s odds of getting a heart attack, the
subject-specific coefficient is the clear choice. On the other hand,
if you are a state health official and you want to know how the number
of people who die of heart attacks would change if everyone in the
at-risk population took the stain drug, you would probably want to use
the population–averaged coefficients. (Allison, 2009)
The two kinds of scientific questions correspond to these two models.
Illustration
The best illustration I have seen so far is the following figure in Applied Longitudinal Analysis (Fitzmaurice, Laird and Ware, 2011, Page 479), if we change the covariate from "statin drug" to "time". It is clear that the two models differ in the scale of coefficients, which can be essentially explained by the fact that the mean of a nonlinear function of a random variable does not equal the nonlinear function of the mean.
Interpretation
In the above figure, the dotted lines are from a random intercept model. It shows that we need to control the random effects constant when interpreting the fixed effects, i.e. only go along a line when interpreting the slope. This is why we call the estimates from random effects models "subject specific". Specifically,
For conditional models, the interpretation is that, how would the log odds change with one unit change of time for a given subject? (See Page 403 of Fitzmaurice, Laird and Ware (2011) about the discussion about why the interpretation of time-invariant covariates in conditional models is potentially misleading.)
For marginal models, the interpretation is exactly the same as the interpretation of linear regressions, i.e., how would the log odds change with one unit change of time, or the log odds ratio of drug vs. placebo.
There is another example on this site. | Marginal model versus random-effects model – how to choose between them? An advice for a layman | Thank you for linking my answer! I will try to give an explicit explanation. This question has been discussed many times at this site (see the related questions on the right side), but it is really co | Marginal model versus random-effects model – how to choose between them? An advice for a layman
Thank you for linking my answer! I will try to give an explicit explanation. This question has been discussed many times at this site (see the related questions on the right side), but it is really confusing and important for a "layman".
First of all, for linear models (continuous response), the estimates of marginal and conditional (random-effects) models coincide. So I will focus on nonlinear models, especially logistic regression for binary data.
Scientific questions
The mostly used example to distinguish marginal and conditional models is:
If you are a doctor and you want an estimate of how much a statin
drug will lower your patient’s odds of getting a heart attack, the
subject-specific coefficient is the clear choice. On the other hand,
if you are a state health official and you want to know how the number
of people who die of heart attacks would change if everyone in the
at-risk population took the stain drug, you would probably want to use
the population–averaged coefficients. (Allison, 2009)
The two kinds of scientific questions correspond to these two models.
Illustration
The best illustration I have seen so far is the following figure in Applied Longitudinal Analysis (Fitzmaurice, Laird and Ware, 2011, Page 479), if we change the covariate from "statin drug" to "time". It is clear that the two models differ in the scale of coefficients, which can be essentially explained by the fact that the mean of a nonlinear function of a random variable does not equal the nonlinear function of the mean.
Interpretation
In the above figure, the dotted lines are from a random intercept model. It shows that we need to control the random effects constant when interpreting the fixed effects, i.e. only go along a line when interpreting the slope. This is why we call the estimates from random effects models "subject specific". Specifically,
For conditional models, the interpretation is that, how would the log odds change with one unit change of time for a given subject? (See Page 403 of Fitzmaurice, Laird and Ware (2011) about the discussion about why the interpretation of time-invariant covariates in conditional models is potentially misleading.)
For marginal models, the interpretation is exactly the same as the interpretation of linear regressions, i.e., how would the log odds change with one unit change of time, or the log odds ratio of drug vs. placebo.
There is another example on this site. | Marginal model versus random-effects model – how to choose between them? An advice for a layman
Thank you for linking my answer! I will try to give an explicit explanation. This question has been discussed many times at this site (see the related questions on the right side), but it is really co |
17,514 | Closed form expression for the quantiles of $\alpha_1\sin(x)+\alpha_2\cos(x)$ | This problem can quickly be reduced to one of finding the quantile of a trapezoidal distribution.
Let us rewrite the process as
$$
P(x) = U_1 \cdot \frac12 \sin x + U_2 \cdot \frac12 \cos x + \frac{1}{2} (\sin x + \cos x) \>,
$$
where $U_1$ and $U_2$ are iid $\mathcal U(-1,1)$ random variables; and, by symmetry, this has the same marginal distribution as the process
$$
\overline P(x) = U_1 \cdot \left|\frac12 \sin x\right| + U_2 \cdot \left|\frac12 \cos x\right| + \frac{1}{2} (\sin x + \cos x) \>.
$$
The first two terms determine a symmetric trapezoidal density since this is the sum of two mean-zero uniform random variables (with, in general, different half-widths). The last term just results in a translate of this density and the quantile is equivariant with respect to this translate (i.e., the quantile of the shifted distribution is the shifted quantile of the centered distribution).
Quantiles of a trapezoidal distribution
Let $Y = X_1 + X_2$ where $X_1$ and $X_2$ are independent $\mathcal U(-a,a)$ and $\mathcal U(-b,b)$ distributions. Assume without loss of generality that $a \geq b$. Then, the density of $Y$ is formed by convolving the densities of $X_1$ and $X_2$. This is readily seen to be a trapezoid with vertices $(-a-b,0)$, $(-a+b,1/2a)$, $(a-b,1/2a)$ and $(a+b,0)$.
The quantile of the distribution of $Y$, for any $p < 1/2$ is, thus,
$$
q(p) := q(p\,; a,b) =
\begin{cases}
\sqrt{8abp} - (a+b) \,, & p < b/2a \\
(2p - 1) a \,, & b/2a \leq p \leq 1/2 \>.
\end{cases}
$$
By symmetry, for $p > 1/2$, we have $q(p) = - q(1-p)$.
Back to the case at hand
The above already provides enough to give a closed-form expression. All we need is to break into two cases $|\sin x| \geq |\cos x|$ and $|\sin x| < |\cos x|$ to determine which plays the role of $2a$ and which plays the role of $2b$ above. (The factor of 2 here is only to compensate for the divisions by two in the definition of $\overline P(x)$.)
For $p < 1/2$, on $|\sin x| \geq |\cos x|$, we set $a = |\sin x|/2$ and $b=|\cos x|/2$ and get
$$
q_x(p) = q(p \,; a,b) + \frac{1}{2}(\sin x + \cos x) \>,
$$
and on $|\sin x| < |\cos x|$ the roles reverse. Similarly, for $p \geq 1/2$
$$
q_x(p) = -q(1-p \,; a,b) + \frac{1}{2}(\sin x + \cos x) \>,
$$
The quantiles
Below are two heatmaps. The first shows the quantiles of the distribution of $P(x)$ for a grid of $x$ running from $0$ to $2\pi$. The $y$-coordinate gives the probability $p$ associated with each quantile. The colors indicate the value of the quantile with dark red indicating very large (positive) values and dark blue indicating large negative values. Thus each vertical strip is a (marginal) quantile plot associated with $P(x)$.
The second heatmap below shows the quantiles themselves, colored by the corresponding probability. For example, dark red corresponds to $p = 1/2$ and dark blue corresponds to $p=0$ and $p=1$. Cyan is roughly $p=1/4$ and $p=3/4$. This more clearly shows the support of each distribution and the shape.
Some sample R code
The function qproc below calculates the quantile function of $P(x)$ for a given $x$. It uses the more general qtrap to generate the quantiles.
# Pointwise quantiles of a random process:
# P(x) = a_1 sin(x) + a_2 cos(x)
# Trapezoidal distribution quantile
# Assumes X = U + V where U~Uni(-a,a), V~Uni(-b,b) and a >= b
qtrap <- function(p, a, b)
{
if( a < b) stop("I need a >= b.")
s <- 2*(p<=1/2) - 1
p <- ifelse(p<= 1/2, p, 1-p)
s * ifelse( p < b/2/a, sqrt(8*a*b*p)-a-b, (2*p-1)*a )
}
# Now, here is the process's quantile function.
qproc <- function(p, x)
{
s <- abs(sin(x))
c <- abs(cos(x))
a <- ifelse(s>c, s, c)
b <- ifelse(s<c, s, c)
qtrap(p,a/2, b/2) + 0.5*(sin(x)+cos(x))
}
Below is a test with the corresponding output.
# Test case
set.seed(17)
n <- 1e4
x <- -pi/8
r <- runif(n) * sin(x) + runif(n) * cos(x)
# Sample quantiles, then actual.
> round(quantile(r,(0:10)/10),3)
0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%
-0.380 -0.111 -0.002 0.093 0.186 0.275 0.365 0.453 0.550 0.659 0.917
> round(qproc((0:10)/10, x),3)
[1] -0.383 -0.117 -0.007 0.086 0.178 0.271 0.363 0.455 0.548
[10] 0.658 0.924 | Closed form expression for the quantiles of $\alpha_1\sin(x)+\alpha_2\cos(x)$ | This problem can quickly be reduced to one of finding the quantile of a trapezoidal distribution.
Let us rewrite the process as
$$
P(x) = U_1 \cdot \frac12 \sin x + U_2 \cdot \frac12 \cos x + \frac{1 | Closed form expression for the quantiles of $\alpha_1\sin(x)+\alpha_2\cos(x)$
This problem can quickly be reduced to one of finding the quantile of a trapezoidal distribution.
Let us rewrite the process as
$$
P(x) = U_1 \cdot \frac12 \sin x + U_2 \cdot \frac12 \cos x + \frac{1}{2} (\sin x + \cos x) \>,
$$
where $U_1$ and $U_2$ are iid $\mathcal U(-1,1)$ random variables; and, by symmetry, this has the same marginal distribution as the process
$$
\overline P(x) = U_1 \cdot \left|\frac12 \sin x\right| + U_2 \cdot \left|\frac12 \cos x\right| + \frac{1}{2} (\sin x + \cos x) \>.
$$
The first two terms determine a symmetric trapezoidal density since this is the sum of two mean-zero uniform random variables (with, in general, different half-widths). The last term just results in a translate of this density and the quantile is equivariant with respect to this translate (i.e., the quantile of the shifted distribution is the shifted quantile of the centered distribution).
Quantiles of a trapezoidal distribution
Let $Y = X_1 + X_2$ where $X_1$ and $X_2$ are independent $\mathcal U(-a,a)$ and $\mathcal U(-b,b)$ distributions. Assume without loss of generality that $a \geq b$. Then, the density of $Y$ is formed by convolving the densities of $X_1$ and $X_2$. This is readily seen to be a trapezoid with vertices $(-a-b,0)$, $(-a+b,1/2a)$, $(a-b,1/2a)$ and $(a+b,0)$.
The quantile of the distribution of $Y$, for any $p < 1/2$ is, thus,
$$
q(p) := q(p\,; a,b) =
\begin{cases}
\sqrt{8abp} - (a+b) \,, & p < b/2a \\
(2p - 1) a \,, & b/2a \leq p \leq 1/2 \>.
\end{cases}
$$
By symmetry, for $p > 1/2$, we have $q(p) = - q(1-p)$.
Back to the case at hand
The above already provides enough to give a closed-form expression. All we need is to break into two cases $|\sin x| \geq |\cos x|$ and $|\sin x| < |\cos x|$ to determine which plays the role of $2a$ and which plays the role of $2b$ above. (The factor of 2 here is only to compensate for the divisions by two in the definition of $\overline P(x)$.)
For $p < 1/2$, on $|\sin x| \geq |\cos x|$, we set $a = |\sin x|/2$ and $b=|\cos x|/2$ and get
$$
q_x(p) = q(p \,; a,b) + \frac{1}{2}(\sin x + \cos x) \>,
$$
and on $|\sin x| < |\cos x|$ the roles reverse. Similarly, for $p \geq 1/2$
$$
q_x(p) = -q(1-p \,; a,b) + \frac{1}{2}(\sin x + \cos x) \>,
$$
The quantiles
Below are two heatmaps. The first shows the quantiles of the distribution of $P(x)$ for a grid of $x$ running from $0$ to $2\pi$. The $y$-coordinate gives the probability $p$ associated with each quantile. The colors indicate the value of the quantile with dark red indicating very large (positive) values and dark blue indicating large negative values. Thus each vertical strip is a (marginal) quantile plot associated with $P(x)$.
The second heatmap below shows the quantiles themselves, colored by the corresponding probability. For example, dark red corresponds to $p = 1/2$ and dark blue corresponds to $p=0$ and $p=1$. Cyan is roughly $p=1/4$ and $p=3/4$. This more clearly shows the support of each distribution and the shape.
Some sample R code
The function qproc below calculates the quantile function of $P(x)$ for a given $x$. It uses the more general qtrap to generate the quantiles.
# Pointwise quantiles of a random process:
# P(x) = a_1 sin(x) + a_2 cos(x)
# Trapezoidal distribution quantile
# Assumes X = U + V where U~Uni(-a,a), V~Uni(-b,b) and a >= b
qtrap <- function(p, a, b)
{
if( a < b) stop("I need a >= b.")
s <- 2*(p<=1/2) - 1
p <- ifelse(p<= 1/2, p, 1-p)
s * ifelse( p < b/2/a, sqrt(8*a*b*p)-a-b, (2*p-1)*a )
}
# Now, here is the process's quantile function.
qproc <- function(p, x)
{
s <- abs(sin(x))
c <- abs(cos(x))
a <- ifelse(s>c, s, c)
b <- ifelse(s<c, s, c)
qtrap(p,a/2, b/2) + 0.5*(sin(x)+cos(x))
}
Below is a test with the corresponding output.
# Test case
set.seed(17)
n <- 1e4
x <- -pi/8
r <- runif(n) * sin(x) + runif(n) * cos(x)
# Sample quantiles, then actual.
> round(quantile(r,(0:10)/10),3)
0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%
-0.380 -0.111 -0.002 0.093 0.186 0.275 0.365 0.453 0.550 0.659 0.917
> round(qproc((0:10)/10, x),3)
[1] -0.383 -0.117 -0.007 0.086 0.178 0.271 0.363 0.455 0.548
[10] 0.658 0.924 | Closed form expression for the quantiles of $\alpha_1\sin(x)+\alpha_2\cos(x)$
This problem can quickly be reduced to one of finding the quantile of a trapezoidal distribution.
Let us rewrite the process as
$$
P(x) = U_1 \cdot \frac12 \sin x + U_2 \cdot \frac12 \cos x + \frac{1 |
17,515 | What is the difference between wilcox.test and coin::wilcox_test in R? | The key to your question is found in ?wilcox.test in the Notes section:
The literature is not unanimous about the definitions of the Wilcoxon rank sum and Mann-Whitney tests.
So what that means is there is more than one way to do this non-parametric test of change in location between two samples. In addition, given each definition, there is more than one way to get a p value. "exact" means that it is absolutely correct, while "approximate" or "asymptotic" are both approximations of the truth. That's why there are multiple options in both wilcox.test() and wilcox_test(), and only some of them match exactly - when you have both functions doing exactly the same thing. It looks like wilcox_test() can get exact p-values even when there are tied values, while wilcox.test() falls back to an asymptotic approximation when there are tied values. I wouldn't know what combination of statistic and p-value calculations an Excel add-on is doing, but the advantage of R is that it is clear what choices you have made.
Your next question is why wilcox.test() is returning 0 all the time. For the data set you created, the value of the test statistic is 0 when you do
wilcox.test(x,y)
but it will be 49 when you do
wilcox.test(y,x)
although the p-value will be the same. See the wikipedia page for the reasons. wilcox_test() returns a Z transformation of the statistic returned by wilcox.test(), which is why they have different values of the test statistic.
Is there a correct p-value? Yes, but sometimes it is too hard to calculate, and so we need to use approximate methods (see ?wilcox_test for descriptions of how the exact calculation can fail from insufficient memory). The differences between approximation and exact value will mostly not matter unless the true difference in the location of the two groups is very small. | What is the difference between wilcox.test and coin::wilcox_test in R? | The key to your question is found in ?wilcox.test in the Notes section:
The literature is not unanimous about the definitions of the Wilcoxon rank sum and Mann-Whitney tests.
So what that means is t | What is the difference between wilcox.test and coin::wilcox_test in R?
The key to your question is found in ?wilcox.test in the Notes section:
The literature is not unanimous about the definitions of the Wilcoxon rank sum and Mann-Whitney tests.
So what that means is there is more than one way to do this non-parametric test of change in location between two samples. In addition, given each definition, there is more than one way to get a p value. "exact" means that it is absolutely correct, while "approximate" or "asymptotic" are both approximations of the truth. That's why there are multiple options in both wilcox.test() and wilcox_test(), and only some of them match exactly - when you have both functions doing exactly the same thing. It looks like wilcox_test() can get exact p-values even when there are tied values, while wilcox.test() falls back to an asymptotic approximation when there are tied values. I wouldn't know what combination of statistic and p-value calculations an Excel add-on is doing, but the advantage of R is that it is clear what choices you have made.
Your next question is why wilcox.test() is returning 0 all the time. For the data set you created, the value of the test statistic is 0 when you do
wilcox.test(x,y)
but it will be 49 when you do
wilcox.test(y,x)
although the p-value will be the same. See the wikipedia page for the reasons. wilcox_test() returns a Z transformation of the statistic returned by wilcox.test(), which is why they have different values of the test statistic.
Is there a correct p-value? Yes, but sometimes it is too hard to calculate, and so we need to use approximate methods (see ?wilcox_test for descriptions of how the exact calculation can fail from insufficient memory). The differences between approximation and exact value will mostly not matter unless the true difference in the location of the two groups is very small. | What is the difference between wilcox.test and coin::wilcox_test in R?
The key to your question is found in ?wilcox.test in the Notes section:
The literature is not unanimous about the definitions of the Wilcoxon rank sum and Mann-Whitney tests.
So what that means is t |
17,516 | Is there a general method for simulating data from a formula or analysis available? | There actually is an S3 generic simulate that even returns the data frame (or other list) you want. Type
?simulate
It has methods for classes lm (works also for glm or for your aov example) and glm.nb (in MASS) already. You can now write S3 simulate methods for other classes of objects, e.g. for objects from lme4. You can check for which classes there are methods by typing
getAnywhere("simulate.class"), getAnywhere("simulate")
or
getS3method("simulate","class"), methods(simulate) | Is there a general method for simulating data from a formula or analysis available? | There actually is an S3 generic simulate that even returns the data frame (or other list) you want. Type
?simulate
It has methods for classes lm (works also for glm or for your aov example) and gl | Is there a general method for simulating data from a formula or analysis available?
There actually is an S3 generic simulate that even returns the data frame (or other list) you want. Type
?simulate
It has methods for classes lm (works also for glm or for your aov example) and glm.nb (in MASS) already. You can now write S3 simulate methods for other classes of objects, e.g. for objects from lme4. You can check for which classes there are methods by typing
getAnywhere("simulate.class"), getAnywhere("simulate")
or
getS3method("simulate","class"), methods(simulate) | Is there a general method for simulating data from a formula or analysis available?
There actually is an S3 generic simulate that even returns the data frame (or other list) you want. Type
?simulate
It has methods for classes lm (works also for glm or for your aov example) and gl |
17,517 | Is there a general method for simulating data from a formula or analysis available? | There is a new function called simfun in the TeachingDemos package for R (it is currently only in the development version on R-forge, it will be a while before it is on CRAN). It is intended to help with creating functions to do simulations.
One of the intended uses is that a teacher would use the simfun function to create a function and distribute it to students (possibly have a web interface at some point as an alternative). The students would then create a data frame of the factors representing an experimental design, pass this data frame to the created function and get returned the data frame with an additional column of the response simulated according to the parameters and error distribution set up by the teacher, the student can then analyze the data. This allows the teacher to set up a "True" relationship, but allow students to try many different experimental designs to explore ways to get at the "Truth" in much less time than doing an actual experiment and requiring less work for the teacher than to create or find a bunch of different sample datasets representing the different possible designs.
The simfun function is designed to be flexible so the teacher/creator can base the simulations on a fitted regression model, parameters supplied by the teacher/creator, or parameters suplied by the student/user.
The created function can also be easily used in simulations (with the replicate command) to explore power, sample size, effect size, etc. Though the resulting simulation may be slower than hand crafting the simulation process.
This looks like what you describe with the exception that it does not take p-values to create the data, but use of power. functions or pwr. from the pwr package could be incorporated to create simulations based on specifying power and alpha rather than means and differences.
Here is an example from the help page (there are several more examples) that assumes that you are measuring heights of subjects (male and female) that are nested in cities which are nested in states, there is a random effect for state with a SD of 1 and a random effect for city (within state) with a SD of 0.5 then the "error" SD is 3, females have a simulation mean of 64 inches and males have a mean of 69 inches (the error SD and means are realistic, the random effects are a bit contrived). The simfun function is used to create a new function called simheight, then a data frame is created with state ID's, city ID's and a column for sex of the subject (the experimental design or sampling design), this is passed to simheight and the result in a new data frame with the simulated heights (in addition to the other variables) that could then be analyzed using appropriate tools.
# simulate a nested mixed effects model
simheight <- simfun({
n.city <- length(unique(city))
n.state <- length(unique(state))
n <- length(city)
height <- h[sex] + rnorm(n.state,0,sig.state)[state] +
rnorm(n.city,0,sig.city)[city] + rnorm(n,0,sig.e)
}, sig.state=1, sig.city=0.5, sig.e=3, h=c(64,69),
drop=c('sig.state','sig.city','sig.e','h','n.city','n.state','n'))
tmpdat <- data.frame(state=gl(5,20), city=gl(10,10),
sex=gl(2,5,length=100, labels=c('F','M')))
heightdat <- simheight(tmpdat) | Is there a general method for simulating data from a formula or analysis available? | There is a new function called simfun in the TeachingDemos package for R (it is currently only in the development version on R-forge, it will be a while before it is on CRAN). It is intended to help | Is there a general method for simulating data from a formula or analysis available?
There is a new function called simfun in the TeachingDemos package for R (it is currently only in the development version on R-forge, it will be a while before it is on CRAN). It is intended to help with creating functions to do simulations.
One of the intended uses is that a teacher would use the simfun function to create a function and distribute it to students (possibly have a web interface at some point as an alternative). The students would then create a data frame of the factors representing an experimental design, pass this data frame to the created function and get returned the data frame with an additional column of the response simulated according to the parameters and error distribution set up by the teacher, the student can then analyze the data. This allows the teacher to set up a "True" relationship, but allow students to try many different experimental designs to explore ways to get at the "Truth" in much less time than doing an actual experiment and requiring less work for the teacher than to create or find a bunch of different sample datasets representing the different possible designs.
The simfun function is designed to be flexible so the teacher/creator can base the simulations on a fitted regression model, parameters supplied by the teacher/creator, or parameters suplied by the student/user.
The created function can also be easily used in simulations (with the replicate command) to explore power, sample size, effect size, etc. Though the resulting simulation may be slower than hand crafting the simulation process.
This looks like what you describe with the exception that it does not take p-values to create the data, but use of power. functions or pwr. from the pwr package could be incorporated to create simulations based on specifying power and alpha rather than means and differences.
Here is an example from the help page (there are several more examples) that assumes that you are measuring heights of subjects (male and female) that are nested in cities which are nested in states, there is a random effect for state with a SD of 1 and a random effect for city (within state) with a SD of 0.5 then the "error" SD is 3, females have a simulation mean of 64 inches and males have a mean of 69 inches (the error SD and means are realistic, the random effects are a bit contrived). The simfun function is used to create a new function called simheight, then a data frame is created with state ID's, city ID's and a column for sex of the subject (the experimental design or sampling design), this is passed to simheight and the result in a new data frame with the simulated heights (in addition to the other variables) that could then be analyzed using appropriate tools.
# simulate a nested mixed effects model
simheight <- simfun({
n.city <- length(unique(city))
n.state <- length(unique(state))
n <- length(city)
height <- h[sex] + rnorm(n.state,0,sig.state)[state] +
rnorm(n.city,0,sig.city)[city] + rnorm(n,0,sig.e)
}, sig.state=1, sig.city=0.5, sig.e=3, h=c(64,69),
drop=c('sig.state','sig.city','sig.e','h','n.city','n.state','n'))
tmpdat <- data.frame(state=gl(5,20), city=gl(10,10),
sex=gl(2,5,length=100, labels=c('F','M')))
heightdat <- simheight(tmpdat) | Is there a general method for simulating data from a formula or analysis available?
There is a new function called simfun in the TeachingDemos package for R (it is currently only in the development version on R-forge, it will be a while before it is on CRAN). It is intended to help |
17,518 | Is there a general method for simulating data from a formula or analysis available? | Typing methods(simulate) or getAnywhere("simulate") should work. The former gives you a few methods, if package lme4 is loaded:
[1] simulate.lm* simulate.merMod* simulate.negbin* simulate.polr*
Lm-objects are used for both lm and glm models. | Is there a general method for simulating data from a formula or analysis available? | Typing methods(simulate) or getAnywhere("simulate") should work. The former gives you a few methods, if package lme4 is loaded:
[1] simulate.lm* simulate.merMod* simulate.negbin* simulate.polr*
L | Is there a general method for simulating data from a formula or analysis available?
Typing methods(simulate) or getAnywhere("simulate") should work. The former gives you a few methods, if package lme4 is loaded:
[1] simulate.lm* simulate.merMod* simulate.negbin* simulate.polr*
Lm-objects are used for both lm and glm models. | Is there a general method for simulating data from a formula or analysis available?
Typing methods(simulate) or getAnywhere("simulate") should work. The former gives you a few methods, if package lme4 is loaded:
[1] simulate.lm* simulate.merMod* simulate.negbin* simulate.polr*
L |
17,519 | Dealing with datasets with a variable number of features | You can treat these points as missing --- ie. let's assume that vector has at most 20 (x, y) pairs and particular point has 5 (x, y) pairs, in this case treat rest of pairs as missing, and then apply standatd procedures for missing parameters:
These standard procedures may be:
Use a model that handles missing parameters in natural way, for example decision tree models should be able to cope with that.
Replace missing with the mean value for appropriate column.
Use some easy model to 'predict' missing values.
But as @jonsca points --- if presence of absence of given point helps in classyfying the data you should for example build couple of models, each of them models instances with particular number of points. | Dealing with datasets with a variable number of features | You can treat these points as missing --- ie. let's assume that vector has at most 20 (x, y) pairs and particular point has 5 (x, y) pairs, in this case treat rest of pairs as missing, and then apply | Dealing with datasets with a variable number of features
You can treat these points as missing --- ie. let's assume that vector has at most 20 (x, y) pairs and particular point has 5 (x, y) pairs, in this case treat rest of pairs as missing, and then apply standatd procedures for missing parameters:
These standard procedures may be:
Use a model that handles missing parameters in natural way, for example decision tree models should be able to cope with that.
Replace missing with the mean value for appropriate column.
Use some easy model to 'predict' missing values.
But as @jonsca points --- if presence of absence of given point helps in classyfying the data you should for example build couple of models, each of them models instances with particular number of points. | Dealing with datasets with a variable number of features
You can treat these points as missing --- ie. let's assume that vector has at most 20 (x, y) pairs and particular point has 5 (x, y) pairs, in this case treat rest of pairs as missing, and then apply |
17,520 | Dealing with datasets with a variable number of features | From how I understand your question, the points in the data are interchangeable and don't come with any ordering, i.e. you have a set of points for each example.
This setting is different from the "Missing Value" setting that jb. described.
I know about two commonly used methods for this problem, which are actually based on your ideas. A good baseline would probably be to just average all points within one example, but that usually doesn't work well.
To aggregate multiple points to a single feature, bag of words (or bag of feature) representations are quite commonly used, for example in computer vision. The idea is to cluster all points in your training set (using for example k-means) and then describe each point by its cluster. For each example you then get a histogram over which clusters occur how often.
To use all pairs of points, you can make use of set kernels. This might work best with using SVMs but will probably also work with any learning algorithm that can be kernelized or make use of a compatibility function between inputs. Set kernels are basically a way to compute the similarity of two sets of features, as in your setting. | Dealing with datasets with a variable number of features | From how I understand your question, the points in the data are interchangeable and don't come with any ordering, i.e. you have a set of points for each example.
This setting is different from the "Mi | Dealing with datasets with a variable number of features
From how I understand your question, the points in the data are interchangeable and don't come with any ordering, i.e. you have a set of points for each example.
This setting is different from the "Missing Value" setting that jb. described.
I know about two commonly used methods for this problem, which are actually based on your ideas. A good baseline would probably be to just average all points within one example, but that usually doesn't work well.
To aggregate multiple points to a single feature, bag of words (or bag of feature) representations are quite commonly used, for example in computer vision. The idea is to cluster all points in your training set (using for example k-means) and then describe each point by its cluster. For each example you then get a histogram over which clusters occur how often.
To use all pairs of points, you can make use of set kernels. This might work best with using SVMs but will probably also work with any learning algorithm that can be kernelized or make use of a compatibility function between inputs. Set kernels are basically a way to compute the similarity of two sets of features, as in your setting. | Dealing with datasets with a variable number of features
From how I understand your question, the points in the data are interchangeable and don't come with any ordering, i.e. you have a set of points for each example.
This setting is different from the "Mi |
17,521 | How should I organize my poster presentation? | I think one of the things people forget in presenting academic posters is that it is supposed to be a summary of your work, and generally speaking its role is not peer review, so although you might really want to win the poster prize, most poster viewers are more concerned with communication (as you are). Posters at academic conferences tend to be overinclusive and visually confused. Even well designed ones. I like plain backgrounds, understated fonts like myriad or gill, two to three of the same colors throughout the poster, and colour should communicate, not adorn. Colour should be concentrated in areas that then become a focus. And don't be bound by the grid, people like a little disruption. The best thing to do when designing is don't. Hope that's all abstract and useless enough for you. Best of luck. | How should I organize my poster presentation? | I think one of the things people forget in presenting academic posters is that it is supposed to be a summary of your work, and generally speaking its role is not peer review, so although you might re | How should I organize my poster presentation?
I think one of the things people forget in presenting academic posters is that it is supposed to be a summary of your work, and generally speaking its role is not peer review, so although you might really want to win the poster prize, most poster viewers are more concerned with communication (as you are). Posters at academic conferences tend to be overinclusive and visually confused. Even well designed ones. I like plain backgrounds, understated fonts like myriad or gill, two to three of the same colors throughout the poster, and colour should communicate, not adorn. Colour should be concentrated in areas that then become a focus. And don't be bound by the grid, people like a little disruption. The best thing to do when designing is don't. Hope that's all abstract and useless enough for you. Best of luck. | How should I organize my poster presentation?
I think one of the things people forget in presenting academic posters is that it is supposed to be a summary of your work, and generally speaking its role is not peer review, so although you might re |
17,522 | How should I organize my poster presentation? | A few thoughts:
If you're standing by your poster, figures should be big enough that you can point to them without your fingers obscuring the picture.
Your poster is a presentation not a paper. Like a PowerPoint presentation, it should cover the highlights, provide fodder for discussion, and a context in which to place your research. What it should not be is a several foot wide copy of your manuscript.
I too am a fan of simple design. A neutral background (or white), simple fonts and clean, crisp figures.
"Too much text" - when your audience starts reading several paragraphs, or this starts read like a paper and not a simple narrative description, you've gone too far.
Keep it to a small number of main figures/tables. I generally try to limit myself to no more than four. These should be memorable depiction's of your research and jumping off points for discussion. Make them count.
Consider having printed 8.5x11 copies of your poster, and absolutely bring business cards. | How should I organize my poster presentation? | A few thoughts:
If you're standing by your poster, figures should be big enough that you can point to them without your fingers obscuring the picture.
Your poster is a presentation not a paper. Like | How should I organize my poster presentation?
A few thoughts:
If you're standing by your poster, figures should be big enough that you can point to them without your fingers obscuring the picture.
Your poster is a presentation not a paper. Like a PowerPoint presentation, it should cover the highlights, provide fodder for discussion, and a context in which to place your research. What it should not be is a several foot wide copy of your manuscript.
I too am a fan of simple design. A neutral background (or white), simple fonts and clean, crisp figures.
"Too much text" - when your audience starts reading several paragraphs, or this starts read like a paper and not a simple narrative description, you've gone too far.
Keep it to a small number of main figures/tables. I generally try to limit myself to no more than four. These should be memorable depiction's of your research and jumping off points for discussion. Make them count.
Consider having printed 8.5x11 copies of your poster, and absolutely bring business cards. | How should I organize my poster presentation?
A few thoughts:
If you're standing by your poster, figures should be big enough that you can point to them without your fingers obscuring the picture.
Your poster is a presentation not a paper. Like |
17,523 | Can someone shed light on linear vs. nonlinear mixed-effects? | There are several distinctions between linear and nonlinear regression models, but the primary mathematical one is that linear models are linear in the parameters, whereas nonlinear models are nonlinear in the parameters. Pinheiro and Bates (2000, pp. 284-285), authors of the nlme R package, elegantly described the more substantive considerations in model selection:
When choosing a regression model to describe how a response variable varies with covariates, one always has the option of using models, such as polynomial models, that are linear in the parameters. By increasing the order of a polynomial model, one can get increasingly accurate approximations to the true, usually nonlinear, regression function, within the observed range of the data. These empirical models are based only on the observed relationship between the response and the covariates and do not include any theoretical considerations about the underlying mechanism producing the data.
Nonlinear models, on the other hand, are often mechanistic, i.e., based on a model for the mechanism producing the response. As a consequence, the model parameters in a nonlinear model generally have a natural physical interpretation. Even when derived empirically, nonlinear models usually incorporate known, theoretical characteristics of the data, such as asymptotes and monotonicity, and in these cases, can be considered as semi-mechanistic models. A nonlinear model generally uses fewer parameters than a competitor linear model, such as a polynomial, giving a more parsimonious description of the data. Nonlinear models also provide more reliable predictions for the response variable outside the observed range of the data than, say, polynomial models would.
There are also some big differences between the nlme and lme4 packages that go beyond the linearity issue. For example, using nlme you can fit linear or nonlinear models and, for either type, specify the variance and correlation structures for within-group errors (e.g., autoregressive); lme4 can't do that. In addition, random effects can be fixed or crossed in either package, but it's much easier (and more computationally efficient) to specify and model crossed random effects in lme4.
I would advise first considering a) whether you will need a nonlinear model, and b) whether you will need to specify either the within-group variance or correlation structures. If any of these answers is yes, then you have to use nlme (given that you're sticking with R). If you work a lot with linear models that have crossed random effects, or complicated combinations of nested and crossed random effects, then lme4 is probably a better choice. You may need to learn to use both packages. I learned lme4 first and then realized I had to use nlme because I almost always work with autoregressive error structures. However, I still prefer lme4 when I analyze data from experiments with crossed factors. The good news is that a great deal of what I learned about lme4 transferred well to nlme. Either way, Pinheiro and Bates (2000) is a great reference for mixed-effects models, and I'd say it's indispensable if you're using nlme.
References
Pinheiro, J.C., & Bates, D.M. (2000). Mixed-effects models in S and S-PLUS. New York: Springer-Verlag. | Can someone shed light on linear vs. nonlinear mixed-effects? | There are several distinctions between linear and nonlinear regression models, but the primary mathematical one is that linear models are linear in the parameters, whereas nonlinear models are nonline | Can someone shed light on linear vs. nonlinear mixed-effects?
There are several distinctions between linear and nonlinear regression models, but the primary mathematical one is that linear models are linear in the parameters, whereas nonlinear models are nonlinear in the parameters. Pinheiro and Bates (2000, pp. 284-285), authors of the nlme R package, elegantly described the more substantive considerations in model selection:
When choosing a regression model to describe how a response variable varies with covariates, one always has the option of using models, such as polynomial models, that are linear in the parameters. By increasing the order of a polynomial model, one can get increasingly accurate approximations to the true, usually nonlinear, regression function, within the observed range of the data. These empirical models are based only on the observed relationship between the response and the covariates and do not include any theoretical considerations about the underlying mechanism producing the data.
Nonlinear models, on the other hand, are often mechanistic, i.e., based on a model for the mechanism producing the response. As a consequence, the model parameters in a nonlinear model generally have a natural physical interpretation. Even when derived empirically, nonlinear models usually incorporate known, theoretical characteristics of the data, such as asymptotes and monotonicity, and in these cases, can be considered as semi-mechanistic models. A nonlinear model generally uses fewer parameters than a competitor linear model, such as a polynomial, giving a more parsimonious description of the data. Nonlinear models also provide more reliable predictions for the response variable outside the observed range of the data than, say, polynomial models would.
There are also some big differences between the nlme and lme4 packages that go beyond the linearity issue. For example, using nlme you can fit linear or nonlinear models and, for either type, specify the variance and correlation structures for within-group errors (e.g., autoregressive); lme4 can't do that. In addition, random effects can be fixed or crossed in either package, but it's much easier (and more computationally efficient) to specify and model crossed random effects in lme4.
I would advise first considering a) whether you will need a nonlinear model, and b) whether you will need to specify either the within-group variance or correlation structures. If any of these answers is yes, then you have to use nlme (given that you're sticking with R). If you work a lot with linear models that have crossed random effects, or complicated combinations of nested and crossed random effects, then lme4 is probably a better choice. You may need to learn to use both packages. I learned lme4 first and then realized I had to use nlme because I almost always work with autoregressive error structures. However, I still prefer lme4 when I analyze data from experiments with crossed factors. The good news is that a great deal of what I learned about lme4 transferred well to nlme. Either way, Pinheiro and Bates (2000) is a great reference for mixed-effects models, and I'd say it's indispensable if you're using nlme.
References
Pinheiro, J.C., & Bates, D.M. (2000). Mixed-effects models in S and S-PLUS. New York: Springer-Verlag. | Can someone shed light on linear vs. nonlinear mixed-effects?
There are several distinctions between linear and nonlinear regression models, but the primary mathematical one is that linear models are linear in the parameters, whereas nonlinear models are nonline |
17,524 | Can someone shed light on linear vs. nonlinear mixed-effects? | For the linear-nonlinear part, see: CrossValidated article on the topic, particularly the second-ranked answer by Charlie. I don't think there are any changes when dealing with mixed effects. | Can someone shed light on linear vs. nonlinear mixed-effects? | For the linear-nonlinear part, see: CrossValidated article on the topic, particularly the second-ranked answer by Charlie. I don't think there are any changes when dealing with mixed effects. | Can someone shed light on linear vs. nonlinear mixed-effects?
For the linear-nonlinear part, see: CrossValidated article on the topic, particularly the second-ranked answer by Charlie. I don't think there are any changes when dealing with mixed effects. | Can someone shed light on linear vs. nonlinear mixed-effects?
For the linear-nonlinear part, see: CrossValidated article on the topic, particularly the second-ranked answer by Charlie. I don't think there are any changes when dealing with mixed effects. |
17,525 | Why do Excel and WolframAlpha give different values for skewness | They are using different methods to compute the skew. Searching in the help pages for skewness() within the R package e1071 yields:
Joanes and Gill (1998) discuss three methods for estimating skewness:
Type 1:
g_1 = m_3 / m_2^(3/2). This is the typical definition used in many older textbooks.
Type 2:
G_1 = g_1 * sqrt(n(n-1)) / (n-2). Used in SAS and SPSS.
Type 3:
b_1 = m_3 / s^3 = g_1 ((n-1)/n)^(3/2). Used in MINITAB and BMDP.
All three skewness measures are unbiased under normality.
#Why are these numbers different?
> skewness(c(222,1122,45444), type = 2)
[1] 1.729690
> skewness(c(222,1122,45444), type = 1)
[1] 0.7061429
Here's a link to the paper referenced if someone has the credentials to get it for further discussion or education: http://onlinelibrary.wiley.com/doi/10.1111/1467-9884.00122/abstract | Why do Excel and WolframAlpha give different values for skewness | They are using different methods to compute the skew. Searching in the help pages for skewness() within the R package e1071 yields:
Joanes and Gill (1998) discuss three methods for estimating skewness | Why do Excel and WolframAlpha give different values for skewness
They are using different methods to compute the skew. Searching in the help pages for skewness() within the R package e1071 yields:
Joanes and Gill (1998) discuss three methods for estimating skewness:
Type 1:
g_1 = m_3 / m_2^(3/2). This is the typical definition used in many older textbooks.
Type 2:
G_1 = g_1 * sqrt(n(n-1)) / (n-2). Used in SAS and SPSS.
Type 3:
b_1 = m_3 / s^3 = g_1 ((n-1)/n)^(3/2). Used in MINITAB and BMDP.
All three skewness measures are unbiased under normality.
#Why are these numbers different?
> skewness(c(222,1122,45444), type = 2)
[1] 1.729690
> skewness(c(222,1122,45444), type = 1)
[1] 0.7061429
Here's a link to the paper referenced if someone has the credentials to get it for further discussion or education: http://onlinelibrary.wiley.com/doi/10.1111/1467-9884.00122/abstract | Why do Excel and WolframAlpha give different values for skewness
They are using different methods to compute the skew. Searching in the help pages for skewness() within the R package e1071 yields:
Joanes and Gill (1998) discuss three methods for estimating skewness |
17,526 | An Unexpected Expectation! | Simons' counterexample considers random variables that don't have finite marginal expectations. If you sum 3 (or more) random variables that have finite marginal expectations, then the expectation of their sum equals the sum of their expectations. So to say "this is not true for three random variables" is not quite right.
Based on a comment from the OP, the content below is edited from my original response.
What I interpret Simons to be claiming is that if $E[X+Y]^+$ or $E[X+Y]^-$ is finite, then to calculate $E[X+Y]$ you do not need to know or assume anything about how $X$ and $Y$ are jointly distributed. Rather, you only need to know about marginal distributions. But, he says, this doesn't extend to the case of three or more variables. In other words, the finitude of $E[X+Y+Z]^+$ or $E[X+Y+Z]^-$ does not imply that one can calculate $E[X+Y+Z]$ using only knowledge of the marginal distributions of $X$, $Y$, and $Z$. He gives a counterexample to demonstrate this point.
The result only seems to contradict the usual thing we teach ("expectations are additive") because we are implicitly assuming that the marginal expectations are finite. Simons is allowing for non-finite marginal expectations.
When Simon writes We have no explanations why the theorem given above should hold for two variables but fail for three, I understand this to be him saying that he does have a good intuitive explanation for why this mathematical result - which he has shown rigorously - holds. | An Unexpected Expectation! | Simons' counterexample considers random variables that don't have finite marginal expectations. If you sum 3 (or more) random variables that have finite marginal expectations, then the expectation of | An Unexpected Expectation!
Simons' counterexample considers random variables that don't have finite marginal expectations. If you sum 3 (or more) random variables that have finite marginal expectations, then the expectation of their sum equals the sum of their expectations. So to say "this is not true for three random variables" is not quite right.
Based on a comment from the OP, the content below is edited from my original response.
What I interpret Simons to be claiming is that if $E[X+Y]^+$ or $E[X+Y]^-$ is finite, then to calculate $E[X+Y]$ you do not need to know or assume anything about how $X$ and $Y$ are jointly distributed. Rather, you only need to know about marginal distributions. But, he says, this doesn't extend to the case of three or more variables. In other words, the finitude of $E[X+Y+Z]^+$ or $E[X+Y+Z]^-$ does not imply that one can calculate $E[X+Y+Z]$ using only knowledge of the marginal distributions of $X$, $Y$, and $Z$. He gives a counterexample to demonstrate this point.
The result only seems to contradict the usual thing we teach ("expectations are additive") because we are implicitly assuming that the marginal expectations are finite. Simons is allowing for non-finite marginal expectations.
When Simon writes We have no explanations why the theorem given above should hold for two variables but fail for three, I understand this to be him saying that he does have a good intuitive explanation for why this mathematical result - which he has shown rigorously - holds. | An Unexpected Expectation!
Simons' counterexample considers random variables that don't have finite marginal expectations. If you sum 3 (or more) random variables that have finite marginal expectations, then the expectation of |
17,527 | Why does Covariance measure only Linear dependence? | A1) Say two variables X and Y are linearly dependent, then $X = \alpha Y + c$ for some $\alpha,c \in \mathbb{R}$.
A2) The formula for covariance is:
$$COV(X,Y) = E([X-E(X)][Y-E(Y)]) = E(XY)-E(X)E(Y)$$
From A1, consider some linear relationship $X = \alpha Y + c$, but all we have is the data from individual points in each variable. How do we get the value of $\alpha$? Well, it turns out we can instead ask the question, "how do we draw a line between these points so as to minimise the sum of squared differences between each point and the line?". And when we do this analysis for two variables, we get a closed form equation that looks like this:
$$\alpha = \dfrac{E(XY) -E(Y)E(X)}{E(X^2) - E(X)^2}$$
Please note that the numerator is the covariance. I.e.
$$ \alpha = \dfrac{COV(X,Y)}{E(X^2) - E(X)^2}$$
Correlation (e.g. Pearson) is often a measure of the covariance normalised against something to give it a comparable value. So you see the entire measure precedes from the analysis of how to fit a line to some data.
A3) Covariance doesn't measure non-linear relationships for the exact same reason it measures linear ones. Namely, that you can basically think of it as the slope in a linear equation (e.g. $X=\alpha Y + c$), so when you try and fit a line to a curve, the sum of square differences between the points and the line may be large. Here is a good diagram illustrating the implications. The numbers indicate Pearson's correlation coefficient, whilst the diagrams show the corresponding scatter plots. | Why does Covariance measure only Linear dependence? | A1) Say two variables X and Y are linearly dependent, then $X = \alpha Y + c$ for some $\alpha,c \in \mathbb{R}$.
A2) The formula for covariance is:
$$COV(X,Y) = E([X-E(X)][Y-E(Y)]) = E(XY)-E(X)E(Y)$$ | Why does Covariance measure only Linear dependence?
A1) Say two variables X and Y are linearly dependent, then $X = \alpha Y + c$ for some $\alpha,c \in \mathbb{R}$.
A2) The formula for covariance is:
$$COV(X,Y) = E([X-E(X)][Y-E(Y)]) = E(XY)-E(X)E(Y)$$
From A1, consider some linear relationship $X = \alpha Y + c$, but all we have is the data from individual points in each variable. How do we get the value of $\alpha$? Well, it turns out we can instead ask the question, "how do we draw a line between these points so as to minimise the sum of squared differences between each point and the line?". And when we do this analysis for two variables, we get a closed form equation that looks like this:
$$\alpha = \dfrac{E(XY) -E(Y)E(X)}{E(X^2) - E(X)^2}$$
Please note that the numerator is the covariance. I.e.
$$ \alpha = \dfrac{COV(X,Y)}{E(X^2) - E(X)^2}$$
Correlation (e.g. Pearson) is often a measure of the covariance normalised against something to give it a comparable value. So you see the entire measure precedes from the analysis of how to fit a line to some data.
A3) Covariance doesn't measure non-linear relationships for the exact same reason it measures linear ones. Namely, that you can basically think of it as the slope in a linear equation (e.g. $X=\alpha Y + c$), so when you try and fit a line to a curve, the sum of square differences between the points and the line may be large. Here is a good diagram illustrating the implications. The numbers indicate Pearson's correlation coefficient, whilst the diagrams show the corresponding scatter plots. | Why does Covariance measure only Linear dependence?
A1) Say two variables X and Y are linearly dependent, then $X = \alpha Y + c$ for some $\alpha,c \in \mathbb{R}$.
A2) The formula for covariance is:
$$COV(X,Y) = E([X-E(X)][Y-E(Y)]) = E(XY)-E(X)E(Y)$$ |
17,528 | Why does Covariance measure only Linear dependence? | Before moving to the interesting stuff, let's dispose of two of the questions. Covariance is too complicated for our purposes because it depends on three things: the magnitude of variable $X,$ the magnitude of variable $Y,$ and their correlation. (See the discussion at the end of https://stats.stackexchange.com/a/18200/919 for the details.)
The individual magnitudes tell us nothing about the relationship between the variables. Therefore we take them out of the picture by turning the covariance into the correlation: this is the quantity we need to pay attention to. Thus, questions (2) and (3) are meaningless because they are misguided: covariance does not measure linear dependence, nor does it tell us anything (by itself) about "non-linear" dependence.
Question (1) remains, though: what really is "linear dependence"?
This answer adduces five simple general principles (highlighted below) to identify a class of possible ways to quantify departures from linear dependence (between two variables $X$ and $Y$). Within that class, the correlation coefficient $\rho(X,Y)$ and its square $R^2$ emerge as being among the mathematically simplest choices.
In effect, I am proposing that the concept of "linear dependence" is deeply and inextricably associated with these five principles: to understand one is to understand the other.
It may be insightful to ground an answer in fundamental, widely general principles. How would we want to characterize "linear"? Let's hold that in abeyance and first consider the kinds of simplifications we might permit ourselves to make in such situations. I propose beginning with the concept of invariance to changes of units.
This means that
any relationship between two variables $X$ and $Y$ that is considered to have some degree of "linearity," no matter what that might be, must have exactly the same degree of linearity when these variables are expressed in other units.
For instance, if $X$ is a temperature and $Y$ is a mass, the linearity of their relationship ought to be the same no matter whether we express $X$ in degrees C, F, R, or K; and no matter whether we express $Y$ in g, Kg, lb, oz, metric tons, or whatever.
This form of invariance permits us freely to adopt initial "normalizations" of the variables. One possible normalization chooses units in which (a) the average of each variable is zero and (b) the variance of each variable is $1.$ In effect, this uses the standard deviation as a natural measure of the "size" of a variable: a metric. It's not the only possibility, but it's an extremely useful one (as suggested by the Central Limit Theorem: see my discussion at https://stats.stackexchange.com/a/3904/919).
At this point I can suggest two avenues of investigation. One is to view all variables as random variables and to analyze their joint distributions by means of the joint cumulant generating function (which always exists and provides full information about the distribution). After these preliminary normalizations, the c.g.f. (which is a function of two variables $(s,t)$) takes the form
$$\psi_{X,Y}(s,t) = -\frac{1}{2}t^2 - \frac{1}{2}s^2 - \kappa_{11} s t + o(|(s,t)|^2).$$
See, for instance, Stuart & Ord, Kendall's Advanced Theory of Statistics Vol. I (5th Ed.), sections 3.28 and 3.29. From this perspective, the first, simplest, and most dominant scalar indicator of any bivariate distribution is its standardized bivariate cumulant $\kappa_{11} = \operatorname{Cor}(X,Y)=\rho_{XY}$ (the correlation coefficient). We might then define the concept we are pursuing as
"linearity" of an association (between either random variables or data vectors) is the degree to which their bivariate distribution is well approximated by the terms in their c.g.f. through second order.
In particular, the Bivariate Normal distribution equals the foregoing expression, and therefore is the "most linear" of all possible distributions; consequently its "degree of linearity" must be solely a function of the correlation coefficient $\rho.$
However, to those not well accustomed to thinking (rather physically) in terms of moments and (rather abstractly) in terms of cumulants, this characterization might be of little help. Let's therefore return to the program at hand, of exploring where basic invariance principles might lead.
No matter whether your "variable" is a finite dataset or a random variable, it "lives" in a natural vector space (wherein variables may be rescaled and added to each other). Normalization places all variables on the unit sphere in this vector space. When two variables (before normalization) differ by an affine function (one is a scaled, shifted version of the other), then after normalization they will either coincide or be diametrically opposite points on this sphere. We may therefore conceive of the amount of nonlinearity as being some function of distances on this sphere.
A "nice" distance will vary smoothly. Such distances are given by Riemann metrics.. Although that tells us little in general, it has an interesting implication for "very nearly linear" relations: that is, when the distance between $X$ and $Y$ is small. A basic (and elementary) result of Riemannian geometry is that locally (that is, to a very good approximation for nearby points), the squared distance between $X$ and $Y,$ written $\delta(X,Y)^2,$ is a quadratic function of the vector difference $X-Y.$ When things are written out in coordinates with $X=(x_1,x_2,\ldots,x_n)$ and $Y=(y_1,y_2,\ldots,y_n),$ this means there exist numbers $g_{i}$ which may vary with $X$ for which
$$\delta(X,Y)^2 \approx \sum_{i=1}^n g_i(X) (x_i - y_i)^2.$$
There are many possible candidates for such a distance. But we may exploit another form of invariance. Because (in this context) "linear" refers to some general relationship holding among matched pairs of data, the order in which we list those pairs should not matter. Mathematically this means
the degree of linearity between $X$ and $Y$ must be the same when the components of $X$ and $Y$ are permuted (in parallel).
This implies all the $g_i(X)$ must be equal and permits us to drop the subscript "$i.$"
There remains one more almost trivial form of invariance it seems natural to demand of any linear relationship:
the degree of linearity between $X$ and $Y$ is the same as the degree of linearity between $Y$ and $X.$
Thus, $X$ is not privileged as the "base point" in the distance calculation, so we may equally well think of the Riemannian metric elements as varying with $Y:$
$$\delta(X,Y)^2 \approx \sum_{i=1}^n g(Y) (x_i - y_i)^2.$$
Now, because this is an approximation, it does not follow that $g(X) = g(Y).$ But it does indicate that $g$ itself ought to vary smoothly and slowly over the sphere.
Since everything is relative--we are discussing relative degrees of "linearity," not any absolute sense of it--we may rescale the function $g$ to make it equal $1/2$ at some point $X.$ Near this point, simple algebra (and our preliminary normalizations) show
$$\delta(X,Y)^2 \approx g(X) \sum_{i=1}^n (x_i-y_i)^2 = \frac{1}{2}\left[\sum_i x_i^2 + \sum_i y_i^2 - 2 \sum_i x_i y_i\right] = 1 - \rho_{XY}.$$
Generally, then, at least for "nearby" vectors $X$ and $Y,$ linearity must be measured as some multiple of $1-\rho_{XY}$ (where the multiple itself could depend on $X$). This often is called the "cosine distance" or "cosine similarity".
Obviously the simplest such multiple is the constant function $1,$ because it just disappears from the formula. But I wish to re-emphasize the point that this is not a unique solution: it's a convention. Maybe it could be useful in some applications to break it. This would amount to weighting $\delta$ according to some relevant pattern of variation among the components of the (standardized!) vectors $X$ and $Y.$ However, as a general proposition, any such weighting would appear arbitrary: it could be suitable only in particular circumstances. As such it doesn't seem to qualify as any part of the concept of linear dependence.
Finally, remember that this characterization of $\delta$ is appropriate only for "nearly linear" associations, where already $X\approx Y.$ It pays to remember that $\rho$ therefore is truly justified in characterizing "linear dependence" only in cases where that dependence is clear and strong--that is, $X$ and $Y$ approximate each other--and in all other cases, $\rho$ may be of little value. Be prepared for $\rho$ to fool you when the relationship between $X$ and $Y$ gets really complicated! Visit our posts on Anscombe's quartet for a well-known set of examples.
On the Riemannian sphere there will be points that get as far from $X$ as possible and, if our distance is any good, those points ought to be close to $-X,$ which is diametrically opposite (at a cosine distance of $1-(-1)=2.$ Because we want to view $X$ as being closely linearly related to vectors near $-X$ (as well as near $X$), we may invoke one more invariance principle:
The degree of linearity between $X$ and $Y$ must be the same as the degree of linearity between $X$ and $-Y.$
Since $\rho(X,-Y) = -\rho(X,Y),$ this last principle implies the degree of linearity--whatever it might mean or be--should be measured by some decreasing function of $|\rho(X,Y)|.$ This explains why $R^2(X,Y) = \rho(X,Y)^2$ is commonly compared to its maximum possible value of $1:$ we are really using $1-R^2$ as a measure of departure from linearity. Clearly this is one of the simplest possible formulas (and the presence of the square simplifies its mathematical analysis). | Why does Covariance measure only Linear dependence? | Before moving to the interesting stuff, let's dispose of two of the questions. Covariance is too complicated for our purposes because it depends on three things: the magnitude of variable $X,$ the mag | Why does Covariance measure only Linear dependence?
Before moving to the interesting stuff, let's dispose of two of the questions. Covariance is too complicated for our purposes because it depends on three things: the magnitude of variable $X,$ the magnitude of variable $Y,$ and their correlation. (See the discussion at the end of https://stats.stackexchange.com/a/18200/919 for the details.)
The individual magnitudes tell us nothing about the relationship between the variables. Therefore we take them out of the picture by turning the covariance into the correlation: this is the quantity we need to pay attention to. Thus, questions (2) and (3) are meaningless because they are misguided: covariance does not measure linear dependence, nor does it tell us anything (by itself) about "non-linear" dependence.
Question (1) remains, though: what really is "linear dependence"?
This answer adduces five simple general principles (highlighted below) to identify a class of possible ways to quantify departures from linear dependence (between two variables $X$ and $Y$). Within that class, the correlation coefficient $\rho(X,Y)$ and its square $R^2$ emerge as being among the mathematically simplest choices.
In effect, I am proposing that the concept of "linear dependence" is deeply and inextricably associated with these five principles: to understand one is to understand the other.
It may be insightful to ground an answer in fundamental, widely general principles. How would we want to characterize "linear"? Let's hold that in abeyance and first consider the kinds of simplifications we might permit ourselves to make in such situations. I propose beginning with the concept of invariance to changes of units.
This means that
any relationship between two variables $X$ and $Y$ that is considered to have some degree of "linearity," no matter what that might be, must have exactly the same degree of linearity when these variables are expressed in other units.
For instance, if $X$ is a temperature and $Y$ is a mass, the linearity of their relationship ought to be the same no matter whether we express $X$ in degrees C, F, R, or K; and no matter whether we express $Y$ in g, Kg, lb, oz, metric tons, or whatever.
This form of invariance permits us freely to adopt initial "normalizations" of the variables. One possible normalization chooses units in which (a) the average of each variable is zero and (b) the variance of each variable is $1.$ In effect, this uses the standard deviation as a natural measure of the "size" of a variable: a metric. It's not the only possibility, but it's an extremely useful one (as suggested by the Central Limit Theorem: see my discussion at https://stats.stackexchange.com/a/3904/919).
At this point I can suggest two avenues of investigation. One is to view all variables as random variables and to analyze their joint distributions by means of the joint cumulant generating function (which always exists and provides full information about the distribution). After these preliminary normalizations, the c.g.f. (which is a function of two variables $(s,t)$) takes the form
$$\psi_{X,Y}(s,t) = -\frac{1}{2}t^2 - \frac{1}{2}s^2 - \kappa_{11} s t + o(|(s,t)|^2).$$
See, for instance, Stuart & Ord, Kendall's Advanced Theory of Statistics Vol. I (5th Ed.), sections 3.28 and 3.29. From this perspective, the first, simplest, and most dominant scalar indicator of any bivariate distribution is its standardized bivariate cumulant $\kappa_{11} = \operatorname{Cor}(X,Y)=\rho_{XY}$ (the correlation coefficient). We might then define the concept we are pursuing as
"linearity" of an association (between either random variables or data vectors) is the degree to which their bivariate distribution is well approximated by the terms in their c.g.f. through second order.
In particular, the Bivariate Normal distribution equals the foregoing expression, and therefore is the "most linear" of all possible distributions; consequently its "degree of linearity" must be solely a function of the correlation coefficient $\rho.$
However, to those not well accustomed to thinking (rather physically) in terms of moments and (rather abstractly) in terms of cumulants, this characterization might be of little help. Let's therefore return to the program at hand, of exploring where basic invariance principles might lead.
No matter whether your "variable" is a finite dataset or a random variable, it "lives" in a natural vector space (wherein variables may be rescaled and added to each other). Normalization places all variables on the unit sphere in this vector space. When two variables (before normalization) differ by an affine function (one is a scaled, shifted version of the other), then after normalization they will either coincide or be diametrically opposite points on this sphere. We may therefore conceive of the amount of nonlinearity as being some function of distances on this sphere.
A "nice" distance will vary smoothly. Such distances are given by Riemann metrics.. Although that tells us little in general, it has an interesting implication for "very nearly linear" relations: that is, when the distance between $X$ and $Y$ is small. A basic (and elementary) result of Riemannian geometry is that locally (that is, to a very good approximation for nearby points), the squared distance between $X$ and $Y,$ written $\delta(X,Y)^2,$ is a quadratic function of the vector difference $X-Y.$ When things are written out in coordinates with $X=(x_1,x_2,\ldots,x_n)$ and $Y=(y_1,y_2,\ldots,y_n),$ this means there exist numbers $g_{i}$ which may vary with $X$ for which
$$\delta(X,Y)^2 \approx \sum_{i=1}^n g_i(X) (x_i - y_i)^2.$$
There are many possible candidates for such a distance. But we may exploit another form of invariance. Because (in this context) "linear" refers to some general relationship holding among matched pairs of data, the order in which we list those pairs should not matter. Mathematically this means
the degree of linearity between $X$ and $Y$ must be the same when the components of $X$ and $Y$ are permuted (in parallel).
This implies all the $g_i(X)$ must be equal and permits us to drop the subscript "$i.$"
There remains one more almost trivial form of invariance it seems natural to demand of any linear relationship:
the degree of linearity between $X$ and $Y$ is the same as the degree of linearity between $Y$ and $X.$
Thus, $X$ is not privileged as the "base point" in the distance calculation, so we may equally well think of the Riemannian metric elements as varying with $Y:$
$$\delta(X,Y)^2 \approx \sum_{i=1}^n g(Y) (x_i - y_i)^2.$$
Now, because this is an approximation, it does not follow that $g(X) = g(Y).$ But it does indicate that $g$ itself ought to vary smoothly and slowly over the sphere.
Since everything is relative--we are discussing relative degrees of "linearity," not any absolute sense of it--we may rescale the function $g$ to make it equal $1/2$ at some point $X.$ Near this point, simple algebra (and our preliminary normalizations) show
$$\delta(X,Y)^2 \approx g(X) \sum_{i=1}^n (x_i-y_i)^2 = \frac{1}{2}\left[\sum_i x_i^2 + \sum_i y_i^2 - 2 \sum_i x_i y_i\right] = 1 - \rho_{XY}.$$
Generally, then, at least for "nearby" vectors $X$ and $Y,$ linearity must be measured as some multiple of $1-\rho_{XY}$ (where the multiple itself could depend on $X$). This often is called the "cosine distance" or "cosine similarity".
Obviously the simplest such multiple is the constant function $1,$ because it just disappears from the formula. But I wish to re-emphasize the point that this is not a unique solution: it's a convention. Maybe it could be useful in some applications to break it. This would amount to weighting $\delta$ according to some relevant pattern of variation among the components of the (standardized!) vectors $X$ and $Y.$ However, as a general proposition, any such weighting would appear arbitrary: it could be suitable only in particular circumstances. As such it doesn't seem to qualify as any part of the concept of linear dependence.
Finally, remember that this characterization of $\delta$ is appropriate only for "nearly linear" associations, where already $X\approx Y.$ It pays to remember that $\rho$ therefore is truly justified in characterizing "linear dependence" only in cases where that dependence is clear and strong--that is, $X$ and $Y$ approximate each other--and in all other cases, $\rho$ may be of little value. Be prepared for $\rho$ to fool you when the relationship between $X$ and $Y$ gets really complicated! Visit our posts on Anscombe's quartet for a well-known set of examples.
On the Riemannian sphere there will be points that get as far from $X$ as possible and, if our distance is any good, those points ought to be close to $-X,$ which is diametrically opposite (at a cosine distance of $1-(-1)=2.$ Because we want to view $X$ as being closely linearly related to vectors near $-X$ (as well as near $X$), we may invoke one more invariance principle:
The degree of linearity between $X$ and $Y$ must be the same as the degree of linearity between $X$ and $-Y.$
Since $\rho(X,-Y) = -\rho(X,Y),$ this last principle implies the degree of linearity--whatever it might mean or be--should be measured by some decreasing function of $|\rho(X,Y)|.$ This explains why $R^2(X,Y) = \rho(X,Y)^2$ is commonly compared to its maximum possible value of $1:$ we are really using $1-R^2$ as a measure of departure from linearity. Clearly this is one of the simplest possible formulas (and the presence of the square simplifies its mathematical analysis). | Why does Covariance measure only Linear dependence?
Before moving to the interesting stuff, let's dispose of two of the questions. Covariance is too complicated for our purposes because it depends on three things: the magnitude of variable $X,$ the mag |
17,529 | Why does Covariance measure only Linear dependence? | Covariance only measures linear relationship and it classifies the slope of the linear relationship into one of three cases: 1)positive, 2)negative, 3) no trend.
If two random variables, X and Y, are not linearly correlated, we can still calculated their covariance. However, the result is not valid, meaning that we cannot explain a positive covariance as that bigger X are associated with bigger Y. Similarly, a negative covariance doesn't necessarily mean that bigger X are associated with smaller Y; nor can we say that if the covariance is 0, then there is no trend between X and Y.
Why is it? Think about this case: Y = X^2. There is a clear trend/pattern between the two variables, but if you calculate their covariance, it is 0. Here is how I got cov(X, Y) = 0: Take four data points from this graph that are symmetric, say (-2, 4), (-1, 1), (1, 1), and (2, 4). Then calculate the covariance using its formula, you get it equals to 0.
To summarize, if two variables doesn't show linear trends, then it is not valid to use covariance to characterize their relationship. That's why we say that covariance only measure linear relationships. | Why does Covariance measure only Linear dependence? | Covariance only measures linear relationship and it classifies the slope of the linear relationship into one of three cases: 1)positive, 2)negative, 3) no trend.
If two random variables, X and Y, are | Why does Covariance measure only Linear dependence?
Covariance only measures linear relationship and it classifies the slope of the linear relationship into one of three cases: 1)positive, 2)negative, 3) no trend.
If two random variables, X and Y, are not linearly correlated, we can still calculated their covariance. However, the result is not valid, meaning that we cannot explain a positive covariance as that bigger X are associated with bigger Y. Similarly, a negative covariance doesn't necessarily mean that bigger X are associated with smaller Y; nor can we say that if the covariance is 0, then there is no trend between X and Y.
Why is it? Think about this case: Y = X^2. There is a clear trend/pattern between the two variables, but if you calculate their covariance, it is 0. Here is how I got cov(X, Y) = 0: Take four data points from this graph that are symmetric, say (-2, 4), (-1, 1), (1, 1), and (2, 4). Then calculate the covariance using its formula, you get it equals to 0.
To summarize, if two variables doesn't show linear trends, then it is not valid to use covariance to characterize their relationship. That's why we say that covariance only measure linear relationships. | Why does Covariance measure only Linear dependence?
Covariance only measures linear relationship and it classifies the slope of the linear relationship into one of three cases: 1)positive, 2)negative, 3) no trend.
If two random variables, X and Y, are |
17,530 | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN) | Yann LeCun has compiled a big list of results (and the associated papers) on MNIST, which may be of interest.
The best non-convolutional neural net result is by Cireşan, Meier, Gambardella and Schmidhuber (2010) (arXiv), who reported an accuracy of 99.65%. As their abstract describes, their approach was essentially brute force:
Good old on-line back-propagation for plain multi-layer perceptrons
yields a very low 0.35% error rate on the famous MNIST handwritten
digits benchmark. All we need to achieve this best result so far are
many hidden layers, many neurons per layer, numerous deformed training
images, and graphics cards to greatly speed up learning.
The network itself was a six layer MLP with 2500, 2000, 1500, 1000, 500, and 10 neurons per layer, and the training set was augmented with affine and elastic deformations. The only other secret ingredient was a lot of compute--the last few pages describe how they parallelized it.
A year later, the same group (Meier et al., 2011) reported similar results using an ensemble of 25 one-layer neural networks (0.39% test error*). These were individually smaller (800 hidden units), but the training strategy is a bit fancier. Similar strategies with convnets do a little bit better (~0.23% test error*). Since they are universal approximations, I can't see why a suitable MLP wouldn't be able to match that though it might be very large and difficult to train.
* Annoyingly very few of these papers report confidence intervals, standard errors, or anything like that, making it difficult to directly compare these results. | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN) | Yann LeCun has compiled a big list of results (and the associated papers) on MNIST, which may be of interest.
The best non-convolutional neural net result is by Cireşan, Meier, Gambardella and Schmid | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN)
Yann LeCun has compiled a big list of results (and the associated papers) on MNIST, which may be of interest.
The best non-convolutional neural net result is by Cireşan, Meier, Gambardella and Schmidhuber (2010) (arXiv), who reported an accuracy of 99.65%. As their abstract describes, their approach was essentially brute force:
Good old on-line back-propagation for plain multi-layer perceptrons
yields a very low 0.35% error rate on the famous MNIST handwritten
digits benchmark. All we need to achieve this best result so far are
many hidden layers, many neurons per layer, numerous deformed training
images, and graphics cards to greatly speed up learning.
The network itself was a six layer MLP with 2500, 2000, 1500, 1000, 500, and 10 neurons per layer, and the training set was augmented with affine and elastic deformations. The only other secret ingredient was a lot of compute--the last few pages describe how they parallelized it.
A year later, the same group (Meier et al., 2011) reported similar results using an ensemble of 25 one-layer neural networks (0.39% test error*). These were individually smaller (800 hidden units), but the training strategy is a bit fancier. Similar strategies with convnets do a little bit better (~0.23% test error*). Since they are universal approximations, I can't see why a suitable MLP wouldn't be able to match that though it might be very large and difficult to train.
* Annoyingly very few of these papers report confidence intervals, standard errors, or anything like that, making it difficult to directly compare these results. | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN)
Yann LeCun has compiled a big list of results (and the associated papers) on MNIST, which may be of interest.
The best non-convolutional neural net result is by Cireşan, Meier, Gambardella and Schmid |
17,531 | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN) | Since it is possible to format a CNN as an MLP the best we could possibly do with an MLP is the same as the we could possibly do with a CNN. To see this, take a trained CNN and copy it's weights once for each input pixel (and channel if using multiple channels). Repeat this process with subsequent layers. Now we have an MLP that is equivalent to the CNN. | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN) | Since it is possible to format a CNN as an MLP the best we could possibly do with an MLP is the same as the we could possibly do with a CNN. To see this, take a trained CNN and copy it's weights once | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN)
Since it is possible to format a CNN as an MLP the best we could possibly do with an MLP is the same as the we could possibly do with a CNN. To see this, take a trained CNN and copy it's weights once for each input pixel (and channel if using multiple channels). Repeat this process with subsequent layers. Now we have an MLP that is equivalent to the CNN. | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN)
Since it is possible to format a CNN as an MLP the best we could possibly do with an MLP is the same as the we could possibly do with a CNN. To see this, take a trained CNN and copy it's weights once |
17,532 | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN) | I am receiving 97.47 % & 98.35 % without convolutions and 99.43 % with convolutions (wide network). I wrote my own DNN trainer using C++ OpenCL (https://github.com/pepe78/WideOpenThoughts) or if you prefer CUDA (https://github.com/pepe78/DeeperThought/). This means you can achieve higher accuracy without convolutions than ~96.2% accuracy.
Also, you can use linear regression & convolutions to achieve ~99.5 % 'Linear Regression on a Set of Selected Templates from a Pool of Randomly Generated Templates' (https://www.researchgate.net/publication/336933653_Linear_Regression_on_a_Set_of_Selected_Templates_from_a_Pool_of_Randomly_Generated_Templates).
All of these are done without any pre-processing of training data (deforming input training images).
Update 2021/10/12: this publication is now accepted and can be found here:
https://www.sciencedirect.com/science/article/pii/S2666827021000633 | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN) | I am receiving 97.47 % & 98.35 % without convolutions and 99.43 % with convolutions (wide network). I wrote my own DNN trainer using C++ OpenCL (https://github.com/pepe78/WideOpenThoughts) or if you p | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN)
I am receiving 97.47 % & 98.35 % without convolutions and 99.43 % with convolutions (wide network). I wrote my own DNN trainer using C++ OpenCL (https://github.com/pepe78/WideOpenThoughts) or if you prefer CUDA (https://github.com/pepe78/DeeperThought/). This means you can achieve higher accuracy without convolutions than ~96.2% accuracy.
Also, you can use linear regression & convolutions to achieve ~99.5 % 'Linear Regression on a Set of Selected Templates from a Pool of Randomly Generated Templates' (https://www.researchgate.net/publication/336933653_Linear_Regression_on_a_Set_of_Selected_Templates_from_a_Pool_of_Randomly_Generated_Templates).
All of these are done without any pre-processing of training data (deforming input training images).
Update 2021/10/12: this publication is now accepted and can be found here:
https://www.sciencedirect.com/science/article/pii/S2666827021000633 | MNIST digit recognition: what is the best we can get with a fully connected NN only? (no CNN)
I am receiving 97.47 % & 98.35 % without convolutions and 99.43 % with convolutions (wide network). I wrote my own DNN trainer using C++ OpenCL (https://github.com/pepe78/WideOpenThoughts) or if you p |
17,533 | Is there a multivariate two-sample Kolmogorov–Smirnov test? | A 2004 article On a new multivariate two-sample test by Baringhaus and Franz maybe helpful, they provided a brief literature review on the two-sample multivariate GoF tests and then a R package cramer. As the package name suggested their method is related to Cramer's test, a predecessor of Cramer-von Mises.
For one-sample problem Justel et al. developed a generalization of Kolmogorov-Smirnov test. In general it seems the difficulty in multivariate case rooted from extending the definition of EDF (empirical distribution function), so methods based on other measures are worth exploring, e.g. multivariate tests based on ECF (empirical characteristic function) by Fan. | Is there a multivariate two-sample Kolmogorov–Smirnov test? | A 2004 article On a new multivariate two-sample test by Baringhaus and Franz maybe helpful, they provided a brief literature review on the two-sample multivariate GoF tests and then a R package cramer | Is there a multivariate two-sample Kolmogorov–Smirnov test?
A 2004 article On a new multivariate two-sample test by Baringhaus and Franz maybe helpful, they provided a brief literature review on the two-sample multivariate GoF tests and then a R package cramer. As the package name suggested their method is related to Cramer's test, a predecessor of Cramer-von Mises.
For one-sample problem Justel et al. developed a generalization of Kolmogorov-Smirnov test. In general it seems the difficulty in multivariate case rooted from extending the definition of EDF (empirical distribution function), so methods based on other measures are worth exploring, e.g. multivariate tests based on ECF (empirical characteristic function) by Fan. | Is there a multivariate two-sample Kolmogorov–Smirnov test?
A 2004 article On a new multivariate two-sample test by Baringhaus and Franz maybe helpful, they provided a brief literature review on the two-sample multivariate GoF tests and then a R package cramer |
17,534 | Is there a multivariate two-sample Kolmogorov–Smirnov test? | Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Yes, the two sample KS test was extended to the multivariate case in 2021. https://www.sciencedirect.com/science/article/pii/S016771522100050X | Is there a multivariate two-sample Kolmogorov–Smirnov test? | Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
| Is there a multivariate two-sample Kolmogorov–Smirnov test?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Yes, the two sample KS test was extended to the multivariate case in 2021. https://www.sciencedirect.com/science/article/pii/S016771522100050X | Is there a multivariate two-sample Kolmogorov–Smirnov test?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
17,535 | Is deep learning useful for combinatorial optimization? | Yep, there's a paper Pointer Networks that tries to use deep learning to solve convex hull, Delaunay triangulation and TSP, the result looks promising, or at least it can be used as a good starting point for optimization algorithms. | Is deep learning useful for combinatorial optimization? | Yep, there's a paper Pointer Networks that tries to use deep learning to solve convex hull, Delaunay triangulation and TSP, the result looks promising, or at least it can be used as a good starting po | Is deep learning useful for combinatorial optimization?
Yep, there's a paper Pointer Networks that tries to use deep learning to solve convex hull, Delaunay triangulation and TSP, the result looks promising, or at least it can be used as a good starting point for optimization algorithms. | Is deep learning useful for combinatorial optimization?
Yep, there's a paper Pointer Networks that tries to use deep learning to solve convex hull, Delaunay triangulation and TSP, the result looks promising, or at least it can be used as a good starting po |
17,536 | Is deep learning useful for combinatorial optimization? | Machine learning can be used in the branch and bound algorithm to
Select a branching variable (Khalil, Elias Boutros, et al. "Learning to branch in mixed integer programming." Thirtieth AAAI Conference on Artificial Intelligence. 2016.)
Decide whether or not to run a primal heuristic at a node (Khalil, Elias B., et al. "Learning to Run Heuristics in Tree Search." IJCAI. 2017.)
Reinforcement learning can be used to
Learn a better criterion for greedy solution construction over a graph distribution (Khalil, Elias, et al. "Learning combinatorial optimization algorithms over graphs." Advances in Neural Information Processing Systems. 2017.)
Check Bistra Dilkina's (who seems to pioneered this approach) talk at USC ISI AI seminar. | Is deep learning useful for combinatorial optimization? | Machine learning can be used in the branch and bound algorithm to
Select a branching variable (Khalil, Elias Boutros, et al. "Learning to branch in mixed integer programming." Thirtieth AAAI Conferen | Is deep learning useful for combinatorial optimization?
Machine learning can be used in the branch and bound algorithm to
Select a branching variable (Khalil, Elias Boutros, et al. "Learning to branch in mixed integer programming." Thirtieth AAAI Conference on Artificial Intelligence. 2016.)
Decide whether or not to run a primal heuristic at a node (Khalil, Elias B., et al. "Learning to Run Heuristics in Tree Search." IJCAI. 2017.)
Reinforcement learning can be used to
Learn a better criterion for greedy solution construction over a graph distribution (Khalil, Elias, et al. "Learning combinatorial optimization algorithms over graphs." Advances in Neural Information Processing Systems. 2017.)
Check Bistra Dilkina's (who seems to pioneered this approach) talk at USC ISI AI seminar. | Is deep learning useful for combinatorial optimization?
Machine learning can be used in the branch and bound algorithm to
Select a branching variable (Khalil, Elias Boutros, et al. "Learning to branch in mixed integer programming." Thirtieth AAAI Conferen |
17,537 | How does k-fold cross validation fit in the context of training/validation/testing sets? | Cross-validation usually helps to avoid the need of a validation set.
The basic idea with training/validation/test data sets is as follows:
Training: You try out different types of models with different choices of hyperparameters on the training data (e.g. linear model with different selection of features, neural net with different choices of layers, random forest with different values of mtry).
Validation: You compare the performance of the models in Step 1 based on the validation set and select the winner. This helps to avoid wrong decisions taken by overfitting the training data set.
Test: You try out the winner model on the test data just to get a feeling how good it performs in reality. This unravels overfitting introduced in Step 2. Here, you would not take any further decision. It is just plain information.
Now, in the case where you replace the validation step by cross-validation, the attack on the data is done almost identically, but you only have a training and a test data set. There is no need for a validation data set.
Training: See above.
Validation: You do cross-validation on the training data to choose the best model of Step 1 with respect to cross-validation performance (here, the original training data is repeatedly split into a temporary training and validation set). The models calculated in cross-validation are only used for choosing the best model of Step 1, which are all computed on the full training set.
Test: See above. | How does k-fold cross validation fit in the context of training/validation/testing sets? | Cross-validation usually helps to avoid the need of a validation set.
The basic idea with training/validation/test data sets is as follows:
Training: You try out different types of models with differ | How does k-fold cross validation fit in the context of training/validation/testing sets?
Cross-validation usually helps to avoid the need of a validation set.
The basic idea with training/validation/test data sets is as follows:
Training: You try out different types of models with different choices of hyperparameters on the training data (e.g. linear model with different selection of features, neural net with different choices of layers, random forest with different values of mtry).
Validation: You compare the performance of the models in Step 1 based on the validation set and select the winner. This helps to avoid wrong decisions taken by overfitting the training data set.
Test: You try out the winner model on the test data just to get a feeling how good it performs in reality. This unravels overfitting introduced in Step 2. Here, you would not take any further decision. It is just plain information.
Now, in the case where you replace the validation step by cross-validation, the attack on the data is done almost identically, but you only have a training and a test data set. There is no need for a validation data set.
Training: See above.
Validation: You do cross-validation on the training data to choose the best model of Step 1 with respect to cross-validation performance (here, the original training data is repeatedly split into a temporary training and validation set). The models calculated in cross-validation are only used for choosing the best model of Step 1, which are all computed on the full training set.
Test: See above. | How does k-fold cross validation fit in the context of training/validation/testing sets?
Cross-validation usually helps to avoid the need of a validation set.
The basic idea with training/validation/test data sets is as follows:
Training: You try out different types of models with differ |
17,538 | How does k-fold cross validation fit in the context of training/validation/testing sets? | $K$-fold cross validation is a (re)sampling strategy like many others.
Splitting into training/validation/testing is also a sampling strategy.
You can substitute the training/validation for another sampling strategy. Then you would perform $K$-fold CV on 80% of the data and test on the remaining 20%.
You can also apply it to the testing part (this is what people call nested cross validation), where $K-1$ folds are used to training/validation and the remainder one to test, then you iterate this over folds. | How does k-fold cross validation fit in the context of training/validation/testing sets? | $K$-fold cross validation is a (re)sampling strategy like many others.
Splitting into training/validation/testing is also a sampling strategy.
You can substitute the training/validation for another sa | How does k-fold cross validation fit in the context of training/validation/testing sets?
$K$-fold cross validation is a (re)sampling strategy like many others.
Splitting into training/validation/testing is also a sampling strategy.
You can substitute the training/validation for another sampling strategy. Then you would perform $K$-fold CV on 80% of the data and test on the remaining 20%.
You can also apply it to the testing part (this is what people call nested cross validation), where $K-1$ folds are used to training/validation and the remainder one to test, then you iterate this over folds. | How does k-fold cross validation fit in the context of training/validation/testing sets?
$K$-fold cross validation is a (re)sampling strategy like many others.
Splitting into training/validation/testing is also a sampling strategy.
You can substitute the training/validation for another sa |
17,539 | Sampling from an Improper Distribution (using MCMC and otherwise) | Sampling from an improper posterior (density) $f$ does not make sense from a probabilistic/theoretical point of view. The reason for this is that the function $f$ does not have a finite integral over the parameter space and, consequently, cannot be linked to a (finite measure) probability model $(\Omega,\sigma,{\mathbb P})$ (space, sigma-algebra, probability measure).
If you have a model with an improper prior that leads to an improper posterior, in many cases you can still sample from it using MCMC, for instance Metropolis-Hastings, and the "posterior samples" may look reasonable. This looks intriguing and paradoxical at first glance. However, the reason for this is that MCMC methods are restricted to numerical limitations of the computers in practice, and therefore, all supports are bounded (and discrete!) for a computer. Then, under those restrictions (boundedness and discreteness) the posterior is actually proper in most cases.
There is a great reference by Hobert and Casella that presents an example (of a slightly different nature) where you can construct a Gibbs sampler for a posterior, the posterior samples look perfectly reasonable, but the posterior is improper!
http://www.jstor.org/stable/2291572
A similar example has recently appeared here. In fact, Hobert and Casella warns the reader that MCMC methods cannot be used to detect impropriety of the posterior and that this has to be checked separately before implementing any MCMC methods.
In summary:
Some MCMC samplers, such as Metropolis-Hastings, can (but shouldn't) be used to sample from an improper posterior since the computer bounds and dicretizes the parameter space. Only if you have huge samples, you may be able to observe some strange things. How well you can detect these issues also depends on the "instrumental" distribution employed in your sampler. The latter point requires a more extensive discussion, so I prefer to leave it here.
(Hobert and Casella). The fact that you can construct a Gibbs sampler (conditional model) for a model with an improper prior does not imply that the posterior (joint model) is proper.
A formal probabilistic interpretation of the posterior samples require the propriety of the posterior. Convergence results and proofs are established only for proper probability distributions/measures.
P.S. (a bit tongue in cheek): Do not always believe what people do in Machine Learning. As Prof. Brian Ripley said: "machine learning is statistics minus any checking of models and assumptions". | Sampling from an Improper Distribution (using MCMC and otherwise) | Sampling from an improper posterior (density) $f$ does not make sense from a probabilistic/theoretical point of view. The reason for this is that the function $f$ does not have a finite integral over | Sampling from an Improper Distribution (using MCMC and otherwise)
Sampling from an improper posterior (density) $f$ does not make sense from a probabilistic/theoretical point of view. The reason for this is that the function $f$ does not have a finite integral over the parameter space and, consequently, cannot be linked to a (finite measure) probability model $(\Omega,\sigma,{\mathbb P})$ (space, sigma-algebra, probability measure).
If you have a model with an improper prior that leads to an improper posterior, in many cases you can still sample from it using MCMC, for instance Metropolis-Hastings, and the "posterior samples" may look reasonable. This looks intriguing and paradoxical at first glance. However, the reason for this is that MCMC methods are restricted to numerical limitations of the computers in practice, and therefore, all supports are bounded (and discrete!) for a computer. Then, under those restrictions (boundedness and discreteness) the posterior is actually proper in most cases.
There is a great reference by Hobert and Casella that presents an example (of a slightly different nature) where you can construct a Gibbs sampler for a posterior, the posterior samples look perfectly reasonable, but the posterior is improper!
http://www.jstor.org/stable/2291572
A similar example has recently appeared here. In fact, Hobert and Casella warns the reader that MCMC methods cannot be used to detect impropriety of the posterior and that this has to be checked separately before implementing any MCMC methods.
In summary:
Some MCMC samplers, such as Metropolis-Hastings, can (but shouldn't) be used to sample from an improper posterior since the computer bounds and dicretizes the parameter space. Only if you have huge samples, you may be able to observe some strange things. How well you can detect these issues also depends on the "instrumental" distribution employed in your sampler. The latter point requires a more extensive discussion, so I prefer to leave it here.
(Hobert and Casella). The fact that you can construct a Gibbs sampler (conditional model) for a model with an improper prior does not imply that the posterior (joint model) is proper.
A formal probabilistic interpretation of the posterior samples require the propriety of the posterior. Convergence results and proofs are established only for proper probability distributions/measures.
P.S. (a bit tongue in cheek): Do not always believe what people do in Machine Learning. As Prof. Brian Ripley said: "machine learning is statistics minus any checking of models and assumptions". | Sampling from an Improper Distribution (using MCMC and otherwise)
Sampling from an improper posterior (density) $f$ does not make sense from a probabilistic/theoretical point of view. The reason for this is that the function $f$ does not have a finite integral over |
17,540 | Sampling from an Improper Distribution (using MCMC and otherwise) | Giving an alternative, more applied, view from Rod's excellent answer above -
In many, if not most, cases, impropriety of the posterior is a result of choices made for convenience, not a true "I'm absolutely certain of my likelihood function and prior distribution, and look what happened!" effect. Given this, we shouldn't take impropriety too seriously in our applied work unless it's going to mess up our computations. As someone famous (Huber? Tukey?) once observed, in a different context, the difference between a standard Cauchy and a Cauchy truncated at $+/- 10^{100}$ is undetectable, but one has no moments and the other has moments of all orders.
In this context, if I have a posterior distribution for demand for hot dogs at AT&T Park next weekend with upper tail proportional to $1/x$, that's bad news for algorithms that calculate expected values, but if I truncate it at the estimated number of people in San Francisco, a number somewhat larger than the number of hot dogs that will in fact be sold at AT&T park next weekend, all is well, at least in terms of existence of moments. In the latter case, you can think of it as a sort of two-stage application of the real prior - one I use for calculation, which doesn't have an upper bound, and the "extra feature" of it where it's equal to zero above the population of San Francisco...", with the "extra feature" being applied in a step subsequent to the generation of the sample. The real prior is not the one that's used in the MCMC computation (in my example.)
So in principle I would be quite OK with using an MCMC-generated sample from an improper distribution in applied work, but I'd be paying a lot of attention to how that impropriety came about, and how the random sample will be affected by it. Ideally, the random sample wouldn't be affected by it, as in my hot-dog example, where in a reasonable world you'd never actually generate a random number greater than the number of people in San Francisco...
You should also be aware of the fact that your results may be quite sensitive to the feature of the posterior that caused it to be improper, even if you do truncate it at some large number later on (or whatever alteration is appropriate for your model.) You'd like your results to be robust to slight changes that shift your posterior from improper to proper. This can be harder to ensure, but is all part of the larger problem of making sure your results are robust to your assumptions, especially the ones which are made for convenience. | Sampling from an Improper Distribution (using MCMC and otherwise) | Giving an alternative, more applied, view from Rod's excellent answer above -
In many, if not most, cases, impropriety of the posterior is a result of choices made for convenience, not a true "I'm ab | Sampling from an Improper Distribution (using MCMC and otherwise)
Giving an alternative, more applied, view from Rod's excellent answer above -
In many, if not most, cases, impropriety of the posterior is a result of choices made for convenience, not a true "I'm absolutely certain of my likelihood function and prior distribution, and look what happened!" effect. Given this, we shouldn't take impropriety too seriously in our applied work unless it's going to mess up our computations. As someone famous (Huber? Tukey?) once observed, in a different context, the difference between a standard Cauchy and a Cauchy truncated at $+/- 10^{100}$ is undetectable, but one has no moments and the other has moments of all orders.
In this context, if I have a posterior distribution for demand for hot dogs at AT&T Park next weekend with upper tail proportional to $1/x$, that's bad news for algorithms that calculate expected values, but if I truncate it at the estimated number of people in San Francisco, a number somewhat larger than the number of hot dogs that will in fact be sold at AT&T park next weekend, all is well, at least in terms of existence of moments. In the latter case, you can think of it as a sort of two-stage application of the real prior - one I use for calculation, which doesn't have an upper bound, and the "extra feature" of it where it's equal to zero above the population of San Francisco...", with the "extra feature" being applied in a step subsequent to the generation of the sample. The real prior is not the one that's used in the MCMC computation (in my example.)
So in principle I would be quite OK with using an MCMC-generated sample from an improper distribution in applied work, but I'd be paying a lot of attention to how that impropriety came about, and how the random sample will be affected by it. Ideally, the random sample wouldn't be affected by it, as in my hot-dog example, where in a reasonable world you'd never actually generate a random number greater than the number of people in San Francisco...
You should also be aware of the fact that your results may be quite sensitive to the feature of the posterior that caused it to be improper, even if you do truncate it at some large number later on (or whatever alteration is appropriate for your model.) You'd like your results to be robust to slight changes that shift your posterior from improper to proper. This can be harder to ensure, but is all part of the larger problem of making sure your results are robust to your assumptions, especially the ones which are made for convenience. | Sampling from an Improper Distribution (using MCMC and otherwise)
Giving an alternative, more applied, view from Rod's excellent answer above -
In many, if not most, cases, impropriety of the posterior is a result of choices made for convenience, not a true "I'm ab |
17,541 | Independent samples t-test: Do data really need to be normally distributed for large sample sizes? | I think this is a common misunderstanding of the CLT. Not only does the CLT have nothing to do with preserving type II error (which no one has mentioned here) but it is often not applicable when you must estimate the population variance. The sample variance can be very far from a scaled chi-squared distribution when the data are non-Gaussian, so the CLT may not apply even when the sample size exceeds tens of thousands. For many distributions the SD is not even a good measure of dispersion.
To really use the CLT, one of two things must be true: (1) the sample standard deviation works as a measure of dispersion for the true unknown distribution or (2) the true population standard deviation is known. That is very often not the case. And an example of n=20,000 being far too small for the CLT to "work" comes from drawing samples from the lognormal distribution as discussed elsewhere on this site.
The sample standard deviation "works" as a dispersion measure if for example the distribution is symmetric and does not have tails that are heavier than the Gaussian distribution.
I do not want to rely on the CLT for any of my analyses. | Independent samples t-test: Do data really need to be normally distributed for large sample sizes? | I think this is a common misunderstanding of the CLT. Not only does the CLT have nothing to do with preserving type II error (which no one has mentioned here) but it is often not applicable when you m | Independent samples t-test: Do data really need to be normally distributed for large sample sizes?
I think this is a common misunderstanding of the CLT. Not only does the CLT have nothing to do with preserving type II error (which no one has mentioned here) but it is often not applicable when you must estimate the population variance. The sample variance can be very far from a scaled chi-squared distribution when the data are non-Gaussian, so the CLT may not apply even when the sample size exceeds tens of thousands. For many distributions the SD is not even a good measure of dispersion.
To really use the CLT, one of two things must be true: (1) the sample standard deviation works as a measure of dispersion for the true unknown distribution or (2) the true population standard deviation is known. That is very often not the case. And an example of n=20,000 being far too small for the CLT to "work" comes from drawing samples from the lognormal distribution as discussed elsewhere on this site.
The sample standard deviation "works" as a dispersion measure if for example the distribution is symmetric and does not have tails that are heavier than the Gaussian distribution.
I do not want to rely on the CLT for any of my analyses. | Independent samples t-test: Do data really need to be normally distributed for large sample sizes?
I think this is a common misunderstanding of the CLT. Not only does the CLT have nothing to do with preserving type II error (which no one has mentioned here) but it is often not applicable when you m |
17,542 | Independent samples t-test: Do data really need to be normally distributed for large sample sizes? | I am leaving this paragraph for the comments to make sense: Probably the assumption of normality in the original populations is too restrictive, and can be forgone focusing on the sampling distribution, and thanks to the central limit theorem, especially for large samples.
Applying the $t$ test is probably a good idea if (as is usually the case) you don't know the population variance, and you are instead using the sample variances as estimators. Note that the assumption of identical variances may need to be tested with an F test of variances or a Lavene test before applying a pooled variance - I have some notes on GitHub here.
As you mention, the t-distribution does converge to the normal distribution as the sample increases, as this quick R plot demonstrates:
In red is the pdf of a normal distribution, and in purple, you can see the progressive change in the "fat tails" (or heavier tails) of the pdf of the $t$ distribution as the degrees of freedom increase until it finally blends with the normal plot.
So applying a z-test would likely be OK with large samples.
Addressing the issues with my initial answer. Thank you, Glen_b for your help with the OP (the likely new mistakes in interpretation are entirely mine).
THE T STATISTIC FOLLOWS A T DISTRIBUTION UNDER NORMALITY ASSUMPTION:
Leaving aside complexities in the formulas for one-sample v. two-sample (paired and unpaired), the general t statistic focusing on the case of comparing a sample mean to a population mean is:
$\text{t-test}= \Large \frac{\bar X-\mu}{\frac{s}{\sqrt{n}}}=\large\frac{\frac{\bar{X}-\mu}{\sigma/\sqrt{n}}}{\sqrt{\frac{s^2}{\sigma^2}}} =\displaystyle \large\frac{\frac{\bar{X}-\mu}{\sigma/\sqrt{n}}}{\sqrt{\frac{\frac{\sum_{x=1}^n(X - \bar{X})^2}{n-1}}{\sigma^2}}} \tag1$
If $X$ follows a normal distribution with mean $\mu$ and variance $\sigma^2$:
The numerator of $(1)$ $\sim N(1,0)$.
The denominator of $(1)$ will be the square root of $\frac{s^2/\sigma^2}{n-1}\sim\frac{1}{n-1}\,\,\chi^2_{n-1}$ (scaled chi squared), since $(n-1)s^2/\sigma^2\sim\chi^2_{n-1}$ as derived here.
Numerator and denominator should be independent.
Under these conditons the $\text{t-statistic} \sim t(df=n-1)$.
CENTRAL LIMIT THEOREM:
The tendency towards normality of the sampling distribution of the sample means
as the sample size increases can justify assuming a normal distribution of the numerator even if the population is not normal. However, it does not influence the other two conditions (chi square distribution of the denominator and independence of the numerator from the denominator).
But not all is lost, in this post it is discussed how Slutzky theorem supports the asymptotic convergence towards a normal distribution even if the chi distribution of the denominator is not met.
ROBUSTNESS:
On the paper "A More Realistic Look at the Robustness and Type II Error Propertiesof the t Test to Departures From Population Normality" by Sawilowsky SS and Blair RC in Psychological Bulletin, 1992, Vol. 111, No. 2, 352-360, where they tested less ideal or more "real world" (less normal) distributions for power and for type I errors, the following assertions can be found: "Despite the conservative nature with regard to Type I error of the t test for some of these real distributions, there was little effect on the power levels for the variety of treatment conditions and sample sizes studied. Researchers may easily compensate for the slight loss in power by selecting a slightly larger sample size".
"The prevailing view seems to be that the independent-samples t test is reasonably robust, insofar as Type I errors are concerned, to non-Gaussian population shape so long as (a) sample sizes are equal or nearly so, (b) sample sizes are fairly large (Boneau, 1960, mentions sample sizes of 25 to 30), and (c) tests are two-tailed rather than one-tailed. Note also that when these conditions are met and differences between nominal alpha and actual alpha do occur, discrepancies are usually of a conservative rather than of a liberal nature."
The authors do stress the controversial aspects of the topic, and I look forward to working on some simulations based on the lognormal distribution as mentioned by Professor Harrell. I would also like to come up with some Monte Carlo comparisons with non-parametric methods (e.g. Mann–Whitney U test). So it's a work in progress...
SIMULATIONS:
Disclaimer: What follows is one of these exercises in "proving it myself" one way or another. The results cannot be used to make generalizations (at least not by me), but I guess I can say that these two (probably flawed) MC simulations don't seem to be too discouraging as to the use of the t test in the circumstances described.
Type I error:
On the issue of type I errors, I ran a Monte Carlo simulation using the Lognormal distribution. Extracting what would be considered larger samples ($n=50$) many times from a lognormal distribution with parameters $\mu=0$ and $\sigma=1$, I calculated the t-values and p-values that would result if we were to compare the means of these samples, all of them arising from the same population, and all of the same size. The lognormal was chosen based on the comments and the marked skewness of the distribution to the right:
Setting a significance level of $5\%$ the actual type I error rate would have been $4.5\%$, not too bad...
In fact the plot of the density of the t tests obtained seemed to overlap the actual pdf of the t-distribution:
The most interesting part was looking at the "denominator" of the t test, the part that was supposed to follow a chi-squared distribution:
$$(n-1)s^2/\sigma^2=98\,\frac{(49 \, (\text{SD}_A^2 + \text{SD}_A^2))/98} {(e^{\sigma^2}-1) \, e^{2\mu+\sigma^2}}$$.
Here we are using the common standard deviation, as in this Wikipedia entry:
$$S_{X_1X_2}=\sqrt{\frac{(n_1 -1)\,S_{X_1}^2 + (n_2 -1)\,S_{X_2}^2}{n_1+n_2-2}}$$
And, surprisingly (or not) the plot was extremely unlike the superimposed chi-squared pdf:
Type II Error and Power:
The distribution of blood pressure is possible log-normal, which comes extremely handy to set up a synthetic scenario in which the comparison groups are separate in average values by a distance of clinical relevance, say in a clinical study testing the effect of a blood pressure drug focusing on the diastolic BP, a significant effect could be considered an average drop of $10$ mmHg (a SD of approximately $9$ mmHg was chosen):
Running comparison t-tests on an otherwise similar Monte Carlo simulation as for type I errors between these fictitious groups, and with a significance level of $5\%$ we end up with $0.024\%$ type II errors, and a power of only $99\%$.
The code is here. | Independent samples t-test: Do data really need to be normally distributed for large sample sizes? | I am leaving this paragraph for the comments to make sense: Probably the assumption of normality in the original populations is too restrictive, and can be forgone focusing on the sampling distributio | Independent samples t-test: Do data really need to be normally distributed for large sample sizes?
I am leaving this paragraph for the comments to make sense: Probably the assumption of normality in the original populations is too restrictive, and can be forgone focusing on the sampling distribution, and thanks to the central limit theorem, especially for large samples.
Applying the $t$ test is probably a good idea if (as is usually the case) you don't know the population variance, and you are instead using the sample variances as estimators. Note that the assumption of identical variances may need to be tested with an F test of variances or a Lavene test before applying a pooled variance - I have some notes on GitHub here.
As you mention, the t-distribution does converge to the normal distribution as the sample increases, as this quick R plot demonstrates:
In red is the pdf of a normal distribution, and in purple, you can see the progressive change in the "fat tails" (or heavier tails) of the pdf of the $t$ distribution as the degrees of freedom increase until it finally blends with the normal plot.
So applying a z-test would likely be OK with large samples.
Addressing the issues with my initial answer. Thank you, Glen_b for your help with the OP (the likely new mistakes in interpretation are entirely mine).
THE T STATISTIC FOLLOWS A T DISTRIBUTION UNDER NORMALITY ASSUMPTION:
Leaving aside complexities in the formulas for one-sample v. two-sample (paired and unpaired), the general t statistic focusing on the case of comparing a sample mean to a population mean is:
$\text{t-test}= \Large \frac{\bar X-\mu}{\frac{s}{\sqrt{n}}}=\large\frac{\frac{\bar{X}-\mu}{\sigma/\sqrt{n}}}{\sqrt{\frac{s^2}{\sigma^2}}} =\displaystyle \large\frac{\frac{\bar{X}-\mu}{\sigma/\sqrt{n}}}{\sqrt{\frac{\frac{\sum_{x=1}^n(X - \bar{X})^2}{n-1}}{\sigma^2}}} \tag1$
If $X$ follows a normal distribution with mean $\mu$ and variance $\sigma^2$:
The numerator of $(1)$ $\sim N(1,0)$.
The denominator of $(1)$ will be the square root of $\frac{s^2/\sigma^2}{n-1}\sim\frac{1}{n-1}\,\,\chi^2_{n-1}$ (scaled chi squared), since $(n-1)s^2/\sigma^2\sim\chi^2_{n-1}$ as derived here.
Numerator and denominator should be independent.
Under these conditons the $\text{t-statistic} \sim t(df=n-1)$.
CENTRAL LIMIT THEOREM:
The tendency towards normality of the sampling distribution of the sample means
as the sample size increases can justify assuming a normal distribution of the numerator even if the population is not normal. However, it does not influence the other two conditions (chi square distribution of the denominator and independence of the numerator from the denominator).
But not all is lost, in this post it is discussed how Slutzky theorem supports the asymptotic convergence towards a normal distribution even if the chi distribution of the denominator is not met.
ROBUSTNESS:
On the paper "A More Realistic Look at the Robustness and Type II Error Propertiesof the t Test to Departures From Population Normality" by Sawilowsky SS and Blair RC in Psychological Bulletin, 1992, Vol. 111, No. 2, 352-360, where they tested less ideal or more "real world" (less normal) distributions for power and for type I errors, the following assertions can be found: "Despite the conservative nature with regard to Type I error of the t test for some of these real distributions, there was little effect on the power levels for the variety of treatment conditions and sample sizes studied. Researchers may easily compensate for the slight loss in power by selecting a slightly larger sample size".
"The prevailing view seems to be that the independent-samples t test is reasonably robust, insofar as Type I errors are concerned, to non-Gaussian population shape so long as (a) sample sizes are equal or nearly so, (b) sample sizes are fairly large (Boneau, 1960, mentions sample sizes of 25 to 30), and (c) tests are two-tailed rather than one-tailed. Note also that when these conditions are met and differences between nominal alpha and actual alpha do occur, discrepancies are usually of a conservative rather than of a liberal nature."
The authors do stress the controversial aspects of the topic, and I look forward to working on some simulations based on the lognormal distribution as mentioned by Professor Harrell. I would also like to come up with some Monte Carlo comparisons with non-parametric methods (e.g. Mann–Whitney U test). So it's a work in progress...
SIMULATIONS:
Disclaimer: What follows is one of these exercises in "proving it myself" one way or another. The results cannot be used to make generalizations (at least not by me), but I guess I can say that these two (probably flawed) MC simulations don't seem to be too discouraging as to the use of the t test in the circumstances described.
Type I error:
On the issue of type I errors, I ran a Monte Carlo simulation using the Lognormal distribution. Extracting what would be considered larger samples ($n=50$) many times from a lognormal distribution with parameters $\mu=0$ and $\sigma=1$, I calculated the t-values and p-values that would result if we were to compare the means of these samples, all of them arising from the same population, and all of the same size. The lognormal was chosen based on the comments and the marked skewness of the distribution to the right:
Setting a significance level of $5\%$ the actual type I error rate would have been $4.5\%$, not too bad...
In fact the plot of the density of the t tests obtained seemed to overlap the actual pdf of the t-distribution:
The most interesting part was looking at the "denominator" of the t test, the part that was supposed to follow a chi-squared distribution:
$$(n-1)s^2/\sigma^2=98\,\frac{(49 \, (\text{SD}_A^2 + \text{SD}_A^2))/98} {(e^{\sigma^2}-1) \, e^{2\mu+\sigma^2}}$$.
Here we are using the common standard deviation, as in this Wikipedia entry:
$$S_{X_1X_2}=\sqrt{\frac{(n_1 -1)\,S_{X_1}^2 + (n_2 -1)\,S_{X_2}^2}{n_1+n_2-2}}$$
And, surprisingly (or not) the plot was extremely unlike the superimposed chi-squared pdf:
Type II Error and Power:
The distribution of blood pressure is possible log-normal, which comes extremely handy to set up a synthetic scenario in which the comparison groups are separate in average values by a distance of clinical relevance, say in a clinical study testing the effect of a blood pressure drug focusing on the diastolic BP, a significant effect could be considered an average drop of $10$ mmHg (a SD of approximately $9$ mmHg was chosen):
Running comparison t-tests on an otherwise similar Monte Carlo simulation as for type I errors between these fictitious groups, and with a significance level of $5\%$ we end up with $0.024\%$ type II errors, and a power of only $99\%$.
The code is here. | Independent samples t-test: Do data really need to be normally distributed for large sample sizes?
I am leaving this paragraph for the comments to make sense: Probably the assumption of normality in the original populations is too restrictive, and can be forgone focusing on the sampling distributio |
17,543 | Neural network - binary vs discrete / continuous input | Whether to convert input variables to binary depends on the input variable. You could think of neural network inputs as representing a kind of "intensity": i.e., larger values of the input variable represent greater intensity of that input variable. After all, assuming the network has only one input, a given hidden node of the network is going to learn some function $f(wx + b)$. where $f$ is the transfer function (e.g. the sigmoid) and $x$ the input variable.
This setup does not make sense for categorical variables. If categories are represented by numbers, it makes no sense to apply the function $f(wx + b)$ to them. E.g. imagine your input variable represents an animal, and sheep=1 and cow=2. It makes no sense to multiply sheep by $w$ and add $b$ to it, nor does it make sense for cow to be always greater in magnitude than sheep. In this case, you should convert the discrete encoding to a binary, 1-of-$k$ encoding.
For real-valued variables, just leave them real-valued (but normalize inputs). E.g. say you have two input variables, one the animal and one the animal's temperature. You'd convert animal to 1-of-$k$, where $k$=number of animals, and you'd leave temperature as-is. | Neural network - binary vs discrete / continuous input | Whether to convert input variables to binary depends on the input variable. You could think of neural network inputs as representing a kind of "intensity": i.e., larger values of the input variable re | Neural network - binary vs discrete / continuous input
Whether to convert input variables to binary depends on the input variable. You could think of neural network inputs as representing a kind of "intensity": i.e., larger values of the input variable represent greater intensity of that input variable. After all, assuming the network has only one input, a given hidden node of the network is going to learn some function $f(wx + b)$. where $f$ is the transfer function (e.g. the sigmoid) and $x$ the input variable.
This setup does not make sense for categorical variables. If categories are represented by numbers, it makes no sense to apply the function $f(wx + b)$ to them. E.g. imagine your input variable represents an animal, and sheep=1 and cow=2. It makes no sense to multiply sheep by $w$ and add $b$ to it, nor does it make sense for cow to be always greater in magnitude than sheep. In this case, you should convert the discrete encoding to a binary, 1-of-$k$ encoding.
For real-valued variables, just leave them real-valued (but normalize inputs). E.g. say you have two input variables, one the animal and one the animal's temperature. You'd convert animal to 1-of-$k$, where $k$=number of animals, and you'd leave temperature as-is. | Neural network - binary vs discrete / continuous input
Whether to convert input variables to binary depends on the input variable. You could think of neural network inputs as representing a kind of "intensity": i.e., larger values of the input variable re |
17,544 | Neural network - binary vs discrete / continuous input | Yes there are. Imagine your goal is to build a binary classifier. Then you model your problem as estimating a Bernoulli distribution where, given a feature vector, the outcome belongs to either one class or the opposite. The output of such a neural network is the conditional probability. If greater than 0.5 you associate it to a class, otherwise to the other one.
In order to be well defined, the output must be between 0 and 1, so you choose your labels to be 0 and 1, and minimize the cross entropy,
$$
E = y(x)^{t}(1-y(x))^{1-t}
$$
where $y(x)$ is the output of your network, and $t$ are the target values for your training samples. Hence, you need $t \in \left\{0, 1\right\}$. | Neural network - binary vs discrete / continuous input | Yes there are. Imagine your goal is to build a binary classifier. Then you model your problem as estimating a Bernoulli distribution where, given a feature vector, the outcome belongs to either one cl | Neural network - binary vs discrete / continuous input
Yes there are. Imagine your goal is to build a binary classifier. Then you model your problem as estimating a Bernoulli distribution where, given a feature vector, the outcome belongs to either one class or the opposite. The output of such a neural network is the conditional probability. If greater than 0.5 you associate it to a class, otherwise to the other one.
In order to be well defined, the output must be between 0 and 1, so you choose your labels to be 0 and 1, and minimize the cross entropy,
$$
E = y(x)^{t}(1-y(x))^{1-t}
$$
where $y(x)$ is the output of your network, and $t$ are the target values for your training samples. Hence, you need $t \in \left\{0, 1\right\}$. | Neural network - binary vs discrete / continuous input
Yes there are. Imagine your goal is to build a binary classifier. Then you model your problem as estimating a Bernoulli distribution where, given a feature vector, the outcome belongs to either one cl |
17,545 | Neural network - binary vs discrete / continuous input | I also faced same dilemma when I was solving a problem. I didn't try both the architecture, but my take is, if the input variable is discrete then the output function of neural network will have the characteristic of impulse function and neural network is good at modeling impulse function. In fact any function can be modeled with neural network with varying precision depending on complexity of neural network. The only difference is, in first architecture , you have increase the number of input so you more number of weight in first hidden layer's node to model the impulse function but for the second architecture you need more number of node in hidden layer compared to first architecture to get same performance. | Neural network - binary vs discrete / continuous input | I also faced same dilemma when I was solving a problem. I didn't try both the architecture, but my take is, if the input variable is discrete then the output function of neural network will have the c | Neural network - binary vs discrete / continuous input
I also faced same dilemma when I was solving a problem. I didn't try both the architecture, but my take is, if the input variable is discrete then the output function of neural network will have the characteristic of impulse function and neural network is good at modeling impulse function. In fact any function can be modeled with neural network with varying precision depending on complexity of neural network. The only difference is, in first architecture , you have increase the number of input so you more number of weight in first hidden layer's node to model the impulse function but for the second architecture you need more number of node in hidden layer compared to first architecture to get same performance. | Neural network - binary vs discrete / continuous input
I also faced same dilemma when I was solving a problem. I didn't try both the architecture, but my take is, if the input variable is discrete then the output function of neural network will have the c |
17,546 | Should partial $R^2$ add up to total $R^2$ in multiple regression? | No.
One way to understand partial $R^2$ for a given predictor is that it equals the $R^2$ that you would get if you first regress your independent variable on all other predictors, take the residuals, and regress those on the remaining predictor.
So if e.g. all predictors are perfectly identical (collinear), one can have decent $R^2$, but partial $R^2$ for all predictors will be exactly zero, because any single predictor has zero additional explanatory power.
On the other hand, if all predictors together explain the dependent variable perfectly, i.e. $R^2=1$, then partial $R^2$ for each predictor will be $1$ too, because whatever is unexplained by all other predictors can be perfectly explained by the remaining one.
So the sum of all partial $R^2$ can easily be below or above the total $R^2$. They do not have to coincide even if all predictors are orthogonal. Partial $R^2$ is a bit of a weird measure.
See this long thread for many more details: Importance of predictors in multiple regression: Partial $R^2$ vs. standardized coefficients. | Should partial $R^2$ add up to total $R^2$ in multiple regression? | No.
One way to understand partial $R^2$ for a given predictor is that it equals the $R^2$ that you would get if you first regress your independent variable on all other predictors, take the residuals, | Should partial $R^2$ add up to total $R^2$ in multiple regression?
No.
One way to understand partial $R^2$ for a given predictor is that it equals the $R^2$ that you would get if you first regress your independent variable on all other predictors, take the residuals, and regress those on the remaining predictor.
So if e.g. all predictors are perfectly identical (collinear), one can have decent $R^2$, but partial $R^2$ for all predictors will be exactly zero, because any single predictor has zero additional explanatory power.
On the other hand, if all predictors together explain the dependent variable perfectly, i.e. $R^2=1$, then partial $R^2$ for each predictor will be $1$ too, because whatever is unexplained by all other predictors can be perfectly explained by the remaining one.
So the sum of all partial $R^2$ can easily be below or above the total $R^2$. They do not have to coincide even if all predictors are orthogonal. Partial $R^2$ is a bit of a weird measure.
See this long thread for many more details: Importance of predictors in multiple regression: Partial $R^2$ vs. standardized coefficients. | Should partial $R^2$ add up to total $R^2$ in multiple regression?
No.
One way to understand partial $R^2$ for a given predictor is that it equals the $R^2$ that you would get if you first regress your independent variable on all other predictors, take the residuals, |
17,547 | Interpreting random effect variance in glmer | While getting an analogue of "proportion variance explained by each effect" is in principle possible for GLMMs, there are several complicating factors (which levels of the model do you consider "total variance", and how do you quantify the sampling variation due to the lowest-level [Binomial in this case] sampling distribution)? Nakagawa and Schielzeth (doi:10.1111/j.2041-210x.2012.00261.x) present a general approach to calculating R^2 (proportion of total variance explained) for (G)LMMs which has gotten pretty popular in ecology; Xu et al 2003 take a similar approach. In principle this approach could probably be extended to consider proportion of variance explained by different terms [but note that the 'proportion of variance' of all the terms in the model considered in this way would probably not add up to 100% -- it could be either more or less].
However, if your reviewer isn't hung up on statistical details and would be satisfied with a more heuristic explanation of "importance", you could point out that the estimated among-plant standard deviation is 1.20, very close to the magnitude of the largest treatment effect (-1.18); this means that the plants vary quite a bit, relative to the magnitude of the treatment effects (e.g., the 95% range of the plant effects is approximately $4\sigma$, from $-1.96 \sigma$ to $+1.96\sigma$).
Visually: | Interpreting random effect variance in glmer | While getting an analogue of "proportion variance explained by each effect" is in principle possible for GLMMs, there are several complicating factors (which levels of the model do you consider "total | Interpreting random effect variance in glmer
While getting an analogue of "proportion variance explained by each effect" is in principle possible for GLMMs, there are several complicating factors (which levels of the model do you consider "total variance", and how do you quantify the sampling variation due to the lowest-level [Binomial in this case] sampling distribution)? Nakagawa and Schielzeth (doi:10.1111/j.2041-210x.2012.00261.x) present a general approach to calculating R^2 (proportion of total variance explained) for (G)LMMs which has gotten pretty popular in ecology; Xu et al 2003 take a similar approach. In principle this approach could probably be extended to consider proportion of variance explained by different terms [but note that the 'proportion of variance' of all the terms in the model considered in this way would probably not add up to 100% -- it could be either more or less].
However, if your reviewer isn't hung up on statistical details and would be satisfied with a more heuristic explanation of "importance", you could point out that the estimated among-plant standard deviation is 1.20, very close to the magnitude of the largest treatment effect (-1.18); this means that the plants vary quite a bit, relative to the magnitude of the treatment effects (e.g., the 95% range of the plant effects is approximately $4\sigma$, from $-1.96 \sigma$ to $+1.96\sigma$).
Visually: | Interpreting random effect variance in glmer
While getting an analogue of "proportion variance explained by each effect" is in principle possible for GLMMs, there are several complicating factors (which levels of the model do you consider "total |
17,548 | Interpreting random effect variance in glmer | What you want is to test if the variance of PlantID is $0$. However, this is a weird test to try to run, because null value is at the boundary of the permissible space. Such tests are still run, but a lot of people are very uncomfortable with them.
In your case, you have multiple measures per plant, so one quick and dirty approach is to run a model with PlantID as a fixed effect, and test that effect. | Interpreting random effect variance in glmer | What you want is to test if the variance of PlantID is $0$. However, this is a weird test to try to run, because null value is at the boundary of the permissible space. Such tests are still run, but | Interpreting random effect variance in glmer
What you want is to test if the variance of PlantID is $0$. However, this is a weird test to try to run, because null value is at the boundary of the permissible space. Such tests are still run, but a lot of people are very uncomfortable with them.
In your case, you have multiple measures per plant, so one quick and dirty approach is to run a model with PlantID as a fixed effect, and test that effect. | Interpreting random effect variance in glmer
What you want is to test if the variance of PlantID is $0$. However, this is a weird test to try to run, because null value is at the boundary of the permissible space. Such tests are still run, but |
17,549 | Interpreting random effect variance in glmer | The simple answer to your reviewer is, "Yes." If he is asking you to test whether the variance of the random effect is significantly different from 0, you have a couple options. Note though that many smart people are uncomfortable with testing if variances of random effects are different from 0.
Simplest is a likelihood ratio test, though not recommended by most. They are very conservative when testing at the boundaries (i.e. your are testing against a variance of 0 which is as low as it can go). There is a rule of thumb out there that the p value is about twice what it really is.
The method recommended most places is a parametric bootstrap. You can use bootMer from the lme4 package. Make sure that your set the REML parameter of your lmer function to FALSE, otherwise your variance will be greater than 0 100% of the time (or close to it... actually it'll probably be greater than 0 nearly 100% of the time anyway).
Some tips and further resources:
http://glmm.wikidot.com/faq (find the How can I test whether a random effect is significant? heading)
lmer() parametric bootstrap testing for fixed effects
http://www.r-bloggers.com/using-bootmer-to-do-model-comparison-in-r/ | Interpreting random effect variance in glmer | The simple answer to your reviewer is, "Yes." If he is asking you to test whether the variance of the random effect is significantly different from 0, you have a couple options. Note though that many | Interpreting random effect variance in glmer
The simple answer to your reviewer is, "Yes." If he is asking you to test whether the variance of the random effect is significantly different from 0, you have a couple options. Note though that many smart people are uncomfortable with testing if variances of random effects are different from 0.
Simplest is a likelihood ratio test, though not recommended by most. They are very conservative when testing at the boundaries (i.e. your are testing against a variance of 0 which is as low as it can go). There is a rule of thumb out there that the p value is about twice what it really is.
The method recommended most places is a parametric bootstrap. You can use bootMer from the lme4 package. Make sure that your set the REML parameter of your lmer function to FALSE, otherwise your variance will be greater than 0 100% of the time (or close to it... actually it'll probably be greater than 0 nearly 100% of the time anyway).
Some tips and further resources:
http://glmm.wikidot.com/faq (find the How can I test whether a random effect is significant? heading)
lmer() parametric bootstrap testing for fixed effects
http://www.r-bloggers.com/using-bootmer-to-do-model-comparison-in-r/ | Interpreting random effect variance in glmer
The simple answer to your reviewer is, "Yes." If he is asking you to test whether the variance of the random effect is significantly different from 0, you have a couple options. Note though that many |
17,550 | Interpreting random effect variance in glmer | In Multiple-Sample Cochran's Q Test , they use anova to compare the results of the two models (one without random effects and one with random effects).
Jairo Rocha
University of the Balearic Islands | Interpreting random effect variance in glmer | In Multiple-Sample Cochran's Q Test , they use anova to compare the results of the two models (one without random effects and one with random effects).
Jairo Rocha
University of the Balearic Islands | Interpreting random effect variance in glmer
In Multiple-Sample Cochran's Q Test , they use anova to compare the results of the two models (one without random effects and one with random effects).
Jairo Rocha
University of the Balearic Islands | Interpreting random effect variance in glmer
In Multiple-Sample Cochran's Q Test , they use anova to compare the results of the two models (one without random effects and one with random effects).
Jairo Rocha
University of the Balearic Islands |
17,551 | Should I remove non-significant variables from my regression model | Leave it in. The data are incapable of really telling you which model is "better" unless you use AIC in a highly structured way (e.g. on a pre-specified large group of variables), and removing insignificant variables invalidates the estimate of $\sigma^2$ and all $P$-values, standard errors, and confidence limits in addition to invalidating the formula for adjusted $R^2$. Much is written about these issues on this site. | Should I remove non-significant variables from my regression model | Leave it in. The data are incapable of really telling you which model is "better" unless you use AIC in a highly structured way (e.g. on a pre-specified large group of variables), and removing insig | Should I remove non-significant variables from my regression model
Leave it in. The data are incapable of really telling you which model is "better" unless you use AIC in a highly structured way (e.g. on a pre-specified large group of variables), and removing insignificant variables invalidates the estimate of $\sigma^2$ and all $P$-values, standard errors, and confidence limits in addition to invalidating the formula for adjusted $R^2$. Much is written about these issues on this site. | Should I remove non-significant variables from my regression model
Leave it in. The data are incapable of really telling you which model is "better" unless you use AIC in a highly structured way (e.g. on a pre-specified large group of variables), and removing insig |
17,552 | Should I remove non-significant variables from my regression model | NB: A corollary to Frank Harrell's answer is that stepwise variable selection should not be used in the first place. That is, not only is it a mistake to discard that final 'leftover' non-significant covariate, but it was even more wrong to employ an automated procedure (stepwise variable selection) designed to produce a cascade of many such mistakes very quickly in an interdependent and irreproducible fashion. | Should I remove non-significant variables from my regression model | NB: A corollary to Frank Harrell's answer is that stepwise variable selection should not be used in the first place. That is, not only is it a mistake to discard that final 'leftover' non-significant | Should I remove non-significant variables from my regression model
NB: A corollary to Frank Harrell's answer is that stepwise variable selection should not be used in the first place. That is, not only is it a mistake to discard that final 'leftover' non-significant covariate, but it was even more wrong to employ an automated procedure (stepwise variable selection) designed to produce a cascade of many such mistakes very quickly in an interdependent and irreproducible fashion. | Should I remove non-significant variables from my regression model
NB: A corollary to Frank Harrell's answer is that stepwise variable selection should not be used in the first place. That is, not only is it a mistake to discard that final 'leftover' non-significant |
17,553 | Should I remove non-significant variables from my regression model | You need to test your model on multiple test datasets. AIC is measure of model fitting not accuracy. Please read section 3.3 ( Subset Selection) in this book -
http://statweb.stanford.edu/~tibs/ElemStatLearn/printings/ESLII_print10.pdf
removing variables is suggested because of 2 reasons-
The first is prediction accuracy: keeping all variables often have
low bias but large variance. Prediction accuracy can sometimes be
improved by shrinking or setting some coefficients to zero. By doing
so we sacrifice a little bit of bias to reduce the variance of the predicted
values, and hence may improve the overall prediction accuracy.
The second reason is interpretation. With a large number of predictors,
we often would like to determine a smaller subset that exhibit
the strongest effects. In order to get the “big picture,” we are willing
to sacrifice some of the small details. | Should I remove non-significant variables from my regression model | You need to test your model on multiple test datasets. AIC is measure of model fitting not accuracy. Please read section 3.3 ( Subset Selection) in this book -
http://statweb.stanford.edu/~tibs/ElemSt | Should I remove non-significant variables from my regression model
You need to test your model on multiple test datasets. AIC is measure of model fitting not accuracy. Please read section 3.3 ( Subset Selection) in this book -
http://statweb.stanford.edu/~tibs/ElemStatLearn/printings/ESLII_print10.pdf
removing variables is suggested because of 2 reasons-
The first is prediction accuracy: keeping all variables often have
low bias but large variance. Prediction accuracy can sometimes be
improved by shrinking or setting some coefficients to zero. By doing
so we sacrifice a little bit of bias to reduce the variance of the predicted
values, and hence may improve the overall prediction accuracy.
The second reason is interpretation. With a large number of predictors,
we often would like to determine a smaller subset that exhibit
the strongest effects. In order to get the “big picture,” we are willing
to sacrifice some of the small details. | Should I remove non-significant variables from my regression model
You need to test your model on multiple test datasets. AIC is measure of model fitting not accuracy. Please read section 3.3 ( Subset Selection) in this book -
http://statweb.stanford.edu/~tibs/ElemSt |
17,554 | Formula for dropping dice (non-brute force) | Solution
Let there be $n=4$ dice each giving equal chances to the outcomes $1, 2, \ldots, d=6$. Let $K$ be the minimum of the values when all $n$ dice are independently thrown.
Consider the distribution of the sum of all $n$ values conditional on $K$. Let $X$ be this sum. The generating function for the number of ways to form any given value of $X$, given that the minimum is at least $k$, is
$$f_{(n,d,k)}(x) = x^k+x^{k+1} + \cdots + x^d = x^k\frac{1-x^{d-k+1}}{1-x}.\tag{1}$$
Since the dice are independent, the generating function for the number of ways to form values of $X$ where all $n$ dice show values of $k$ or greater is
$$f_{(n,d,k)}(x)^n = x^{kn}\left(\frac{1-x^{d-k+1}}{1-x}\right)^n.\tag{2}$$
This generating function includes terms for the events where $K$ exceeds $k$, so we need to subtract them off. Therefore the generating function for the number of ways to form values of $X$, given $K=k$, is
$$f_{(n,d,k)}(x)^n - f_{(n,d,k+1)}(x)^n.\tag{3}$$
Noting that the sum of the $n-1$ highest values is the sum of all values minus the smallest, equal to $X-K$. The generating function therefore needs to be divided by $k$. It becomes a probability generating function upon multiplying by the common chance of any combination of dice, $(1/d)^n$:
$$d^{-n}\sum_{k=1}^dx^{-k}\left(f_{(n,d,k)}(x)^n - f_{(n,d,k+1)}(x)^n\right).\tag{4}$$
Since all the polynomial products and powers can be computed in $O(n\log n)$ operations (they are convolutions and therefore can be carried out with the discrete Fast Fourier Transform), the total computational effort is $O(k\,n\log n)$. In particular, it is a polynomial time algorithm.
Example
Let's work through the example in the question with $n=4$ and $d=6$.
Formula $(1)$ for the PGF of $X$ conditional on $K\ge k$ gives
$$\eqalign{
f_{(4,6,1)}(x) &= x+x^2+x^3+x^4+x^5+x^6 \\
f_{(4,6,2)}(x) &= x^2+x^3+x^4+x^5+x^6 \\
\ldots \\
f_{(4,6,5)}(x) &= x^5+x^6 \\
f_{(4,6,6)}(x) &= x^6 \\
f_{(4,6,7)}(x) &= 0.
}$$
Raising them to the $n=4$ power as in formula $(2)$ produces
$$\eqalign{
f_{(4,6,1)}(x)^4 &= x^4 + 4x^5 + 10 x^6 + \cdots + 4x^{23} + x^{24} \\
f_{(4,6,2)}(x)^4 &= x^8 + 4x^9 + 10x^{10}+ \cdots + 4x^{23} + x^{24} \\
\ldots \\
f_{(4,6,5)}(x)^4 &=x^{20} + 4 x^{21} + 6 x^{22} + 4x^{23} +x^{24}\\
f_{(4,6,6)}(x)^4 &= x^{24}\\
f_{(4,6,7)}(x)^4 &= 0
}$$
Their successive differences in formula $(3)$ are
$$\eqalign{
f_{(4,6,1)}(x)^4 - f_{(4,6,2)}(x)^4 &= x^4 + 4x^5 + 10 x^6 + \cdots + 12 x^{18} + 4x^{19} \\
f_{(4,6,2)}(x)^4 - f_{(4,6,3)}(x)^4 &= x^8 + 4x^9 + 10x^{10} + \cdots + 4 x^{20} \\
\ldots \\
f_{(4,6,5)}(x)^4 - f_{(4,6,6)}(x)^4 &=x^{20} + 4 x^{21} + 6 x^{22} + 4x^{23} \\
f_{(4,6,6)}(x)^4 - f_{(4,6,7)}(x)^4 &= x^{24}.
}$$
The resulting sum in formula $(4)$ is
$$6^{-4}\left(x^3 + 4x^4 + 10x^5 + 21x^6 + 38x^7 + 62x^8 + 91x^9 + 122x^{10} + 148x^{11} + \\167x^{12} + 172x^{13} + 160x^{14} + 131x^{15} + 94x^{16} + 54x^{17} + 21x^{18}\right).$$
For example, the chance that the top three dice sum to $14$ is the coefficient of $x^{14}$, equal to
$$6^{-4}\times 160 = 10/81 = 0.123\,456\,790\,123\,456\,\ldots.$$
It is in perfect agreement with the probabilities quoted in the question.
By the way, the mean (as calculated from this result) is $15869/1296 \approx 12.244598765\ldots$ and the standard deviation is $\sqrt{13\,612\,487/1\,679\,616}\approx 2.8468444$.
A similar (unoptimized) calculation for $n=400$ dice instead of $n=4$ took less than a half a second, supporting the contention that this is not a computationally demanding algorithm. Here is a plot of the main part of the distribution:
Since the minimum $K$ is highly likely to equal $1$ and the sum $X$ will be extremely close to having a Normal$(400\times 7/2, 400\times 35/12)$ distribution (whose mean is $1400$ and standard deviation is approximately $34.1565$), the mean must be extremely close to $1400-1=1399$ and the standard deviation extremely close to $34.16$. This nicely describes the plot, indicating it is likely correct. In fact, the exact calculation gives a mean of around $2.13\times 10^{-32}$ greater than $1399$ and a standard deviation around $1.24\times 10^{-31}$ less than $\sqrt{400\times 35/12}$. | Formula for dropping dice (non-brute force) | Solution
Let there be $n=4$ dice each giving equal chances to the outcomes $1, 2, \ldots, d=6$. Let $K$ be the minimum of the values when all $n$ dice are independently thrown.
Consider the distribu | Formula for dropping dice (non-brute force)
Solution
Let there be $n=4$ dice each giving equal chances to the outcomes $1, 2, \ldots, d=6$. Let $K$ be the minimum of the values when all $n$ dice are independently thrown.
Consider the distribution of the sum of all $n$ values conditional on $K$. Let $X$ be this sum. The generating function for the number of ways to form any given value of $X$, given that the minimum is at least $k$, is
$$f_{(n,d,k)}(x) = x^k+x^{k+1} + \cdots + x^d = x^k\frac{1-x^{d-k+1}}{1-x}.\tag{1}$$
Since the dice are independent, the generating function for the number of ways to form values of $X$ where all $n$ dice show values of $k$ or greater is
$$f_{(n,d,k)}(x)^n = x^{kn}\left(\frac{1-x^{d-k+1}}{1-x}\right)^n.\tag{2}$$
This generating function includes terms for the events where $K$ exceeds $k$, so we need to subtract them off. Therefore the generating function for the number of ways to form values of $X$, given $K=k$, is
$$f_{(n,d,k)}(x)^n - f_{(n,d,k+1)}(x)^n.\tag{3}$$
Noting that the sum of the $n-1$ highest values is the sum of all values minus the smallest, equal to $X-K$. The generating function therefore needs to be divided by $k$. It becomes a probability generating function upon multiplying by the common chance of any combination of dice, $(1/d)^n$:
$$d^{-n}\sum_{k=1}^dx^{-k}\left(f_{(n,d,k)}(x)^n - f_{(n,d,k+1)}(x)^n\right).\tag{4}$$
Since all the polynomial products and powers can be computed in $O(n\log n)$ operations (they are convolutions and therefore can be carried out with the discrete Fast Fourier Transform), the total computational effort is $O(k\,n\log n)$. In particular, it is a polynomial time algorithm.
Example
Let's work through the example in the question with $n=4$ and $d=6$.
Formula $(1)$ for the PGF of $X$ conditional on $K\ge k$ gives
$$\eqalign{
f_{(4,6,1)}(x) &= x+x^2+x^3+x^4+x^5+x^6 \\
f_{(4,6,2)}(x) &= x^2+x^3+x^4+x^5+x^6 \\
\ldots \\
f_{(4,6,5)}(x) &= x^5+x^6 \\
f_{(4,6,6)}(x) &= x^6 \\
f_{(4,6,7)}(x) &= 0.
}$$
Raising them to the $n=4$ power as in formula $(2)$ produces
$$\eqalign{
f_{(4,6,1)}(x)^4 &= x^4 + 4x^5 + 10 x^6 + \cdots + 4x^{23} + x^{24} \\
f_{(4,6,2)}(x)^4 &= x^8 + 4x^9 + 10x^{10}+ \cdots + 4x^{23} + x^{24} \\
\ldots \\
f_{(4,6,5)}(x)^4 &=x^{20} + 4 x^{21} + 6 x^{22} + 4x^{23} +x^{24}\\
f_{(4,6,6)}(x)^4 &= x^{24}\\
f_{(4,6,7)}(x)^4 &= 0
}$$
Their successive differences in formula $(3)$ are
$$\eqalign{
f_{(4,6,1)}(x)^4 - f_{(4,6,2)}(x)^4 &= x^4 + 4x^5 + 10 x^6 + \cdots + 12 x^{18} + 4x^{19} \\
f_{(4,6,2)}(x)^4 - f_{(4,6,3)}(x)^4 &= x^8 + 4x^9 + 10x^{10} + \cdots + 4 x^{20} \\
\ldots \\
f_{(4,6,5)}(x)^4 - f_{(4,6,6)}(x)^4 &=x^{20} + 4 x^{21} + 6 x^{22} + 4x^{23} \\
f_{(4,6,6)}(x)^4 - f_{(4,6,7)}(x)^4 &= x^{24}.
}$$
The resulting sum in formula $(4)$ is
$$6^{-4}\left(x^3 + 4x^4 + 10x^5 + 21x^6 + 38x^7 + 62x^8 + 91x^9 + 122x^{10} + 148x^{11} + \\167x^{12} + 172x^{13} + 160x^{14} + 131x^{15} + 94x^{16} + 54x^{17} + 21x^{18}\right).$$
For example, the chance that the top three dice sum to $14$ is the coefficient of $x^{14}$, equal to
$$6^{-4}\times 160 = 10/81 = 0.123\,456\,790\,123\,456\,\ldots.$$
It is in perfect agreement with the probabilities quoted in the question.
By the way, the mean (as calculated from this result) is $15869/1296 \approx 12.244598765\ldots$ and the standard deviation is $\sqrt{13\,612\,487/1\,679\,616}\approx 2.8468444$.
A similar (unoptimized) calculation for $n=400$ dice instead of $n=4$ took less than a half a second, supporting the contention that this is not a computationally demanding algorithm. Here is a plot of the main part of the distribution:
Since the minimum $K$ is highly likely to equal $1$ and the sum $X$ will be extremely close to having a Normal$(400\times 7/2, 400\times 35/12)$ distribution (whose mean is $1400$ and standard deviation is approximately $34.1565$), the mean must be extremely close to $1400-1=1399$ and the standard deviation extremely close to $34.16$. This nicely describes the plot, indicating it is likely correct. In fact, the exact calculation gives a mean of around $2.13\times 10^{-32}$ greater than $1399$ and a standard deviation around $1.24\times 10^{-31}$ less than $\sqrt{400\times 35/12}$. | Formula for dropping dice (non-brute force)
Solution
Let there be $n=4$ dice each giving equal chances to the outcomes $1, 2, \ldots, d=6$. Let $K$ be the minimum of the values when all $n$ dice are independently thrown.
Consider the distribu |
17,555 | Formula for dropping dice (non-brute force) | Edit: @SkySpiral has had trouble getting the below formula to work. I currently don't have time to work out what the issue is, so if you're reading this it's best to proceed under the assumption it's incorrect.
I'm not sure about the general problem with varying numbers of dice, sides, and drops, but I think I can see an efficient algorithm for the drop-1 case. The qualifier is that I'm not completely sure that it's correct, but right now I can't see any flaws.
Let's start by not dropping any dice. Suppose $X_n$ represents the $n$th die, and suppose $Y_n$ represents the sum of $n$ dice. Then
$$p(Y_n = a) = \sum_k p(Y_{n-1} = a - k)p(X_n=k)$$
Now suppose $Z_n$ is the sum of $n$ dice when one die is dropped. Then
$$p(Z_n = a) = p(\text{$n$th die is the smallest})p(Y_{n-1} = a) + \\
p(\text{$n$th die is not the smallest})\sum_k p(Z_{n-1} = a - k)p(X_n=k)$$
If we define $M_n$ to be distribution of the minimum of $n$ dies, then
$$p(Z_n = a) = p(X_n \leq M_{n-1})p(Y_{n-1} = a | X_n \leq M_{n-1}) + \\
p(X_n > M_{n-1})\sum_k p(Z_{n-1} = a - k)p(X_n=k | X_n > M_{n-1})$$
and we can calculate $M_n$ using
$$p(M_n = a) = p(X_n \leq M_{n-1})p(X_n = a |X_n \leq M_{n-1}) + p(X_n > M_{n-1})p(M_{n-1} = a|X_n > M_{n-1})$$
Anyway, together this all suggests a dynamic programming algorithm based on $Y_n, Z_n$ and $M_n$. Should be quadratic in $n$.
edit: A comment has been raised on how to calculate $p(X_n \leq M_{n-1})$. Since $X_n, M_{n-1}$ can each only take on one of six values, we can just sum over all possibilities:
$$p(X_n \leq M_{n-1}) = \sum_{a,b} p(X_n = a, M_{n-1} = b, a \leq b)$$
Similarly, $p(X_n = k | X_n > M_{n-1})$ can be calculated by applying Bayes rule then summing over the possible values of $X_n, M_{n-1}$. | Formula for dropping dice (non-brute force) | Edit: @SkySpiral has had trouble getting the below formula to work. I currently don't have time to work out what the issue is, so if you're reading this it's best to proceed under the assumption it's | Formula for dropping dice (non-brute force)
Edit: @SkySpiral has had trouble getting the below formula to work. I currently don't have time to work out what the issue is, so if you're reading this it's best to proceed under the assumption it's incorrect.
I'm not sure about the general problem with varying numbers of dice, sides, and drops, but I think I can see an efficient algorithm for the drop-1 case. The qualifier is that I'm not completely sure that it's correct, but right now I can't see any flaws.
Let's start by not dropping any dice. Suppose $X_n$ represents the $n$th die, and suppose $Y_n$ represents the sum of $n$ dice. Then
$$p(Y_n = a) = \sum_k p(Y_{n-1} = a - k)p(X_n=k)$$
Now suppose $Z_n$ is the sum of $n$ dice when one die is dropped. Then
$$p(Z_n = a) = p(\text{$n$th die is the smallest})p(Y_{n-1} = a) + \\
p(\text{$n$th die is not the smallest})\sum_k p(Z_{n-1} = a - k)p(X_n=k)$$
If we define $M_n$ to be distribution of the minimum of $n$ dies, then
$$p(Z_n = a) = p(X_n \leq M_{n-1})p(Y_{n-1} = a | X_n \leq M_{n-1}) + \\
p(X_n > M_{n-1})\sum_k p(Z_{n-1} = a - k)p(X_n=k | X_n > M_{n-1})$$
and we can calculate $M_n$ using
$$p(M_n = a) = p(X_n \leq M_{n-1})p(X_n = a |X_n \leq M_{n-1}) + p(X_n > M_{n-1})p(M_{n-1} = a|X_n > M_{n-1})$$
Anyway, together this all suggests a dynamic programming algorithm based on $Y_n, Z_n$ and $M_n$. Should be quadratic in $n$.
edit: A comment has been raised on how to calculate $p(X_n \leq M_{n-1})$. Since $X_n, M_{n-1}$ can each only take on one of six values, we can just sum over all possibilities:
$$p(X_n \leq M_{n-1}) = \sum_{a,b} p(X_n = a, M_{n-1} = b, a \leq b)$$
Similarly, $p(X_n = k | X_n > M_{n-1})$ can be calculated by applying Bayes rule then summing over the possible values of $X_n, M_{n-1}$. | Formula for dropping dice (non-brute force)
Edit: @SkySpiral has had trouble getting the below formula to work. I currently don't have time to work out what the issue is, so if you're reading this it's best to proceed under the assumption it's |
17,556 | Formula for dropping dice (non-brute force) | I have a reasonably efficient algorithm for this that, on testing, seems to match results of pure brute force while relying less heavily on enumerating all possibilities. It's actually more generalized than the above problem of 4d6, drop 1.
Some notation first: Let $X_NdY$ indicate that you are rolling $X$ dice with $Y$ faces (integer values $1$ to $Y$), and considering only the highest $N$ dice rolled. The output is a sequence of dice values, e.g. $4_3d6$ yields $3, 4, 5$ if you rolled $1, 3, 4, 5$ on the four dice. (Note that I'm calling it a "sequence," but the order is not important here, particularly since all we care about in the end is the sum of the sequence.)
The probability $P(X_NdY = S)$ (or more specifically, $P(4_3d6 = S)$) is a simplified version of the original problem, where we are only considering a specific set of dice, and not all possible sets that add up to a given sum.
Suppose $S$ has $k$ distinct values, $s_0, s_1, ..., s_k$, such that $s_i > s_{i+1}$, and each $s_i$ has a count of $c_i$. For example, if $S = 3, 4, 4, 5$, then $(s_0,c_0) = (5,1)$, $(s_1,c_1) = (4,2)$, and $(s_2,c_2) = (3,1)$.
You can calculate $P(X_NdY = S)$ in the following way:
$$ P(X_NdY = S) = \frac{ \left( \prod_{i=0}^{k-1} {X - \sum_{h=0}^{i-1} c_h \choose c_i} \right) \left( \sum_{j=0}^{X-N} { c_k+X-N \choose c_k+X-N-j} (s_k-1)^j \right)}{ Y^X }$$
That's pretty messy, I know.
The product expression $\prod_{i=0}^{k-1}$ is iterating through all but the lowest of the values in $S$, and calculating all the ways those values may be distributed among the dice. For $s_0$, that's just $X \choose c_i$, but for $s_1$, we have to remove the $c_0$ dice that have already been set aside for $s_0$, and likewise for $s_i$ you must remove $\sum_{h=0}^{i-1}c_h$.
The sum expression $\sum_{j=0}^{X-N}$ is iterating through all the possibilities of how many of the dropped dice were equal to $s_k$, since that affects the possible combinations for the un-dropped dice with $s_k$ as their value.
By example, let's consider $P[4_3d6=(5,4,4)]$:
$$ (s_1, c_1) = (5, 1) $$
$$ (s_2, c_2) = (4, 2) $$
So using the formula above:
$$ P[4_3d6=(5,4,4)] \\
= \frac{ {4 \choose 1} \left( {3 \choose 3} \cdot 3^0 + {3 \choose 2} \cdot 3^1 \right) }{ 6^4 } \\
= \frac{5}{162} = 0.0\overline{308641975}$$
The formula breaks down on a domain issue when $s_k=1$ and $j=0$ in the summation, leading to a first term of $0^0$, which is indeterminate and needs to be treated as $1$. In such a case, a summation is not actually necessary at all, and can be omitted, since all the dropped dice will also have a value of $s_k = 1$.
Now here's where I do need to rely on some brute force. The original problem was to calculate the probability of the sum being some value, and $X_NdY$ represents the individual dice left after dropping. This means you must add up the probabilities for all possible sequences $S$ (ignoring ordering) whose sum is the given value. Perhaps there is a formula to calculate this across all such values of $S$ at once, but I haven't even tried broaching that yet.
I've implemented this in Python first, and the above is an attempt to express it mathematically. My Python algorithm is accurate and reasonably efficient. There are some optimizations that could be made for the case of calculating the entire distribution of $\sum X_NdY$, and maybe I'll do that later. | Formula for dropping dice (non-brute force) | I have a reasonably efficient algorithm for this that, on testing, seems to match results of pure brute force while relying less heavily on enumerating all possibilities. It's actually more generalize | Formula for dropping dice (non-brute force)
I have a reasonably efficient algorithm for this that, on testing, seems to match results of pure brute force while relying less heavily on enumerating all possibilities. It's actually more generalized than the above problem of 4d6, drop 1.
Some notation first: Let $X_NdY$ indicate that you are rolling $X$ dice with $Y$ faces (integer values $1$ to $Y$), and considering only the highest $N$ dice rolled. The output is a sequence of dice values, e.g. $4_3d6$ yields $3, 4, 5$ if you rolled $1, 3, 4, 5$ on the four dice. (Note that I'm calling it a "sequence," but the order is not important here, particularly since all we care about in the end is the sum of the sequence.)
The probability $P(X_NdY = S)$ (or more specifically, $P(4_3d6 = S)$) is a simplified version of the original problem, where we are only considering a specific set of dice, and not all possible sets that add up to a given sum.
Suppose $S$ has $k$ distinct values, $s_0, s_1, ..., s_k$, such that $s_i > s_{i+1}$, and each $s_i$ has a count of $c_i$. For example, if $S = 3, 4, 4, 5$, then $(s_0,c_0) = (5,1)$, $(s_1,c_1) = (4,2)$, and $(s_2,c_2) = (3,1)$.
You can calculate $P(X_NdY = S)$ in the following way:
$$ P(X_NdY = S) = \frac{ \left( \prod_{i=0}^{k-1} {X - \sum_{h=0}^{i-1} c_h \choose c_i} \right) \left( \sum_{j=0}^{X-N} { c_k+X-N \choose c_k+X-N-j} (s_k-1)^j \right)}{ Y^X }$$
That's pretty messy, I know.
The product expression $\prod_{i=0}^{k-1}$ is iterating through all but the lowest of the values in $S$, and calculating all the ways those values may be distributed among the dice. For $s_0$, that's just $X \choose c_i$, but for $s_1$, we have to remove the $c_0$ dice that have already been set aside for $s_0$, and likewise for $s_i$ you must remove $\sum_{h=0}^{i-1}c_h$.
The sum expression $\sum_{j=0}^{X-N}$ is iterating through all the possibilities of how many of the dropped dice were equal to $s_k$, since that affects the possible combinations for the un-dropped dice with $s_k$ as their value.
By example, let's consider $P[4_3d6=(5,4,4)]$:
$$ (s_1, c_1) = (5, 1) $$
$$ (s_2, c_2) = (4, 2) $$
So using the formula above:
$$ P[4_3d6=(5,4,4)] \\
= \frac{ {4 \choose 1} \left( {3 \choose 3} \cdot 3^0 + {3 \choose 2} \cdot 3^1 \right) }{ 6^4 } \\
= \frac{5}{162} = 0.0\overline{308641975}$$
The formula breaks down on a domain issue when $s_k=1$ and $j=0$ in the summation, leading to a first term of $0^0$, which is indeterminate and needs to be treated as $1$. In such a case, a summation is not actually necessary at all, and can be omitted, since all the dropped dice will also have a value of $s_k = 1$.
Now here's where I do need to rely on some brute force. The original problem was to calculate the probability of the sum being some value, and $X_NdY$ represents the individual dice left after dropping. This means you must add up the probabilities for all possible sequences $S$ (ignoring ordering) whose sum is the given value. Perhaps there is a formula to calculate this across all such values of $S$ at once, but I haven't even tried broaching that yet.
I've implemented this in Python first, and the above is an attempt to express it mathematically. My Python algorithm is accurate and reasonably efficient. There are some optimizations that could be made for the case of calculating the entire distribution of $\sum X_NdY$, and maybe I'll do that later. | Formula for dropping dice (non-brute force)
I have a reasonably efficient algorithm for this that, on testing, seems to match results of pure brute force while relying less heavily on enumerating all possibilities. It's actually more generalize |
17,557 | Formula for dropping dice (non-brute force) | whuber's fast Fourier transform is fantastically efficient. However, I'm going to take another angle at the problem. Let's go back to the beginning:
Why might one think this problem is NP-complete?
If the result of the roll is allowed to depend on the entire sequence of individual dice, then each of the $d^n$ possible rolls must be considered, which results in an exponential number of evaluations. If we only consider the multiset of dice rolls (or equivalently, the possible sorted sequences that could result from the roll), then this reduces to $\binom{n + d - 1}{d - 1}$, which is still exponential if both the number of dice $n$ and die size $d$ are both allowed to increase linearly. If $d$ is fixed, then this becomes polynomial---though of order $d - 1$, which can be quite large if the dice have many faces, explode, or are themselves the result of other computations, e.g. a "die" with faces 3 to 18 representing a D&D ability score.
Of course, as whuber's answer shows, the problem is well within P. How can this be? We are not evaluating an arbitrary function over the dice rolls; rather, the action of dropping the lowest and taking the sum has structure that we can exploit using convolution and FFTs.
This raises the question: is there some more general type of structure that we can exploit in some way?
"Single-pass" functions over order statistics
Consider this procedure for evaulating the roll of a dice pool. I first encountered the seeds of this idea in this answer by Ilmari Karonen, and similar ideas were also used in this paper.
First, I tell you how many ones you rolled.
Then, I tell you how many twos you rolled.
Then, I tell you how many threes you rolled.
Then, I tell you how many fours you rolled.
Then, I tell you how many fives you rolled.
Then, I tell you how many sixes you rolled.
You're allowed to remember things between each step, typically a "running total" of some sort, ideally without too many distinct possibilities.
Or in terms of Python code with a transition function next_state:
state = None
state = next_state(state, 1, num_ones)
state = next_state(state, 2, num_twos)
state = next_state(state, 3, num_threes)
state = next_state(state, 4, num_fours)
state = next_state(state, 5, num_fives)
state = next_state(state, 6, num_sixes)
For example, if we wanted to find the sum of the dice, we could use the transition function
def next_state(state, outcome, count):
if state is None:
return outcome * count
else:
return state + outcome * count
What about dropping dice? We can augment the state with a "count-list", and whenever we decide that $k$ dice rolled the current outcome, we pop $k$ elements off the list and use them to determine how many of those dice should contribute. Thus, this formulation also covers SkySpiral7's follow-up question where two dice are dropped, or if an arbitrary number of dice are dropped (granted, not in the form of a generating function). In fact, we can count each sorted position multiple times, or even a negative number of times.
The algorithm
The key to the algorithm's efficiency is dynamic programming. To find the probability distribution for a dice pool of $\ell$ outcomes per die and $n$ dice, the algorithm recursively uses memoized solutions for dice pools of $\ell-1$ outcomes per die and $0 \ldots n$ dice. For example, to compute the solution to a pool of 4d6, we use memoized solutions to pools of 0d5, 1d5, 2d5, 3d5, and 4d5.
Specifically, in each call we pop the greatest outcome from the die, and then for $k = 0 \ldots n$:
Compute how many ways there are for $k$ out of $n$ dice to roll the current outcome. This is just the binomial coefficient $\binom{n}{k}$. These coefficients can be efficiently computed and memoized using Pascal's triangle.
Recursively compute the solution for a pool with the current outcome removed from the die, and $n - k$ dice in the pool.
For each state in the recursive distribution, apply the transition function, giving the current outcome and $k$ as the other arguments. Then add the resulting state to the output distribution with weight equal to its recursive weight times the binomial coefficient.
If the last remaining outcome is popped, all $n$ dice must roll that outcome, leading to the base case of a die with an empty set of outcomes and 0 dice in the pool. This is considered to produce a distribution consisting of just the state None (Python's null value) with weight 1.
Here is sample Python code for the basic algorithm:
@cache
def solve(die, n):
outcome, die = die.pop()
if len(die) == 0:
state = next_state(None, outcome, n)
return {state : 1}
result = defaultdict(int)
for k in range(n + 1):
tail = solve(die, n - k)
for state, weight in tail.items():
state = next_state(state, outcome, k)
weight *= comb(n, k)
result[state] += weight
return result
Here is an example call graph:
Vertexes are unique calls. Since the algorithm is memoized, the state distribution at each vertex will be computed exactly once.
Edges are all calls. Each edge has weight equal to a binomial coefficient.
Each path from a vertex to the sink (base case) corresponds one-to-one with a possible sorted sequence of dice rolls of the starting vertex's dice pool. The product of the weights of the edges on the path is the weight of rolling that sorted sequence. This is equivalent to the decomposition of a multinomial coefficient as the product of binomial coefficients.
While not as fast as the FFT, this dynamic programming approach is much more flexible while remaining reasonably efficient over a variety of dice mechanics: the number of unique calls is $O\left(n^2d\right)$, times some hopefully small number of states and time needed to transition each state and accumulate weights. By changing the transition function, we can do things like finding the size and outcome of the largest matching set:
def next_state(state, outcome, count):
if state is None:
return count, outcome
else:
return max(state, (count, outcome))
Or other things such as looking for straights, evaluating RISK-like mechanics, and more.
Further reading
If you would like to know more, you can read my paper on the subject:
title={Icepool: Efficient Computation of Dice Pool Probabilities},
author={Albert Julius Liu},
booktitle={Eighteenth AAAI Conference on Artificial Intelligence and Interactive Digital Entertainment},
volume={18},
number={1},
pages={258-265},
year={2022},
month={Oct.},
eventdate={2022-10-24/2022-10-28},
venue={Pomona, California},
url={https://ojs.aaai.org/index.php/AIIDE/article/view/21971},
doi={10.1609/aiide.v18i1.21971}
Or try out my Icepool implementation, which includes several demo web apps and JupyterLite notebooks. For the particular problem of drop-lowest, you can try my Cortex Prime calculator, which will compute the probability distribution of the sum of a (possibly mixed) pool of standard dice. | Formula for dropping dice (non-brute force) | whuber's fast Fourier transform is fantastically efficient. However, I'm going to take another angle at the problem. Let's go back to the beginning:
Why might one think this problem is NP-complete?
If | Formula for dropping dice (non-brute force)
whuber's fast Fourier transform is fantastically efficient. However, I'm going to take another angle at the problem. Let's go back to the beginning:
Why might one think this problem is NP-complete?
If the result of the roll is allowed to depend on the entire sequence of individual dice, then each of the $d^n$ possible rolls must be considered, which results in an exponential number of evaluations. If we only consider the multiset of dice rolls (or equivalently, the possible sorted sequences that could result from the roll), then this reduces to $\binom{n + d - 1}{d - 1}$, which is still exponential if both the number of dice $n$ and die size $d$ are both allowed to increase linearly. If $d$ is fixed, then this becomes polynomial---though of order $d - 1$, which can be quite large if the dice have many faces, explode, or are themselves the result of other computations, e.g. a "die" with faces 3 to 18 representing a D&D ability score.
Of course, as whuber's answer shows, the problem is well within P. How can this be? We are not evaluating an arbitrary function over the dice rolls; rather, the action of dropping the lowest and taking the sum has structure that we can exploit using convolution and FFTs.
This raises the question: is there some more general type of structure that we can exploit in some way?
"Single-pass" functions over order statistics
Consider this procedure for evaulating the roll of a dice pool. I first encountered the seeds of this idea in this answer by Ilmari Karonen, and similar ideas were also used in this paper.
First, I tell you how many ones you rolled.
Then, I tell you how many twos you rolled.
Then, I tell you how many threes you rolled.
Then, I tell you how many fours you rolled.
Then, I tell you how many fives you rolled.
Then, I tell you how many sixes you rolled.
You're allowed to remember things between each step, typically a "running total" of some sort, ideally without too many distinct possibilities.
Or in terms of Python code with a transition function next_state:
state = None
state = next_state(state, 1, num_ones)
state = next_state(state, 2, num_twos)
state = next_state(state, 3, num_threes)
state = next_state(state, 4, num_fours)
state = next_state(state, 5, num_fives)
state = next_state(state, 6, num_sixes)
For example, if we wanted to find the sum of the dice, we could use the transition function
def next_state(state, outcome, count):
if state is None:
return outcome * count
else:
return state + outcome * count
What about dropping dice? We can augment the state with a "count-list", and whenever we decide that $k$ dice rolled the current outcome, we pop $k$ elements off the list and use them to determine how many of those dice should contribute. Thus, this formulation also covers SkySpiral7's follow-up question where two dice are dropped, or if an arbitrary number of dice are dropped (granted, not in the form of a generating function). In fact, we can count each sorted position multiple times, or even a negative number of times.
The algorithm
The key to the algorithm's efficiency is dynamic programming. To find the probability distribution for a dice pool of $\ell$ outcomes per die and $n$ dice, the algorithm recursively uses memoized solutions for dice pools of $\ell-1$ outcomes per die and $0 \ldots n$ dice. For example, to compute the solution to a pool of 4d6, we use memoized solutions to pools of 0d5, 1d5, 2d5, 3d5, and 4d5.
Specifically, in each call we pop the greatest outcome from the die, and then for $k = 0 \ldots n$:
Compute how many ways there are for $k$ out of $n$ dice to roll the current outcome. This is just the binomial coefficient $\binom{n}{k}$. These coefficients can be efficiently computed and memoized using Pascal's triangle.
Recursively compute the solution for a pool with the current outcome removed from the die, and $n - k$ dice in the pool.
For each state in the recursive distribution, apply the transition function, giving the current outcome and $k$ as the other arguments. Then add the resulting state to the output distribution with weight equal to its recursive weight times the binomial coefficient.
If the last remaining outcome is popped, all $n$ dice must roll that outcome, leading to the base case of a die with an empty set of outcomes and 0 dice in the pool. This is considered to produce a distribution consisting of just the state None (Python's null value) with weight 1.
Here is sample Python code for the basic algorithm:
@cache
def solve(die, n):
outcome, die = die.pop()
if len(die) == 0:
state = next_state(None, outcome, n)
return {state : 1}
result = defaultdict(int)
for k in range(n + 1):
tail = solve(die, n - k)
for state, weight in tail.items():
state = next_state(state, outcome, k)
weight *= comb(n, k)
result[state] += weight
return result
Here is an example call graph:
Vertexes are unique calls. Since the algorithm is memoized, the state distribution at each vertex will be computed exactly once.
Edges are all calls. Each edge has weight equal to a binomial coefficient.
Each path from a vertex to the sink (base case) corresponds one-to-one with a possible sorted sequence of dice rolls of the starting vertex's dice pool. The product of the weights of the edges on the path is the weight of rolling that sorted sequence. This is equivalent to the decomposition of a multinomial coefficient as the product of binomial coefficients.
While not as fast as the FFT, this dynamic programming approach is much more flexible while remaining reasonably efficient over a variety of dice mechanics: the number of unique calls is $O\left(n^2d\right)$, times some hopefully small number of states and time needed to transition each state and accumulate weights. By changing the transition function, we can do things like finding the size and outcome of the largest matching set:
def next_state(state, outcome, count):
if state is None:
return count, outcome
else:
return max(state, (count, outcome))
Or other things such as looking for straights, evaluating RISK-like mechanics, and more.
Further reading
If you would like to know more, you can read my paper on the subject:
title={Icepool: Efficient Computation of Dice Pool Probabilities},
author={Albert Julius Liu},
booktitle={Eighteenth AAAI Conference on Artificial Intelligence and Interactive Digital Entertainment},
volume={18},
number={1},
pages={258-265},
year={2022},
month={Oct.},
eventdate={2022-10-24/2022-10-28},
venue={Pomona, California},
url={https://ojs.aaai.org/index.php/AIIDE/article/view/21971},
doi={10.1609/aiide.v18i1.21971}
Or try out my Icepool implementation, which includes several demo web apps and JupyterLite notebooks. For the particular problem of drop-lowest, you can try my Cortex Prime calculator, which will compute the probability distribution of the sum of a (possibly mixed) pool of standard dice. | Formula for dropping dice (non-brute force)
whuber's fast Fourier transform is fantastically efficient. However, I'm going to take another angle at the problem. Let's go back to the beginning:
Why might one think this problem is NP-complete?
If |
17,558 | dispersion in summary.glm() | Firstly, you should not use summary.glm on an object of class "negbin". If you look at the function code for summary.glm, right at the top you'll see the computation of the dispersion. Note that summary.glm only knows about models that can be fitted by glm and hence it singles out the binomial and Poisson families for special treatment, where the dispersion parameter $\phi$ is assumed to be equal to 1. For models other than these, $\phi$ is computed from the model object, but note that this is based on an assumption that this is appropriate for a family that is not binomial or Poisson. The family for the model fitted by glm.nb is "Negative Binomial(theta)". Hence when you use summary.glm on the model fitted by glm.nb, the in code
if (is.null(dispersion))
dispersion <- if (object$family$family %in% c("poisson",
"binomial"))
1
else if (df.r > 0) {
est.disp <- TRUE
if (any(object$weights == 0))
warning("observations with zero weight not used for calculating dispersion")
sum((object$weights * object$residuals^2)[object$weights >
0])/df.r
}
the test for "poisson" or "binomial" fails and it then computes $\phi$ where in actual fact it is assumed to be equal to 1 by default for this family (as per the definition of summary.negbin.
There is no problem with this, it is just simpler to call the correct method and supply a different value for $\phi$ via argument dispersion.
Secondly, you misunderstand the output. When you see
Negative Binomial(0.7109)
as I alluded to above, the number quoted in parentheses is $\hat{\theta}$, the parameter of the Negative Binomial distribution. This value is that estimated during fitting. It is not $\phi$, the dispersion parameter, and hence the two numbers should not necessarily be equal; they are just two numbers.
As the computed dispersion $\phi$ (following the code I quote above) is pretty close to one (~0.95), the assumption that $\phi = 1$ used for the standard errors is not too bad in summary.negbin. You could of course, just do
summary(glm1, dispersion = 0.9509)
and get the additional output that the negbin method gives you, plus the computed rather than assumed value of $\phi$. | dispersion in summary.glm() | Firstly, you should not use summary.glm on an object of class "negbin". If you look at the function code for summary.glm, right at the top you'll see the computation of the dispersion. Note that summa | dispersion in summary.glm()
Firstly, you should not use summary.glm on an object of class "negbin". If you look at the function code for summary.glm, right at the top you'll see the computation of the dispersion. Note that summary.glm only knows about models that can be fitted by glm and hence it singles out the binomial and Poisson families for special treatment, where the dispersion parameter $\phi$ is assumed to be equal to 1. For models other than these, $\phi$ is computed from the model object, but note that this is based on an assumption that this is appropriate for a family that is not binomial or Poisson. The family for the model fitted by glm.nb is "Negative Binomial(theta)". Hence when you use summary.glm on the model fitted by glm.nb, the in code
if (is.null(dispersion))
dispersion <- if (object$family$family %in% c("poisson",
"binomial"))
1
else if (df.r > 0) {
est.disp <- TRUE
if (any(object$weights == 0))
warning("observations with zero weight not used for calculating dispersion")
sum((object$weights * object$residuals^2)[object$weights >
0])/df.r
}
the test for "poisson" or "binomial" fails and it then computes $\phi$ where in actual fact it is assumed to be equal to 1 by default for this family (as per the definition of summary.negbin.
There is no problem with this, it is just simpler to call the correct method and supply a different value for $\phi$ via argument dispersion.
Secondly, you misunderstand the output. When you see
Negative Binomial(0.7109)
as I alluded to above, the number quoted in parentheses is $\hat{\theta}$, the parameter of the Negative Binomial distribution. This value is that estimated during fitting. It is not $\phi$, the dispersion parameter, and hence the two numbers should not necessarily be equal; they are just two numbers.
As the computed dispersion $\phi$ (following the code I quote above) is pretty close to one (~0.95), the assumption that $\phi = 1$ used for the standard errors is not too bad in summary.negbin. You could of course, just do
summary(glm1, dispersion = 0.9509)
and get the additional output that the negbin method gives you, plus the computed rather than assumed value of $\phi$. | dispersion in summary.glm()
Firstly, you should not use summary.glm on an object of class "negbin". If you look at the function code for summary.glm, right at the top you'll see the computation of the dispersion. Note that summa |
17,559 | dispersion in summary.glm() | From Venables & Ripley (2002), Modern Applied Statistics with S: 'Theta' defines a gamma distribution with shape $\theta$ & scale $\frac{1}{\theta}$, hence mean $1$ & variance $\frac{1}{\theta}$. Let $E$ be a random variable with this distribution; a response $Y$ is distributed conditionally on $E$ as Poisson with mean $\mu E$, where $\mu$ is a function of the predictors & coefficients depending on your choice of link. Marginally, its distribution is negative binomial, with mass function
$$
f(y)=\frac{\Gamma(\theta +y)}{\Gamma(\theta) y!}\cdot\frac{\mu^y \theta^\theta}{(\mu+\theta)^{\theta+y}}
$$
expectation
$$\operatorname{E}Y=\mu$$
& variance
$$\operatorname{Var} Y = \mu +\frac{\mu^2}{\theta}$$
As @Momo points out, the dispersion parameter is another thing entirely, which you'd let vary to do quasi-likelihood estimation. For the negative binomial model & the (true) Poisson model, it's rightly fixed to a value of one. | dispersion in summary.glm() | From Venables & Ripley (2002), Modern Applied Statistics with S: 'Theta' defines a gamma distribution with shape $\theta$ & scale $\frac{1}{\theta}$, hence mean $1$ & variance $\frac{1}{\theta}$. Let | dispersion in summary.glm()
From Venables & Ripley (2002), Modern Applied Statistics with S: 'Theta' defines a gamma distribution with shape $\theta$ & scale $\frac{1}{\theta}$, hence mean $1$ & variance $\frac{1}{\theta}$. Let $E$ be a random variable with this distribution; a response $Y$ is distributed conditionally on $E$ as Poisson with mean $\mu E$, where $\mu$ is a function of the predictors & coefficients depending on your choice of link. Marginally, its distribution is negative binomial, with mass function
$$
f(y)=\frac{\Gamma(\theta +y)}{\Gamma(\theta) y!}\cdot\frac{\mu^y \theta^\theta}{(\mu+\theta)^{\theta+y}}
$$
expectation
$$\operatorname{E}Y=\mu$$
& variance
$$\operatorname{Var} Y = \mu +\frac{\mu^2}{\theta}$$
As @Momo points out, the dispersion parameter is another thing entirely, which you'd let vary to do quasi-likelihood estimation. For the negative binomial model & the (true) Poisson model, it's rightly fixed to a value of one. | dispersion in summary.glm()
From Venables & Ripley (2002), Modern Applied Statistics with S: 'Theta' defines a gamma distribution with shape $\theta$ & scale $\frac{1}{\theta}$, hence mean $1$ & variance $\frac{1}{\theta}$. Let |
17,560 | Wilcoxon rank sum test in R | The Note in the help on the wilcox.test function clearly explains why R's value is smaller than yours:
Note
The literature is not unanimous about the definitions of the Wilcoxon rank sum and Mann-Whitney tests. The two most common definitions correspond to the sum of the ranks of the first sample with the minimum value subtracted or not: R subtracts and S-PLUS does not, giving a value which is larger by m(m+1)/2 for a first sample of size m. (It seems Wilcoxon's original paper used the unadjusted sum of the ranks but subsequent tables subtracted the minimum.)
That is, the definition R uses is $n_1(n_1+1)/2$ smaller than the version you use, where $n_1$ is the number of observations in the first sample.
As for modifying the result, you could assign the output from wilcox.test into a variable, say a, and then manipulate a$statistic - adding the minimum to its value and changing its name. Then when you print a (e.g. by typing a), it will look the way you want.
To see what I am getting at, try this:
a <- wilcox.test(x,y,correct=FALSE)
str(a)
So for example if you do this:
n1 <- length(x)
a$statistic <- a$statistic + n1*(n1+1)/2
names(a$statistic) <- "T.W"
a
then you get:
Wilcoxon rank sum test with continuity correction
data: x and y
T.W = 156.5, p-value = 0.006768
alternative hypothesis: true location shift is not equal to 0
It's quite common to refer to the rank sum test (whether shifted by $n_1(n_1+1)/2$ or not) as either $W$ or $w$ or some close variant (e.g. here or here). It also often gets called '$U$' because of Mann & Whitney. There's plenty of precedent for using $W$, so for myself I wouldn't bother with the line that changes the name of the statistic, but if it suits you to do so there's no reason why you shouldn't, either. | Wilcoxon rank sum test in R | The Note in the help on the wilcox.test function clearly explains why R's value is smaller than yours:
Note
The literature is not unanimous about the definitions of the Wilcoxon rank sum and Mann-Wh | Wilcoxon rank sum test in R
The Note in the help on the wilcox.test function clearly explains why R's value is smaller than yours:
Note
The literature is not unanimous about the definitions of the Wilcoxon rank sum and Mann-Whitney tests. The two most common definitions correspond to the sum of the ranks of the first sample with the minimum value subtracted or not: R subtracts and S-PLUS does not, giving a value which is larger by m(m+1)/2 for a first sample of size m. (It seems Wilcoxon's original paper used the unadjusted sum of the ranks but subsequent tables subtracted the minimum.)
That is, the definition R uses is $n_1(n_1+1)/2$ smaller than the version you use, where $n_1$ is the number of observations in the first sample.
As for modifying the result, you could assign the output from wilcox.test into a variable, say a, and then manipulate a$statistic - adding the minimum to its value and changing its name. Then when you print a (e.g. by typing a), it will look the way you want.
To see what I am getting at, try this:
a <- wilcox.test(x,y,correct=FALSE)
str(a)
So for example if you do this:
n1 <- length(x)
a$statistic <- a$statistic + n1*(n1+1)/2
names(a$statistic) <- "T.W"
a
then you get:
Wilcoxon rank sum test with continuity correction
data: x and y
T.W = 156.5, p-value = 0.006768
alternative hypothesis: true location shift is not equal to 0
It's quite common to refer to the rank sum test (whether shifted by $n_1(n_1+1)/2$ or not) as either $W$ or $w$ or some close variant (e.g. here or here). It also often gets called '$U$' because of Mann & Whitney. There's plenty of precedent for using $W$, so for myself I wouldn't bother with the line that changes the name of the statistic, but if it suits you to do so there's no reason why you shouldn't, either. | Wilcoxon rank sum test in R
The Note in the help on the wilcox.test function clearly explains why R's value is smaller than yours:
Note
The literature is not unanimous about the definitions of the Wilcoxon rank sum and Mann-Wh |
17,561 | Random forest and prediction | Each tree in the forest is built from a bootstrap sample of the observations in your training data. Those observations in the bootstrap sample build the tree, whilst those not in the bootstrap sample form the out-of-bag (or OOB) samples.
It should be clear that the same variables are available for cases in the data used to build a tree as for the cases in the OOB sample. To get predictions for the OOB sample, each one is passed down the current tree and the rules for the tree followed until it arrives in a terminal node. That yields the OOB predictions for that particular tree.
This process is repeated a large number of times, each tree trained on a new bootstrap sample from the training data and predictions for the new OOB samples derived.
As the number of trees grows, any one sample will be in the OOB samples more than once, thus the "average" of the predictions over the N trees where a sample is in the OOB is used as the OOB prediction for each training sample for trees 1, ..., N. By "average" we use the mean of the predictions for a continuous response, or the majority vote may be used for a categorical response (the majority vote is the class with most votes over the set of trees 1, ..., N).
For example, assume we had the following OOB predictions for 10 samples in training set on 10 trees
set.seed(123)
oob.p <- matrix(rpois(100, lambda = 4), ncol = 10)
colnames(oob.p) <- paste0("tree", seq_len(ncol(oob.p)))
rownames(oob.p) <- paste0("samp", seq_len(nrow(oob.p)))
oob.p[sample(length(oob.p), 50)] <- NA
oob.p
> oob.p
tree1 tree2 tree3 tree4 tree5 tree6 tree7 tree8 tree9 tree10
samp1 NA NA 7 8 2 1 NA 5 3 2
samp2 6 NA 5 7 3 NA NA NA NA NA
samp3 3 NA 5 NA NA NA 3 5 NA NA
samp4 6 NA 10 6 NA NA 3 NA 6 NA
samp5 NA 2 NA NA 2 NA 6 4 NA NA
samp6 NA 7 NA 4 NA 2 4 2 NA NA
samp7 NA NA NA 5 NA NA NA 3 9 5
samp8 7 1 4 NA NA 5 6 NA 7 NA
samp9 4 NA NA 3 NA 7 6 3 NA NA
samp10 4 8 2 2 NA NA 4 NA NA 4
Where NA means the sample was in the training data for that tree (in other words it was not in the OOB sample).
The mean of the non-NA values for each row gives the the OOB prediction for each sample, for the entire forest
> rowMeans(oob.p, na.rm = TRUE)
samp1 samp2 samp3 samp4 samp5 samp6 samp7 samp8 samp9 samp10
4.00 5.25 4.00 6.20 3.50 3.80 5.50 5.00 4.60 4.00
As each tree is added to the forest, we can compute the OOB error up to an including that tree. For example, below are the cummulative means for each sample:
FUN <- function(x) {
na <- is.na(x)
cs <- cumsum(x[!na]) / seq_len(sum(!na))
x[!na] <- cs
x
}
t(apply(oob.p, 1, FUN))
> print(t(apply(oob.p, 1, FUN)), digits = 3)
tree1 tree2 tree3 tree4 tree5 tree6 tree7 tree8 tree9 tree10
samp1 NA NA 7.00 7.50 5.67 4.50 NA 4.6 4.33 4.0
samp2 6 NA 5.50 6.00 5.25 NA NA NA NA NA
samp3 3 NA 4.00 NA NA NA 3.67 4.0 NA NA
samp4 6 NA 8.00 7.33 NA NA 6.25 NA 6.20 NA
samp5 NA 2 NA NA 2.00 NA 3.33 3.5 NA NA
samp6 NA 7 NA 5.50 NA 4.33 4.25 3.8 NA NA
samp7 NA NA NA 5.00 NA NA NA 4.0 5.67 5.5
samp8 7 4 4.00 NA NA 4.25 4.60 NA 5.00 NA
samp9 4 NA NA 3.50 NA 4.67 5.00 4.6 NA NA
samp10 4 6 4.67 4.00 NA NA 4.00 NA NA 4.0
In this way we see how the prediction is accumulated over the N trees in the forest up to a given iteration. If you read across the rows, the right-most non-NA value is the one I show above for the OOB prediction. That is how traces of OOB performance can be made - a RMSEP can be computed for the OOB samples based on the OOB predictions accumulated cumulatively over the N trees.
Note that the R code shown is not take from the internals of the randomForest code in the randomForest package for R - I just knocked up some simple code so that you can follow what is going on once the predictions from each tree are determined.
It is because each tree is built from a bootstrap sample and that there are a large number of trees in a random forest, such that each training set observation is in the OOB sample for one or more trees, that OOB predictions can be provided for all samples in the training data.
I have glossed over issues such as missing data for some OOB cases etc, but these issues also pertain to a single regression or classification tree. Also note that each tree in a forest uses only mtry randomly-selected variables. | Random forest and prediction | Each tree in the forest is built from a bootstrap sample of the observations in your training data. Those observations in the bootstrap sample build the tree, whilst those not in the bootstrap sample | Random forest and prediction
Each tree in the forest is built from a bootstrap sample of the observations in your training data. Those observations in the bootstrap sample build the tree, whilst those not in the bootstrap sample form the out-of-bag (or OOB) samples.
It should be clear that the same variables are available for cases in the data used to build a tree as for the cases in the OOB sample. To get predictions for the OOB sample, each one is passed down the current tree and the rules for the tree followed until it arrives in a terminal node. That yields the OOB predictions for that particular tree.
This process is repeated a large number of times, each tree trained on a new bootstrap sample from the training data and predictions for the new OOB samples derived.
As the number of trees grows, any one sample will be in the OOB samples more than once, thus the "average" of the predictions over the N trees where a sample is in the OOB is used as the OOB prediction for each training sample for trees 1, ..., N. By "average" we use the mean of the predictions for a continuous response, or the majority vote may be used for a categorical response (the majority vote is the class with most votes over the set of trees 1, ..., N).
For example, assume we had the following OOB predictions for 10 samples in training set on 10 trees
set.seed(123)
oob.p <- matrix(rpois(100, lambda = 4), ncol = 10)
colnames(oob.p) <- paste0("tree", seq_len(ncol(oob.p)))
rownames(oob.p) <- paste0("samp", seq_len(nrow(oob.p)))
oob.p[sample(length(oob.p), 50)] <- NA
oob.p
> oob.p
tree1 tree2 tree3 tree4 tree5 tree6 tree7 tree8 tree9 tree10
samp1 NA NA 7 8 2 1 NA 5 3 2
samp2 6 NA 5 7 3 NA NA NA NA NA
samp3 3 NA 5 NA NA NA 3 5 NA NA
samp4 6 NA 10 6 NA NA 3 NA 6 NA
samp5 NA 2 NA NA 2 NA 6 4 NA NA
samp6 NA 7 NA 4 NA 2 4 2 NA NA
samp7 NA NA NA 5 NA NA NA 3 9 5
samp8 7 1 4 NA NA 5 6 NA 7 NA
samp9 4 NA NA 3 NA 7 6 3 NA NA
samp10 4 8 2 2 NA NA 4 NA NA 4
Where NA means the sample was in the training data for that tree (in other words it was not in the OOB sample).
The mean of the non-NA values for each row gives the the OOB prediction for each sample, for the entire forest
> rowMeans(oob.p, na.rm = TRUE)
samp1 samp2 samp3 samp4 samp5 samp6 samp7 samp8 samp9 samp10
4.00 5.25 4.00 6.20 3.50 3.80 5.50 5.00 4.60 4.00
As each tree is added to the forest, we can compute the OOB error up to an including that tree. For example, below are the cummulative means for each sample:
FUN <- function(x) {
na <- is.na(x)
cs <- cumsum(x[!na]) / seq_len(sum(!na))
x[!na] <- cs
x
}
t(apply(oob.p, 1, FUN))
> print(t(apply(oob.p, 1, FUN)), digits = 3)
tree1 tree2 tree3 tree4 tree5 tree6 tree7 tree8 tree9 tree10
samp1 NA NA 7.00 7.50 5.67 4.50 NA 4.6 4.33 4.0
samp2 6 NA 5.50 6.00 5.25 NA NA NA NA NA
samp3 3 NA 4.00 NA NA NA 3.67 4.0 NA NA
samp4 6 NA 8.00 7.33 NA NA 6.25 NA 6.20 NA
samp5 NA 2 NA NA 2.00 NA 3.33 3.5 NA NA
samp6 NA 7 NA 5.50 NA 4.33 4.25 3.8 NA NA
samp7 NA NA NA 5.00 NA NA NA 4.0 5.67 5.5
samp8 7 4 4.00 NA NA 4.25 4.60 NA 5.00 NA
samp9 4 NA NA 3.50 NA 4.67 5.00 4.6 NA NA
samp10 4 6 4.67 4.00 NA NA 4.00 NA NA 4.0
In this way we see how the prediction is accumulated over the N trees in the forest up to a given iteration. If you read across the rows, the right-most non-NA value is the one I show above for the OOB prediction. That is how traces of OOB performance can be made - a RMSEP can be computed for the OOB samples based on the OOB predictions accumulated cumulatively over the N trees.
Note that the R code shown is not take from the internals of the randomForest code in the randomForest package for R - I just knocked up some simple code so that you can follow what is going on once the predictions from each tree are determined.
It is because each tree is built from a bootstrap sample and that there are a large number of trees in a random forest, such that each training set observation is in the OOB sample for one or more trees, that OOB predictions can be provided for all samples in the training data.
I have glossed over issues such as missing data for some OOB cases etc, but these issues also pertain to a single regression or classification tree. Also note that each tree in a forest uses only mtry randomly-selected variables. | Random forest and prediction
Each tree in the forest is built from a bootstrap sample of the observations in your training data. Those observations in the bootstrap sample build the tree, whilst those not in the bootstrap sample |
17,562 | multiple regression and multiple comparisons | You're right. The problem of multiple comparisons exists everywhere, but, because of the way it's typically taught, people only think it pertains to comparing many groups against each other via a whole bunch of $t$-tests. In reality, there are many examples where the problem of multiple comparisons exists, but where it doesn't look like lots of pairwise comparisons; for example, if you have a lot of continuous variables and you wonder if any are correlated, you will have a multiple comparisons problem (see here: Look and you shall find a correlation).
Another example is the one you raise. If you were to run a multiple regression with 20 variables, and you used $\alpha=.05$ as your threshold, you would expect one of your variables to be 'significant' by chance alone, even if all nulls were true. The problem of multiple comparisons simply comes from the mathematics of running lots of analyses. If all null hypotheses were true and the variables were perfectly uncorrelated, the probability of not falsely rejecting any true null would be $1-(1-\alpha)^p$ (e.g., with $p=5$, this is $.23$).
The first strategy to mitigate against this is to conduct a simultaneous test of your model. If you are fitting an OLS regression, most software will give you a global $F$-test as a default part of your output. If you are running a generalized linear model, most software will give you an analogous global likelihood ratio test. This test will give you some protection against type I error inflation due to the problem of multiple comparisons (cf., my answer here: Significance of coefficients in linear regression: significant t-test vs non-significant F-statistic). A similar case is when you have a categorical variable that is represented with several dummy codes; you wouldn't want to interpret those $t$-tests, but would drop all dummy codes and perform a nested model test instead.
Another possible strategy is to use an alpha adjustment procedure, like the Bonferroni correction. You should realize that doing this will reduce your power as well as reducing your familywise type I error rate. Whether this tradeoff is worthwhile is a judgment call for you to make. (FWIW, I don't typically use alpha corrections in multiple regression.)
Regarding the issue of using $p$-values to do model selection, I think this is a really bad idea. I would not move from a model with 5 variables to one with only 2 because the others were 'non-significant'. When people do this, they bias their model. It may help you to read my answer here: algorithms for automatic model selection to understand this better.
Regarding your update, I would not suggest you assess univariate correlations first so as to decide which variables to use in the final multiple regression model. Doing this will lead to problems with endogeneity unless the variables are perfectly uncorrelated with each other. I discussed this issue in my answer here: Estimating $b_1x_1+b_2x_2$ instead of $b_1x_1+b_2x_2+b_3x_3$.
With regard to the question of how to handle analyses with different dependent variables, whether you'd want to use some sort of adjustment is based on how you see the analyses relative to each other. The traditional idea is to determine whether they are meaningfully considered to be a 'family'. This is discussed here: What might be a clear, practical definition for a "family of hypotheses"? You might also want to read this thread: Methods to predict multiple dependent variables. | multiple regression and multiple comparisons | You're right. The problem of multiple comparisons exists everywhere, but, because of the way it's typically taught, people only think it pertains to comparing many groups against each other via a who | multiple regression and multiple comparisons
You're right. The problem of multiple comparisons exists everywhere, but, because of the way it's typically taught, people only think it pertains to comparing many groups against each other via a whole bunch of $t$-tests. In reality, there are many examples where the problem of multiple comparisons exists, but where it doesn't look like lots of pairwise comparisons; for example, if you have a lot of continuous variables and you wonder if any are correlated, you will have a multiple comparisons problem (see here: Look and you shall find a correlation).
Another example is the one you raise. If you were to run a multiple regression with 20 variables, and you used $\alpha=.05$ as your threshold, you would expect one of your variables to be 'significant' by chance alone, even if all nulls were true. The problem of multiple comparisons simply comes from the mathematics of running lots of analyses. If all null hypotheses were true and the variables were perfectly uncorrelated, the probability of not falsely rejecting any true null would be $1-(1-\alpha)^p$ (e.g., with $p=5$, this is $.23$).
The first strategy to mitigate against this is to conduct a simultaneous test of your model. If you are fitting an OLS regression, most software will give you a global $F$-test as a default part of your output. If you are running a generalized linear model, most software will give you an analogous global likelihood ratio test. This test will give you some protection against type I error inflation due to the problem of multiple comparisons (cf., my answer here: Significance of coefficients in linear regression: significant t-test vs non-significant F-statistic). A similar case is when you have a categorical variable that is represented with several dummy codes; you wouldn't want to interpret those $t$-tests, but would drop all dummy codes and perform a nested model test instead.
Another possible strategy is to use an alpha adjustment procedure, like the Bonferroni correction. You should realize that doing this will reduce your power as well as reducing your familywise type I error rate. Whether this tradeoff is worthwhile is a judgment call for you to make. (FWIW, I don't typically use alpha corrections in multiple regression.)
Regarding the issue of using $p$-values to do model selection, I think this is a really bad idea. I would not move from a model with 5 variables to one with only 2 because the others were 'non-significant'. When people do this, they bias their model. It may help you to read my answer here: algorithms for automatic model selection to understand this better.
Regarding your update, I would not suggest you assess univariate correlations first so as to decide which variables to use in the final multiple regression model. Doing this will lead to problems with endogeneity unless the variables are perfectly uncorrelated with each other. I discussed this issue in my answer here: Estimating $b_1x_1+b_2x_2$ instead of $b_1x_1+b_2x_2+b_3x_3$.
With regard to the question of how to handle analyses with different dependent variables, whether you'd want to use some sort of adjustment is based on how you see the analyses relative to each other. The traditional idea is to determine whether they are meaningfully considered to be a 'family'. This is discussed here: What might be a clear, practical definition for a "family of hypotheses"? You might also want to read this thread: Methods to predict multiple dependent variables. | multiple regression and multiple comparisons
You're right. The problem of multiple comparisons exists everywhere, but, because of the way it's typically taught, people only think it pertains to comparing many groups against each other via a who |
17,563 | multiple regression and multiple comparisons | On a practical level, I think one needs to also consider if the Betas reflect the levels of a categorical variables (i.e. dummies). In these circumstances it's reasonable to be interested in knowing whether a given Beta is different compared to a (meaningful) referent Beta. But before even doing pairwise comparisons, one would need to know whether overall the levels of the categorical variable are important (using a joint F test or a likelihood ratio test). Doing this has the advantage of using less d.f. | multiple regression and multiple comparisons | On a practical level, I think one needs to also consider if the Betas reflect the levels of a categorical variables (i.e. dummies). In these circumstances it's reasonable to be interested in knowing | multiple regression and multiple comparisons
On a practical level, I think one needs to also consider if the Betas reflect the levels of a categorical variables (i.e. dummies). In these circumstances it's reasonable to be interested in knowing whether a given Beta is different compared to a (meaningful) referent Beta. But before even doing pairwise comparisons, one would need to know whether overall the levels of the categorical variable are important (using a joint F test or a likelihood ratio test). Doing this has the advantage of using less d.f. | multiple regression and multiple comparisons
On a practical level, I think one needs to also consider if the Betas reflect the levels of a categorical variables (i.e. dummies). In these circumstances it's reasonable to be interested in knowing |
17,564 | Ensemble time series model | Combining forecasts is an excellent idea. (I think it is not an exaggeration to say that this is one of the few things academic forecasters agree on.)
I happen to have written a paper a while back looking at different ways to weight forecasts in combining them: http://www.sciencedirect.com/science/article/pii/S0169207010001032 Basically, using (Akaike) weights did not consistently improve combinations over simple or trimmed/winsorized means or medians, so I personally would think twice before implementing a complex procedure that may not yield a definite benefit (recall, though, that combinations consistently outperformed selection single methods by information criteria). This may depend on the particular time series you have, of course.
I looked at combining prediction intervals in the paper above, but not at combining variance as such. I seem to recall a paper not long back in the IJF with this focus, so you may want to search for "combining" or "combination" through back issues of the IJF.
A few other papers that have looked at combining forecasts are here (from 1989, but a review) and here and here (also looks at densities) and here and here. Many of these note that it is still poorly understood why forecast combinations frequently outperform single selected models. The second-to-last paper is on the M3 forecasting competition; one of their main findings was (number (3) on p. 458) that "The accuracy of the combination of various methods outperforms, on average, the specific methods being combined and does well in comparison with other methods." The last of these papers finds that combinations do not necessarily perform better than single models, but that they can considerably reduce the risk of catastrophic failure (which is one of your goals). More literature should readily be found in the International Journal of Forecasting, the Journal of Forecasting and for more specific applications in the econometrics or supply chain literature. | Ensemble time series model | Combining forecasts is an excellent idea. (I think it is not an exaggeration to say that this is one of the few things academic forecasters agree on.)
I happen to have written a paper a while back loo | Ensemble time series model
Combining forecasts is an excellent idea. (I think it is not an exaggeration to say that this is one of the few things academic forecasters agree on.)
I happen to have written a paper a while back looking at different ways to weight forecasts in combining them: http://www.sciencedirect.com/science/article/pii/S0169207010001032 Basically, using (Akaike) weights did not consistently improve combinations over simple or trimmed/winsorized means or medians, so I personally would think twice before implementing a complex procedure that may not yield a definite benefit (recall, though, that combinations consistently outperformed selection single methods by information criteria). This may depend on the particular time series you have, of course.
I looked at combining prediction intervals in the paper above, but not at combining variance as such. I seem to recall a paper not long back in the IJF with this focus, so you may want to search for "combining" or "combination" through back issues of the IJF.
A few other papers that have looked at combining forecasts are here (from 1989, but a review) and here and here (also looks at densities) and here and here. Many of these note that it is still poorly understood why forecast combinations frequently outperform single selected models. The second-to-last paper is on the M3 forecasting competition; one of their main findings was (number (3) on p. 458) that "The accuracy of the combination of various methods outperforms, on average, the specific methods being combined and does well in comparison with other methods." The last of these papers finds that combinations do not necessarily perform better than single models, but that they can considerably reduce the risk of catastrophic failure (which is one of your goals). More literature should readily be found in the International Journal of Forecasting, the Journal of Forecasting and for more specific applications in the econometrics or supply chain literature. | Ensemble time series model
Combining forecasts is an excellent idea. (I think it is not an exaggeration to say that this is one of the few things academic forecasters agree on.)
I happen to have written a paper a while back loo |
17,565 | Ensemble time series model | Why not specify it further? I don't think that any one model you would produce could be better or good enough than a specific choice.
With that said, if you can narrow down your choices a bit to those you can test for, and the data input can be standardized, then why not write an automated testing procedure in R?
Say you decide your data will fall within a range to be estimated by five models as well as one "fallback". Say you can characterize the input by different tests. Then just go ahead and write an R (or a program like that) algorithm that runs this for you. This works if you could produce a flowchart of which model to run based on test data, that is if any point of the decision tree is binary.
If this is not an option because the decision may not be binary, I suggest you implement a rating system based on applicable tests and run some "extreme cases" simulated data through your grid to see if the results are what you are looking for.
You can combine these things obviously, for example testing for non-stationarity may be give a definitve yes-no, while other attributes may fall into a range such as multicollinearity.
You can draw this out on paper first, then build it, simulate it with known distributions you expect to have.
Then just run the R program everytime new data arrives.
I see no need to combine several models with the computational capabilities you most likely have at hand. | Ensemble time series model | Why not specify it further? I don't think that any one model you would produce could be better or good enough than a specific choice.
With that said, if you can narrow down your choices a bit to those | Ensemble time series model
Why not specify it further? I don't think that any one model you would produce could be better or good enough than a specific choice.
With that said, if you can narrow down your choices a bit to those you can test for, and the data input can be standardized, then why not write an automated testing procedure in R?
Say you decide your data will fall within a range to be estimated by five models as well as one "fallback". Say you can characterize the input by different tests. Then just go ahead and write an R (or a program like that) algorithm that runs this for you. This works if you could produce a flowchart of which model to run based on test data, that is if any point of the decision tree is binary.
If this is not an option because the decision may not be binary, I suggest you implement a rating system based on applicable tests and run some "extreme cases" simulated data through your grid to see if the results are what you are looking for.
You can combine these things obviously, for example testing for non-stationarity may be give a definitve yes-no, while other attributes may fall into a range such as multicollinearity.
You can draw this out on paper first, then build it, simulate it with known distributions you expect to have.
Then just run the R program everytime new data arrives.
I see no need to combine several models with the computational capabilities you most likely have at hand. | Ensemble time series model
Why not specify it further? I don't think that any one model you would produce could be better or good enough than a specific choice.
With that said, if you can narrow down your choices a bit to those |
17,566 | Ensemble time series model | There is a nice and simple formulae for combining two forecasting methods, you just weight them multipling the first by a and the other by (1 - a), where a is found by minimizing the variance of this combined forecast. As you know the errors of both forecasting methods, you can calculate the errors of the combination wich will depend on "a".
The calculation is simple when the mean of each method is = 0. For combining more than 2 methods the formulae is still "simple" in the sense that you can calculate it analytically "by hand", or also use the Solver option from EXCEL | Ensemble time series model | There is a nice and simple formulae for combining two forecasting methods, you just weight them multipling the first by a and the other by (1 - a), where a is found by minimizing the variance of this | Ensemble time series model
There is a nice and simple formulae for combining two forecasting methods, you just weight them multipling the first by a and the other by (1 - a), where a is found by minimizing the variance of this combined forecast. As you know the errors of both forecasting methods, you can calculate the errors of the combination wich will depend on "a".
The calculation is simple when the mean of each method is = 0. For combining more than 2 methods the formulae is still "simple" in the sense that you can calculate it analytically "by hand", or also use the Solver option from EXCEL | Ensemble time series model
There is a nice and simple formulae for combining two forecasting methods, you just weight them multipling the first by a and the other by (1 - a), where a is found by minimizing the variance of this |
17,567 | What is percentage of variance in PCA? [duplicate] | I assume they are referring to the eigenvalues of the corresponding eigenvectors. The eigenvalues in PCA tell you how much variance can be explained by its associated eigenvector. Therefore, the highest eigenvalue indicates the highest variance in the data was observed in the direction of its eigenvector. Accordingly, if you take all eigenvectors together, you can explain all the variance in the data sample. Instead of using the absolute value of variance explained, as indicated by the eigenvalue, you can also get relative numbers by first summing up all eigenvalues and then divide an eigenvalue $\lambda_i$ by this sum
$$
\frac{\lambda_i}{\sum_{i=1}^n \lambda_i} .
$$
This way you end up with a "percentage of variance" for each eigenvector. | What is percentage of variance in PCA? [duplicate] | I assume they are referring to the eigenvalues of the corresponding eigenvectors. The eigenvalues in PCA tell you how much variance can be explained by its associated eigenvector. Therefore, the highe | What is percentage of variance in PCA? [duplicate]
I assume they are referring to the eigenvalues of the corresponding eigenvectors. The eigenvalues in PCA tell you how much variance can be explained by its associated eigenvector. Therefore, the highest eigenvalue indicates the highest variance in the data was observed in the direction of its eigenvector. Accordingly, if you take all eigenvectors together, you can explain all the variance in the data sample. Instead of using the absolute value of variance explained, as indicated by the eigenvalue, you can also get relative numbers by first summing up all eigenvalues and then divide an eigenvalue $\lambda_i$ by this sum
$$
\frac{\lambda_i}{\sum_{i=1}^n \lambda_i} .
$$
This way you end up with a "percentage of variance" for each eigenvector. | What is percentage of variance in PCA? [duplicate]
I assume they are referring to the eigenvalues of the corresponding eigenvectors. The eigenvalues in PCA tell you how much variance can be explained by its associated eigenvector. Therefore, the highe |
17,568 | Standard error of a count | The population is the (hypothetical) set of all people who are at risk to get the disease; usually, that consists of all people (or some clearly identifiable subgroup of people) residing in the study area. It is important to define this population clearly, because it is the target of the study and of all inferences made from the data.
When cases of the disease are independent (which might be a reasonable hypothesis when the disease is not readily communicated between people and is not caused by local environmental conditions) and they are rare, then the counts should closely follow a Poisson distribution. For this distribution, a good estimate of its standard deviation is the square root of the count.
Using these heuristics, the data $(180, 90, 45, 210)$ would have associated standard deviations of $(13.4, 9.5, 6.7, 14.5)$, which we can take provisionally as rough assessments of error. Conceptually, in each season there is a hypothetical true disease incidence rate--everybody in the population during that season has the same (low) risk of contracting the disease--but because getting this disease is thought of as a random event, the actual numbers of diseases observed during a season will vary from that true rate. The square root of the true (but unknown!) rate quantifies the amount of variation likely to occur. Because the observed counts ought to be close to the true rates, their square roots should be reasonable proxies for the square roots of the true rates. These proxies are exactly what is meant by a "standard error."
The first thing to notice about this calculation is the variation among the counts (which have a range of $165$ and a standard deviation of $77$) is much greater than the individual SDs, which do not exceed $14.5$. This confirms that the underlying rate is significantly changing by season: that's to be expected. Accordingly, reporting the SD of $77$ for this batch of data could be useful for indicating the magnitude of seasonal variation, but it is not relevant for indicating standard errors of the values.
But what if the data are not independent? Disease outbreaks often occur in clusters. If, for instance, a typical cluster size were $9$, then these data (approximately) reflect $(20, 10, 5, 23)$ clusters, respectively. If we take these to be realizations of four Poisson variables and use their square roots to estimate SDs, we get $(4.5, 3.2, 2.2, 4.8)$. Multiplying by $9$ to convert from clusters to people gives $(40, 28.5, 20, 44)$. Notice how much larger these values are than before: clustering increases relative error.
That's about as far as one can go with these limited data. These simple calculations have revealed that:
Characterizing the population is critical,
The square root of a count is a rough starting point for assessing its standard error,
The square root has to be multiplied (roughly) by some factor to reflect lack of independence in the disease cases (and this factor can approximately be related to sizes of disease clusters),
Variation among these counts primarily reflects variation in the disease rate over time rather than uncertainty (about the underlying Poisson intensity). | Standard error of a count | The population is the (hypothetical) set of all people who are at risk to get the disease; usually, that consists of all people (or some clearly identifiable subgroup of people) residing in the study | Standard error of a count
The population is the (hypothetical) set of all people who are at risk to get the disease; usually, that consists of all people (or some clearly identifiable subgroup of people) residing in the study area. It is important to define this population clearly, because it is the target of the study and of all inferences made from the data.
When cases of the disease are independent (which might be a reasonable hypothesis when the disease is not readily communicated between people and is not caused by local environmental conditions) and they are rare, then the counts should closely follow a Poisson distribution. For this distribution, a good estimate of its standard deviation is the square root of the count.
Using these heuristics, the data $(180, 90, 45, 210)$ would have associated standard deviations of $(13.4, 9.5, 6.7, 14.5)$, which we can take provisionally as rough assessments of error. Conceptually, in each season there is a hypothetical true disease incidence rate--everybody in the population during that season has the same (low) risk of contracting the disease--but because getting this disease is thought of as a random event, the actual numbers of diseases observed during a season will vary from that true rate. The square root of the true (but unknown!) rate quantifies the amount of variation likely to occur. Because the observed counts ought to be close to the true rates, their square roots should be reasonable proxies for the square roots of the true rates. These proxies are exactly what is meant by a "standard error."
The first thing to notice about this calculation is the variation among the counts (which have a range of $165$ and a standard deviation of $77$) is much greater than the individual SDs, which do not exceed $14.5$. This confirms that the underlying rate is significantly changing by season: that's to be expected. Accordingly, reporting the SD of $77$ for this batch of data could be useful for indicating the magnitude of seasonal variation, but it is not relevant for indicating standard errors of the values.
But what if the data are not independent? Disease outbreaks often occur in clusters. If, for instance, a typical cluster size were $9$, then these data (approximately) reflect $(20, 10, 5, 23)$ clusters, respectively. If we take these to be realizations of four Poisson variables and use their square roots to estimate SDs, we get $(4.5, 3.2, 2.2, 4.8)$. Multiplying by $9$ to convert from clusters to people gives $(40, 28.5, 20, 44)$. Notice how much larger these values are than before: clustering increases relative error.
That's about as far as one can go with these limited data. These simple calculations have revealed that:
Characterizing the population is critical,
The square root of a count is a rough starting point for assessing its standard error,
The square root has to be multiplied (roughly) by some factor to reflect lack of independence in the disease cases (and this factor can approximately be related to sizes of disease clusters),
Variation among these counts primarily reflects variation in the disease rate over time rather than uncertainty (about the underlying Poisson intensity). | Standard error of a count
The population is the (hypothetical) set of all people who are at risk to get the disease; usually, that consists of all people (or some clearly identifiable subgroup of people) residing in the study |
17,569 | Standard error of a count | I'm not being facetious when I ask, "Standard error of what?" You can take the mean of these four figures, and you can compute the standard error of that mean. That statistic, and a resulting confidence interval, would make sense if you believed you were justified in treating those 4 seasons as representative of all the sets of 4 seasons to which you might generalize. To the extent that you are so justified, the data you have would indeed be a random sample of the population. The sampling you mention would entail an additional layer of sampling--you might call it cluster sampling, where each year constitutes a cluster. | Standard error of a count | I'm not being facetious when I ask, "Standard error of what?" You can take the mean of these four figures, and you can compute the standard error of that mean. That statistic, and a resulting confid | Standard error of a count
I'm not being facetious when I ask, "Standard error of what?" You can take the mean of these four figures, and you can compute the standard error of that mean. That statistic, and a resulting confidence interval, would make sense if you believed you were justified in treating those 4 seasons as representative of all the sets of 4 seasons to which you might generalize. To the extent that you are so justified, the data you have would indeed be a random sample of the population. The sampling you mention would entail an additional layer of sampling--you might call it cluster sampling, where each year constitutes a cluster. | Standard error of a count
I'm not being facetious when I ask, "Standard error of what?" You can take the mean of these four figures, and you can compute the standard error of that mean. That statistic, and a resulting confid |
17,570 | Interpreting PCA scores | Basically, the factor scores are computed as the raw responses weighted by the factor loadings. So, you need to look at the factor loadings of your first dimension to see how each variable relate to the principal component. Observing high positive (resp. negative) loadings associated to specific variables means that these variables contribute positively (resp. negatively) to this component; hence, people scoring high on these variables will tend to have higher (resp. lower) factor scores on this particular dimension.
Drawing the correlation circle is useful to have a general idea of the variables that contribute "positively" vs. "negatively" (if any) to the first principal axis, but if you are using R you may have a look at the FactoMineR package and the dimdesc() function.
Here is an example with the USArrests data:
> data(USArrests)
> library(FactoMineR)
> res <- PCA(USArrests)
> dimdesc(res, axes=1) # show correlation of variables with 1st axis
$Dim.1
$Dim.1$quanti
correlation p.value
Assault 0.918 5.76e-21
Rape 0.856 2.40e-15
Murder 0.844 1.39e-14
UrbanPop 0.438 1.46e-03
> res$var$coord # show loadings associated to each axis
Dim.1 Dim.2 Dim.3 Dim.4
Murder 0.844 -0.416 0.204 0.2704
Assault 0.918 -0.187 0.160 -0.3096
UrbanPop 0.438 0.868 0.226 0.0558
Rape 0.856 0.166 -0.488 0.0371
As can be seen from the latest result, the first dimension mainly reflects violent acts (of any kind). If we look at the individual map, it is clear that states located on the right are those where such acts are most frequent.
You may also be interested in this related question: What are principal component scores? | Interpreting PCA scores | Basically, the factor scores are computed as the raw responses weighted by the factor loadings. So, you need to look at the factor loadings of your first dimension to see how each variable relate to t | Interpreting PCA scores
Basically, the factor scores are computed as the raw responses weighted by the factor loadings. So, you need to look at the factor loadings of your first dimension to see how each variable relate to the principal component. Observing high positive (resp. negative) loadings associated to specific variables means that these variables contribute positively (resp. negatively) to this component; hence, people scoring high on these variables will tend to have higher (resp. lower) factor scores on this particular dimension.
Drawing the correlation circle is useful to have a general idea of the variables that contribute "positively" vs. "negatively" (if any) to the first principal axis, but if you are using R you may have a look at the FactoMineR package and the dimdesc() function.
Here is an example with the USArrests data:
> data(USArrests)
> library(FactoMineR)
> res <- PCA(USArrests)
> dimdesc(res, axes=1) # show correlation of variables with 1st axis
$Dim.1
$Dim.1$quanti
correlation p.value
Assault 0.918 5.76e-21
Rape 0.856 2.40e-15
Murder 0.844 1.39e-14
UrbanPop 0.438 1.46e-03
> res$var$coord # show loadings associated to each axis
Dim.1 Dim.2 Dim.3 Dim.4
Murder 0.844 -0.416 0.204 0.2704
Assault 0.918 -0.187 0.160 -0.3096
UrbanPop 0.438 0.868 0.226 0.0558
Rape 0.856 0.166 -0.488 0.0371
As can be seen from the latest result, the first dimension mainly reflects violent acts (of any kind). If we look at the individual map, it is clear that states located on the right are those where such acts are most frequent.
You may also be interested in this related question: What are principal component scores? | Interpreting PCA scores
Basically, the factor scores are computed as the raw responses weighted by the factor loadings. So, you need to look at the factor loadings of your first dimension to see how each variable relate to t |
17,571 | Interpreting PCA scores | For me, PCA scores are just re-arrangements of the data in a form that allows me to explain the data set with less variables. The scores represent how much each item relates to the component. You can name them as per factor analysis, but its important to remember that they are not latent variables, as PCA analyses all variance in the data set, not just the elements held in common (as factor analysis does). | Interpreting PCA scores | For me, PCA scores are just re-arrangements of the data in a form that allows me to explain the data set with less variables. The scores represent how much each item relates to the component. You can | Interpreting PCA scores
For me, PCA scores are just re-arrangements of the data in a form that allows me to explain the data set with less variables. The scores represent how much each item relates to the component. You can name them as per factor analysis, but its important to remember that they are not latent variables, as PCA analyses all variance in the data set, not just the elements held in common (as factor analysis does). | Interpreting PCA scores
For me, PCA scores are just re-arrangements of the data in a form that allows me to explain the data set with less variables. The scores represent how much each item relates to the component. You can |
17,572 | Interpreting PCA scores | PCA results (the different dimensions or commponents) generally can't be translated into a real concept I think is wrong to assume that one of the components is "fear of bears" what lead you to think that was what the component meant?
Principal components procedure transforms your data matrix to a new data matrix with the same or less amount of dimensions, and the resulting dimensions range from the one that better explains the variance to the one that explains it the less. This components are calculated based on a combination of the original variables with the calculated eigenvectors.
Overal PCA procedure does convert the original variables to orthogonal ones (linearly independent).
Hope this helps you clarify a little about pca procedure | Interpreting PCA scores | PCA results (the different dimensions or commponents) generally can't be translated into a real concept I think is wrong to assume that one of the components is "fear of bears" what lead you to think | Interpreting PCA scores
PCA results (the different dimensions or commponents) generally can't be translated into a real concept I think is wrong to assume that one of the components is "fear of bears" what lead you to think that was what the component meant?
Principal components procedure transforms your data matrix to a new data matrix with the same or less amount of dimensions, and the resulting dimensions range from the one that better explains the variance to the one that explains it the less. This components are calculated based on a combination of the original variables with the calculated eigenvectors.
Overal PCA procedure does convert the original variables to orthogonal ones (linearly independent).
Hope this helps you clarify a little about pca procedure | Interpreting PCA scores
PCA results (the different dimensions or commponents) generally can't be translated into a real concept I think is wrong to assume that one of the components is "fear of bears" what lead you to think |
17,573 | What is the origin of the name "conjugate prior"? | The Oxford English Dictionary defines "conjugate" as an adjective meaning "joined together, esp. in a pair, coupled; connected, related" and the statistical use is in that sense.
Many fields use it similarly:
chemistry: an acid that donates a proton to a base is a "conjugate acid"; whatever's left over is called a "conjugate base"
botany: "conjugate leaves" grow in pairs, especially when there's only one such pair,
optics: "conjugate foci" are the points where light is emitted and/or converges on opposite sides of a lens.
linguistics: conjugations are forms of the same root word.
A related word, conjugal, often refers to romantic/life partner in legal contexts.
Some of these senses do have a "reciprocal" implication, but it's often figurative, rather than strictly mathematical, and it doesn't seem like an essential part of the definition. It's not a huge stretch to imagine that a conjugate prior has a special and strong connection to its posterior.
Wikipedia credits Raiffa and Schlaifer for coining the term (annoyingly, it's not in the OED). Here's the first mention of it in their 1961 book Applied Statistical Decision Theory (worldcat,full text) which seems to be using the "joined" sense of conjugate.
We show that whenever (1) any possible experimental outcome can be
described by a sufficient statistic of fixed dimensionality (i.e., an
$s$-tuple $(y_1, y_2, \ldots y_s)$ where $s$ does not depend on the
"size" of the experiment), and 2) the likelihood of every outcome is
given by a reasonably simple formula with $y_1, y_2, \ldots y_s$ as
its arguments, we can obtain a very tractable family of "conjugate"
prior distributions simply by interchanging the roles of variables and
parameters in the algebraic expression for the sample likelihood, and
the posterior distribution will be a member of the same family as the
prior." | What is the origin of the name "conjugate prior"? | The Oxford English Dictionary defines "conjugate" as an adjective meaning "joined together, esp. in a pair, coupled; connected, related" and the statistical use is in that sense.
Many fields use it si | What is the origin of the name "conjugate prior"?
The Oxford English Dictionary defines "conjugate" as an adjective meaning "joined together, esp. in a pair, coupled; connected, related" and the statistical use is in that sense.
Many fields use it similarly:
chemistry: an acid that donates a proton to a base is a "conjugate acid"; whatever's left over is called a "conjugate base"
botany: "conjugate leaves" grow in pairs, especially when there's only one such pair,
optics: "conjugate foci" are the points where light is emitted and/or converges on opposite sides of a lens.
linguistics: conjugations are forms of the same root word.
A related word, conjugal, often refers to romantic/life partner in legal contexts.
Some of these senses do have a "reciprocal" implication, but it's often figurative, rather than strictly mathematical, and it doesn't seem like an essential part of the definition. It's not a huge stretch to imagine that a conjugate prior has a special and strong connection to its posterior.
Wikipedia credits Raiffa and Schlaifer for coining the term (annoyingly, it's not in the OED). Here's the first mention of it in their 1961 book Applied Statistical Decision Theory (worldcat,full text) which seems to be using the "joined" sense of conjugate.
We show that whenever (1) any possible experimental outcome can be
described by a sufficient statistic of fixed dimensionality (i.e., an
$s$-tuple $(y_1, y_2, \ldots y_s)$ where $s$ does not depend on the
"size" of the experiment), and 2) the likelihood of every outcome is
given by a reasonably simple formula with $y_1, y_2, \ldots y_s$ as
its arguments, we can obtain a very tractable family of "conjugate"
prior distributions simply by interchanging the roles of variables and
parameters in the algebraic expression for the sample likelihood, and
the posterior distribution will be a member of the same family as the
prior." | What is the origin of the name "conjugate prior"?
The Oxford English Dictionary defines "conjugate" as an adjective meaning "joined together, esp. in a pair, coupled; connected, related" and the statistical use is in that sense.
Many fields use it si |
17,574 | What is the origin of the name "conjugate prior"? | I believe the origin is somehow related to the following concepts:
eigenvector: a vector $ \mathbf{x} $ is called an eigenvector of a matrix $ \mathbf{A} $ if $ \mathbf{A}\mathbf{x} $ = $k\mathbf{x}$ , meaning $ \mathbf{A}\mathbf{x} $ has the same form as $ \mathbf{x} $ (just different by a scaling factor $k$ called eigenvalue of $ \mathbf{A} $), hope you start to see this is the same logic with conjugate prior.
eigenfunction: see this analogy between conjugate prior and eigenfunction. The concept of eigenvector is extended to functions in Functional Analysis. Given a linear transformation $L$ (eg. a differential or integral operator), its eigenfunctions are functions $f$ such that $Lf$ is simply $kf$, ie. $f$ scaled by a scalar. The eigenfunctions are very useful in solving differential equations as they provide us with very convenient representation of their solutions. These are also related to Fourier transforms, where eigenfunctions of a Fourier transform are sine and cosine functions. In fact, it can be proved that any periodical function can be approximated as a linear combination of sine and cosine functions. Also, Fourier transform of a Gaussian function is another Gaussian function, again same logic with conjugated prior. | What is the origin of the name "conjugate prior"? | I believe the origin is somehow related to the following concepts:
eigenvector: a vector $ \mathbf{x} $ is called an eigenvector of a matrix $ \mathbf{A} $ if $ \mathbf{A}\mathbf{x} $ = $k\mathbf{x}$ | What is the origin of the name "conjugate prior"?
I believe the origin is somehow related to the following concepts:
eigenvector: a vector $ \mathbf{x} $ is called an eigenvector of a matrix $ \mathbf{A} $ if $ \mathbf{A}\mathbf{x} $ = $k\mathbf{x}$ , meaning $ \mathbf{A}\mathbf{x} $ has the same form as $ \mathbf{x} $ (just different by a scaling factor $k$ called eigenvalue of $ \mathbf{A} $), hope you start to see this is the same logic with conjugate prior.
eigenfunction: see this analogy between conjugate prior and eigenfunction. The concept of eigenvector is extended to functions in Functional Analysis. Given a linear transformation $L$ (eg. a differential or integral operator), its eigenfunctions are functions $f$ such that $Lf$ is simply $kf$, ie. $f$ scaled by a scalar. The eigenfunctions are very useful in solving differential equations as they provide us with very convenient representation of their solutions. These are also related to Fourier transforms, where eigenfunctions of a Fourier transform are sine and cosine functions. In fact, it can be proved that any periodical function can be approximated as a linear combination of sine and cosine functions. Also, Fourier transform of a Gaussian function is another Gaussian function, again same logic with conjugated prior. | What is the origin of the name "conjugate prior"?
I believe the origin is somehow related to the following concepts:
eigenvector: a vector $ \mathbf{x} $ is called an eigenvector of a matrix $ \mathbf{A} $ if $ \mathbf{A}\mathbf{x} $ = $k\mathbf{x}$ |
17,575 | Definition of family of a distribution? | The statistical and mathematical concepts are exactly the same, understanding that "family" is a generic mathematical term with technical variations adapted to different circumstances:
A parametric family is a curve (or surface or other finite-dimensional generalization thereof) in the space of all distributions.
The rest of this post explains what that means. As an aside, I don't think any of this is controversial, either mathematically or statistically (apart from one minor issue which is noted below). In support of this opinion I have supplied many references (mostly to Wikipedia articles).
This terminology of "families" tends to be used when studying classes $\mathcal C_Y$ of functions into a set $Y$ or "maps." Given a domain $X$, a family $\mathcal F$ of maps on $X$ parameterized by some set $\Theta$ (the "parameters") is a function
$$\mathcal F : X\times \Theta\to Y$$
for which (1) for each $\theta\in\Theta$, the function $\mathcal{F}_\theta:X\to Y$ given by $\mathcal{F}_\theta(x)=\mathcal{F}(x,\theta)$ is in $\mathcal{C}_Y$ and (2) $\mathcal F$ itself has certain "nice" properties.
The idea is that we want to vary functions from $X$ to $Y$ in a "smooth" or controlled manner. Property (1) means that each $\theta$ designates such a function, while the details of property (2) will capture the sense in which a "small" change in $\theta$ induces a sufficiently "small" change in $\mathcal{F}_\theta$.
A standard mathematical example, close to the one mentioned in the question, is a homotopy. In this case $\mathcal{C}_Y$ is the category of continuous maps from topological spaces $X$ into the topological space $Y$; $\Theta=[0,1]\subset\mathbb{R}$ is the unit interval with its usual topology, and we require that $\mathcal{F}$ be a continuous map from the topological product $X \times \Theta$ into $Y$. It can be thought of as a "continuous deformation of the map $\mathcal{F}_0$ to $\mathcal{F}_1$." When $X=[0,1]$ is itself an interval, such maps are curves in $Y$ and the homotopy is a smooth deformation from one curve to another.
For statistical applications, $\mathcal{C}_Y$ is the set of all distributions on $\mathbb{R}$ (or, in practice, on $\mathbb{R}^n$ for some $n$, but to keep the exposition simple I will focus on $n=1$). We may identify it with the set of all non-decreasing càdlàg functions $\mathbb{R}\to [0,1]$ where the closure of their range includes both $0$ and $1$: these are the cumulative distribution functions, or simply distribution functions. Thus, $X=\mathbb R$ and $Y=[0,1]$.
A family of distributions is any subset of $\mathcal{C}_Y$. Another name for a family is statistical model. It consists of all distributions that we suppose govern our observations, but we do not otherwise know which distribution is the actual one.
A family can be empty.
$\mathcal{C}_Y$ itself is a family.
A family may consist of a single distribution or just a finite number of them.
These abstract set-theoretic characteristics are of relatively little interest or utility. It is only when we consider additional (relevant) mathematical structure on $\mathcal{C}_Y$ that this concept becomes useful. But what properties of $\mathcal{C}_Y$ are of statistical interest? Some that show up frequently are:
$\mathcal{C}_Y$ is a convex set: given any two distributions ${F}, {G}\in \mathcal{C}_Y$, we may form the mixture distribution $(1-t){F}+t{G}\in Y$ for all $t\in[0,1]$. This is a kind of "homotopy" from $F$ to $G$.
Large parts of $\mathcal{C}_Y$ support various pseudo metrics, such as the Kullback-Leibler divergence or the closely related Fisher Information metric.
$\mathcal{C}_Y$ has an additive structure: corresponding to any two distributions $F$ and $G$ is their sum, ${F}\star {G}$.
$\mathcal{C}_Y$ supports many useful, natural functions, often termed "properties." These include any fixed quantile (such as the median) as well as the cumulants.
$\mathcal{C}_Y$ is a subset of a function space. As such, it inherits many useful metrics, such as the sup norm ($L^\infty$ norm) given by $$||F-G||_\infty = \sup_{x\in\mathbb{R}}|F(x)-G(x)|.$$
Natural group actions on $\mathbb R$ induce actions on $\mathcal{C}_Y$. The commonest actions are translations $T_\mu:x \to x+\mu$ and scalings $S_\sigma:x\to x\sigma$ for $\sigma\gt 0$. The effect these have on a distribution is to send $F$ to the distribution given by $F^{\mu,\sigma}(x) = F((x-\mu)/\sigma)$. These lead to the concepts of location-scale families and their generalizations. (I don't supply a reference, because extensive Web searches turn up a variety of different definitions: here, at least, may be a tiny bit of controversy.)
The properties that matter depend on the statistical problem and on how you intend to analyze the data. Addressing all the variations suggested by the preceding characteristics would take too much space for this medium. Let's focus on one common important application.
Take, for instance, Maximum Likelihood. In most applications you will want to be able to use Calculus to obtain an estimate. For this to work, you must be able to "take derivatives" in the family.
(Technical aside: The usual way in which this is accomplished is to select a domain $\Theta\subset \mathbb{R}^d$ for $d\ge 0$ and specify a continuous, locally invertible function $p$ from $\Theta$ into $\mathcal{C}_Y$. (This means that for every $\theta\in\Theta$ there exists a ball $B(\theta, \epsilon)$, with $\epsilon\gt 0$ for which $p\mid_{B(\theta,\epsilon)}: B(\theta,\epsilon)\cap \Theta \to \mathcal{C}_Y$ is one-to-one. In other words, if we alter $\theta$ by a sufficiently small amount we will always get a different distribution.))
Consequently, in most ML applications we require that $p$ be continuous (and hopefully, almost everywhere differentiable) in the $\Theta$ component. (Without continuity, maximizing the likelihood generally becomes an intractable problem.) This leads to the following likelihood-oriented definition of a parametric family:
A parametric family of (univariate) distributions is a locally invertible map $$\mathcal{F}:\mathbb{R}\times\Theta \to [0,1],$$ with $\Theta\subset \mathbb{R}^n$, for which (a) each $\mathcal{F}_\theta$ is a distribution function and (b) for each $x\in\mathbb R$, the function $\mathcal{L}_x: \theta\to [0,1]$ given by $\mathcal{L}_x(\theta) = \mathcal{F}(x,\theta)$ is continuous and almost everywhere differentiable.
Note that a parametric family $\mathcal F$ is more than just the collection of $\mathcal{F}_\theta$: it also includes the specific way in which parameter values $\theta$ correspond to distributions.
Let's end up with some illustrative examples.
Let $\mathcal{C}_Y$ be the set of all Normal distributions. As
given, this is not a parametric family: it's just a family. To be
parametric, we have to choose a parameterization. One way is to
choose $\Theta = \{(\mu,\sigma)\in\mathbb{R}^2\mid \sigma \gt 0\}$
and to map $(\mu,\sigma)$ to the Normal distribution with mean $\mu$
and variance $\sigma^2$.
The set of Poisson$(\lambda)$ distributions is a parametric family
with $\lambda\in\Theta=(0,\infty)\subset\mathbb{R}^1$.
The set of Uniform$(\theta, \theta+1)$ distributions (which features
prominently in many textbook exercises) is a parametric family with
$\theta\in\mathbb{R}^1$. In this case, $F_\theta(x) = \max(0,
\min(1, x-\theta))$ is differentiable in $\theta$ except for
$\theta\in\{x, x-1\}$.
Let $F$ and $G$ be any two distributions. Then $\mathcal{F}(x,\theta)=(1-\theta)F(x)+\theta G(x)$ is a parametric family for $\theta\in[0,1]$. (Proof: the image of $\mathcal F$ is a set of distributions and its partial derivative in $\theta$ equals $-F(x)+G(x)$ which is defined everywhere.)
The Pearson family is a four-dimensional family, $\Theta\subset\mathbb{R}^4$, which includes (among others) the Normal distributions, Beta distributions, and Inverse Gamma distributions. This illustrates the fact that any one given distribution may belong to many different distribution families. This is perfectly analogous to observing that any point in a (sufficiently large) space may belong to many paths that intersect there. This, together with the previous construction, shows us that no distribution uniquely determines a family to which it belongs.
The family $\mathcal{C}_Y$ of all finite-variance absolutely continuous distributions is not parametric. The proof requires a deep theorem of topology: if we endow $\mathcal{C}_Y$ with any topology (whether statistically useful or not) and $p: \Theta\to\mathcal{C}_Y$ is continuous and locally has a continuous inverse, then locally $\mathcal{C}_Y$ must have the same dimension as that of $\Theta$. However, in all statistically meaningful topologies, $\mathcal{C}_Y$ is infinite dimensional. | Definition of family of a distribution? | The statistical and mathematical concepts are exactly the same, understanding that "family" is a generic mathematical term with technical variations adapted to different circumstances:
A parametric | Definition of family of a distribution?
The statistical and mathematical concepts are exactly the same, understanding that "family" is a generic mathematical term with technical variations adapted to different circumstances:
A parametric family is a curve (or surface or other finite-dimensional generalization thereof) in the space of all distributions.
The rest of this post explains what that means. As an aside, I don't think any of this is controversial, either mathematically or statistically (apart from one minor issue which is noted below). In support of this opinion I have supplied many references (mostly to Wikipedia articles).
This terminology of "families" tends to be used when studying classes $\mathcal C_Y$ of functions into a set $Y$ or "maps." Given a domain $X$, a family $\mathcal F$ of maps on $X$ parameterized by some set $\Theta$ (the "parameters") is a function
$$\mathcal F : X\times \Theta\to Y$$
for which (1) for each $\theta\in\Theta$, the function $\mathcal{F}_\theta:X\to Y$ given by $\mathcal{F}_\theta(x)=\mathcal{F}(x,\theta)$ is in $\mathcal{C}_Y$ and (2) $\mathcal F$ itself has certain "nice" properties.
The idea is that we want to vary functions from $X$ to $Y$ in a "smooth" or controlled manner. Property (1) means that each $\theta$ designates such a function, while the details of property (2) will capture the sense in which a "small" change in $\theta$ induces a sufficiently "small" change in $\mathcal{F}_\theta$.
A standard mathematical example, close to the one mentioned in the question, is a homotopy. In this case $\mathcal{C}_Y$ is the category of continuous maps from topological spaces $X$ into the topological space $Y$; $\Theta=[0,1]\subset\mathbb{R}$ is the unit interval with its usual topology, and we require that $\mathcal{F}$ be a continuous map from the topological product $X \times \Theta$ into $Y$. It can be thought of as a "continuous deformation of the map $\mathcal{F}_0$ to $\mathcal{F}_1$." When $X=[0,1]$ is itself an interval, such maps are curves in $Y$ and the homotopy is a smooth deformation from one curve to another.
For statistical applications, $\mathcal{C}_Y$ is the set of all distributions on $\mathbb{R}$ (or, in practice, on $\mathbb{R}^n$ for some $n$, but to keep the exposition simple I will focus on $n=1$). We may identify it with the set of all non-decreasing càdlàg functions $\mathbb{R}\to [0,1]$ where the closure of their range includes both $0$ and $1$: these are the cumulative distribution functions, or simply distribution functions. Thus, $X=\mathbb R$ and $Y=[0,1]$.
A family of distributions is any subset of $\mathcal{C}_Y$. Another name for a family is statistical model. It consists of all distributions that we suppose govern our observations, but we do not otherwise know which distribution is the actual one.
A family can be empty.
$\mathcal{C}_Y$ itself is a family.
A family may consist of a single distribution or just a finite number of them.
These abstract set-theoretic characteristics are of relatively little interest or utility. It is only when we consider additional (relevant) mathematical structure on $\mathcal{C}_Y$ that this concept becomes useful. But what properties of $\mathcal{C}_Y$ are of statistical interest? Some that show up frequently are:
$\mathcal{C}_Y$ is a convex set: given any two distributions ${F}, {G}\in \mathcal{C}_Y$, we may form the mixture distribution $(1-t){F}+t{G}\in Y$ for all $t\in[0,1]$. This is a kind of "homotopy" from $F$ to $G$.
Large parts of $\mathcal{C}_Y$ support various pseudo metrics, such as the Kullback-Leibler divergence or the closely related Fisher Information metric.
$\mathcal{C}_Y$ has an additive structure: corresponding to any two distributions $F$ and $G$ is their sum, ${F}\star {G}$.
$\mathcal{C}_Y$ supports many useful, natural functions, often termed "properties." These include any fixed quantile (such as the median) as well as the cumulants.
$\mathcal{C}_Y$ is a subset of a function space. As such, it inherits many useful metrics, such as the sup norm ($L^\infty$ norm) given by $$||F-G||_\infty = \sup_{x\in\mathbb{R}}|F(x)-G(x)|.$$
Natural group actions on $\mathbb R$ induce actions on $\mathcal{C}_Y$. The commonest actions are translations $T_\mu:x \to x+\mu$ and scalings $S_\sigma:x\to x\sigma$ for $\sigma\gt 0$. The effect these have on a distribution is to send $F$ to the distribution given by $F^{\mu,\sigma}(x) = F((x-\mu)/\sigma)$. These lead to the concepts of location-scale families and their generalizations. (I don't supply a reference, because extensive Web searches turn up a variety of different definitions: here, at least, may be a tiny bit of controversy.)
The properties that matter depend on the statistical problem and on how you intend to analyze the data. Addressing all the variations suggested by the preceding characteristics would take too much space for this medium. Let's focus on one common important application.
Take, for instance, Maximum Likelihood. In most applications you will want to be able to use Calculus to obtain an estimate. For this to work, you must be able to "take derivatives" in the family.
(Technical aside: The usual way in which this is accomplished is to select a domain $\Theta\subset \mathbb{R}^d$ for $d\ge 0$ and specify a continuous, locally invertible function $p$ from $\Theta$ into $\mathcal{C}_Y$. (This means that for every $\theta\in\Theta$ there exists a ball $B(\theta, \epsilon)$, with $\epsilon\gt 0$ for which $p\mid_{B(\theta,\epsilon)}: B(\theta,\epsilon)\cap \Theta \to \mathcal{C}_Y$ is one-to-one. In other words, if we alter $\theta$ by a sufficiently small amount we will always get a different distribution.))
Consequently, in most ML applications we require that $p$ be continuous (and hopefully, almost everywhere differentiable) in the $\Theta$ component. (Without continuity, maximizing the likelihood generally becomes an intractable problem.) This leads to the following likelihood-oriented definition of a parametric family:
A parametric family of (univariate) distributions is a locally invertible map $$\mathcal{F}:\mathbb{R}\times\Theta \to [0,1],$$ with $\Theta\subset \mathbb{R}^n$, for which (a) each $\mathcal{F}_\theta$ is a distribution function and (b) for each $x\in\mathbb R$, the function $\mathcal{L}_x: \theta\to [0,1]$ given by $\mathcal{L}_x(\theta) = \mathcal{F}(x,\theta)$ is continuous and almost everywhere differentiable.
Note that a parametric family $\mathcal F$ is more than just the collection of $\mathcal{F}_\theta$: it also includes the specific way in which parameter values $\theta$ correspond to distributions.
Let's end up with some illustrative examples.
Let $\mathcal{C}_Y$ be the set of all Normal distributions. As
given, this is not a parametric family: it's just a family. To be
parametric, we have to choose a parameterization. One way is to
choose $\Theta = \{(\mu,\sigma)\in\mathbb{R}^2\mid \sigma \gt 0\}$
and to map $(\mu,\sigma)$ to the Normal distribution with mean $\mu$
and variance $\sigma^2$.
The set of Poisson$(\lambda)$ distributions is a parametric family
with $\lambda\in\Theta=(0,\infty)\subset\mathbb{R}^1$.
The set of Uniform$(\theta, \theta+1)$ distributions (which features
prominently in many textbook exercises) is a parametric family with
$\theta\in\mathbb{R}^1$. In this case, $F_\theta(x) = \max(0,
\min(1, x-\theta))$ is differentiable in $\theta$ except for
$\theta\in\{x, x-1\}$.
Let $F$ and $G$ be any two distributions. Then $\mathcal{F}(x,\theta)=(1-\theta)F(x)+\theta G(x)$ is a parametric family for $\theta\in[0,1]$. (Proof: the image of $\mathcal F$ is a set of distributions and its partial derivative in $\theta$ equals $-F(x)+G(x)$ which is defined everywhere.)
The Pearson family is a four-dimensional family, $\Theta\subset\mathbb{R}^4$, which includes (among others) the Normal distributions, Beta distributions, and Inverse Gamma distributions. This illustrates the fact that any one given distribution may belong to many different distribution families. This is perfectly analogous to observing that any point in a (sufficiently large) space may belong to many paths that intersect there. This, together with the previous construction, shows us that no distribution uniquely determines a family to which it belongs.
The family $\mathcal{C}_Y$ of all finite-variance absolutely continuous distributions is not parametric. The proof requires a deep theorem of topology: if we endow $\mathcal{C}_Y$ with any topology (whether statistically useful or not) and $p: \Theta\to\mathcal{C}_Y$ is continuous and locally has a continuous inverse, then locally $\mathcal{C}_Y$ must have the same dimension as that of $\Theta$. However, in all statistically meaningful topologies, $\mathcal{C}_Y$ is infinite dimensional. | Definition of family of a distribution?
The statistical and mathematical concepts are exactly the same, understanding that "family" is a generic mathematical term with technical variations adapted to different circumstances:
A parametric |
17,576 | Definition of family of a distribution? | To address a specific point brought up in the question: "exponential family" does not denote a set of distributions. (The standard, say, exponential distribution is a member of the family of exponential distributions, an exponential family; of the family of gamma distributions, also an exponential family; of the family of Weibull distributions, not an exponential family; & of any number of other families you might dream up.) Rather, "exponential" here refers to a property possessed by a family of distributions. So we shouldn't talk of "distributions in the exponential family" but of "exponential families of distributions"—the former is an abuse of terminology, as @JuhoKokkala points out. For some reason no-one commits this abuse when talking of location–scale families. | Definition of family of a distribution? | To address a specific point brought up in the question: "exponential family" does not denote a set of distributions. (The standard, say, exponential distribution is a member of the family of exponenti | Definition of family of a distribution?
To address a specific point brought up in the question: "exponential family" does not denote a set of distributions. (The standard, say, exponential distribution is a member of the family of exponential distributions, an exponential family; of the family of gamma distributions, also an exponential family; of the family of Weibull distributions, not an exponential family; & of any number of other families you might dream up.) Rather, "exponential" here refers to a property possessed by a family of distributions. So we shouldn't talk of "distributions in the exponential family" but of "exponential families of distributions"—the former is an abuse of terminology, as @JuhoKokkala points out. For some reason no-one commits this abuse when talking of location–scale families. | Definition of family of a distribution?
To address a specific point brought up in the question: "exponential family" does not denote a set of distributions. (The standard, say, exponential distribution is a member of the family of exponenti |
17,577 | Definition of family of a distribution? | Thanks to @whuber there is enough information to summarize in what I hope is a simpler form relating to the question from which this post arose. "Another name for a family [Sic, statistical family] is [a] statistical model."
From that Wikipedia entry: A statistical model consists of all distributions that we suppose govern our observations, but we do not otherwise know which distribution is the actual one. What distinguishes a statistical model from other mathematical models is that a statistical model is non-deterministic. Thus, in a statistical model specified via mathematical equations, some of the variables do not have specific values, but instead have probability distributions; i.e., some of the variables are stochastic. A statistical model is usually thought of as a pair $( S , P )$, where $S$ is the set of possible observations, i.e., the sample space, and $P$ is a set of probability distributions on $S$.
Suppose that we have a statistical model $(S, \mathcal{P})$ with $\mathcal{P}=\{P_{\theta} : \theta \in \Theta\}$. The model is said to be a Parametric model if $\Theta$ has a finite dimension. In notation, we write that $\Theta \subseteq \mathbb{R}^d$ where $d$ is a positive integer ($\mathbb{R}$ denotes the real numbers; other sets can be used, in principle). Here, $d$ is called the dimension of the model.
As an example, if we assume that data arise from a univariate Gaussian distribution, then we are assuming that
$$\mathcal{P}=\left\{P_{\mu,\sigma }(x) \equiv \frac{1}{\sqrt{2 \pi} \sigma} \exp\left( -\frac{(x-\mu)^2}{2\sigma^2}\right) : \mu \in \mathbb{R}, \sigma > 0 \right\}. $$
In this example, the dimension, $d$, equals 2, end quote.
Thus, if we reduce the dimensionality by assigning, for the example above, $\mu=0$, we can show a family of curves by plotting $\sigma=1,2,3,4,5$ or whatever choices for $\sigma$. | Definition of family of a distribution? | Thanks to @whuber there is enough information to summarize in what I hope is a simpler form relating to the question from which this post arose. "Another name for a family [Sic, statistical family] is | Definition of family of a distribution?
Thanks to @whuber there is enough information to summarize in what I hope is a simpler form relating to the question from which this post arose. "Another name for a family [Sic, statistical family] is [a] statistical model."
From that Wikipedia entry: A statistical model consists of all distributions that we suppose govern our observations, but we do not otherwise know which distribution is the actual one. What distinguishes a statistical model from other mathematical models is that a statistical model is non-deterministic. Thus, in a statistical model specified via mathematical equations, some of the variables do not have specific values, but instead have probability distributions; i.e., some of the variables are stochastic. A statistical model is usually thought of as a pair $( S , P )$, where $S$ is the set of possible observations, i.e., the sample space, and $P$ is a set of probability distributions on $S$.
Suppose that we have a statistical model $(S, \mathcal{P})$ with $\mathcal{P}=\{P_{\theta} : \theta \in \Theta\}$. The model is said to be a Parametric model if $\Theta$ has a finite dimension. In notation, we write that $\Theta \subseteq \mathbb{R}^d$ where $d$ is a positive integer ($\mathbb{R}$ denotes the real numbers; other sets can be used, in principle). Here, $d$ is called the dimension of the model.
As an example, if we assume that data arise from a univariate Gaussian distribution, then we are assuming that
$$\mathcal{P}=\left\{P_{\mu,\sigma }(x) \equiv \frac{1}{\sqrt{2 \pi} \sigma} \exp\left( -\frac{(x-\mu)^2}{2\sigma^2}\right) : \mu \in \mathbb{R}, \sigma > 0 \right\}. $$
In this example, the dimension, $d$, equals 2, end quote.
Thus, if we reduce the dimensionality by assigning, for the example above, $\mu=0$, we can show a family of curves by plotting $\sigma=1,2,3,4,5$ or whatever choices for $\sigma$. | Definition of family of a distribution?
Thanks to @whuber there is enough information to summarize in what I hope is a simpler form relating to the question from which this post arose. "Another name for a family [Sic, statistical family] is |
17,578 | Difference between multitask learning and transfer learning | Single Task Learning: Giving a set of learning tasks, t1 , t2 , …, t(n), learn each task independently. This is the most commonly used machine learning paradigm in practice.
Multitask Learning: Giving a set of learning tasks, t1 , t2 , …, t(n), co-learn all tasks simultaneously. In other words, the learner optimizes the learning/performance across all of the n tasks through some shared knowledge. This may also be called batch multitask learning. Online multitask learning is more like lifelong learning (see below).
Transfer Learning (or Domain Adaptation): Giving a set of source domains/tasks t1, t2, …, t(n-1) and the target domain/task t(n), the goal is to learn well for t(n) by transferring some shared knowledge from t1, t2, …, t(n-1) to t(n). Although this definition is quite general, almost the entire literature on transfer learning is about supervised transfer learning and the number of source domains is only one (i.e., n=2). It also assumes that there are labeled training data for the source domain and few or no labeled examples in the target domain/task, but there are a large amount of unlabeled data in t(n). Note that the goal of transfer learning is to learn well only for the target task. Learning of the source task(s) is irrelevant.
Lifelong Learning: The learner has performed learning on a sequence of tasks, from t1 to t(n-1). When faced with the nth task, it uses the relevant knowledge gained in the past n-1 tasks to help learning for the nth task. Based on this definition, lifelong learning is similar to the general transfer learning involving multiple source domains or tasks. However, some researchers have a narrower definition of lifelong learning. They regard it as the learning process that aims to learn well on the future task t(n) without seeing any future task data so far. This means that the system should generate some prior knowledge from the past observed tasks to help new/future task learning without observing any information from the future task t(n). The future task learning simply uses the knowledge. This definition makes lifelong learning different from both transfer learning and multitask learning. It is different from transfer learning because transfer learning identifies prior knowledge using the target/future task labeled and unlabeled data. It is different from multitask learning because lifelong learning does not jointly optimize the learning of the other tasks, which multitask learning does.
All content lifted from https://www.cs.uic.edu/~liub/IJCAI15-tutorial.html. | Difference between multitask learning and transfer learning | Single Task Learning: Giving a set of learning tasks, t1 , t2 , …, t(n), learn each task independently. This is the most commonly used machine learning paradigm in practice.
Multitask Learning: Giving | Difference between multitask learning and transfer learning
Single Task Learning: Giving a set of learning tasks, t1 , t2 , …, t(n), learn each task independently. This is the most commonly used machine learning paradigm in practice.
Multitask Learning: Giving a set of learning tasks, t1 , t2 , …, t(n), co-learn all tasks simultaneously. In other words, the learner optimizes the learning/performance across all of the n tasks through some shared knowledge. This may also be called batch multitask learning. Online multitask learning is more like lifelong learning (see below).
Transfer Learning (or Domain Adaptation): Giving a set of source domains/tasks t1, t2, …, t(n-1) and the target domain/task t(n), the goal is to learn well for t(n) by transferring some shared knowledge from t1, t2, …, t(n-1) to t(n). Although this definition is quite general, almost the entire literature on transfer learning is about supervised transfer learning and the number of source domains is only one (i.e., n=2). It also assumes that there are labeled training data for the source domain and few or no labeled examples in the target domain/task, but there are a large amount of unlabeled data in t(n). Note that the goal of transfer learning is to learn well only for the target task. Learning of the source task(s) is irrelevant.
Lifelong Learning: The learner has performed learning on a sequence of tasks, from t1 to t(n-1). When faced with the nth task, it uses the relevant knowledge gained in the past n-1 tasks to help learning for the nth task. Based on this definition, lifelong learning is similar to the general transfer learning involving multiple source domains or tasks. However, some researchers have a narrower definition of lifelong learning. They regard it as the learning process that aims to learn well on the future task t(n) without seeing any future task data so far. This means that the system should generate some prior knowledge from the past observed tasks to help new/future task learning without observing any information from the future task t(n). The future task learning simply uses the knowledge. This definition makes lifelong learning different from both transfer learning and multitask learning. It is different from transfer learning because transfer learning identifies prior knowledge using the target/future task labeled and unlabeled data. It is different from multitask learning because lifelong learning does not jointly optimize the learning of the other tasks, which multitask learning does.
All content lifted from https://www.cs.uic.edu/~liub/IJCAI15-tutorial.html. | Difference between multitask learning and transfer learning
Single Task Learning: Giving a set of learning tasks, t1 , t2 , …, t(n), learn each task independently. This is the most commonly used machine learning paradigm in practice.
Multitask Learning: Giving |
17,579 | Difference between multitask learning and transfer learning | Multi-task Learning and Transfer Learning methods although they have some things in common, they are not the same. Transfer Learning only aims at achieving high performance in the target task by transferring knowledge from the source task, while Multi-task Learning tries to learn the target and the source task simultaneously.
A major assumption in many machine learning and data mining algorithms is that the training and future data must be in the same feature space and have the same distribution. This assumption is weak and in many cases may not hold. For example, imagine that we have a classification task in one domain of interest, but we only have sufficient training data in another domain of interest, where the latter data may be in a different feature space or follow a different data distribution. In Multi-task Learning there is no mandatory to observe a difference in the distributions of the different tasks.
Transfer Learning is a broader topic than Domain Adaptation. The latter is the process that attempts to alter the source domain in a way to bring the distribution of the source closer to that of the target domain. Transfer Learning can include also the case when we want to transfer knowledge from an old task to newer and different one (e.g. in a classification problem that we have different labels), which has some similarities with the old, apart from the above explained situation where we have one task but there is a difference in the distributions of the data (e.g. sample bias etc). | Difference between multitask learning and transfer learning | Multi-task Learning and Transfer Learning methods although they have some things in common, they are not the same. Transfer Learning only aims at achieving high performance in the target task by trans | Difference between multitask learning and transfer learning
Multi-task Learning and Transfer Learning methods although they have some things in common, they are not the same. Transfer Learning only aims at achieving high performance in the target task by transferring knowledge from the source task, while Multi-task Learning tries to learn the target and the source task simultaneously.
A major assumption in many machine learning and data mining algorithms is that the training and future data must be in the same feature space and have the same distribution. This assumption is weak and in many cases may not hold. For example, imagine that we have a classification task in one domain of interest, but we only have sufficient training data in another domain of interest, where the latter data may be in a different feature space or follow a different data distribution. In Multi-task Learning there is no mandatory to observe a difference in the distributions of the different tasks.
Transfer Learning is a broader topic than Domain Adaptation. The latter is the process that attempts to alter the source domain in a way to bring the distribution of the source closer to that of the target domain. Transfer Learning can include also the case when we want to transfer knowledge from an old task to newer and different one (e.g. in a classification problem that we have different labels), which has some similarities with the old, apart from the above explained situation where we have one task but there is a difference in the distributions of the data (e.g. sample bias etc). | Difference between multitask learning and transfer learning
Multi-task Learning and Transfer Learning methods although they have some things in common, they are not the same. Transfer Learning only aims at achieving high performance in the target task by trans |
17,580 | Difference between multitask learning and transfer learning | There is a slightly different (and I think better) answer in the ICML 2018 review ( https://towardsdatascience.com/icml-2018-advances-in-transfer-multitask-and-semi-supervised-learning-2a15ef7208ec ), where multi-task learning, domain adaptation and fine-tuning are specific cases of transfer learning.
Lifelong learning (or Metalearning) accumulates knowledge from multiple "historical" tasks seen in the past, with the objective of improving performances on future tasks. It's related to multi-task learning, except that the tasks come from the past, and the targets are in the future. | Difference between multitask learning and transfer learning | There is a slightly different (and I think better) answer in the ICML 2018 review ( https://towardsdatascience.com/icml-2018-advances-in-transfer-multitask-and-semi-supervised-learning-2a15ef7208ec ), | Difference between multitask learning and transfer learning
There is a slightly different (and I think better) answer in the ICML 2018 review ( https://towardsdatascience.com/icml-2018-advances-in-transfer-multitask-and-semi-supervised-learning-2a15ef7208ec ), where multi-task learning, domain adaptation and fine-tuning are specific cases of transfer learning.
Lifelong learning (or Metalearning) accumulates knowledge from multiple "historical" tasks seen in the past, with the objective of improving performances on future tasks. It's related to multi-task learning, except that the tasks come from the past, and the targets are in the future. | Difference between multitask learning and transfer learning
There is a slightly different (and I think better) answer in the ICML 2018 review ( https://towardsdatascience.com/icml-2018-advances-in-transfer-multitask-and-semi-supervised-learning-2a15ef7208ec ), |
17,581 | How to set mini-batch size in SGD in keras | Yes you are right. In Keras batch_size refers to the batch size in Mini-batch Gradient Descent. If you want to run a Batch Gradient Descent, you need to set the batch_size to the number of training samples. Your code looks perfect except that I don't understand why you store the model.fit function to an object history. | How to set mini-batch size in SGD in keras | Yes you are right. In Keras batch_size refers to the batch size in Mini-batch Gradient Descent. If you want to run a Batch Gradient Descent, you need to set the batch_size to the number of training sa | How to set mini-batch size in SGD in keras
Yes you are right. In Keras batch_size refers to the batch size in Mini-batch Gradient Descent. If you want to run a Batch Gradient Descent, you need to set the batch_size to the number of training samples. Your code looks perfect except that I don't understand why you store the model.fit function to an object history. | How to set mini-batch size in SGD in keras
Yes you are right. In Keras batch_size refers to the batch size in Mini-batch Gradient Descent. If you want to run a Batch Gradient Descent, you need to set the batch_size to the number of training sa |
17,582 | How to set mini-batch size in SGD in keras | Taking theoretical considerations aside, given real-life dataset and size of typical modern neural network, it would usually take unreasonably long to train on batches of size one, and you won't have enough RAM and/or GPU memory to train on whole dataset at once. So it is usually not the question "if" mini-batch should be used, but "what size" of batches should you use. The batch_size argument is the number of observations to train on in a single step, usually smaller sizes work better because having regularizing effect. Moreover, often people use more complicated optimizers (e.g. Adam, RMSprop) and other regularization tricks, what makes the relation between model performance, batch size, learning rate and computation time more complicated. | How to set mini-batch size in SGD in keras | Taking theoretical considerations aside, given real-life dataset and size of typical modern neural network, it would usually take unreasonably long to train on batches of size one, and you won't have | How to set mini-batch size in SGD in keras
Taking theoretical considerations aside, given real-life dataset and size of typical modern neural network, it would usually take unreasonably long to train on batches of size one, and you won't have enough RAM and/or GPU memory to train on whole dataset at once. So it is usually not the question "if" mini-batch should be used, but "what size" of batches should you use. The batch_size argument is the number of observations to train on in a single step, usually smaller sizes work better because having regularizing effect. Moreover, often people use more complicated optimizers (e.g. Adam, RMSprop) and other regularization tricks, what makes the relation between model performance, batch size, learning rate and computation time more complicated. | How to set mini-batch size in SGD in keras
Taking theoretical considerations aside, given real-life dataset and size of typical modern neural network, it would usually take unreasonably long to train on batches of size one, and you won't have |
17,583 | Do you have to adhere to the likelihood principle to be a Bayesian? | In the use of Bayes' Theorem to calculate the posterior probabilities that constitute inference about model parameters, the weak likelihood principle is automatically adhered to:
$$\mathrm{posterior} \propto \mathrm{prior} \times \mathrm{likelihood}$$
Nevertheless, in some objective Bayesian approaches the sampling scheme determines the choice of prior, the motivation being that an uninformative prior should maximize the divergence between the prior and posterior distributions—letting the data have as much influence as possible. Thus they violate the strong likelihood principle.
Jeffreys priors, for instance, are proportional to the square root of the determinant of the Fisher information, an expectation over the sample space. Consider inference about the probability parameter $\pi$ of Bernoulli trials under binomial & negative binomial sampling. The Jeffreys priors are
$$
\def\Pr{\mathop{\rm Pr}\nolimits}
\begin{align}
\Pr_\mathrm{NB}(\pi) &\propto \pi^{-1} (1-\pi)^{-\tfrac{1}{2}}\\
\Pr_\mathrm{Bin}(\pi) &\propto \pi^{-\tfrac{1}{2}} (1-\pi)^{-\tfrac{1}{2}}
\end{align}
$$
& conditioning on $x$ successes from $n$ trials leads to the posterior distributions
$$
\begin{align}
\Pr_\mathrm{NB}(\pi \mid x,n) \sim \mathrm{Beta}(x, n-x+\tfrac{1}{2})\\
\Pr_\mathrm{Bin}(\pi \mid x,n)\sim \mathrm{Beta}(x+\tfrac{1}{2}, n-x+\tfrac{1}{2})
\end{align}
$$
So observing say 1 success from 10 trials would lead to quite different posterior distributions under the two sampling schemes:
Though following such rules for deriving uninformative priors can sometimes leave you with improper priors, that in itself isn't the root of the violation of the likelhood principle entailed by the practice. An approximation to the Jeffreys prior, $ \pi^{-1+c} (1-\pi)^{-1/2}$,
where $0 < c\ll 1$, is quite proper, & makes negligible difference to the posterior.
You might also consider model checking—or doing anything as a result of your checks—as contrary to the weak likelihood principle; a flagrant case of using the ancillary part of the data. | Do you have to adhere to the likelihood principle to be a Bayesian? | In the use of Bayes' Theorem to calculate the posterior probabilities that constitute inference about model parameters, the weak likelihood principle is automatically adhered to:
$$\mathrm{posterior} | Do you have to adhere to the likelihood principle to be a Bayesian?
In the use of Bayes' Theorem to calculate the posterior probabilities that constitute inference about model parameters, the weak likelihood principle is automatically adhered to:
$$\mathrm{posterior} \propto \mathrm{prior} \times \mathrm{likelihood}$$
Nevertheless, in some objective Bayesian approaches the sampling scheme determines the choice of prior, the motivation being that an uninformative prior should maximize the divergence between the prior and posterior distributions—letting the data have as much influence as possible. Thus they violate the strong likelihood principle.
Jeffreys priors, for instance, are proportional to the square root of the determinant of the Fisher information, an expectation over the sample space. Consider inference about the probability parameter $\pi$ of Bernoulli trials under binomial & negative binomial sampling. The Jeffreys priors are
$$
\def\Pr{\mathop{\rm Pr}\nolimits}
\begin{align}
\Pr_\mathrm{NB}(\pi) &\propto \pi^{-1} (1-\pi)^{-\tfrac{1}{2}}\\
\Pr_\mathrm{Bin}(\pi) &\propto \pi^{-\tfrac{1}{2}} (1-\pi)^{-\tfrac{1}{2}}
\end{align}
$$
& conditioning on $x$ successes from $n$ trials leads to the posterior distributions
$$
\begin{align}
\Pr_\mathrm{NB}(\pi \mid x,n) \sim \mathrm{Beta}(x, n-x+\tfrac{1}{2})\\
\Pr_\mathrm{Bin}(\pi \mid x,n)\sim \mathrm{Beta}(x+\tfrac{1}{2}, n-x+\tfrac{1}{2})
\end{align}
$$
So observing say 1 success from 10 trials would lead to quite different posterior distributions under the two sampling schemes:
Though following such rules for deriving uninformative priors can sometimes leave you with improper priors, that in itself isn't the root of the violation of the likelhood principle entailed by the practice. An approximation to the Jeffreys prior, $ \pi^{-1+c} (1-\pi)^{-1/2}$,
where $0 < c\ll 1$, is quite proper, & makes negligible difference to the posterior.
You might also consider model checking—or doing anything as a result of your checks—as contrary to the weak likelihood principle; a flagrant case of using the ancillary part of the data. | Do you have to adhere to the likelihood principle to be a Bayesian?
In the use of Bayes' Theorem to calculate the posterior probabilities that constitute inference about model parameters, the weak likelihood principle is automatically adhered to:
$$\mathrm{posterior} |
17,584 | What are the pros and cons of applying pointwise mutual information on a word cooccurrence matrix before SVD? | according to Dan Jurafsky and James H. Martin book:
"It turns out, however, that simple frequency isn’t
the best measure of association between words. One problem is that raw frequency
is very skewed and not very discriminative. If we want to know what kinds of
contexts are shared by apricot and pineapple but not by digital and information,
we’re not going to get good discrimination from words like the, it, or they, which
occur frequently with all sorts of words and aren’t informative about any particular
word."
sometimes we replace this raw frequency with positive pointwise mutual information:
$$\text{PPMI}(w,c) = \max{\left(\log_{2}{\frac{P(w,c)}{P(w)P(c)}},0\right)}$$
PMI on its own shows how much it's possible to observe a word w with a context word C compare to observing them independently. In PPMI we only keep positive values of PMI. Let's think about when PMI is + or - and why we only keep negative ones:
What does positive PMI mean?
$\frac{P(w,c)}{(P(w)P(c))} > 1$
$P(w,c) > (P(w)P(c))$
it happens when $w$ and $c$ occur mutually more than individually
like kick and ball. We'd like to keep these!
What does negative PMI mean?
$\frac{P(w,c)}{(P(w)P(c))} < 1$
$P(w,c) < (P(w)P(c))$
it means both of $w$ and $c$ or one of them tend to occur individually! It might indicate unreliable stats due to limited data otherwise it shows uninformative co-occurrences e.g., 'the' and 'ball'. ('the' occurs with most of the words too.)
PMI or particularly PPMI helps us to catch such situations with informative co-occurrence. | What are the pros and cons of applying pointwise mutual information on a word cooccurrence matrix be | according to Dan Jurafsky and James H. Martin book:
"It turns out, however, that simple frequency isn’t
the best measure of association between words. One problem is that raw frequency
is very skewed | What are the pros and cons of applying pointwise mutual information on a word cooccurrence matrix before SVD?
according to Dan Jurafsky and James H. Martin book:
"It turns out, however, that simple frequency isn’t
the best measure of association between words. One problem is that raw frequency
is very skewed and not very discriminative. If we want to know what kinds of
contexts are shared by apricot and pineapple but not by digital and information,
we’re not going to get good discrimination from words like the, it, or they, which
occur frequently with all sorts of words and aren’t informative about any particular
word."
sometimes we replace this raw frequency with positive pointwise mutual information:
$$\text{PPMI}(w,c) = \max{\left(\log_{2}{\frac{P(w,c)}{P(w)P(c)}},0\right)}$$
PMI on its own shows how much it's possible to observe a word w with a context word C compare to observing them independently. In PPMI we only keep positive values of PMI. Let's think about when PMI is + or - and why we only keep negative ones:
What does positive PMI mean?
$\frac{P(w,c)}{(P(w)P(c))} > 1$
$P(w,c) > (P(w)P(c))$
it happens when $w$ and $c$ occur mutually more than individually
like kick and ball. We'd like to keep these!
What does negative PMI mean?
$\frac{P(w,c)}{(P(w)P(c))} < 1$
$P(w,c) < (P(w)P(c))$
it means both of $w$ and $c$ or one of them tend to occur individually! It might indicate unreliable stats due to limited data otherwise it shows uninformative co-occurrences e.g., 'the' and 'ball'. ('the' occurs with most of the words too.)
PMI or particularly PPMI helps us to catch such situations with informative co-occurrence. | What are the pros and cons of applying pointwise mutual information on a word cooccurrence matrix be
according to Dan Jurafsky and James H. Martin book:
"It turns out, however, that simple frequency isn’t
the best measure of association between words. One problem is that raw frequency
is very skewed |
17,585 | Mann-Whitney U-test: confidence interval for effect size | One choice of effect size for the Mann-Whitney U test is the common language effect size. For the Mann-Whitney U, this is the proportion of sample pairs that supports a stated hypothesis.
A second choice is the rank correlation; because the rank correlation ranges from -1 to +1, it has properties that are similar to the Pearson r. In addition, by the simple difference formula, the rank correlation is the difference between the common language effect size and its complement, a fact that promotes interpretation. For example, if there are 100 sample pairs, and if 70 sample pairs support the hypothesis, then the common language effect size is 70%, and the rank correlation is r = .70 = .30 = .40. A clear discussion of the common language effect size and of four formulas to compute the rank correlation is given by Kerby in the journal Innovative Teaching: Kerby (2014) Innovative Teaching
By the way, though the paper does not mention it, I am fairly certain that Somers d and the rank correlation for the Mann-Whitney are equivalent. | Mann-Whitney U-test: confidence interval for effect size | One choice of effect size for the Mann-Whitney U test is the common language effect size. For the Mann-Whitney U, this is the proportion of sample pairs that supports a stated hypothesis.
A second | Mann-Whitney U-test: confidence interval for effect size
One choice of effect size for the Mann-Whitney U test is the common language effect size. For the Mann-Whitney U, this is the proportion of sample pairs that supports a stated hypothesis.
A second choice is the rank correlation; because the rank correlation ranges from -1 to +1, it has properties that are similar to the Pearson r. In addition, by the simple difference formula, the rank correlation is the difference between the common language effect size and its complement, a fact that promotes interpretation. For example, if there are 100 sample pairs, and if 70 sample pairs support the hypothesis, then the common language effect size is 70%, and the rank correlation is r = .70 = .30 = .40. A clear discussion of the common language effect size and of four formulas to compute the rank correlation is given by Kerby in the journal Innovative Teaching: Kerby (2014) Innovative Teaching
By the way, though the paper does not mention it, I am fairly certain that Somers d and the rank correlation for the Mann-Whitney are equivalent. | Mann-Whitney U-test: confidence interval for effect size
One choice of effect size for the Mann-Whitney U test is the common language effect size. For the Mann-Whitney U, this is the proportion of sample pairs that supports a stated hypothesis.
A second |
17,586 | Mann-Whitney U-test: confidence interval for effect size | Your link leads me to an opportunity to purchase the article.
More fundamental to the Wilcoxon-Mann-Whitney 2-sample test is the concordance probability, which is a pure measure of separation of the two groups. You can get confidence intervals for this $c$-index a variety of ways, e.g., in R the Hmisc package rcorr.cens function which does not assume equal variance in the two groups. You can also convert $c$ to Somers' $D_{xy}$ rank correlation through $D_{xy} = 2\times (c - \frac{1}{2})$. | Mann-Whitney U-test: confidence interval for effect size | Your link leads me to an opportunity to purchase the article.
More fundamental to the Wilcoxon-Mann-Whitney 2-sample test is the concordance probability, which is a pure measure of separation of the t | Mann-Whitney U-test: confidence interval for effect size
Your link leads me to an opportunity to purchase the article.
More fundamental to the Wilcoxon-Mann-Whitney 2-sample test is the concordance probability, which is a pure measure of separation of the two groups. You can get confidence intervals for this $c$-index a variety of ways, e.g., in R the Hmisc package rcorr.cens function which does not assume equal variance in the two groups. You can also convert $c$ to Somers' $D_{xy}$ rank correlation through $D_{xy} = 2\times (c - \frac{1}{2})$. | Mann-Whitney U-test: confidence interval for effect size
Your link leads me to an opportunity to purchase the article.
More fundamental to the Wilcoxon-Mann-Whitney 2-sample test is the concordance probability, which is a pure measure of separation of the t |
17,587 | How does PCA improve the accuracy of a predictive model? [duplicate] | Dadi Perlmutter once said: "What is the difference between theory and practice? In theory they are the same while in practice they are different". This is one of those cases.
Methods like Neural Networks often use gradient descent derived methods. In theory if you had infinite number of iterations and retries, the algorithm is going to converge to the same result independent of coordinate system. Neural Networks do not like the "curse of dimensionality" and so using PCA to reduce the dimension of the data can improve speed of convergence and quality of results. The transformation of the data, by centering, rotating and scaling informed by PCA can improve the convergence time and the quality of results.
In theory the PCA makes no difference, but in practice it improves rate of training, simplifies the required neural structure to represent the data, and results in systems that better characterize the "intermediate structure" of the data instead of having to account for multiple scales - it is more accurate.
My guess is that there are analogous reasons that apply to random forests of gradient boosted trees or other similar creatures. (Link) | How does PCA improve the accuracy of a predictive model? [duplicate] | Dadi Perlmutter once said: "What is the difference between theory and practice? In theory they are the same while in practice they are different". This is one of those cases.
Methods like Neural Net | How does PCA improve the accuracy of a predictive model? [duplicate]
Dadi Perlmutter once said: "What is the difference between theory and practice? In theory they are the same while in practice they are different". This is one of those cases.
Methods like Neural Networks often use gradient descent derived methods. In theory if you had infinite number of iterations and retries, the algorithm is going to converge to the same result independent of coordinate system. Neural Networks do not like the "curse of dimensionality" and so using PCA to reduce the dimension of the data can improve speed of convergence and quality of results. The transformation of the data, by centering, rotating and scaling informed by PCA can improve the convergence time and the quality of results.
In theory the PCA makes no difference, but in practice it improves rate of training, simplifies the required neural structure to represent the data, and results in systems that better characterize the "intermediate structure" of the data instead of having to account for multiple scales - it is more accurate.
My guess is that there are analogous reasons that apply to random forests of gradient boosted trees or other similar creatures. (Link) | How does PCA improve the accuracy of a predictive model? [duplicate]
Dadi Perlmutter once said: "What is the difference between theory and practice? In theory they are the same while in practice they are different". This is one of those cases.
Methods like Neural Net |
17,588 | How does PCA improve the accuracy of a predictive model? [duplicate] | Disclaimer: I'm usually wrong at things.
Decision trees, by virtue of doing recursive splitting of your samples, with splits being based on a single variable, can only generate decision boundaries parallel to the axes of your co-ordinate system. So by rotating the data to directions of maximum variance/diagonalizing your covariance matrix as best you can, it might be easier to put decision boundaries between your class distributions
That being said, I'm not sure why you'd do PCA (without discarding some of your eigenvectors) before using a neural network model or whatever, because the rotation alone makes no difference - the network can approximate any function through the feature space. | How does PCA improve the accuracy of a predictive model? [duplicate] | Disclaimer: I'm usually wrong at things.
Decision trees, by virtue of doing recursive splitting of your samples, with splits being based on a single variable, can only generate decision boundaries par | How does PCA improve the accuracy of a predictive model? [duplicate]
Disclaimer: I'm usually wrong at things.
Decision trees, by virtue of doing recursive splitting of your samples, with splits being based on a single variable, can only generate decision boundaries parallel to the axes of your co-ordinate system. So by rotating the data to directions of maximum variance/diagonalizing your covariance matrix as best you can, it might be easier to put decision boundaries between your class distributions
That being said, I'm not sure why you'd do PCA (without discarding some of your eigenvectors) before using a neural network model or whatever, because the rotation alone makes no difference - the network can approximate any function through the feature space. | How does PCA improve the accuracy of a predictive model? [duplicate]
Disclaimer: I'm usually wrong at things.
Decision trees, by virtue of doing recursive splitting of your samples, with splits being based on a single variable, can only generate decision boundaries par |
17,589 | How does PCA improve the accuracy of a predictive model? [duplicate] | An insight I gained from Jonathon Shlens' "A Tutorial on Principal Component Analysis":
Performing PCA is like choosing a camera angle, to gain the best possible view of the variance to be explained.
So I'm joining user1843053. At proper angle, decision boundaries parallel to the axes of new, rotated coordinate system might make more sense than in original feature space, allowing for better performance of e.g. decision trees, even without discarding "non-principal" dimensions. | How does PCA improve the accuracy of a predictive model? [duplicate] | An insight I gained from Jonathon Shlens' "A Tutorial on Principal Component Analysis":
Performing PCA is like choosing a camera angle, to gain the best possible view of the variance to be explained. | How does PCA improve the accuracy of a predictive model? [duplicate]
An insight I gained from Jonathon Shlens' "A Tutorial on Principal Component Analysis":
Performing PCA is like choosing a camera angle, to gain the best possible view of the variance to be explained.
So I'm joining user1843053. At proper angle, decision boundaries parallel to the axes of new, rotated coordinate system might make more sense than in original feature space, allowing for better performance of e.g. decision trees, even without discarding "non-principal" dimensions. | How does PCA improve the accuracy of a predictive model? [duplicate]
An insight I gained from Jonathon Shlens' "A Tutorial on Principal Component Analysis":
Performing PCA is like choosing a camera angle, to gain the best possible view of the variance to be explained. |
17,590 | How does PCA improve the accuracy of a predictive model? [duplicate] | The PCA is a change of variables, using the correlations explained by orthogonal directions.
Removing directions with non-representative corresponding correlation is like removing noise. You will only keep significant datas.
By the way, thanks for the site. | How does PCA improve the accuracy of a predictive model? [duplicate] | The PCA is a change of variables, using the correlations explained by orthogonal directions.
Removing directions with non-representative corresponding correlation is like removing noise. You will only | How does PCA improve the accuracy of a predictive model? [duplicate]
The PCA is a change of variables, using the correlations explained by orthogonal directions.
Removing directions with non-representative corresponding correlation is like removing noise. You will only keep significant datas.
By the way, thanks for the site. | How does PCA improve the accuracy of a predictive model? [duplicate]
The PCA is a change of variables, using the correlations explained by orthogonal directions.
Removing directions with non-representative corresponding correlation is like removing noise. You will only |
17,591 | Some questions about statistical randomness | The concept can be neatly illustrated by some executable code. We begin (in R) by using a good pseudo random number generator to create a sequence of 10,000 zeros and ones:
set.seed(17)
x <- floor(runif(10000, min=0, max=2))
This passes some basic random number tests. For instance, a t-test to compare the mean to $1/2$ has a p-value of $40.09$%, which allows us to accept the hypothesis that zeros and ones are equally likely.
From these numbers we proceed to extract a subsequence of $1000$ successive values starting at the 5081st value:
x0 <- x[1:1000 + 5080]
If these are to look random, they should also pass the same random number tests. For instance, let's test whether their mean is 1/2:
> t.test(x0-1/2)
One Sample t-test
data: x0 - 1/2
t = 2.6005, df = 999, p-value = 0.009445
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
0.01006167 0.07193833
sample estimates:
mean of x
0.041
The low p-value (less than 1%) strongly suggests the mean is significantly greater than $1/2$. Indeed, the cumulative sum of this subsequence has a strong upward trend:
> plot(cumsum(x0-1/2))
That's not random behavior!
Comparing the original sequence (plotted as a cumulative sum) to this subsequence reveals what's going on:
The long sequence indeed behaves like a random walk--as it should--but the particular subsequence I extracted contains the longest upward rise among all subsequences of the same length. It looks like I could have extracted some other subsequences exhibiting "nonrandom" behavior, too, such as the one centered around $9000$ where approximately 20 ones in a row appear!
As these simple analyses have shown, no test can "prove" that a sequence appears random. All we can do is test whether sequences deviate enough from the behaviors expected of random sequences to offer evidence that they are not random. This is how batteries of random-number tests work: they look for patterns highly unlikely to arise in random number sequences. Every once in a long while they will cause us to conclude that a truly random sequence of numbers does not appear random: we will reject it an try something else.
In the long run, though--just as we are all dead--any truly random number generator will generate every possible sequence of 1000 digits, and it will do so infinitely many times. What rescues us from a logical quandary is that we would have to wait an awfully long time for such an apparent aberration to occur. | Some questions about statistical randomness | The concept can be neatly illustrated by some executable code. We begin (in R) by using a good pseudo random number generator to create a sequence of 10,000 zeros and ones:
set.seed(17)
x <- floor(ru | Some questions about statistical randomness
The concept can be neatly illustrated by some executable code. We begin (in R) by using a good pseudo random number generator to create a sequence of 10,000 zeros and ones:
set.seed(17)
x <- floor(runif(10000, min=0, max=2))
This passes some basic random number tests. For instance, a t-test to compare the mean to $1/2$ has a p-value of $40.09$%, which allows us to accept the hypothesis that zeros and ones are equally likely.
From these numbers we proceed to extract a subsequence of $1000$ successive values starting at the 5081st value:
x0 <- x[1:1000 + 5080]
If these are to look random, they should also pass the same random number tests. For instance, let's test whether their mean is 1/2:
> t.test(x0-1/2)
One Sample t-test
data: x0 - 1/2
t = 2.6005, df = 999, p-value = 0.009445
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
0.01006167 0.07193833
sample estimates:
mean of x
0.041
The low p-value (less than 1%) strongly suggests the mean is significantly greater than $1/2$. Indeed, the cumulative sum of this subsequence has a strong upward trend:
> plot(cumsum(x0-1/2))
That's not random behavior!
Comparing the original sequence (plotted as a cumulative sum) to this subsequence reveals what's going on:
The long sequence indeed behaves like a random walk--as it should--but the particular subsequence I extracted contains the longest upward rise among all subsequences of the same length. It looks like I could have extracted some other subsequences exhibiting "nonrandom" behavior, too, such as the one centered around $9000$ where approximately 20 ones in a row appear!
As these simple analyses have shown, no test can "prove" that a sequence appears random. All we can do is test whether sequences deviate enough from the behaviors expected of random sequences to offer evidence that they are not random. This is how batteries of random-number tests work: they look for patterns highly unlikely to arise in random number sequences. Every once in a long while they will cause us to conclude that a truly random sequence of numbers does not appear random: we will reject it an try something else.
In the long run, though--just as we are all dead--any truly random number generator will generate every possible sequence of 1000 digits, and it will do so infinitely many times. What rescues us from a logical quandary is that we would have to wait an awfully long time for such an apparent aberration to occur. | Some questions about statistical randomness
The concept can be neatly illustrated by some executable code. We begin (in R) by using a good pseudo random number generator to create a sequence of 10,000 zeros and ones:
set.seed(17)
x <- floor(ru |
17,592 | Some questions about statistical randomness | This excerpt uses terms "local randomness" and "global randomness" to distinguish between what can occur with a finite number of samples of a random variable, and the probability distribution or expectation of a random variable.
For example, repeated trials $x_i$ of a Bernoulli random variable (taking values in $\{0,1\}$) with expectation $\theta$ will, as the number of samples of goes to infinity, produce sample mean $\theta$. That is, $\lim_{n \to \infty} \frac{1}{n} \sum_{i=1}^n x_i = \theta$. This comes from the law of large numbers.
However, when evaluating the sample mean for finite samples we will get all kinds of values in $[0,1]$. In fact there is a finite probability of getting the sample mean to fall in the range $[a,b]$ for any $0 \leq a < b \leq 1$ for any value of $\theta$.
Nothing new here.
However, this excerpt seems to be making the rather obvious point that the larger $n$ is, the more likely we are to see behavior looks "locally random" with "locally random" defined (incorrectly) as exhibiting patterns that are close to the mean (in this example.)
Thus, I wouldn't burn too many brain cells thinking about this excerpt. It's not mathematically so precise and is actually misleading about the nature of randomness.
Edit based on comment: @kjetilbhalvorsen +1 to your comment for the historical knowledge. However, I still think the value of these terms is limited and misleading. The tables you're describing seem to make the misleading implication that small samples which have, for example, sample mean far from the actual expected value or perhaps an improbable but certainly possible long sequence of repeated 0's (in my Bernoulli example), somehow exhibit less randomness (by saying they do not exhibit this phony "local randomness"). I can't think of anything more misleading for the budding statistician! | Some questions about statistical randomness | This excerpt uses terms "local randomness" and "global randomness" to distinguish between what can occur with a finite number of samples of a random variable, and the probability distribution or expec | Some questions about statistical randomness
This excerpt uses terms "local randomness" and "global randomness" to distinguish between what can occur with a finite number of samples of a random variable, and the probability distribution or expectation of a random variable.
For example, repeated trials $x_i$ of a Bernoulli random variable (taking values in $\{0,1\}$) with expectation $\theta$ will, as the number of samples of goes to infinity, produce sample mean $\theta$. That is, $\lim_{n \to \infty} \frac{1}{n} \sum_{i=1}^n x_i = \theta$. This comes from the law of large numbers.
However, when evaluating the sample mean for finite samples we will get all kinds of values in $[0,1]$. In fact there is a finite probability of getting the sample mean to fall in the range $[a,b]$ for any $0 \leq a < b \leq 1$ for any value of $\theta$.
Nothing new here.
However, this excerpt seems to be making the rather obvious point that the larger $n$ is, the more likely we are to see behavior looks "locally random" with "locally random" defined (incorrectly) as exhibiting patterns that are close to the mean (in this example.)
Thus, I wouldn't burn too many brain cells thinking about this excerpt. It's not mathematically so precise and is actually misleading about the nature of randomness.
Edit based on comment: @kjetilbhalvorsen +1 to your comment for the historical knowledge. However, I still think the value of these terms is limited and misleading. The tables you're describing seem to make the misleading implication that small samples which have, for example, sample mean far from the actual expected value or perhaps an improbable but certainly possible long sequence of repeated 0's (in my Bernoulli example), somehow exhibit less randomness (by saying they do not exhibit this phony "local randomness"). I can't think of anything more misleading for the budding statistician! | Some questions about statistical randomness
This excerpt uses terms "local randomness" and "global randomness" to distinguish between what can occur with a finite number of samples of a random variable, and the probability distribution or expec |
17,593 | Some questions about statistical randomness | I think the authors of the Wikipedia post are misconstruing randomness. Yes, there might be stretches that appear not to be random, but if the process that created the sequence is truly random, so must be the output. If certain sequences appear to be non random, that is an erroneous perception of the reader (i.e. humans are designed to find patterns). Our ability to see the Big Dipper, and Orion, etc in the night sky is no evidence that the patterns of stars is nonrandom. I agree that randomness often appears nonrandom. If a process generates truly nonrandom patterns for short sequences, it isn't a random process.
I don't think that the process changes at different sample sizes. You increase the sample size, you increase the probability that we see a random sequence that appears to us to be nonrandom. If there is a 10% chance that we would see a pattern in 20 random observations, increasing the total number of observations to 10000 would increase the likelihood that we would see nonrandomness, somewhere. | Some questions about statistical randomness | I think the authors of the Wikipedia post are misconstruing randomness. Yes, there might be stretches that appear not to be random, but if the process that created the sequence is truly random, so mus | Some questions about statistical randomness
I think the authors of the Wikipedia post are misconstruing randomness. Yes, there might be stretches that appear not to be random, but if the process that created the sequence is truly random, so must be the output. If certain sequences appear to be non random, that is an erroneous perception of the reader (i.e. humans are designed to find patterns). Our ability to see the Big Dipper, and Orion, etc in the night sky is no evidence that the patterns of stars is nonrandom. I agree that randomness often appears nonrandom. If a process generates truly nonrandom patterns for short sequences, it isn't a random process.
I don't think that the process changes at different sample sizes. You increase the sample size, you increase the probability that we see a random sequence that appears to us to be nonrandom. If there is a 10% chance that we would see a pattern in 20 random observations, increasing the total number of observations to 10000 would increase the likelihood that we would see nonrandomness, somewhere. | Some questions about statistical randomness
I think the authors of the Wikipedia post are misconstruing randomness. Yes, there might be stretches that appear not to be random, but if the process that created the sequence is truly random, so mus |
17,594 | Gaussian process : function approximation properties | Suppose data sample is $D = (X, \mathbf{y}) = \{\mathbf{x}_i, y_i = y(x_i)\}_{i = 1}^N$.
Also suppose, that we have a covariance function $k(\mathbf{x}_1, \mathbf{x}_2)$ and zero mean specified for a Gussian process. Distribution for a new point $\mathbf{x}$ will be Gaussian with mean $$m(\mathbf{x}) = \mathbf{k} K^{-1} \mathbf{y}$$ and variance $$V(\mathbf{x}) = k(\mathbf{x}, \mathbf{x}) - \mathbf{k} K^{-1} \mathbf{k}^T.$$ Vector $\mathbf{k} = \{k(\mathbf{x}, \mathbf{x}_1), \ldots, k(\mathbf{x}, \mathbf{x}_N)\}$ is a vector of covariances, matrix $K = \{k(\mathbf{x}_i, \mathbf{x}_j)\}_{i, j = 1}^N$ is a matrix of sample covariances. In case we make prediction using mean value of posterior distribution for sample interpolation property holds. Really,
$$m(X) = K K^{-1} \mathbf{y} = \mathbf{y}.$$
But, it isn't the case if we use regularization i.e. incorporate white noise term. in this case covariance matrix for sample has form $K + \sigma I$, but for covariances with real function values we have covariance matrix $K$, and posterior mean is
$$
m(X) = K (K + \sigma I)^{-1} \mathbf{y} \neq \mathbf{y}.
$$
In addition, regularization makes problem more computationally stable.
Choosing noise variance $\sigma$ we can select if we want interpolation ($\sigma = 0$) or we want to handle noisy observations ($\sigma$ is big).
Also, the Gaussian processes regression is local method because variance of predictions grows with distance to learning sample, but we can select appropriate covariance function $k$ and handle more complex problems, than with RBF. Another nice property is small number of parameters. Usually it equals $O(n)$, where $n$ is data dimension. | Gaussian process : function approximation properties | Suppose data sample is $D = (X, \mathbf{y}) = \{\mathbf{x}_i, y_i = y(x_i)\}_{i = 1}^N$.
Also suppose, that we have a covariance function $k(\mathbf{x}_1, \mathbf{x}_2)$ and zero mean specified for a | Gaussian process : function approximation properties
Suppose data sample is $D = (X, \mathbf{y}) = \{\mathbf{x}_i, y_i = y(x_i)\}_{i = 1}^N$.
Also suppose, that we have a covariance function $k(\mathbf{x}_1, \mathbf{x}_2)$ and zero mean specified for a Gussian process. Distribution for a new point $\mathbf{x}$ will be Gaussian with mean $$m(\mathbf{x}) = \mathbf{k} K^{-1} \mathbf{y}$$ and variance $$V(\mathbf{x}) = k(\mathbf{x}, \mathbf{x}) - \mathbf{k} K^{-1} \mathbf{k}^T.$$ Vector $\mathbf{k} = \{k(\mathbf{x}, \mathbf{x}_1), \ldots, k(\mathbf{x}, \mathbf{x}_N)\}$ is a vector of covariances, matrix $K = \{k(\mathbf{x}_i, \mathbf{x}_j)\}_{i, j = 1}^N$ is a matrix of sample covariances. In case we make prediction using mean value of posterior distribution for sample interpolation property holds. Really,
$$m(X) = K K^{-1} \mathbf{y} = \mathbf{y}.$$
But, it isn't the case if we use regularization i.e. incorporate white noise term. in this case covariance matrix for sample has form $K + \sigma I$, but for covariances with real function values we have covariance matrix $K$, and posterior mean is
$$
m(X) = K (K + \sigma I)^{-1} \mathbf{y} \neq \mathbf{y}.
$$
In addition, regularization makes problem more computationally stable.
Choosing noise variance $\sigma$ we can select if we want interpolation ($\sigma = 0$) or we want to handle noisy observations ($\sigma$ is big).
Also, the Gaussian processes regression is local method because variance of predictions grows with distance to learning sample, but we can select appropriate covariance function $k$ and handle more complex problems, than with RBF. Another nice property is small number of parameters. Usually it equals $O(n)$, where $n$ is data dimension. | Gaussian process : function approximation properties
Suppose data sample is $D = (X, \mathbf{y}) = \{\mathbf{x}_i, y_i = y(x_i)\}_{i = 1}^N$.
Also suppose, that we have a covariance function $k(\mathbf{x}_1, \mathbf{x}_2)$ and zero mean specified for a |
17,595 | Interpretation and validation of a Cox proportional hazards regression model using R in plain English | To get started, consider a few things. First, you are excluding too many observations with missing data and this will cause a bias. Consider multiple imputation. Second, there is a plot method for cox.zph which is useful in assessing proportional hazards. Third, you have assumed linearity for the covariate effects. Fourth, the number of events in your training sample is just barely large enough to fit a reliable model if all covariate effects happen to be linear (which is rare). And your test sample would have to have perhaps 400 events before it would yield a reliable assessment of prediction accuracy. It is not clear that you had enough data to split the data into two parts. Resampling validation (100 repeats of 10-fold cross-validation, or use the bootstrap) is a better solution. Both your original external validation (functions rcorr.cens and val.surv) and resampling internal validation (functions validate, calibrate) are implemented in the R rms package. Case studies for the rms package are found in my course notes at http://biostat.mc.vanderbilt.edu/rms (and I have a 3-day course on this in Nashville next month). Note that $2\times 2$ tables are not appropriate for use with continuous data. | Interpretation and validation of a Cox proportional hazards regression model using R in plain Englis | To get started, consider a few things. First, you are excluding too many observations with missing data and this will cause a bias. Consider multiple imputation. Second, there is a plot method for | Interpretation and validation of a Cox proportional hazards regression model using R in plain English
To get started, consider a few things. First, you are excluding too many observations with missing data and this will cause a bias. Consider multiple imputation. Second, there is a plot method for cox.zph which is useful in assessing proportional hazards. Third, you have assumed linearity for the covariate effects. Fourth, the number of events in your training sample is just barely large enough to fit a reliable model if all covariate effects happen to be linear (which is rare). And your test sample would have to have perhaps 400 events before it would yield a reliable assessment of prediction accuracy. It is not clear that you had enough data to split the data into two parts. Resampling validation (100 repeats of 10-fold cross-validation, or use the bootstrap) is a better solution. Both your original external validation (functions rcorr.cens and val.surv) and resampling internal validation (functions validate, calibrate) are implemented in the R rms package. Case studies for the rms package are found in my course notes at http://biostat.mc.vanderbilt.edu/rms (and I have a 3-day course on this in Nashville next month). Note that $2\times 2$ tables are not appropriate for use with continuous data. | Interpretation and validation of a Cox proportional hazards regression model using R in plain Englis
To get started, consider a few things. First, you are excluding too many observations with missing data and this will cause a bias. Consider multiple imputation. Second, there is a plot method for |
17,596 | Interpretation and validation of a Cox proportional hazards regression model using R in plain English | The output of the R cph function, based on a relevant example, is explained in this easy-to-follow paper by J. Fox.
I would strongly advise reading this paper if you have not already. | Interpretation and validation of a Cox proportional hazards regression model using R in plain Englis | The output of the R cph function, based on a relevant example, is explained in this easy-to-follow paper by J. Fox.
I would strongly advise reading this paper if you have not already. | Interpretation and validation of a Cox proportional hazards regression model using R in plain English
The output of the R cph function, based on a relevant example, is explained in this easy-to-follow paper by J. Fox.
I would strongly advise reading this paper if you have not already. | Interpretation and validation of a Cox proportional hazards regression model using R in plain Englis
The output of the R cph function, based on a relevant example, is explained in this easy-to-follow paper by J. Fox.
I would strongly advise reading this paper if you have not already. |
17,597 | How to test if my data is discrete or continuous? | The only reason I can immediately think of to require this decision, is to decide on the inclusion of a variable as continuous or categorical in a regression.
First off, sometimes you have no choice: character variables, or factors (where someone providing the data.frame has made the decision for you) are obviously categorical.
That leaves us with numerical variables. You may be tempted to simply check whether the variables are integers, but this is not a good criterion: look at the first line of code below (x1): these are 1000 observations of only the two values $-1.5$ and $2.5$: even though these are not integers, this seems an obvious categorical variable. What you could do for some x is check how many different values are in your data, though any threshold you might use for this will be subjective, I guess:
x1<-sample(c(-1.5, 2.5), 1000)
length(unique(x1)) #absolute number of different variables
length(unique(x1))/length(x1) #relative
x2<-runif(1000)
length(unique(x2)) #absolute number of different variables
length(unique(x2))/length(x2) #relative
I would tend to say that a variable that has only 5% unique values could be safely called discrete (but, as mentioned: this is subjective). However: this does not make it a good candidate for including it as a categorical variable in your model: If you have 1000000 observations, and 5% unique values, that still leaves 50000 'categories': if you include this as categorical, you're going to spend a hell of a lot of degrees of freedom.
I guess this call is even more subjective, and depends greatly on sample size and method of choice. Without more context, it's hard to give guidelines here.
So now you probably have some variables that you could add as categorical in your model. But should you? This question can be answered (though it really depends, again, on your goal) with a likelihood ratio test: The model where the variable is categorical is a supermodel of the model with the variable as a continuous covariate. To see this, imagine a linear regression on a variable xthat hold three values 0, 1 and 2. Fitting a model:
$$E[y] = \beta_0 + \beta_11 x_{1} + \beta_12 x_{2}$$
where the $x_i$ is a dummy variable indicator (it is equal to 1 if $x==i$) is just a more flexible way of fitting a model
$$E[y] = \beta_0 + \beta_1 x$$
because the last one is equivalent to
$$E[y] = \beta_0 + \beta_1 x_{1} + 2 \beta_1 x_{2}$$
With super/submodel structure, you can find out whether there is evidence in the data that the more complex structure is necessary, by doing a likelihood ratio test: -2 times the difference in log maximum likelihood (typically indicated as deviance in R) will follow a $\chi^2$ distribution with df= the difference in number of parameters (in the example above: 4 parameters - 3 parameters). | How to test if my data is discrete or continuous? | The only reason I can immediately think of to require this decision, is to decide on the inclusion of a variable as continuous or categorical in a regression.
First off, sometimes you have no choice: | How to test if my data is discrete or continuous?
The only reason I can immediately think of to require this decision, is to decide on the inclusion of a variable as continuous or categorical in a regression.
First off, sometimes you have no choice: character variables, or factors (where someone providing the data.frame has made the decision for you) are obviously categorical.
That leaves us with numerical variables. You may be tempted to simply check whether the variables are integers, but this is not a good criterion: look at the first line of code below (x1): these are 1000 observations of only the two values $-1.5$ and $2.5$: even though these are not integers, this seems an obvious categorical variable. What you could do for some x is check how many different values are in your data, though any threshold you might use for this will be subjective, I guess:
x1<-sample(c(-1.5, 2.5), 1000)
length(unique(x1)) #absolute number of different variables
length(unique(x1))/length(x1) #relative
x2<-runif(1000)
length(unique(x2)) #absolute number of different variables
length(unique(x2))/length(x2) #relative
I would tend to say that a variable that has only 5% unique values could be safely called discrete (but, as mentioned: this is subjective). However: this does not make it a good candidate for including it as a categorical variable in your model: If you have 1000000 observations, and 5% unique values, that still leaves 50000 'categories': if you include this as categorical, you're going to spend a hell of a lot of degrees of freedom.
I guess this call is even more subjective, and depends greatly on sample size and method of choice. Without more context, it's hard to give guidelines here.
So now you probably have some variables that you could add as categorical in your model. But should you? This question can be answered (though it really depends, again, on your goal) with a likelihood ratio test: The model where the variable is categorical is a supermodel of the model with the variable as a continuous covariate. To see this, imagine a linear regression on a variable xthat hold three values 0, 1 and 2. Fitting a model:
$$E[y] = \beta_0 + \beta_11 x_{1} + \beta_12 x_{2}$$
where the $x_i$ is a dummy variable indicator (it is equal to 1 if $x==i$) is just a more flexible way of fitting a model
$$E[y] = \beta_0 + \beta_1 x$$
because the last one is equivalent to
$$E[y] = \beta_0 + \beta_1 x_{1} + 2 \beta_1 x_{2}$$
With super/submodel structure, you can find out whether there is evidence in the data that the more complex structure is necessary, by doing a likelihood ratio test: -2 times the difference in log maximum likelihood (typically indicated as deviance in R) will follow a $\chi^2$ distribution with df= the difference in number of parameters (in the example above: 4 parameters - 3 parameters). | How to test if my data is discrete or continuous?
The only reason I can immediately think of to require this decision, is to decide on the inclusion of a variable as continuous or categorical in a regression.
First off, sometimes you have no choice: |
17,598 | Getting started with neural networks for forecasting | Here's a good quick introduction:
intro to neural networks.
Note that R has neural-network functionality, so no need to spend any time implementing NN yourself until you've given it a spin and decided it looks promising for your application.
Neural networks are not obsolete, but they have gone through a couple of hype cycles, and then after realizing they don't do everything as was claimed, their reputation goes into a trough for a while (we're currently in one of those). Neural networks are good at certain tasks, and generally are better for tasks in which a human can do a similar task, but cannot explain exactly how they do it.
Neural networks do not give you much insight into the system you're using them to analyze, even after they are trained and operating well. That is, they can predict what will happen (for some systems), but not tell you why. In some cases, that is fine. In others, that is not fine. Generally, if you want or especially if you already have an understanding of the rules of how something works, you can use other techniques.
But, for certain tasks, they work well.
For time-series in particular, see this question's discussion:
Proper way of using recurrent neural network for time series analysis | Getting started with neural networks for forecasting | Here's a good quick introduction:
intro to neural networks.
Note that R has neural-network functionality, so no need to spend any time implementing NN yourself until you've given it a spin and decided | Getting started with neural networks for forecasting
Here's a good quick introduction:
intro to neural networks.
Note that R has neural-network functionality, so no need to spend any time implementing NN yourself until you've given it a spin and decided it looks promising for your application.
Neural networks are not obsolete, but they have gone through a couple of hype cycles, and then after realizing they don't do everything as was claimed, their reputation goes into a trough for a while (we're currently in one of those). Neural networks are good at certain tasks, and generally are better for tasks in which a human can do a similar task, but cannot explain exactly how they do it.
Neural networks do not give you much insight into the system you're using them to analyze, even after they are trained and operating well. That is, they can predict what will happen (for some systems), but not tell you why. In some cases, that is fine. In others, that is not fine. Generally, if you want or especially if you already have an understanding of the rules of how something works, you can use other techniques.
But, for certain tasks, they work well.
For time-series in particular, see this question's discussion:
Proper way of using recurrent neural network for time series analysis | Getting started with neural networks for forecasting
Here's a good quick introduction:
intro to neural networks.
Note that R has neural-network functionality, so no need to spend any time implementing NN yourself until you've given it a spin and decided |
17,599 | Getting started with neural networks for forecasting | While it is focussed on statistical pattern recognition, rather than time series forecasting, I would strongly recommend Chris Bishop's book Neural Networks for Pattern Recognition becuase it is the best introduction to neural networks in general, and I think it would be a good idea to get to grips with the potential pitfalls in the use of neural networks in a more simple context, where the problems are more easily visualised an understood. Then move on to the book on recurrent neural networks by Mandic and Chambers. The bishop book is a classic, nobody should use neural nets for anything until they feel confident that they understand the material contained in that book; ANN make it all too easy to shoot yourself in the foot!
I also disagree with mbq, nn are not obsolete, while many problems are better solved with linear models or more modern machine learning techniques (e.g. kernel methods), there are some problems where they work well and other methods don't. It is still a tool that should be in our toolboxes. | Getting started with neural networks for forecasting | While it is focussed on statistical pattern recognition, rather than time series forecasting, I would strongly recommend Chris Bishop's book Neural Networks for Pattern Recognition becuase it is the b | Getting started with neural networks for forecasting
While it is focussed on statistical pattern recognition, rather than time series forecasting, I would strongly recommend Chris Bishop's book Neural Networks for Pattern Recognition becuase it is the best introduction to neural networks in general, and I think it would be a good idea to get to grips with the potential pitfalls in the use of neural networks in a more simple context, where the problems are more easily visualised an understood. Then move on to the book on recurrent neural networks by Mandic and Chambers. The bishop book is a classic, nobody should use neural nets for anything until they feel confident that they understand the material contained in that book; ANN make it all too easy to shoot yourself in the foot!
I also disagree with mbq, nn are not obsolete, while many problems are better solved with linear models or more modern machine learning techniques (e.g. kernel methods), there are some problems where they work well and other methods don't. It is still a tool that should be in our toolboxes. | Getting started with neural networks for forecasting
While it is focussed on statistical pattern recognition, rather than time series forecasting, I would strongly recommend Chris Bishop's book Neural Networks for Pattern Recognition becuase it is the b |
17,600 | The connection between Bayesian statistics and generative modeling | In machine learning a full probability model p(x,y) is called generative because it can be used to generate the data whereas a conditional model p(y|x) is called discriminative because it does not specify a probability model for p(x) and can only generate y given x. Both can be estimated in Bayesian fashion.
Bayesian estimation is inherently about specifying a full probability model and performing inference conditional on the model and data. That makes many Bayesian models have a generative feel. However to a Bayesian the important distinction is not so much about how to generate the data, but more about what is needed to obtain the posterior distribution of the unknown parameters of interest.
The discriminative model p(y|x) is part of bigger model where p(y, x) = p(y|x)p(x). In many instances, p(x) is irrelevant to the posterior distribution of the parameters in the model p(y|x). Specifically, if the parameters of p(x) are distinct from p(y|x) and the priors are independent, then the model p(x) contains no information about the unknown parameters of the conditional model p(y|x), so a Bayesian does not need to model it.
At a more intuitive level, there is a clear link between "generating data" and "computing the posterior distribution." Rubin (1984) gives the following excellent description of this link:
Bayesian statistics is useful given missing data primarily because it provides a unified way to eliminate nuisance parameters -- integration. Missing data can be thought of as (many) nuisance parameters. Alternative proposals such as plugging in the expected value typically will perform poorly because we can rarely estimate missing data cells with high levels of accuracy. Here, integration is better than maximization.
Discriminative models like p(y|x) also become problematic if x includes missing data because we only have data to estimate p(y|x_obs) but most sensible models are written with respect to the complete data p(y|x). If you have a fully probability model p(y,x) and are Bayesian, then you're fine because you can just integrate over the missing data like you would any other unknown quantity. | The connection between Bayesian statistics and generative modeling | In machine learning a full probability model p(x,y) is called generative because it can be used to generate the data whereas a conditional model p(y|x) is called discriminative because it does not spe | The connection between Bayesian statistics and generative modeling
In machine learning a full probability model p(x,y) is called generative because it can be used to generate the data whereas a conditional model p(y|x) is called discriminative because it does not specify a probability model for p(x) and can only generate y given x. Both can be estimated in Bayesian fashion.
Bayesian estimation is inherently about specifying a full probability model and performing inference conditional on the model and data. That makes many Bayesian models have a generative feel. However to a Bayesian the important distinction is not so much about how to generate the data, but more about what is needed to obtain the posterior distribution of the unknown parameters of interest.
The discriminative model p(y|x) is part of bigger model where p(y, x) = p(y|x)p(x). In many instances, p(x) is irrelevant to the posterior distribution of the parameters in the model p(y|x). Specifically, if the parameters of p(x) are distinct from p(y|x) and the priors are independent, then the model p(x) contains no information about the unknown parameters of the conditional model p(y|x), so a Bayesian does not need to model it.
At a more intuitive level, there is a clear link between "generating data" and "computing the posterior distribution." Rubin (1984) gives the following excellent description of this link:
Bayesian statistics is useful given missing data primarily because it provides a unified way to eliminate nuisance parameters -- integration. Missing data can be thought of as (many) nuisance parameters. Alternative proposals such as plugging in the expected value typically will perform poorly because we can rarely estimate missing data cells with high levels of accuracy. Here, integration is better than maximization.
Discriminative models like p(y|x) also become problematic if x includes missing data because we only have data to estimate p(y|x_obs) but most sensible models are written with respect to the complete data p(y|x). If you have a fully probability model p(y,x) and are Bayesian, then you're fine because you can just integrate over the missing data like you would any other unknown quantity. | The connection between Bayesian statistics and generative modeling
In machine learning a full probability model p(x,y) is called generative because it can be used to generate the data whereas a conditional model p(y|x) is called discriminative because it does not spe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.