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
|
|---|---|---|---|---|---|---|
13,201
|
Computing the decision boundary of a linear SVM model
|
It's a linear combination of the support vectors where the coefficients are given by the Lagrange multipliers corresponding to these support vectors.
|
Computing the decision boundary of a linear SVM model
|
It's a linear combination of the support vectors where the coefficients are given by the Lagrange multipliers corresponding to these support vectors.
|
Computing the decision boundary of a linear SVM model
It's a linear combination of the support vectors where the coefficients are given by the Lagrange multipliers corresponding to these support vectors.
|
Computing the decision boundary of a linear SVM model
It's a linear combination of the support vectors where the coefficients are given by the Lagrange multipliers corresponding to these support vectors.
|
13,202
|
How do survival models "account for censoring"? (Do they?)
|
Censoring is built into survival models by incorporating it into the likelihood function underlying the analysis. The most common form of censoring occurs when we observe an item for a finite period of time $T$ and it does not fail in that time. Below I will show you how the censoring is built into the likelihood function and how this affects the Cox proportional hazards model.
Incorporating censored data into the likelihood function: As a common example, suppose we have items where the time-to-failure has a survival function $S$ and corresponding density function $f$, both of which area parameterised by some parameter $\theta$. If an item $i$ is observed to fail at time $0 \leqslant t_i \leqslant T$ then it is incorporated into the likelihood function using the density term:
$$f(t_i | \theta).$$
However, if an item $i$ is observed throughout the whole time $T$ and it does not fail then this is considered to be a "right-censored" data point (only known to fail at some time after $G$) and it is incorporated into the likelihoood function using the survival term:
$$S(T|\theta).$$
Suppose we have a survival model based on observation for a fixed period of length $T$, where the times-to-failure for each observation are IID conditional on some underlying parameters. Without further loss of generality, we will have $n$ observed failures at times $t_1,...,t_n$ (all within the interval $[0,T]$) and we will will have $m$ right-censored values that did not fail in the oberved time $T$. The overall likelihood function for this data is then given by:
$$L_\mathbf{t}(\theta) = \bigg( \prod_{i=1}^n f(t_i|\theta) \bigg) \times S(T|\theta)^m.$$
In this likelihood function you can see that the censoring of data is "built in" by the fact that right-censored values are incorporated through their survival function instead of the density function for the time-to-failure.
Extending to the Cox proportional hazards model: The Cox proportional hazards model still uses a likelihood function for the observed times-to-failure and survival times, but it now adds covariates to the data and uses an assumption of proportional hazards in how these manifest in the hazard function. This does not change the underlying method of how censored values are built into the likelihood function --- e.g., right-censored values still enter through their survival function instead of the density of the time-to-failure.
Extension to other kinds of censoring: The above shows the common case where we have right-censored observations with the same censoring time $T$. Of course, this is not the only kind of censorship that can occur. Another possibility is that we might observe items up to different end-times, in which case the right-censored values would occur with different observation periods $t_{n+1},...,t_{n+m}$. In this case the likelihood function would be generalised to:
$$L_\mathbf{t}(\theta) = \bigg( \prod_{i=1}^n f(t_i|\theta) \bigg) \times \bigg( \prod_{i=1}^m S(t_{n+i}|\theta) \bigg).$$
Another possibility (which is uncommon in survival analysis) is left-censorship, where we know that an item failed no later than some time $T_i$. Left-censored observations enter into the likelihood function through the cumulative distribution function $F$. If we extend our model to assume that we have $r$ left-censored observations with observation times $t_{n+m+i},...,t_{n+m+r}$ then the likelihood function would be further generalised to:
$$L_\mathbf{t}(\theta) = \bigg( \prod_{i=1}^n f(t_i|\theta) \bigg) \times \bigg( \prod_{i=1}^m S(t_{n+i}|\theta) \bigg) \times \bigg( \prod_{i=1}^r F(t_{n+m+i}|\theta) \bigg).$$
And of course, you can extend this event further to allow for more complicated kinds of censorship. In general, if a censored observation is known to fall in some set $\mathscr{A}$ then it should enter into the likelihood function through the probability term:
$$\mathbb{P}(t_i \in \mathscr{A}|\theta) = \int \limits_\mathscr{A} f(t|\theta) \ dt.$$
|
How do survival models "account for censoring"? (Do they?)
|
Censoring is built into survival models by incorporating it into the likelihood function underlying the analysis. The most common form of censoring occurs when we observe an item for a finite period
|
How do survival models "account for censoring"? (Do they?)
Censoring is built into survival models by incorporating it into the likelihood function underlying the analysis. The most common form of censoring occurs when we observe an item for a finite period of time $T$ and it does not fail in that time. Below I will show you how the censoring is built into the likelihood function and how this affects the Cox proportional hazards model.
Incorporating censored data into the likelihood function: As a common example, suppose we have items where the time-to-failure has a survival function $S$ and corresponding density function $f$, both of which area parameterised by some parameter $\theta$. If an item $i$ is observed to fail at time $0 \leqslant t_i \leqslant T$ then it is incorporated into the likelihood function using the density term:
$$f(t_i | \theta).$$
However, if an item $i$ is observed throughout the whole time $T$ and it does not fail then this is considered to be a "right-censored" data point (only known to fail at some time after $G$) and it is incorporated into the likelihoood function using the survival term:
$$S(T|\theta).$$
Suppose we have a survival model based on observation for a fixed period of length $T$, where the times-to-failure for each observation are IID conditional on some underlying parameters. Without further loss of generality, we will have $n$ observed failures at times $t_1,...,t_n$ (all within the interval $[0,T]$) and we will will have $m$ right-censored values that did not fail in the oberved time $T$. The overall likelihood function for this data is then given by:
$$L_\mathbf{t}(\theta) = \bigg( \prod_{i=1}^n f(t_i|\theta) \bigg) \times S(T|\theta)^m.$$
In this likelihood function you can see that the censoring of data is "built in" by the fact that right-censored values are incorporated through their survival function instead of the density function for the time-to-failure.
Extending to the Cox proportional hazards model: The Cox proportional hazards model still uses a likelihood function for the observed times-to-failure and survival times, but it now adds covariates to the data and uses an assumption of proportional hazards in how these manifest in the hazard function. This does not change the underlying method of how censored values are built into the likelihood function --- e.g., right-censored values still enter through their survival function instead of the density of the time-to-failure.
Extension to other kinds of censoring: The above shows the common case where we have right-censored observations with the same censoring time $T$. Of course, this is not the only kind of censorship that can occur. Another possibility is that we might observe items up to different end-times, in which case the right-censored values would occur with different observation periods $t_{n+1},...,t_{n+m}$. In this case the likelihood function would be generalised to:
$$L_\mathbf{t}(\theta) = \bigg( \prod_{i=1}^n f(t_i|\theta) \bigg) \times \bigg( \prod_{i=1}^m S(t_{n+i}|\theta) \bigg).$$
Another possibility (which is uncommon in survival analysis) is left-censorship, where we know that an item failed no later than some time $T_i$. Left-censored observations enter into the likelihood function through the cumulative distribution function $F$. If we extend our model to assume that we have $r$ left-censored observations with observation times $t_{n+m+i},...,t_{n+m+r}$ then the likelihood function would be further generalised to:
$$L_\mathbf{t}(\theta) = \bigg( \prod_{i=1}^n f(t_i|\theta) \bigg) \times \bigg( \prod_{i=1}^m S(t_{n+i}|\theta) \bigg) \times \bigg( \prod_{i=1}^r F(t_{n+m+i}|\theta) \bigg).$$
And of course, you can extend this event further to allow for more complicated kinds of censorship. In general, if a censored observation is known to fall in some set $\mathscr{A}$ then it should enter into the likelihood function through the probability term:
$$\mathbb{P}(t_i \in \mathscr{A}|\theta) = \int \limits_\mathscr{A} f(t|\theta) \ dt.$$
|
How do survival models "account for censoring"? (Do they?)
Censoring is built into survival models by incorporating it into the likelihood function underlying the analysis. The most common form of censoring occurs when we observe an item for a finite period
|
13,203
|
How do survival models "account for censoring"? (Do they?)
|
Some students might benefit from the following way to represent the partial likelihood for a Cox model, as an example of Ben's answer (+1) about censoring in general. Display the partial likelihood under the proportional-hazards assumption (without tied event times) as follows:
$$\prod_{i=1}^{n}\frac{h_0(t_i)\text{exp}(\beta X_i(t_i))}{\sum_{j\in\mathcal{R(t_i)}}h_0(t_i)\text{exp}(\beta X_j(t_i)))}= \prod_{i=1}^{n}\frac{\text{exp}(\beta X_i(t_i))}{\sum_{j\in\mathcal{R(t_i)}}\text{exp}(\beta X_j(t_i)))}$$
where cases with events are indexed by i and their event times are $t_i$, covariate values are $X$ with corresponding regression coefficients $\beta$, and the risk set at time $t_i$, $\mathcal{R(t_i)}$, consists of all cases $j$ at risk of an event at that time. The baseline hazard $h_0(t_i)$ factors out.
The risk score for individual j at time $t_i$, based on that individual's covariate values, is $\text{exp}(\beta X_j(t_i))$. This form emphasizes that the risk for individual i having the event is effectively compared against the summed risks of all individuals at risk at that time.
So the way that the Cox model "accounts for censoring" is by letting all individuals contribute to the partial likelihood, via their risk scores in the denominator, so long as they are at risk of an event. It doesn't matter whether those in the risk set have an event at a later time; they provide information so long as they are at risk and are omitted from analysis thereafter. You can think about that as related to the survival-function contribution that Ben describes. The overall product, however, is only over individuals who have events; that's related to the density-function contribution that Ben describes.
There also can be truncated, as opposed to censored, survival times. That's, for example, how models with time-varying covariate values can be set up: left truncated before the new covariate value takes effect, with right censoring or an event thereafter. Contributions of truncated survival times to likelihood also can be expressed in terms of the density and survival functions; this page presents those contributions as described by Klein and Moeschberger.
One caution: both my and Ben's answers implicitly assume that censoring is non-informative; that is, the fact of censoring provides no information about survival except that survival was longer than the observed time of censoring. That's not always a safe assumption. The review by Leung et al on "Censoring Issues in Survival Analysis," Annu Rev Public Health 18:83–104 (1997) explains and illustrates those further considerations.
|
How do survival models "account for censoring"? (Do they?)
|
Some students might benefit from the following way to represent the partial likelihood for a Cox model, as an example of Ben's answer (+1) about censoring in general. Display the partial likelihood un
|
How do survival models "account for censoring"? (Do they?)
Some students might benefit from the following way to represent the partial likelihood for a Cox model, as an example of Ben's answer (+1) about censoring in general. Display the partial likelihood under the proportional-hazards assumption (without tied event times) as follows:
$$\prod_{i=1}^{n}\frac{h_0(t_i)\text{exp}(\beta X_i(t_i))}{\sum_{j\in\mathcal{R(t_i)}}h_0(t_i)\text{exp}(\beta X_j(t_i)))}= \prod_{i=1}^{n}\frac{\text{exp}(\beta X_i(t_i))}{\sum_{j\in\mathcal{R(t_i)}}\text{exp}(\beta X_j(t_i)))}$$
where cases with events are indexed by i and their event times are $t_i$, covariate values are $X$ with corresponding regression coefficients $\beta$, and the risk set at time $t_i$, $\mathcal{R(t_i)}$, consists of all cases $j$ at risk of an event at that time. The baseline hazard $h_0(t_i)$ factors out.
The risk score for individual j at time $t_i$, based on that individual's covariate values, is $\text{exp}(\beta X_j(t_i))$. This form emphasizes that the risk for individual i having the event is effectively compared against the summed risks of all individuals at risk at that time.
So the way that the Cox model "accounts for censoring" is by letting all individuals contribute to the partial likelihood, via their risk scores in the denominator, so long as they are at risk of an event. It doesn't matter whether those in the risk set have an event at a later time; they provide information so long as they are at risk and are omitted from analysis thereafter. You can think about that as related to the survival-function contribution that Ben describes. The overall product, however, is only over individuals who have events; that's related to the density-function contribution that Ben describes.
There also can be truncated, as opposed to censored, survival times. That's, for example, how models with time-varying covariate values can be set up: left truncated before the new covariate value takes effect, with right censoring or an event thereafter. Contributions of truncated survival times to likelihood also can be expressed in terms of the density and survival functions; this page presents those contributions as described by Klein and Moeschberger.
One caution: both my and Ben's answers implicitly assume that censoring is non-informative; that is, the fact of censoring provides no information about survival except that survival was longer than the observed time of censoring. That's not always a safe assumption. The review by Leung et al on "Censoring Issues in Survival Analysis," Annu Rev Public Health 18:83–104 (1997) explains and illustrates those further considerations.
|
How do survival models "account for censoring"? (Do they?)
Some students might benefit from the following way to represent the partial likelihood for a Cox model, as an example of Ben's answer (+1) about censoring in general. Display the partial likelihood un
|
13,204
|
How do survival models "account for censoring"? (Do they?)
|
I thought I’d directly answer the specific questions above: this is intended to address the top-level conceptual issues with some thoughts on teaching to this kind of audience, rather than a technical explanation.
The Questions
1. Is it true, strictly speaking, that something like a Kaplan-Meier estimator or a Cox proportional hazards model is "accounting" for censoring?
Yes!
2. If so, how is it doing that?
See other answers for technical details on how implemented for a Cox PH model.
I find the intuition clearer for Kaplan-Meier estimation, and in my experience (short-course teaching of these methods to researchers/analysts in health sciences settings) this is reasonably approachable for the kind of audience you are dealing with, or at least a good starting point.
(I appreciate that this question is as much for your own understanding as being about what/how to teach your students)
This applies for both visualisation (“included in denominator up to point of event/censoring” with x marks the spot on the survival curve) and for calculation (showing how we calculate cumulative survival by multiplying the preceding interval’s cumulative survival with the current interval’s survival in the set of individuals at risk).
3. If a survival model indeed accounts for censoring, is this a "feature" of survival methods over others, or a "bug", an inevitable artifact of the sorts of questions one uses survival methods to answer?
Very much by design – these methods were developed to address the problems that arise when survival times are censored (and to maximise efficiency, see below)
4. Why is censoring a problem? I'm thinking that, if ignored, censoring is a huge potential source of bias in making survival estimates: if you don't know what happened after Mr. Smith dropped out of your study (i.e. was lost to follow-up, i.e. was censored) your estimates may be off in one direction or the other. [snip]
If your time data are subject to censoring, but you have ignored this in analysis, then results will be biased. In some cases (since there are lots of different ways in which one might inappropriately address this issue) you might be treating people with only short-term follow-up as though they had the full period of follow-up.
Different issues can arise depending on how that inappropriate “non-survival analysis” were to proceed: for example, issues arise if the risk set accrues across a period (e.g. infants born with a particular condition across a ten year study period) and outcomes tend to be in earlier periods (e.g. highest risk in first two years of life).
5. So maybe what survival models have found a way to do is keep in the analysis everyone who contributed survival time, regardless of whether we know about their outcome status, while other methods would simply drop all of those people's data as missing.
I think this is a reasonable summary: basically you can include people in follow-up time up to that point at which their information runs out. So you can view survival analysis as being more efficient, as you can (loosely speaking) include all the available numerator and denominator information (subject to a whole heap of assumptions, well described elsewhere).
To run a valid “non-survival analysis” would require everyone to have the same amount of potential follow-up time (e.g. every cancer patient followed up to at least five years) irrespective of their event status.
As a final note on how things can go wrong when not accounting for censoring:
As with any research endeavour, there are lots of different ways in which people might naively approach this kind of analysis without accounting for censoring: for example, I've seen some ideas for analysis that would include people in follow-up if they had the event at any time, but only include people with no events in the denominator if they reached the final follow-up time (net result: bad news!)
|
How do survival models "account for censoring"? (Do they?)
|
I thought I’d directly answer the specific questions above: this is intended to address the top-level conceptual issues with some thoughts on teaching to this kind of audience, rather than a technical
|
How do survival models "account for censoring"? (Do they?)
I thought I’d directly answer the specific questions above: this is intended to address the top-level conceptual issues with some thoughts on teaching to this kind of audience, rather than a technical explanation.
The Questions
1. Is it true, strictly speaking, that something like a Kaplan-Meier estimator or a Cox proportional hazards model is "accounting" for censoring?
Yes!
2. If so, how is it doing that?
See other answers for technical details on how implemented for a Cox PH model.
I find the intuition clearer for Kaplan-Meier estimation, and in my experience (short-course teaching of these methods to researchers/analysts in health sciences settings) this is reasonably approachable for the kind of audience you are dealing with, or at least a good starting point.
(I appreciate that this question is as much for your own understanding as being about what/how to teach your students)
This applies for both visualisation (“included in denominator up to point of event/censoring” with x marks the spot on the survival curve) and for calculation (showing how we calculate cumulative survival by multiplying the preceding interval’s cumulative survival with the current interval’s survival in the set of individuals at risk).
3. If a survival model indeed accounts for censoring, is this a "feature" of survival methods over others, or a "bug", an inevitable artifact of the sorts of questions one uses survival methods to answer?
Very much by design – these methods were developed to address the problems that arise when survival times are censored (and to maximise efficiency, see below)
4. Why is censoring a problem? I'm thinking that, if ignored, censoring is a huge potential source of bias in making survival estimates: if you don't know what happened after Mr. Smith dropped out of your study (i.e. was lost to follow-up, i.e. was censored) your estimates may be off in one direction or the other. [snip]
If your time data are subject to censoring, but you have ignored this in analysis, then results will be biased. In some cases (since there are lots of different ways in which one might inappropriately address this issue) you might be treating people with only short-term follow-up as though they had the full period of follow-up.
Different issues can arise depending on how that inappropriate “non-survival analysis” were to proceed: for example, issues arise if the risk set accrues across a period (e.g. infants born with a particular condition across a ten year study period) and outcomes tend to be in earlier periods (e.g. highest risk in first two years of life).
5. So maybe what survival models have found a way to do is keep in the analysis everyone who contributed survival time, regardless of whether we know about their outcome status, while other methods would simply drop all of those people's data as missing.
I think this is a reasonable summary: basically you can include people in follow-up time up to that point at which their information runs out. So you can view survival analysis as being more efficient, as you can (loosely speaking) include all the available numerator and denominator information (subject to a whole heap of assumptions, well described elsewhere).
To run a valid “non-survival analysis” would require everyone to have the same amount of potential follow-up time (e.g. every cancer patient followed up to at least five years) irrespective of their event status.
As a final note on how things can go wrong when not accounting for censoring:
As with any research endeavour, there are lots of different ways in which people might naively approach this kind of analysis without accounting for censoring: for example, I've seen some ideas for analysis that would include people in follow-up if they had the event at any time, but only include people with no events in the denominator if they reached the final follow-up time (net result: bad news!)
|
How do survival models "account for censoring"? (Do they?)
I thought I’d directly answer the specific questions above: this is intended to address the top-level conceptual issues with some thoughts on teaching to this kind of audience, rather than a technical
|
13,205
|
How do survival models "account for censoring"? (Do they?)
|
Update: @James Stanley address the same point in his answer; see point #4.
This is not an answer but an extended comment to clarify some terminology and highlight an important assumption.
You write:
if you don't know what happened after Mr. Smith dropped out of your study (i.e. was lost to follow-up, i.e. was censored) ...
implying that "loss to follow-up" is the same as "censoring". Not exactly.
Say we do a randomized control trial (RCT) of treatment T vs control C and the outcome of interest Y is the time to event (or equivalently, survival). We start recruiting subjects on January 1st and the study concludes on December 31, the same year. We follow up with subjects every month from recruitment until Dec 31.
loss to follow-up: The patient A is recruited and randomized to T or C in Jan. We have data for the first 8 visits and no data for the last 3 visits from Oct to Dec. We know the patient survived for at least 8 months.
censoring: The patient B is recruited and randomized to T or C in Apr. We have data for all 8 visits until the study concludes in Dec. We know that the patient survived for at least 8 months.
You may ask: Why make the distinction between loss to follow-up and censoring? Patients A and B appear "similar" ("exchangeable"): we followed them for 8 visits post-treatment, so we know they survived at least 8 months, but we don't know how long they survived.
They would contribute the same term $\operatorname{S}(t_i = \text{8 months} | \theta)$ in the likelihood function. [Here I refer to the likelihood $L_t(\theta)$ in @Ben's answer.]
The subtlety is that we don't know why patient A dropped out from the study. Often in analysis when we don't know something, we assume that it happened randomly. This will make the math work out just as described in Ben's answer.
However, suppose that the treatment has severe side effects and patients who received the treatment have a higher probability to discontinue treatment early. This means that subjects in the treament group are more likely to be lost to follow-up. This (potentially) introduces bias in the estimate of the treatment effect, unless more sophisticated analyses come to the rescue.
|
How do survival models "account for censoring"? (Do they?)
|
Update: @James Stanley address the same point in his answer; see point #4.
This is not an answer but an extended comment to clarify some terminology and highlight an important assumption.
You write:
|
How do survival models "account for censoring"? (Do they?)
Update: @James Stanley address the same point in his answer; see point #4.
This is not an answer but an extended comment to clarify some terminology and highlight an important assumption.
You write:
if you don't know what happened after Mr. Smith dropped out of your study (i.e. was lost to follow-up, i.e. was censored) ...
implying that "loss to follow-up" is the same as "censoring". Not exactly.
Say we do a randomized control trial (RCT) of treatment T vs control C and the outcome of interest Y is the time to event (or equivalently, survival). We start recruiting subjects on January 1st and the study concludes on December 31, the same year. We follow up with subjects every month from recruitment until Dec 31.
loss to follow-up: The patient A is recruited and randomized to T or C in Jan. We have data for the first 8 visits and no data for the last 3 visits from Oct to Dec. We know the patient survived for at least 8 months.
censoring: The patient B is recruited and randomized to T or C in Apr. We have data for all 8 visits until the study concludes in Dec. We know that the patient survived for at least 8 months.
You may ask: Why make the distinction between loss to follow-up and censoring? Patients A and B appear "similar" ("exchangeable"): we followed them for 8 visits post-treatment, so we know they survived at least 8 months, but we don't know how long they survived.
They would contribute the same term $\operatorname{S}(t_i = \text{8 months} | \theta)$ in the likelihood function. [Here I refer to the likelihood $L_t(\theta)$ in @Ben's answer.]
The subtlety is that we don't know why patient A dropped out from the study. Often in analysis when we don't know something, we assume that it happened randomly. This will make the math work out just as described in Ben's answer.
However, suppose that the treatment has severe side effects and patients who received the treatment have a higher probability to discontinue treatment early. This means that subjects in the treament group are more likely to be lost to follow-up. This (potentially) introduces bias in the estimate of the treatment effect, unless more sophisticated analyses come to the rescue.
|
How do survival models "account for censoring"? (Do they?)
Update: @James Stanley address the same point in his answer; see point #4.
This is not an answer but an extended comment to clarify some terminology and highlight an important assumption.
You write:
|
13,206
|
Intuition behind Box-Cox transform
|
The design goals of the family of Box-Cox transformations of non-negative data were these:
The formulas should be simple, straightforward, well understood, and easy to calculate.
They should not change the middle of the data much, but affect the tails more.
The family should be rich enough to induce large changes in the skewness of the data if necessary: this means it should be able to contract or extend one tail of the data while extending or contracting the other, by arbitrary amounts.
Let's consider the implications of each in turn.
1. Simplicity
Linear transformations--those of the form $x\to \alpha x + \beta$ for constants $\alpha$ and $\beta$--merely change the scale and location of data; they cannot change the shape of their distribution. The next simplest formula is to consider power transformations, of the form $x\to x^\lambda$ for (nonzero) constant $\lambda.$
2. Stability
A power transformation enjoys the nice property that rescaling the data results in rescaling their powers. That is, multiplying the data $x$ by some positive scale factor $\alpha$ results in multiplying $x^\lambda$ by $\alpha^\lambda.$ OK, it's not the same scale factor, but it is still just a rescaling.
In light of this, let's always standardize any batch of data $(x_1, x_2, \ldots, x_n)$ by rescaling it to place its center (perhaps its median) at $1.$ Specifically, this replaces each $x_i$ by $x_i$ divided by the middle value of all the $x$'s. This won't change the shape of the data distribution--it really amounts to choosing a suitable unit of measurement for expressing the values. For those who like formulas, let $\mu$ be the median of the batch. We will be studying the transformations
$$x \to \frac{(x/\mu)^\lambda - 1}{\lambda} = \frac{\mu^{-\lambda}}{\lambda}\,x^\lambda + \frac{-1}{\lambda} = \alpha\, x^\lambda + \beta$$
for various $\lambda.$ The effects of $\alpha$ and $\beta$ (which depend on $\lambda$ and $\mu$) on $x^\lambda$ do not change the shape of the distribution of the $x_i^\lambda.$ In this sense, the Box-Cox transformations of the standardized data really are just the power transformations.
Because we have made $1$ the central value of the batch, design crition 2--"stability"--requires that different values of the power $\lambda$ have relatively little effect on values near $1.$
Let's look at this in a little more detail by examining what a power does to numbers near $1.$ According to the Binomial Theorem, if we write $x$ as $x=1+\epsilon$ (for fairly small $\epsilon$), then approximately
$$(1 + \epsilon)^\lambda = 1 + \lambda \epsilon + \text{Something}\times \epsilon^2.$$
Ignoring $\epsilon^2$ as being truly tiny, this tells us that
Taking a power $\lambda$ of a number $x$ near $1$ is a nearly linear function that changes the distance between $x$ and $1$ by a factor $\lambda.$
In light of this, we can match the effects of different possible $\lambda$ by means of a compensating division of the distance by $\lambda.$ That is, we will use
$$\operatorname{BC}_\lambda(x) = \frac{x^\lambda - 1^\lambda}{\lambda} = \frac{x^\lambda - 1}{\lambda}.$$
The numerator is the (signed) distance between the power transform of $x$ and the power transform of the middle of the data ($1$); the denominator adjusts for the expansion of $x-1$ by the factor $\lambda$ when taking the power. $\operatorname{BC}_\lambda$ is the Box-Cox transformation with parameter $\lambda.$
By means of this construction, we guarantee that when $x$ is close to a typical value of its batch of data, $\operatorname{BC}_\lambda(x)$ will approximately be the same value (and close to zero) no matter what $\lambda$ might be (within reason, of course: extreme values of $\lambda$ can do extreme things).
3. Flexibility
We have many possible values of $\lambda$ to choose from. How do they differ?
This can be explored by graphing the Box-Cox transformations for various $\lambda.$ Here is a set of graphs for $\lambda \in \{-1,-1/2, 0, 1/2, 1, 2\}.$ (For the meaning of $\lambda=0,$ see Natural Log Approximation elsewhere on this site.)
The solid black line graphs the Box-Cox transformation for $\lambda=1,$ which is just $x\to x-1.$ It merely shifts the center of the batch to $0$ (as do all the Box-Cox transformations). The upward curving pink graph is for $\lambda=2.$ The downward curving graphs show, in order of increasing curvature, the smaller values of $\lambda$ down to $-1.$
The differing amounts and directions of curvature provide the desired flexibility to change the shape of a batch of data.
For instance, the upward curving graph for $\lambda=2$ exemplifies the effect of all Box-Cox transformations with $\lambda$ exceeding $1:$ values of $x$ above $1$ (that is, greater than the middle of the batch, and therefore out in its upper tail) are pulled further and further away from the new middle (at $0$). Values of $x$ below $1$ (less than the middle of the batch, and therefore out in its lower tail) are pushed closer to the new middle. This "skews" the data to the right, or high values (rather strongly, even for $\lambda=2$).
The downward curving graphs, for $\lambda \lt 1,$ have the opposite effect: they push the higher values in the batch towards the new middle and pull the lower values away from the new middle. This skews the data to the left (or lower values).
The coincidence of all the graphs near the point $(1,0)$ is a result of the previous standardizations: it constitutes visual verification that choice of $\lambda$ makes little difference for values near the middle of the batch.
Finally, let's look at what different Box-Cox transformations do to a small batch of data.
Transformed values are indicated by the horizontal positions. (The original data look just like the black dots, shown at $\lambda=1,$ but are located $+1$ units to the right.) The colors correspond to the ones used in the first figure. The underlying gray lines show what happens to the transformed values when $\lambda$ is smoothly varied from $-1$ to $+2.$ It's another way of appreciating the effects of these transformations in the tails of the data. (It also shows why the value of $\lambda=0$ makes sense: it corresponds to taking values of $\lambda$ arbitrarily close to $0.$)
|
Intuition behind Box-Cox transform
|
The design goals of the family of Box-Cox transformations of non-negative data were these:
The formulas should be simple, straightforward, well understood, and easy to calculate.
They should not cha
|
Intuition behind Box-Cox transform
The design goals of the family of Box-Cox transformations of non-negative data were these:
The formulas should be simple, straightforward, well understood, and easy to calculate.
They should not change the middle of the data much, but affect the tails more.
The family should be rich enough to induce large changes in the skewness of the data if necessary: this means it should be able to contract or extend one tail of the data while extending or contracting the other, by arbitrary amounts.
Let's consider the implications of each in turn.
1. Simplicity
Linear transformations--those of the form $x\to \alpha x + \beta$ for constants $\alpha$ and $\beta$--merely change the scale and location of data; they cannot change the shape of their distribution. The next simplest formula is to consider power transformations, of the form $x\to x^\lambda$ for (nonzero) constant $\lambda.$
2. Stability
A power transformation enjoys the nice property that rescaling the data results in rescaling their powers. That is, multiplying the data $x$ by some positive scale factor $\alpha$ results in multiplying $x^\lambda$ by $\alpha^\lambda.$ OK, it's not the same scale factor, but it is still just a rescaling.
In light of this, let's always standardize any batch of data $(x_1, x_2, \ldots, x_n)$ by rescaling it to place its center (perhaps its median) at $1.$ Specifically, this replaces each $x_i$ by $x_i$ divided by the middle value of all the $x$'s. This won't change the shape of the data distribution--it really amounts to choosing a suitable unit of measurement for expressing the values. For those who like formulas, let $\mu$ be the median of the batch. We will be studying the transformations
$$x \to \frac{(x/\mu)^\lambda - 1}{\lambda} = \frac{\mu^{-\lambda}}{\lambda}\,x^\lambda + \frac{-1}{\lambda} = \alpha\, x^\lambda + \beta$$
for various $\lambda.$ The effects of $\alpha$ and $\beta$ (which depend on $\lambda$ and $\mu$) on $x^\lambda$ do not change the shape of the distribution of the $x_i^\lambda.$ In this sense, the Box-Cox transformations of the standardized data really are just the power transformations.
Because we have made $1$ the central value of the batch, design crition 2--"stability"--requires that different values of the power $\lambda$ have relatively little effect on values near $1.$
Let's look at this in a little more detail by examining what a power does to numbers near $1.$ According to the Binomial Theorem, if we write $x$ as $x=1+\epsilon$ (for fairly small $\epsilon$), then approximately
$$(1 + \epsilon)^\lambda = 1 + \lambda \epsilon + \text{Something}\times \epsilon^2.$$
Ignoring $\epsilon^2$ as being truly tiny, this tells us that
Taking a power $\lambda$ of a number $x$ near $1$ is a nearly linear function that changes the distance between $x$ and $1$ by a factor $\lambda.$
In light of this, we can match the effects of different possible $\lambda$ by means of a compensating division of the distance by $\lambda.$ That is, we will use
$$\operatorname{BC}_\lambda(x) = \frac{x^\lambda - 1^\lambda}{\lambda} = \frac{x^\lambda - 1}{\lambda}.$$
The numerator is the (signed) distance between the power transform of $x$ and the power transform of the middle of the data ($1$); the denominator adjusts for the expansion of $x-1$ by the factor $\lambda$ when taking the power. $\operatorname{BC}_\lambda$ is the Box-Cox transformation with parameter $\lambda.$
By means of this construction, we guarantee that when $x$ is close to a typical value of its batch of data, $\operatorname{BC}_\lambda(x)$ will approximately be the same value (and close to zero) no matter what $\lambda$ might be (within reason, of course: extreme values of $\lambda$ can do extreme things).
3. Flexibility
We have many possible values of $\lambda$ to choose from. How do they differ?
This can be explored by graphing the Box-Cox transformations for various $\lambda.$ Here is a set of graphs for $\lambda \in \{-1,-1/2, 0, 1/2, 1, 2\}.$ (For the meaning of $\lambda=0,$ see Natural Log Approximation elsewhere on this site.)
The solid black line graphs the Box-Cox transformation for $\lambda=1,$ which is just $x\to x-1.$ It merely shifts the center of the batch to $0$ (as do all the Box-Cox transformations). The upward curving pink graph is for $\lambda=2.$ The downward curving graphs show, in order of increasing curvature, the smaller values of $\lambda$ down to $-1.$
The differing amounts and directions of curvature provide the desired flexibility to change the shape of a batch of data.
For instance, the upward curving graph for $\lambda=2$ exemplifies the effect of all Box-Cox transformations with $\lambda$ exceeding $1:$ values of $x$ above $1$ (that is, greater than the middle of the batch, and therefore out in its upper tail) are pulled further and further away from the new middle (at $0$). Values of $x$ below $1$ (less than the middle of the batch, and therefore out in its lower tail) are pushed closer to the new middle. This "skews" the data to the right, or high values (rather strongly, even for $\lambda=2$).
The downward curving graphs, for $\lambda \lt 1,$ have the opposite effect: they push the higher values in the batch towards the new middle and pull the lower values away from the new middle. This skews the data to the left (or lower values).
The coincidence of all the graphs near the point $(1,0)$ is a result of the previous standardizations: it constitutes visual verification that choice of $\lambda$ makes little difference for values near the middle of the batch.
Finally, let's look at what different Box-Cox transformations do to a small batch of data.
Transformed values are indicated by the horizontal positions. (The original data look just like the black dots, shown at $\lambda=1,$ but are located $+1$ units to the right.) The colors correspond to the ones used in the first figure. The underlying gray lines show what happens to the transformed values when $\lambda$ is smoothly varied from $-1$ to $+2.$ It's another way of appreciating the effects of these transformations in the tails of the data. (It also shows why the value of $\lambda=0$ makes sense: it corresponds to taking values of $\lambda$ arbitrarily close to $0.$)
|
Intuition behind Box-Cox transform
The design goals of the family of Box-Cox transformations of non-negative data were these:
The formulas should be simple, straightforward, well understood, and easy to calculate.
They should not cha
|
13,207
|
Intuition behind Box-Cox transform
|
Adding something to the great answer by whuber. Let's say you have $k$ independent random variables $X_1, X_2,..., X_k$ normally distributed with mean $m_i$ and variance $\sigma_i^2$ for $i=1,...,k$.
Now, let's assume that $\sigma_i = f(m_i)$ and $f$ is some known function. In simple situations we can guess this function, for example from a graph of sample standard deviation and sample mean. We want to find such a transformation $t$ that a sequence of independent random variables $Y_1 = t(X_1),...,Y_k = t(X_k)$ has (at least approximately) constant variance $\mathrm{Var}(Y_i) = const$ for $i=1,...,k.$
You can use Taylor expansion around mean to achieve this as follows
$$Y_i = t(X_i) \approx t(m_i)+t'(m_i)(X_i-m_i).$$
The condition of constant variance leads to differential equation $t'(x)f(x)=c$ and the transformation $t$ has the form
$$t(x)=c_1 \int \frac{1}{f(x)}dx + c_2,$$
where $c_1$ and $c_2$ are constants. Note that if $f(x)=x$, then the transformation is $t(x)=\ln(x).$ If $f(x) = x^\alpha$ ($\alpha \neq 1$), then the transformation is $t(x) = \frac{1}{1-\alpha}x^{1-\alpha}.$ Using the well known fact that $\lim_{x\to 0} \frac{a^x-1}{x} = \ln(a)$ we finally get
$$t_\lambda(x) = \begin{cases} \frac{x^{\lambda}-1}{\lambda} & \lambda \neq 0 \\
\ln(x), & \lambda = 0 \end{cases} $$
for $x>0$, which is Box-Cox family of transformations. Transformation $t_\lambda(x)$ corresponds to $f(x) = x^{1-\lambda}.$
|
Intuition behind Box-Cox transform
|
Adding something to the great answer by whuber. Let's say you have $k$ independent random variables $X_1, X_2,..., X_k$ normally distributed with mean $m_i$ and variance $\sigma_i^2$ for $i=1,...,k$.
|
Intuition behind Box-Cox transform
Adding something to the great answer by whuber. Let's say you have $k$ independent random variables $X_1, X_2,..., X_k$ normally distributed with mean $m_i$ and variance $\sigma_i^2$ for $i=1,...,k$.
Now, let's assume that $\sigma_i = f(m_i)$ and $f$ is some known function. In simple situations we can guess this function, for example from a graph of sample standard deviation and sample mean. We want to find such a transformation $t$ that a sequence of independent random variables $Y_1 = t(X_1),...,Y_k = t(X_k)$ has (at least approximately) constant variance $\mathrm{Var}(Y_i) = const$ for $i=1,...,k.$
You can use Taylor expansion around mean to achieve this as follows
$$Y_i = t(X_i) \approx t(m_i)+t'(m_i)(X_i-m_i).$$
The condition of constant variance leads to differential equation $t'(x)f(x)=c$ and the transformation $t$ has the form
$$t(x)=c_1 \int \frac{1}{f(x)}dx + c_2,$$
where $c_1$ and $c_2$ are constants. Note that if $f(x)=x$, then the transformation is $t(x)=\ln(x).$ If $f(x) = x^\alpha$ ($\alpha \neq 1$), then the transformation is $t(x) = \frac{1}{1-\alpha}x^{1-\alpha}.$ Using the well known fact that $\lim_{x\to 0} \frac{a^x-1}{x} = \ln(a)$ we finally get
$$t_\lambda(x) = \begin{cases} \frac{x^{\lambda}-1}{\lambda} & \lambda \neq 0 \\
\ln(x), & \lambda = 0 \end{cases} $$
for $x>0$, which is Box-Cox family of transformations. Transformation $t_\lambda(x)$ corresponds to $f(x) = x^{1-\lambda}.$
|
Intuition behind Box-Cox transform
Adding something to the great answer by whuber. Let's say you have $k$ independent random variables $X_1, X_2,..., X_k$ normally distributed with mean $m_i$ and variance $\sigma_i^2$ for $i=1,...,k$.
|
13,208
|
Intuition behind Box-Cox transform
|
The answers provided here are already useful. I just wanted to drop a couple more resources for learning about Box-Cox. There is actually an excellent episode from Quantitude dedicated to this very subject, which explains both the history and intuition behind this transformation (including the amusing history that the creators literally did this for the sole reason that their authorship on the paper would rhyme). I also would like to recommend this paper as a less math heavy article on the subject that shows examples of the transformation if you would like to see the practical side of the transformation in action. One of the useful things they do in this paper is show how different anchoring points affect the transformation, with an example shown below:
|
Intuition behind Box-Cox transform
|
The answers provided here are already useful. I just wanted to drop a couple more resources for learning about Box-Cox. There is actually an excellent episode from Quantitude dedicated to this very su
|
Intuition behind Box-Cox transform
The answers provided here are already useful. I just wanted to drop a couple more resources for learning about Box-Cox. There is actually an excellent episode from Quantitude dedicated to this very subject, which explains both the history and intuition behind this transformation (including the amusing history that the creators literally did this for the sole reason that their authorship on the paper would rhyme). I also would like to recommend this paper as a less math heavy article on the subject that shows examples of the transformation if you would like to see the practical side of the transformation in action. One of the useful things they do in this paper is show how different anchoring points affect the transformation, with an example shown below:
|
Intuition behind Box-Cox transform
The answers provided here are already useful. I just wanted to drop a couple more resources for learning about Box-Cox. There is actually an excellent episode from Quantitude dedicated to this very su
|
13,209
|
k-means implementation with custom distance matrix in input
|
Since k-means needs to be able to find the means of different subsets of the points you want to cluster, it does not really make sense to ask for a version of k-means that takes a distance matrix as input.
You could try k-medoids instead. There are some matlab implementations available.
|
k-means implementation with custom distance matrix in input
|
Since k-means needs to be able to find the means of different subsets of the points you want to cluster, it does not really make sense to ask for a version of k-means that takes a distance matrix as i
|
k-means implementation with custom distance matrix in input
Since k-means needs to be able to find the means of different subsets of the points you want to cluster, it does not really make sense to ask for a version of k-means that takes a distance matrix as input.
You could try k-medoids instead. There are some matlab implementations available.
|
k-means implementation with custom distance matrix in input
Since k-means needs to be able to find the means of different subsets of the points you want to cluster, it does not really make sense to ask for a version of k-means that takes a distance matrix as i
|
13,210
|
k-means implementation with custom distance matrix in input
|
You could turn your matrix of distances into raw data and input these to K-Means clustering. The steps would be as follows:
Distances between your N points must be squared euclidean ones. Perform "double centering" of the matrix:
From each element, substract its row mean of elements, substract its column mean of elements, add matrix mean of elements, and divide by minus 2. (The row, column, and matrix means are from the initial squared distance matrix. The vectors of row means and the column means contain, of course, the same values, because the distance matrix is symmetric. The matrix mean scalar should be based on all matrix elements, including diagonal.)$^1$
The matrix you have now is the SSCP (sum-of-squares-and-cross-product) matrix between your points wherein the origin is put at geometrical centre of the cloud of N points. (Read explanation of the double centering here.)
Perform PCA (Principal component analysis) on that matrix and obtain NxN component loading matrix. Some of last columns of it are likely to be all 0, - so cut them off. What you stay with now is actually principal component scores, the coordinates of your N points onto principal components that pass, as axes, through your cloud. This data can be treated as raw data suitable for K-Means input.
P.S. If your distances aren't geometrically correct squared euclidean ones you may encounter problem: the SSCP matrix may be not positive (semi)definite. This problem can be coped with in several ways but with loss of precision.
$^1$ It is easy to show that the subtrahend from $d_{ij}^2$, the [rowmean + colmean - matrixmean], equals $h_i^2+h_j^2$ of the euclidean space's law of cosines: $d_{ij}^2 = h_i^2+h_j^2-2 s_{ij}$, where $s_{ij}$ is the scalar product similarity between the two vectors. Thus, the double centration operation is the reversing a (euclidean) distance into the corresponding angular similarity by that law. Specifically, it is a particular case of that law, the case when we put (via the specific subtrahend) the origin into the centroid of the bunch of points (the vectors' endpoints).
|
k-means implementation with custom distance matrix in input
|
You could turn your matrix of distances into raw data and input these to K-Means clustering. The steps would be as follows:
Distances between your N points must be squared euclidean ones. Perform "do
|
k-means implementation with custom distance matrix in input
You could turn your matrix of distances into raw data and input these to K-Means clustering. The steps would be as follows:
Distances between your N points must be squared euclidean ones. Perform "double centering" of the matrix:
From each element, substract its row mean of elements, substract its column mean of elements, add matrix mean of elements, and divide by minus 2. (The row, column, and matrix means are from the initial squared distance matrix. The vectors of row means and the column means contain, of course, the same values, because the distance matrix is symmetric. The matrix mean scalar should be based on all matrix elements, including diagonal.)$^1$
The matrix you have now is the SSCP (sum-of-squares-and-cross-product) matrix between your points wherein the origin is put at geometrical centre of the cloud of N points. (Read explanation of the double centering here.)
Perform PCA (Principal component analysis) on that matrix and obtain NxN component loading matrix. Some of last columns of it are likely to be all 0, - so cut them off. What you stay with now is actually principal component scores, the coordinates of your N points onto principal components that pass, as axes, through your cloud. This data can be treated as raw data suitable for K-Means input.
P.S. If your distances aren't geometrically correct squared euclidean ones you may encounter problem: the SSCP matrix may be not positive (semi)definite. This problem can be coped with in several ways but with loss of precision.
$^1$ It is easy to show that the subtrahend from $d_{ij}^2$, the [rowmean + colmean - matrixmean], equals $h_i^2+h_j^2$ of the euclidean space's law of cosines: $d_{ij}^2 = h_i^2+h_j^2-2 s_{ij}$, where $s_{ij}$ is the scalar product similarity between the two vectors. Thus, the double centration operation is the reversing a (euclidean) distance into the corresponding angular similarity by that law. Specifically, it is a particular case of that law, the case when we put (via the specific subtrahend) the origin into the centroid of the bunch of points (the vectors' endpoints).
|
k-means implementation with custom distance matrix in input
You could turn your matrix of distances into raw data and input these to K-Means clustering. The steps would be as follows:
Distances between your N points must be squared euclidean ones. Perform "do
|
13,211
|
k-means implementation with custom distance matrix in input
|
Please see this article, written by one of my acquaintances ;)
http://arxiv.org/abs/1304.6899
It is about a generalized k-means implementation, which takes an arbitrary distance matrix as input. It can be any symmetrical nonnegative matrix with a zero diagonal. Note that it may not give sensible results for weird distance matrices. The program is written in C#.
Source code can be obtained by visiting the above link, then clicking Other Formats, then clicking Download Source. Then you will get a .tar.gz containing Program.cs. Alternatively, the source code can be copied out from the PDF as well.
|
k-means implementation with custom distance matrix in input
|
Please see this article, written by one of my acquaintances ;)
http://arxiv.org/abs/1304.6899
It is about a generalized k-means implementation, which takes an arbitrary distance matrix as input. It ca
|
k-means implementation with custom distance matrix in input
Please see this article, written by one of my acquaintances ;)
http://arxiv.org/abs/1304.6899
It is about a generalized k-means implementation, which takes an arbitrary distance matrix as input. It can be any symmetrical nonnegative matrix with a zero diagonal. Note that it may not give sensible results for weird distance matrices. The program is written in C#.
Source code can be obtained by visiting the above link, then clicking Other Formats, then clicking Download Source. Then you will get a .tar.gz containing Program.cs. Alternatively, the source code can be copied out from the PDF as well.
|
k-means implementation with custom distance matrix in input
Please see this article, written by one of my acquaintances ;)
http://arxiv.org/abs/1304.6899
It is about a generalized k-means implementation, which takes an arbitrary distance matrix as input. It ca
|
13,212
|
k-means implementation with custom distance matrix in input
|
You can use Java Machine Learning Library. They have a K-Means implementation. One of the constructors accepts three arguments
K Value.
An object of that is an instance of the DistanceMeasure Class.
Number of iterations.
One can easily extend the DistanceMeasure class to achieve the desired result. The idea is to return values from a custom distance matrix in the measure(Instance x, Instance y) method of this class.
K-Means is guarnateed to converge assuming certain properties of the distance metric. Euclidean distance, Manhattan distance or other standard metrics satisfy these assumptions. Since a custom distance metric may not satisfy these assumptions, the constructor has a third parameter specifying the number of iterations to run for building the clusterer.
|
k-means implementation with custom distance matrix in input
|
You can use Java Machine Learning Library. They have a K-Means implementation. One of the constructors accepts three arguments
K Value.
An object of that is an instance of the DistanceMeasure Class.
|
k-means implementation with custom distance matrix in input
You can use Java Machine Learning Library. They have a K-Means implementation. One of the constructors accepts three arguments
K Value.
An object of that is an instance of the DistanceMeasure Class.
Number of iterations.
One can easily extend the DistanceMeasure class to achieve the desired result. The idea is to return values from a custom distance matrix in the measure(Instance x, Instance y) method of this class.
K-Means is guarnateed to converge assuming certain properties of the distance metric. Euclidean distance, Manhattan distance or other standard metrics satisfy these assumptions. Since a custom distance metric may not satisfy these assumptions, the constructor has a third parameter specifying the number of iterations to run for building the clusterer.
|
k-means implementation with custom distance matrix in input
You can use Java Machine Learning Library. They have a K-Means implementation. One of the constructors accepts three arguments
K Value.
An object of that is an instance of the DistanceMeasure Class.
|
13,213
|
Why would one suppress the intercept in linear regression?
|
If for some reason you know the intercept (particularly if it is zero), you can avoid wasting the variance in your data for estimating something you already know, and have more confidence in the values you do have to estimate.
A somewhat oversimplified example is if you already know (from domain knowledge) that one variable is (on average) a multiple of another, and you are trying to find that multiple.
|
Why would one suppress the intercept in linear regression?
|
If for some reason you know the intercept (particularly if it is zero), you can avoid wasting the variance in your data for estimating something you already know, and have more confidence in the value
|
Why would one suppress the intercept in linear regression?
If for some reason you know the intercept (particularly if it is zero), you can avoid wasting the variance in your data for estimating something you already know, and have more confidence in the values you do have to estimate.
A somewhat oversimplified example is if you already know (from domain knowledge) that one variable is (on average) a multiple of another, and you are trying to find that multiple.
|
Why would one suppress the intercept in linear regression?
If for some reason you know the intercept (particularly if it is zero), you can avoid wasting the variance in your data for estimating something you already know, and have more confidence in the value
|
13,214
|
Why would one suppress the intercept in linear regression?
|
Consider the case of a 3-level categorical covariate. If one has an intercept, that would require 2 indicator variables. Using the usual coding for indicator variables, the coefficient for either indicator variable is the mean difference compared to the reference group. By suppressing the intercept, you would have 3 variables representing the categorical covariate, instead of just 2. A coefficient is then the mean estimate for that group. A more concrete example of where to do this is in political science where one may be studying the 50 states of the United States. Instead of having an intercept and 49 indicator variables for the states, it is often preferable to suppress the intercept and instead have 50 variables.
|
Why would one suppress the intercept in linear regression?
|
Consider the case of a 3-level categorical covariate. If one has an intercept, that would require 2 indicator variables. Using the usual coding for indicator variables, the coefficient for either in
|
Why would one suppress the intercept in linear regression?
Consider the case of a 3-level categorical covariate. If one has an intercept, that would require 2 indicator variables. Using the usual coding for indicator variables, the coefficient for either indicator variable is the mean difference compared to the reference group. By suppressing the intercept, you would have 3 variables representing the categorical covariate, instead of just 2. A coefficient is then the mean estimate for that group. A more concrete example of where to do this is in political science where one may be studying the 50 states of the United States. Instead of having an intercept and 49 indicator variables for the states, it is often preferable to suppress the intercept and instead have 50 variables.
|
Why would one suppress the intercept in linear regression?
Consider the case of a 3-level categorical covariate. If one has an intercept, that would require 2 indicator variables. Using the usual coding for indicator variables, the coefficient for either in
|
13,215
|
Why would one suppress the intercept in linear regression?
|
To illustrate @Nick Sabbe's point with a specific example.
I once saw a researcher present a model of the age of a tree as a function of its width. It can be assumed that when the tree is at age zero, it effectively has a width of zero. Thus, an intercept is not required.
|
Why would one suppress the intercept in linear regression?
|
To illustrate @Nick Sabbe's point with a specific example.
I once saw a researcher present a model of the age of a tree as a function of its width. It can be assumed that when the tree is at age zero,
|
Why would one suppress the intercept in linear regression?
To illustrate @Nick Sabbe's point with a specific example.
I once saw a researcher present a model of the age of a tree as a function of its width. It can be assumed that when the tree is at age zero, it effectively has a width of zero. Thus, an intercept is not required.
|
Why would one suppress the intercept in linear regression?
To illustrate @Nick Sabbe's point with a specific example.
I once saw a researcher present a model of the age of a tree as a function of its width. It can be assumed that when the tree is at age zero,
|
13,216
|
Calculating required sample size, precision of variance estimate?
|
For i.i.d. random variables $X_1, \dotsc, X_n$, the unbiased estimator for the variance $s^2$ (the one with denominator $n-1$) has variance:
$$\mathrm{Var}(s^2) = \sigma^4 \left(\frac{2}{n-1} + \frac{\kappa}{n}\right)$$
where $\kappa$ is the excess kurtosis of the distribution (reference: Wikipedia). So now you need to estimate the kurtosis of your distribution as well. You can use a quantity sometimes described as $\gamma_2$ (also from Wikipedia):
$$\gamma_2 = \frac{\mu_4}{\sigma_4} - 3$$
I would assume that if you use $s$ as an estimate for $\sigma$ and $\gamma_2$ as an estimate for $\kappa$, that you get a reasonable estimate for $\mathrm{Var}(s^2)$, although I don't see a guarantee that it is unbiased. See if it matches with the variance among the subsets of your 500 data points reasonably, and if it does don't worry about it anymore :)
|
Calculating required sample size, precision of variance estimate?
|
For i.i.d. random variables $X_1, \dotsc, X_n$, the unbiased estimator for the variance $s^2$ (the one with denominator $n-1$) has variance:
$$\mathrm{Var}(s^2) = \sigma^4 \left(\frac{2}{n-1} + \frac{
|
Calculating required sample size, precision of variance estimate?
For i.i.d. random variables $X_1, \dotsc, X_n$, the unbiased estimator for the variance $s^2$ (the one with denominator $n-1$) has variance:
$$\mathrm{Var}(s^2) = \sigma^4 \left(\frac{2}{n-1} + \frac{\kappa}{n}\right)$$
where $\kappa$ is the excess kurtosis of the distribution (reference: Wikipedia). So now you need to estimate the kurtosis of your distribution as well. You can use a quantity sometimes described as $\gamma_2$ (also from Wikipedia):
$$\gamma_2 = \frac{\mu_4}{\sigma_4} - 3$$
I would assume that if you use $s$ as an estimate for $\sigma$ and $\gamma_2$ as an estimate for $\kappa$, that you get a reasonable estimate for $\mathrm{Var}(s^2)$, although I don't see a guarantee that it is unbiased. See if it matches with the variance among the subsets of your 500 data points reasonably, and if it does don't worry about it anymore :)
|
Calculating required sample size, precision of variance estimate?
For i.i.d. random variables $X_1, \dotsc, X_n$, the unbiased estimator for the variance $s^2$ (the one with denominator $n-1$) has variance:
$$\mathrm{Var}(s^2) = \sigma^4 \left(\frac{2}{n-1} + \frac{
|
13,217
|
Calculating required sample size, precision of variance estimate?
|
Learning a variance is hard.
It takes a (perhaps surprisingly) large number of samples to estimate a variance well in many cases. Below, I'll show the development for the "canonical" case of an i.i.d. normal sample.
Suppose $Y_i$, $i=1,\ldots,n$ are independent $\mathcal{N}(\mu, \sigma^2)$ random variables. We seek a $100(1-\alpha)\%$ confidence interval for the variance such that the width of the interval is $\rho s^2$, i.e., the width is $100\rho \%$ of the point estimate. For example, if $\rho = 1/2$, then the width of the CI is half the value of the point estimate, e.g., if $s^2 = 10$, then the CI would be something like $(8,\,13)$, having a width of 5. Note the asymmetry around the point estimate, as well. ($s^2$ is the unbiased estimator for the variance.)
"The" (rather, "a") confidence interval for $s^2$ is
$$
\frac{(n-1) s^2}{\chi_{(n-1)}^{2\;(1-\alpha/2)}} \leq \sigma^2 \leq \frac{(n-1) s^2}{\chi_{(n-1)}^{2\;(\alpha/2)}} \>,
$$
where $\chi_{(n-1)}^{2\;\beta}$ is the $\beta$ quantile of the chi-squared distribution with $n-1$ degrees of freedom. (This arises from the fact that $(n-1)s^2/\sigma^2$ is a pivotal quantity in a Gaussian setting.)
We want to minimize the width so that
$$
L(n) = \frac{(n-1) s^2}{\chi_{(n-1)}^{2\;(\alpha/2)}} - \frac{(n-1) s^2}{\chi_{(n-1)}^{2\;(1-\alpha/2)}} < \rho s^2 \>,
$$
so we are left to solve for $n$ such that
$$
(n-1) \left(\frac{1}{\chi_{(n-1)}^{2\;(\alpha/2)}} - \frac{1}{\chi_{(n-1)}^{2\;(1-\alpha/2)}} \right) < \rho .
$$
For the case of a 99% confidence interval, we get $n = 65$ for $\rho = 1$ and $n = 5321$ for $\rho = 0.1$. This last case yields an interval that is (still!) 10% as large as the point estimate of the variance.
If your chosen confidence level is less than 99%, then the same width interval will be obtained for a lower value of $n$. But, $n$ may still may be larger than you would have guessed.
A plot of the sample size $n$ versus the proportional width $\rho$ shows something that looks asymptotically linear on a log-log scale; in other words, a power-law--like relationship. We can estimate the power of this power-law relationship (crudely) as
$$
\hat{\alpha} \approx \frac{\log 0.1 - \log 1}{\log 5321 - \log 65} = \frac{-\log 10}{\log \frac{5231}{65}} \approx -0.525 ,
$$
which is, unfortunately, decidedly slow!
This is sort of the "canonical" case to give you a feel for how to go about the calculation. Based on your plots, your data don't look particularly normal; in particular, there is what appears to be noticeable skewness.
But, this should give you a ballpark idea of what to expect. Note that to answer your second question above, it is necessary to fix some confidence level first, which I've set to 99% in the development above for demonstration purposes.
|
Calculating required sample size, precision of variance estimate?
|
Learning a variance is hard.
It takes a (perhaps surprisingly) large number of samples to estimate a variance well in many cases. Below, I'll show the development for the "canonical" case of an i.i.d.
|
Calculating required sample size, precision of variance estimate?
Learning a variance is hard.
It takes a (perhaps surprisingly) large number of samples to estimate a variance well in many cases. Below, I'll show the development for the "canonical" case of an i.i.d. normal sample.
Suppose $Y_i$, $i=1,\ldots,n$ are independent $\mathcal{N}(\mu, \sigma^2)$ random variables. We seek a $100(1-\alpha)\%$ confidence interval for the variance such that the width of the interval is $\rho s^2$, i.e., the width is $100\rho \%$ of the point estimate. For example, if $\rho = 1/2$, then the width of the CI is half the value of the point estimate, e.g., if $s^2 = 10$, then the CI would be something like $(8,\,13)$, having a width of 5. Note the asymmetry around the point estimate, as well. ($s^2$ is the unbiased estimator for the variance.)
"The" (rather, "a") confidence interval for $s^2$ is
$$
\frac{(n-1) s^2}{\chi_{(n-1)}^{2\;(1-\alpha/2)}} \leq \sigma^2 \leq \frac{(n-1) s^2}{\chi_{(n-1)}^{2\;(\alpha/2)}} \>,
$$
where $\chi_{(n-1)}^{2\;\beta}$ is the $\beta$ quantile of the chi-squared distribution with $n-1$ degrees of freedom. (This arises from the fact that $(n-1)s^2/\sigma^2$ is a pivotal quantity in a Gaussian setting.)
We want to minimize the width so that
$$
L(n) = \frac{(n-1) s^2}{\chi_{(n-1)}^{2\;(\alpha/2)}} - \frac{(n-1) s^2}{\chi_{(n-1)}^{2\;(1-\alpha/2)}} < \rho s^2 \>,
$$
so we are left to solve for $n$ such that
$$
(n-1) \left(\frac{1}{\chi_{(n-1)}^{2\;(\alpha/2)}} - \frac{1}{\chi_{(n-1)}^{2\;(1-\alpha/2)}} \right) < \rho .
$$
For the case of a 99% confidence interval, we get $n = 65$ for $\rho = 1$ and $n = 5321$ for $\rho = 0.1$. This last case yields an interval that is (still!) 10% as large as the point estimate of the variance.
If your chosen confidence level is less than 99%, then the same width interval will be obtained for a lower value of $n$. But, $n$ may still may be larger than you would have guessed.
A plot of the sample size $n$ versus the proportional width $\rho$ shows something that looks asymptotically linear on a log-log scale; in other words, a power-law--like relationship. We can estimate the power of this power-law relationship (crudely) as
$$
\hat{\alpha} \approx \frac{\log 0.1 - \log 1}{\log 5321 - \log 65} = \frac{-\log 10}{\log \frac{5231}{65}} \approx -0.525 ,
$$
which is, unfortunately, decidedly slow!
This is sort of the "canonical" case to give you a feel for how to go about the calculation. Based on your plots, your data don't look particularly normal; in particular, there is what appears to be noticeable skewness.
But, this should give you a ballpark idea of what to expect. Note that to answer your second question above, it is necessary to fix some confidence level first, which I've set to 99% in the development above for demonstration purposes.
|
Calculating required sample size, precision of variance estimate?
Learning a variance is hard.
It takes a (perhaps surprisingly) large number of samples to estimate a variance well in many cases. Below, I'll show the development for the "canonical" case of an i.i.d.
|
13,218
|
Calculating required sample size, precision of variance estimate?
|
I would focus on the SD rather than the variance, since it's on a scale that is more easily interpreted.
People do sometimes look at confidence intervals for SDs or variances, but the focus is generally on means.
The results you give for the distribution of $s^2/\sigma^2$ can be used to get a confidence interval for $\sigma^2$ (and so also $\sigma$); most introductory math/stat texts would give the details in the same section in which the ditribution of $\sigma^2$ was mentioned. I would just take 2.5% from each tail.
|
Calculating required sample size, precision of variance estimate?
|
I would focus on the SD rather than the variance, since it's on a scale that is more easily interpreted.
People do sometimes look at confidence intervals for SDs or variances, but the focus is general
|
Calculating required sample size, precision of variance estimate?
I would focus on the SD rather than the variance, since it's on a scale that is more easily interpreted.
People do sometimes look at confidence intervals for SDs or variances, but the focus is generally on means.
The results you give for the distribution of $s^2/\sigma^2$ can be used to get a confidence interval for $\sigma^2$ (and so also $\sigma$); most introductory math/stat texts would give the details in the same section in which the ditribution of $\sigma^2$ was mentioned. I would just take 2.5% from each tail.
|
Calculating required sample size, precision of variance estimate?
I would focus on the SD rather than the variance, since it's on a scale that is more easily interpreted.
People do sometimes look at confidence intervals for SDs or variances, but the focus is general
|
13,219
|
Calculating required sample size, precision of variance estimate?
|
The following solution was given by Greenwood and Sandomire in a 1950 JASA paper.
Let $X_1,\dots,X_n$ be a random sample from a $\mathrm{N}(\mu,\sigma^2)$ distribution. You will make inferences about $\sigma$ using as (biased) estimator the sample standard deviation
$$
S=\sqrt{\sum_{i=1}^n\frac{(X_i-\bar{X})^2}{n-1}},
$$
and you want to control the probability that the relative deviation between $S$ and $\sigma$ is within a fraction $0<u<1$. That is,
$$
\Pr\{S<(1-u)\cdot\sigma\}=a \quad\text{and}\quad \Pr\{S>(1+u)\cdot\sigma\}=b,
$$
in which the significance level $\gamma=1-a-b$.
It follows that
$$
\Pr\!\left\{ \frac{(n-1)S^2}{\sigma^2} < (n-1)(1-u)^2\right\} = a
$$
and
$$
\Pr\!\left\{ \frac{(n-1)S^2}{\sigma^2} > (n-1)(1+u)^2\right\} = b.
$$
Since the pivotal quantity $(n-1)S^2/\sigma^2$ has $\chi^2_{n-1}$ distribution, adding the two probabilities, we find
$$
\gamma = F_{\chi^2_{(n-1)}}((n-1)(1+u)^2) - F_{\chi^2_{(n-1)}}((n-1)(1-u)^2),
$$
and the necessary sample size is found solving the former equation in $n$ for given $\gamma$ and $u$.
R code.
gamma <- 0.95
u <- 0.1
g <- function(n) pchisq((n-1)*(1+u)^2, df = n-1) - pchisq((n-1)*(1-u)^2, df = n-1) - gamma
cat("Sample size n = ", ceiling(uniroot(g, interval = c(2, 10^6))$root), "\n")
Output for $u=10\%$ and $\gamma=95\%$.
Sample size n = 193
|
Calculating required sample size, precision of variance estimate?
|
The following solution was given by Greenwood and Sandomire in a 1950 JASA paper.
Let $X_1,\dots,X_n$ be a random sample from a $\mathrm{N}(\mu,\sigma^2)$ distribution. You will make inferences about
|
Calculating required sample size, precision of variance estimate?
The following solution was given by Greenwood and Sandomire in a 1950 JASA paper.
Let $X_1,\dots,X_n$ be a random sample from a $\mathrm{N}(\mu,\sigma^2)$ distribution. You will make inferences about $\sigma$ using as (biased) estimator the sample standard deviation
$$
S=\sqrt{\sum_{i=1}^n\frac{(X_i-\bar{X})^2}{n-1}},
$$
and you want to control the probability that the relative deviation between $S$ and $\sigma$ is within a fraction $0<u<1$. That is,
$$
\Pr\{S<(1-u)\cdot\sigma\}=a \quad\text{and}\quad \Pr\{S>(1+u)\cdot\sigma\}=b,
$$
in which the significance level $\gamma=1-a-b$.
It follows that
$$
\Pr\!\left\{ \frac{(n-1)S^2}{\sigma^2} < (n-1)(1-u)^2\right\} = a
$$
and
$$
\Pr\!\left\{ \frac{(n-1)S^2}{\sigma^2} > (n-1)(1+u)^2\right\} = b.
$$
Since the pivotal quantity $(n-1)S^2/\sigma^2$ has $\chi^2_{n-1}$ distribution, adding the two probabilities, we find
$$
\gamma = F_{\chi^2_{(n-1)}}((n-1)(1+u)^2) - F_{\chi^2_{(n-1)}}((n-1)(1-u)^2),
$$
and the necessary sample size is found solving the former equation in $n$ for given $\gamma$ and $u$.
R code.
gamma <- 0.95
u <- 0.1
g <- function(n) pchisq((n-1)*(1+u)^2, df = n-1) - pchisq((n-1)*(1-u)^2, df = n-1) - gamma
cat("Sample size n = ", ceiling(uniroot(g, interval = c(2, 10^6))$root), "\n")
Output for $u=10\%$ and $\gamma=95\%$.
Sample size n = 193
|
Calculating required sample size, precision of variance estimate?
The following solution was given by Greenwood and Sandomire in a 1950 JASA paper.
Let $X_1,\dots,X_n$ be a random sample from a $\mathrm{N}(\mu,\sigma^2)$ distribution. You will make inferences about
|
13,220
|
Removing outliers based on cook's distance in R Language
|
This post has around 6000 views in 2 years so I guess an answer is much needed. Although I borrowed a lot of ideas from the reference, I made some modifications. We will be using the cars data in base r.
library(tidyverse)
# Inject outliers into data.
cars1 <- cars[1:30, ] # original data
cars_outliers <- data.frame(speed=c(1,19), dist=c(198,199)) # introduce outliers.
cars2 <- rbind(cars1, cars_outliers) # data with outliers.
Let's plot the data with outliers to see how extreme they are.
# Plot of data with outliers.
plot1 <- ggplot(data = cars1, aes(x = speed, y = dist)) +
geom_point() +
geom_smooth(method = lm) +
xlim(0, 20) + ylim(0, 220) +
ggtitle("No Outliers")
plot2 <- ggplot(data = cars2, aes(x = speed, y = dist)) +
geom_point() +
geom_smooth(method = lm) +
xlim(0, 20) + ylim(0, 220) +
ggtitle("With Outliers")
gridExtra::grid.arrange(plot1, plot2, ncol=2)
We can see that the regression line has a poor fit after introducing the outliers. Therefore, let's us Cook's Distance to identity them. I am using the traditional cut-off of $\frac{4}{n}$. Notice that cut-off value just helps you to think about what's wrong with the data.
mod <- lm(dist ~ speed, data = cars2)
cooksd <- cooks.distance(mod)
# Plot the Cook's Distance using the traditional 4/n criterion
sample_size <- nrow(cars2)
plot(cooksd, pch="*", cex=2, main="Influential Obs by Cooks distance") # plot cook's distance
abline(h = 4/sample_size, col="red") # add cutoff line
text(x=1:length(cooksd)+1, y=cooksd, labels=ifelse(cooksd>4/sample_size, names(cooksd),""), col="red") # add labels
There are many ways to deal with outliers as noted in the Reference. Now, I just want to simply remove them.
# Removing Outliers
# influential row numbers
influential <- as.numeric(names(cooksd)[(cooksd > (4/sample_size))])
# Alternatively, you can try to remove the top x outliers to have a look
# top_x_outlier <- 2
# influential <- as.numeric(names(sort(cooksd, decreasing = TRUE)[1:top_x_outlier]))
cars2_screen <- cars2[-influential, ]
plot3 <- ggplot(data = cars2, aes(x = speed, y = dist)) +
geom_point() +
geom_smooth(method = lm) +
xlim(0, 20) + ylim(0, 220) +
ggtitle("Before")
plot4 <- ggplot(data = cars2_screen, aes(x = speed, y = dist)) +
geom_point() +
geom_smooth(method = lm) +
xlim(0, 20) + ylim(0, 220) +
ggtitle("After")
gridExtra::grid.arrange(plot3, plot4, ncol=2)
Hooray, we have successfully removed the outliers~
Excellent Reference:Outlier Treatment
|
Removing outliers based on cook's distance in R Language
|
This post has around 6000 views in 2 years so I guess an answer is much needed. Although I borrowed a lot of ideas from the reference, I made some modifications. We will be using the cars data in base
|
Removing outliers based on cook's distance in R Language
This post has around 6000 views in 2 years so I guess an answer is much needed. Although I borrowed a lot of ideas from the reference, I made some modifications. We will be using the cars data in base r.
library(tidyverse)
# Inject outliers into data.
cars1 <- cars[1:30, ] # original data
cars_outliers <- data.frame(speed=c(1,19), dist=c(198,199)) # introduce outliers.
cars2 <- rbind(cars1, cars_outliers) # data with outliers.
Let's plot the data with outliers to see how extreme they are.
# Plot of data with outliers.
plot1 <- ggplot(data = cars1, aes(x = speed, y = dist)) +
geom_point() +
geom_smooth(method = lm) +
xlim(0, 20) + ylim(0, 220) +
ggtitle("No Outliers")
plot2 <- ggplot(data = cars2, aes(x = speed, y = dist)) +
geom_point() +
geom_smooth(method = lm) +
xlim(0, 20) + ylim(0, 220) +
ggtitle("With Outliers")
gridExtra::grid.arrange(plot1, plot2, ncol=2)
We can see that the regression line has a poor fit after introducing the outliers. Therefore, let's us Cook's Distance to identity them. I am using the traditional cut-off of $\frac{4}{n}$. Notice that cut-off value just helps you to think about what's wrong with the data.
mod <- lm(dist ~ speed, data = cars2)
cooksd <- cooks.distance(mod)
# Plot the Cook's Distance using the traditional 4/n criterion
sample_size <- nrow(cars2)
plot(cooksd, pch="*", cex=2, main="Influential Obs by Cooks distance") # plot cook's distance
abline(h = 4/sample_size, col="red") # add cutoff line
text(x=1:length(cooksd)+1, y=cooksd, labels=ifelse(cooksd>4/sample_size, names(cooksd),""), col="red") # add labels
There are many ways to deal with outliers as noted in the Reference. Now, I just want to simply remove them.
# Removing Outliers
# influential row numbers
influential <- as.numeric(names(cooksd)[(cooksd > (4/sample_size))])
# Alternatively, you can try to remove the top x outliers to have a look
# top_x_outlier <- 2
# influential <- as.numeric(names(sort(cooksd, decreasing = TRUE)[1:top_x_outlier]))
cars2_screen <- cars2[-influential, ]
plot3 <- ggplot(data = cars2, aes(x = speed, y = dist)) +
geom_point() +
geom_smooth(method = lm) +
xlim(0, 20) + ylim(0, 220) +
ggtitle("Before")
plot4 <- ggplot(data = cars2_screen, aes(x = speed, y = dist)) +
geom_point() +
geom_smooth(method = lm) +
xlim(0, 20) + ylim(0, 220) +
ggtitle("After")
gridExtra::grid.arrange(plot3, plot4, ncol=2)
Hooray, we have successfully removed the outliers~
Excellent Reference:Outlier Treatment
|
Removing outliers based on cook's distance in R Language
This post has around 6000 views in 2 years so I guess an answer is much needed. Although I borrowed a lot of ideas from the reference, I made some modifications. We will be using the cars data in base
|
13,221
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
|
The relevant manuscript is here.
The difference between ward.D and ward.D2 is the difference between the two clustering criteria that in the manuscript are called Ward1 and Ward2.
It basically boils down to the fact that the Ward algorithm is directly correctly implemented in just Ward2 (ward.D2), but Ward1 (ward.D) can also be used, if the Euclidean distances (from dist()) are squared before inputing them to the hclust() using the ward.D as the method.
For example, SPSS also implements Ward1, but warn the users that distances should be squared to obtain the Ward criterion. In such sense implementation of ward.D is not deprecated, and nonetheless it might be a good idea to retain it for backward compatibility.
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
|
The relevant manuscript is here.
The difference between ward.D and ward.D2 is the difference between the two clustering criteria that in the manuscript are called Ward1 and Ward2.
It basically boils d
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
The relevant manuscript is here.
The difference between ward.D and ward.D2 is the difference between the two clustering criteria that in the manuscript are called Ward1 and Ward2.
It basically boils down to the fact that the Ward algorithm is directly correctly implemented in just Ward2 (ward.D2), but Ward1 (ward.D) can also be used, if the Euclidean distances (from dist()) are squared before inputing them to the hclust() using the ward.D as the method.
For example, SPSS also implements Ward1, but warn the users that distances should be squared to obtain the Ward criterion. In such sense implementation of ward.D is not deprecated, and nonetheless it might be a good idea to retain it for backward compatibility.
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
The relevant manuscript is here.
The difference between ward.D and ward.D2 is the difference between the two clustering criteria that in the manuscript are called Ward1 and Ward2.
It basically boils d
|
13,222
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
|
The only difference between ward.D & ward.D2 is the input parameter.
hclust(dist(x)^2,method="ward.D") ~ hclust(dist(x)^2,method="ward")
which are equivalent to: hclust(dist(x),method="ward.D2")
You can find the reserach paper :
Ward’s Hierarchical Clustering Method:
Clustering Criterion and Agglomerative Algorithm
The Ward2 criterion values are “on a scale of distances” whereas the Ward1 criterion values are “on a scale of distances squared”.
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
|
The only difference between ward.D & ward.D2 is the input parameter.
hclust(dist(x)^2,method="ward.D") ~ hclust(dist(x)^2,method="ward")
which are equivalent to: hclust(dist(x),method="ward.D2")
You
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
The only difference between ward.D & ward.D2 is the input parameter.
hclust(dist(x)^2,method="ward.D") ~ hclust(dist(x)^2,method="ward")
which are equivalent to: hclust(dist(x),method="ward.D2")
You can find the reserach paper :
Ward’s Hierarchical Clustering Method:
Clustering Criterion and Agglomerative Algorithm
The Ward2 criterion values are “on a scale of distances” whereas the Ward1 criterion values are “on a scale of distances squared”.
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
The only difference between ward.D & ward.D2 is the input parameter.
hclust(dist(x)^2,method="ward.D") ~ hclust(dist(x)^2,method="ward")
which are equivalent to: hclust(dist(x),method="ward.D2")
You
|
13,223
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
|
I came across the research paper that corresponds to the objective function that is being optimized by "Ward1 (ward.D)": Hierarchical Clustering via Joint Between-Within Distances: Extending Ward's Minimum Variance Method. It turns out that R's implementation of "Ward1 (ward.D)" is equivalent to minimizing the energy distance between cluster groups.
2.1 Cluster $e$-distance and Objective Function
Let $A = \{a_1, \ldots, a_{n_1}\}$ and $B = \{b_1, \ldots, b_{n_2}\}$ be nonempty subsets of $\mathbb R^d$. Define the between-within, or $e$-distance $e(A, B)$, between $A$ and $B$ as
\begin{align}
e(A, B) = &\frac{n_1n_2}{n_1+n_2}\bigg(\frac{2}{n_1n_2}\sum_{i=1}^{n_1} \sum_{j=1}^{n_2} \|a_i-b_j\| \\
&- \frac{1}{n_1^2}\sum_{i=1}^{n_1}\sum_{j=1}^{n_1}\|a_i-a_j\| -
\frac{1}{n_2^2}\sum_{i=1}^{n_2}\sum_{j=1}^{n_2}\|b_i-b_j\|\bigg). \tag{1}
\end{align}
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
|
I came across the research paper that corresponds to the objective function that is being optimized by "Ward1 (ward.D)": Hierarchical Clustering via Joint Between-Within Distances: Extending Ward's Mi
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
I came across the research paper that corresponds to the objective function that is being optimized by "Ward1 (ward.D)": Hierarchical Clustering via Joint Between-Within Distances: Extending Ward's Minimum Variance Method. It turns out that R's implementation of "Ward1 (ward.D)" is equivalent to minimizing the energy distance between cluster groups.
2.1 Cluster $e$-distance and Objective Function
Let $A = \{a_1, \ldots, a_{n_1}\}$ and $B = \{b_1, \ldots, b_{n_2}\}$ be nonempty subsets of $\mathbb R^d$. Define the between-within, or $e$-distance $e(A, B)$, between $A$ and $B$ as
\begin{align}
e(A, B) = &\frac{n_1n_2}{n_1+n_2}\bigg(\frac{2}{n_1n_2}\sum_{i=1}^{n_1} \sum_{j=1}^{n_2} \|a_i-b_j\| \\
&- \frac{1}{n_1^2}\sum_{i=1}^{n_1}\sum_{j=1}^{n_1}\|a_i-a_j\| -
\frac{1}{n_2^2}\sum_{i=1}^{n_2}\sum_{j=1}^{n_2}\|b_i-b_j\|\bigg). \tag{1}
\end{align}
|
What algorithm does ward.D in hclust() implement if it is not Ward's criterion?
I came across the research paper that corresponds to the objective function that is being optimized by "Ward1 (ward.D)": Hierarchical Clustering via Joint Between-Within Distances: Extending Ward's Mi
|
13,224
|
SVM for unbalanced data
|
Many SVM implementations address this by assigning different weights to positive and negative instances. Essentially you weigh the samples so that the sum of the weights for the positives will be equal to that of the negatives. Of course, in your evaluation of the SVM you have to remember that if 95% of the data is negative, it is trivial to get 95% accuracy by always predicting negative. So you have to make sure your evaluation metrics are also weighted so that they are balanced.
Specifically in libsvm, which you added as a tag, there is a flag that allows you to set the class weights (-w I believe, but check the docs).
Finally, from personal experience I can tell you that I often find that an SVM will yield very similar results with or without the weight correction.
|
SVM for unbalanced data
|
Many SVM implementations address this by assigning different weights to positive and negative instances. Essentially you weigh the samples so that the sum of the weights for the positives will be equa
|
SVM for unbalanced data
Many SVM implementations address this by assigning different weights to positive and negative instances. Essentially you weigh the samples so that the sum of the weights for the positives will be equal to that of the negatives. Of course, in your evaluation of the SVM you have to remember that if 95% of the data is negative, it is trivial to get 95% accuracy by always predicting negative. So you have to make sure your evaluation metrics are also weighted so that they are balanced.
Specifically in libsvm, which you added as a tag, there is a flag that allows you to set the class weights (-w I believe, but check the docs).
Finally, from personal experience I can tell you that I often find that an SVM will yield very similar results with or without the weight correction.
|
SVM for unbalanced data
Many SVM implementations address this by assigning different weights to positive and negative instances. Essentially you weigh the samples so that the sum of the weights for the positives will be equa
|
13,225
|
SVM for unbalanced data
|
SVMs work fine on sparse and unbalanced data. Class-weighted SVM is designed to deal with unbalanced data by assigning higher misclassification penalties to training instances of the minority class.
|
SVM for unbalanced data
|
SVMs work fine on sparse and unbalanced data. Class-weighted SVM is designed to deal with unbalanced data by assigning higher misclassification penalties to training instances of the minority class.
|
SVM for unbalanced data
SVMs work fine on sparse and unbalanced data. Class-weighted SVM is designed to deal with unbalanced data by assigning higher misclassification penalties to training instances of the minority class.
|
SVM for unbalanced data
SVMs work fine on sparse and unbalanced data. Class-weighted SVM is designed to deal with unbalanced data by assigning higher misclassification penalties to training instances of the minority class.
|
13,226
|
SVM for unbalanced data
|
In the case of sparse data like that SVM will work well.
As stated by @Bitwise you should not use accuracy to measure the performance of the algorithm.
Instead you should calculate the precision, recall and F-Score of the algorithm.
|
SVM for unbalanced data
|
In the case of sparse data like that SVM will work well.
As stated by @Bitwise you should not use accuracy to measure the performance of the algorithm.
Instead you should calculate the precision, reca
|
SVM for unbalanced data
In the case of sparse data like that SVM will work well.
As stated by @Bitwise you should not use accuracy to measure the performance of the algorithm.
Instead you should calculate the precision, recall and F-Score of the algorithm.
|
SVM for unbalanced data
In the case of sparse data like that SVM will work well.
As stated by @Bitwise you should not use accuracy to measure the performance of the algorithm.
Instead you should calculate the precision, reca
|
13,227
|
What is the difference between descriptive and inferential statistics?
|
Coming from a behavioural sciences background, I associate this terminology particularly with introductory statistics textbooks. In this context the distinction is that :
Descriptive statistics are functions of the sample data that are intrinsically interesting in describing some feature of the data. Classic descriptive statistics include mean, min, max, standard deviation, median, skew, kurtosis.
Inferential statistics are a function of the sample data that assists you to draw an inference regarding an hypothesis about a population parameter. Classic inferential statistics include z, t, $\chi^2$, F-ratio, etc.
The important point is that any statistic, inferential or descriptive, is a function of the sample data. A parameter is a function of the population, where the term population is the same as saying the underlying data generating process.
From this perspective the status of a given function of the data as a descriptive or inferential statistic depends on the purpose for which you are using it.
That said, some statistics are clearly more useful in describing relevant features of the data, and some are well suited to aiding inference.
Inferential statistics: Standard test statistics like t and z, for a given data generating process, where the null hypothesis is false, the expected value is strongly influenced by sample size. Most researchers would not see such statistics as estimating a population parameter of intrinsic interest.
Descriptive statistics: In contrast descriptive statistics do estimate population parameters that are typically of intrinsic interest. For example the sample mean and standard deviation provide estimates of the equivalent population parameters. Even descriptive statistics like the minimum and maximum provide information about equivalent or similar population parameters, although of course in this case, much more care is required. Furthermore, many descriptive statistics might be biased or otherwise less than ideal estimators. However, they still have some utility in estimating a population parameter of interest.
So from this perspective, the important things to understand are:
statistic: function of the sample data
parameter: function of the population (data generating process)
estimator: function of the sample data used to provide an estimate of a parameter
inference: process of reaching a conclusion about a parameter
Thus, you could either define the distinction between descriptive and inferential based on the intention of the researcher using the statistic, or you could define a statistic based on how it is typically used.
|
What is the difference between descriptive and inferential statistics?
|
Coming from a behavioural sciences background, I associate this terminology particularly with introductory statistics textbooks. In this context the distinction is that :
Descriptive statistics are
|
What is the difference between descriptive and inferential statistics?
Coming from a behavioural sciences background, I associate this terminology particularly with introductory statistics textbooks. In this context the distinction is that :
Descriptive statistics are functions of the sample data that are intrinsically interesting in describing some feature of the data. Classic descriptive statistics include mean, min, max, standard deviation, median, skew, kurtosis.
Inferential statistics are a function of the sample data that assists you to draw an inference regarding an hypothesis about a population parameter. Classic inferential statistics include z, t, $\chi^2$, F-ratio, etc.
The important point is that any statistic, inferential or descriptive, is a function of the sample data. A parameter is a function of the population, where the term population is the same as saying the underlying data generating process.
From this perspective the status of a given function of the data as a descriptive or inferential statistic depends on the purpose for which you are using it.
That said, some statistics are clearly more useful in describing relevant features of the data, and some are well suited to aiding inference.
Inferential statistics: Standard test statistics like t and z, for a given data generating process, where the null hypothesis is false, the expected value is strongly influenced by sample size. Most researchers would not see such statistics as estimating a population parameter of intrinsic interest.
Descriptive statistics: In contrast descriptive statistics do estimate population parameters that are typically of intrinsic interest. For example the sample mean and standard deviation provide estimates of the equivalent population parameters. Even descriptive statistics like the minimum and maximum provide information about equivalent or similar population parameters, although of course in this case, much more care is required. Furthermore, many descriptive statistics might be biased or otherwise less than ideal estimators. However, they still have some utility in estimating a population parameter of interest.
So from this perspective, the important things to understand are:
statistic: function of the sample data
parameter: function of the population (data generating process)
estimator: function of the sample data used to provide an estimate of a parameter
inference: process of reaching a conclusion about a parameter
Thus, you could either define the distinction between descriptive and inferential based on the intention of the researcher using the statistic, or you could define a statistic based on how it is typically used.
|
What is the difference between descriptive and inferential statistics?
Coming from a behavioural sciences background, I associate this terminology particularly with introductory statistics textbooks. In this context the distinction is that :
Descriptive statistics are
|
13,228
|
What is the difference between descriptive and inferential statistics?
|
One form of inference is based on the random assignment of experimental treatments, & not on random sampling from a population (even hypothetically). Oscar Kempthorne was a proponent.
The first example in Edgington (1995), Randomization Tests illustrates the approach well. A researcher obtains ten subjects, divides them into two groups at random, allocates treatment $A$ to one group & $B$ to the other, measures their responses & calculates Student's t-statistic for the difference in group means. Rather than using normal sampling theory to assess significance he calculates $t$ for every possible way the treatments might have been assigned (there are 252 of them); then, noting that each permutation is equally probable under the null hypothesis of no treatment effect, he sees that nine give a higher value of $t$ than that observed & calculates a p-value of $10/252=0.04$. "Obtains" here, as very often, could mean anything at all—perhaps the first ten undergraduates at his lecture to put up their hands were picked—but with this analysis there's no need to maintain the pretence that the subjects have been randomly sampled from the population of interest (the downside is that any generalization beyond these ten is extra-statistical).
Prediction is another area where you're not necessarily formulating propositions about populations. (I don't know that everyone would want to call prediction "inference", but there's Geisser (1993), Predictive Inference: An Introduction). Often prediction follows from a fitted population model, but not always; e.g. @Matt's classification example, model averaging (Bayesian or based on Akaike weights), or forecasting algorithms such as exponential smoothing.
NB I think "inferential vs descriptive statistics" more often refers to the discipline Statistics, rather than to quantities calculated from samples. There's no essential difference between an inferential & a descriptive statistic; as @Jeremy has pointed out, it's a matter of what use you're putting it to.
|
What is the difference between descriptive and inferential statistics?
|
One form of inference is based on the random assignment of experimental treatments, & not on random sampling from a population (even hypothetically). Oscar Kempthorne was a proponent.
The first exampl
|
What is the difference between descriptive and inferential statistics?
One form of inference is based on the random assignment of experimental treatments, & not on random sampling from a population (even hypothetically). Oscar Kempthorne was a proponent.
The first example in Edgington (1995), Randomization Tests illustrates the approach well. A researcher obtains ten subjects, divides them into two groups at random, allocates treatment $A$ to one group & $B$ to the other, measures their responses & calculates Student's t-statistic for the difference in group means. Rather than using normal sampling theory to assess significance he calculates $t$ for every possible way the treatments might have been assigned (there are 252 of them); then, noting that each permutation is equally probable under the null hypothesis of no treatment effect, he sees that nine give a higher value of $t$ than that observed & calculates a p-value of $10/252=0.04$. "Obtains" here, as very often, could mean anything at all—perhaps the first ten undergraduates at his lecture to put up their hands were picked—but with this analysis there's no need to maintain the pretence that the subjects have been randomly sampled from the population of interest (the downside is that any generalization beyond these ten is extra-statistical).
Prediction is another area where you're not necessarily formulating propositions about populations. (I don't know that everyone would want to call prediction "inference", but there's Geisser (1993), Predictive Inference: An Introduction). Often prediction follows from a fitted population model, but not always; e.g. @Matt's classification example, model averaging (Bayesian or based on Akaike weights), or forecasting algorithms such as exponential smoothing.
NB I think "inferential vs descriptive statistics" more often refers to the discipline Statistics, rather than to quantities calculated from samples. There's no essential difference between an inferential & a descriptive statistic; as @Jeremy has pointed out, it's a matter of what use you're putting it to.
|
What is the difference between descriptive and inferential statistics?
One form of inference is based on the random assignment of experimental treatments, & not on random sampling from a population (even hypothetically). Oscar Kempthorne was a proponent.
The first exampl
|
13,229
|
What is the difference between descriptive and inferential statistics?
|
I'm not sure that classification necessarily makes a statement about the population(s) from which the data points are drawn. Classification, as you probably know, uses training data consisting of some "feature" vectors, each labelled with a specific class, to predict the class labels belonging to other unlabeled feature vectors. For example, we might use a patient's vital signs and a doctor's diagnosis to predict whether other patients are healthy or ill.
Some classifiers, called "generative classifiers", try to explicitly model the populations or data generating process that produces each class. For example, the Naive Bayes algorithm computes $P(\textrm{class}=c|\textrm{features})$ for each class $c$, assuming that the features are all independent. These models could reasonably be seen as statements about the population.
However, other classifiers look for differences between the classes without modeling the classes themselves; these are called discriminative classifiers. One classic example is the nearest neighbour classifier, which assigns an unlabeled example to the class of its closest neighbor (where close is defined in some sensible way for the problem). This doesn't seem like it contains much, if any, information about the populations from which the data points were drawn.
If you are interested in the difference between descriptive and inferential statistics, it might be more fruitful to think about the purpose of the analysis. A descriptive statistic, like the mean, might tell you how many trout are in a typical lake--they describe something. An inferential statistic, like a $t$-test, might tell you if there are typically more trout than bass in these lakes-- it lets you make a claim about a descriptive statistic.
|
What is the difference between descriptive and inferential statistics?
|
I'm not sure that classification necessarily makes a statement about the population(s) from which the data points are drawn. Classification, as you probably know, uses training data consisting of some
|
What is the difference between descriptive and inferential statistics?
I'm not sure that classification necessarily makes a statement about the population(s) from which the data points are drawn. Classification, as you probably know, uses training data consisting of some "feature" vectors, each labelled with a specific class, to predict the class labels belonging to other unlabeled feature vectors. For example, we might use a patient's vital signs and a doctor's diagnosis to predict whether other patients are healthy or ill.
Some classifiers, called "generative classifiers", try to explicitly model the populations or data generating process that produces each class. For example, the Naive Bayes algorithm computes $P(\textrm{class}=c|\textrm{features})$ for each class $c$, assuming that the features are all independent. These models could reasonably be seen as statements about the population.
However, other classifiers look for differences between the classes without modeling the classes themselves; these are called discriminative classifiers. One classic example is the nearest neighbour classifier, which assigns an unlabeled example to the class of its closest neighbor (where close is defined in some sensible way for the problem). This doesn't seem like it contains much, if any, information about the populations from which the data points were drawn.
If you are interested in the difference between descriptive and inferential statistics, it might be more fruitful to think about the purpose of the analysis. A descriptive statistic, like the mean, might tell you how many trout are in a typical lake--they describe something. An inferential statistic, like a $t$-test, might tell you if there are typically more trout than bass in these lakes-- it lets you make a claim about a descriptive statistic.
|
What is the difference between descriptive and inferential statistics?
I'm not sure that classification necessarily makes a statement about the population(s) from which the data points are drawn. Classification, as you probably know, uses training data consisting of some
|
13,230
|
What is the difference between descriptive and inferential statistics?
|
In one line, given the data, descriptive statistics try to summarize the content of your data with minimum loss of information ( depending on what measure do you use). You get to see the geography of the data.( Something like, see the performance graph of the class and say who is on top, the bottom and so on)
In one line, given the data, you try to estimate and infer to the properties of the hypothetical population from which the data comes from. ( Something like, understanding 7th grade students through the good sample from the class, assuming that the underlying population is large enough that you cannot take them into account in totality)
|
What is the difference between descriptive and inferential statistics?
|
In one line, given the data, descriptive statistics try to summarize the content of your data with minimum loss of information ( depending on what measure do you use). You get to see the geography of
|
What is the difference between descriptive and inferential statistics?
In one line, given the data, descriptive statistics try to summarize the content of your data with minimum loss of information ( depending on what measure do you use). You get to see the geography of the data.( Something like, see the performance graph of the class and say who is on top, the bottom and so on)
In one line, given the data, you try to estimate and infer to the properties of the hypothetical population from which the data comes from. ( Something like, understanding 7th grade students through the good sample from the class, assuming that the underlying population is large enough that you cannot take them into account in totality)
|
What is the difference between descriptive and inferential statistics?
In one line, given the data, descriptive statistics try to summarize the content of your data with minimum loss of information ( depending on what measure do you use). You get to see the geography of
|
13,231
|
What is the difference between descriptive and inferential statistics?
|
In Short
Descriptive statistics is the analysis of data that describe, show or summarize data in a meaningful; it simply a way to describe our data/talk about the whole population. some of them are Measures of central tendency and Measure of dispersion
Inferential statistics is technique that allow us to use samples to make generalizations about the populations from which the samples were drawn.example hypothesis testing and
|
What is the difference between descriptive and inferential statistics?
|
In Short
Descriptive statistics is the analysis of data that describe, show or summarize data in a meaningful; it simply a way to describe our data/talk about the whole population. some of them are
|
What is the difference between descriptive and inferential statistics?
In Short
Descriptive statistics is the analysis of data that describe, show or summarize data in a meaningful; it simply a way to describe our data/talk about the whole population. some of them are Measures of central tendency and Measure of dispersion
Inferential statistics is technique that allow us to use samples to make generalizations about the populations from which the samples were drawn.example hypothesis testing and
|
What is the difference between descriptive and inferential statistics?
In Short
Descriptive statistics is the analysis of data that describe, show or summarize data in a meaningful; it simply a way to describe our data/talk about the whole population. some of them are
|
13,232
|
What is the relationship between R-squared and p-value in a regression?
|
The answer is no, there is no such regular relationship between $R^2$ and the overall regression p-value, because $R^2$ depends as much on the variance of the independent variables as it does on the variance of the residuals (to which it is inversely proportional), and you are free to change the variance of the independent variables by arbitrary amounts.
As an example, consider any set of multivariate data $((x_{i1}, x_{i2}, \ldots, x_{ip}, y_i))$ with $i$ indexing the cases and suppose that the set of values of the first independent variable, $\{x_{i1}\}$, has a unique maximum $x^*$ separated from the second-highest value by a positive amount $\epsilon$. Apply a non-linear transformation of the first variable that sends all values less than $x^* - \epsilon/2$ to the range $[0,1]$ and sends $x^*$ itself to some large value $M \gg 1$. For any such $M$ this can be done by a suitable (scaled) Box-Cox transformation $x \to a((x-x_0)^\lambda - 1)/(\lambda-1))$, for instance, so we're not talking about anything strange or "pathological." Then, as $M$ grows arbitrarily large, $R^2$ approaches $1$ as closely as you please, regardless of how bad the fit is, because the variance of the residuals will be bounded while the variance of the first independent variable is asymptotically proportional to $M^2$.
You should instead be using goodness of fit tests (among other techniques) to select an appropriate model in your exploration: you ought to be concerned about the linearity of the fit and of the homoscedasticity of the residuals. And don't take any p-values from the resulting regression on trust: they will end up being almost meaningless after you have gone through this exercise, because their interpretation assumes the choice of expressing the independent variables did not depend on the values of the dependent variable at all, which is very much not the case here.
|
What is the relationship between R-squared and p-value in a regression?
|
The answer is no, there is no such regular relationship between $R^2$ and the overall regression p-value, because $R^2$ depends as much on the variance of the independent variables as it does on the v
|
What is the relationship between R-squared and p-value in a regression?
The answer is no, there is no such regular relationship between $R^2$ and the overall regression p-value, because $R^2$ depends as much on the variance of the independent variables as it does on the variance of the residuals (to which it is inversely proportional), and you are free to change the variance of the independent variables by arbitrary amounts.
As an example, consider any set of multivariate data $((x_{i1}, x_{i2}, \ldots, x_{ip}, y_i))$ with $i$ indexing the cases and suppose that the set of values of the first independent variable, $\{x_{i1}\}$, has a unique maximum $x^*$ separated from the second-highest value by a positive amount $\epsilon$. Apply a non-linear transformation of the first variable that sends all values less than $x^* - \epsilon/2$ to the range $[0,1]$ and sends $x^*$ itself to some large value $M \gg 1$. For any such $M$ this can be done by a suitable (scaled) Box-Cox transformation $x \to a((x-x_0)^\lambda - 1)/(\lambda-1))$, for instance, so we're not talking about anything strange or "pathological." Then, as $M$ grows arbitrarily large, $R^2$ approaches $1$ as closely as you please, regardless of how bad the fit is, because the variance of the residuals will be bounded while the variance of the first independent variable is asymptotically proportional to $M^2$.
You should instead be using goodness of fit tests (among other techniques) to select an appropriate model in your exploration: you ought to be concerned about the linearity of the fit and of the homoscedasticity of the residuals. And don't take any p-values from the resulting regression on trust: they will end up being almost meaningless after you have gone through this exercise, because their interpretation assumes the choice of expressing the independent variables did not depend on the values of the dependent variable at all, which is very much not the case here.
|
What is the relationship between R-squared and p-value in a regression?
The answer is no, there is no such regular relationship between $R^2$ and the overall regression p-value, because $R^2$ depends as much on the variance of the independent variables as it does on the v
|
13,233
|
What is the relationship between R-squared and p-value in a regression?
|
This answer doesn't directly deal with the central question; it's nothing more than some additional information that's too long for a comment.
I point this out because econometricstatsquestion will no doubt encounter this information, or something like it at some point (stating that $F$ and $R^2$ are related) and wonder if the information given in other answers here is wrong - it's not wrong - but I think it pays to be clear about what's going on.
There is a relationship under a particular set of circumstances; if you hold the number of observations and the number of predictors fixed for a given model, $F$ is in fact monotonic in $R^2$, since
$$
F = \frac{R^2/(k-1)}{(1-R^2)/(N-k)}
$$
(If you divide numerator and denominator by $R^2$, and pull the constants in $k$ out, you can see that $1/F \propto 1/R^2 - 1$ if you hold $N$ and $k$ constant.)
Since for fixed d.f. $F$ and the p-value are monotonically related, $R^2$ and the $p$-value are also monotonically related.
But change almost anything about the model, and that relationship doesn't hold across the changed circumstances.
For example, adding a point makes $(N-k)/(k-1)$ larger and removing one makes it smaller but doing either can increase or decrease $R^2$, so it looks like $F$ and $R^2$ don't necessarily move together if you add or delete data. Adding a variable decreases $(N-k)/(k-1)$ but increases $R^2$ (and vice-versa), so again, $R^2$ is not necessarily related to $F$ when you do that.
Clearly, once you compare $R^2$ and $p$-values across models with different characteristics, this relationship doesn't necessarily hold, as whuber proved in the case of nonlinear transformations.
|
What is the relationship between R-squared and p-value in a regression?
|
This answer doesn't directly deal with the central question; it's nothing more than some additional information that's too long for a comment.
I point this out because econometricstatsquestion will no
|
What is the relationship between R-squared and p-value in a regression?
This answer doesn't directly deal with the central question; it's nothing more than some additional information that's too long for a comment.
I point this out because econometricstatsquestion will no doubt encounter this information, or something like it at some point (stating that $F$ and $R^2$ are related) and wonder if the information given in other answers here is wrong - it's not wrong - but I think it pays to be clear about what's going on.
There is a relationship under a particular set of circumstances; if you hold the number of observations and the number of predictors fixed for a given model, $F$ is in fact monotonic in $R^2$, since
$$
F = \frac{R^2/(k-1)}{(1-R^2)/(N-k)}
$$
(If you divide numerator and denominator by $R^2$, and pull the constants in $k$ out, you can see that $1/F \propto 1/R^2 - 1$ if you hold $N$ and $k$ constant.)
Since for fixed d.f. $F$ and the p-value are monotonically related, $R^2$ and the $p$-value are also monotonically related.
But change almost anything about the model, and that relationship doesn't hold across the changed circumstances.
For example, adding a point makes $(N-k)/(k-1)$ larger and removing one makes it smaller but doing either can increase or decrease $R^2$, so it looks like $F$ and $R^2$ don't necessarily move together if you add or delete data. Adding a variable decreases $(N-k)/(k-1)$ but increases $R^2$ (and vice-versa), so again, $R^2$ is not necessarily related to $F$ when you do that.
Clearly, once you compare $R^2$ and $p$-values across models with different characteristics, this relationship doesn't necessarily hold, as whuber proved in the case of nonlinear transformations.
|
What is the relationship between R-squared and p-value in a regression?
This answer doesn't directly deal with the central question; it's nothing more than some additional information that's too long for a comment.
I point this out because econometricstatsquestion will no
|
13,234
|
What is the relationship between R-squared and p-value in a regression?
|
"for OLS regression, does a higher R-squared also imply a higher
P-value? Specifically for a single explanatory variable (Y = a + bX + e) "
Specifically for a single explanatory variable, given the sample size, the answer is yes. As Glen_b has explained, there is a direct relationship between $R^2$ and the test statistic (be it a $F$ or $t$). For instance, as explained in this other question (High $R^2$ squared and high $p$-value for simple linear regression) for the simple linear regression with one covariate (and a constant), the relationship between $t$ and $R^2$ is:
$|t| = \sqrt{\frac{R^2}{(1- R^2)}(n -2)}$
So in this case, once you fix $n$, the higher the $R^2$ the higher the $t$ statistic and the lower the p-value.
"but would also be interested to know for n multiple explanatory
variables (Y = a + b1X + ... bnX + e)."
The answer is the same, but instead of looking at one variable only, we now look at all variables together -- hence the $F$ statistic, as Glen_b has shown. And here you have to fix both $n$ and the number of parameters. Or, to put it better, fix the degrees of freedom.
Context - I'm performing OLS regression on a range of variables and am
trying to develop the best explanatory functional form (...)
Ok, so this is actually a different problem. If you are looking at the best explanatory functional form, you should also take a look at cross-validation techniques. Even if $R^2$ is the quantity of interest for your problem (it usually isn't), finding the best fit in-sample can be very misleading -- you usually want your findings to generalize out of sample, and proper cross-validation can help you not overfit your data too much.
And here I'm guessing that you want "predictive" power (since you say you want to find "the best explanatory functional form"). If you want to do causal inference, for instance, then the $R^2$ or other predictive performance metrics are of little help without more structural/substantive knowledge of the problem.
|
What is the relationship between R-squared and p-value in a regression?
|
"for OLS regression, does a higher R-squared also imply a higher
P-value? Specifically for a single explanatory variable (Y = a + bX + e) "
Specifically for a single explanatory variable, given the
|
What is the relationship between R-squared and p-value in a regression?
"for OLS regression, does a higher R-squared also imply a higher
P-value? Specifically for a single explanatory variable (Y = a + bX + e) "
Specifically for a single explanatory variable, given the sample size, the answer is yes. As Glen_b has explained, there is a direct relationship between $R^2$ and the test statistic (be it a $F$ or $t$). For instance, as explained in this other question (High $R^2$ squared and high $p$-value for simple linear regression) for the simple linear regression with one covariate (and a constant), the relationship between $t$ and $R^2$ is:
$|t| = \sqrt{\frac{R^2}{(1- R^2)}(n -2)}$
So in this case, once you fix $n$, the higher the $R^2$ the higher the $t$ statistic and the lower the p-value.
"but would also be interested to know for n multiple explanatory
variables (Y = a + b1X + ... bnX + e)."
The answer is the same, but instead of looking at one variable only, we now look at all variables together -- hence the $F$ statistic, as Glen_b has shown. And here you have to fix both $n$ and the number of parameters. Or, to put it better, fix the degrees of freedom.
Context - I'm performing OLS regression on a range of variables and am
trying to develop the best explanatory functional form (...)
Ok, so this is actually a different problem. If you are looking at the best explanatory functional form, you should also take a look at cross-validation techniques. Even if $R^2$ is the quantity of interest for your problem (it usually isn't), finding the best fit in-sample can be very misleading -- you usually want your findings to generalize out of sample, and proper cross-validation can help you not overfit your data too much.
And here I'm guessing that you want "predictive" power (since you say you want to find "the best explanatory functional form"). If you want to do causal inference, for instance, then the $R^2$ or other predictive performance metrics are of little help without more structural/substantive knowledge of the problem.
|
What is the relationship between R-squared and p-value in a regression?
"for OLS regression, does a higher R-squared also imply a higher
P-value? Specifically for a single explanatory variable (Y = a + bX + e) "
Specifically for a single explanatory variable, given the
|
13,235
|
How to model bounded target variable?
|
You don't necessarily have to do anything. It's possible the predictor will work fine. Even if the predictor extrapolates to values outside the range, possibly clamping the predictions to the range (that is, use $\max(0, \min(70, \hat{y}))$ instead of $\hat{y}$) will do well. Cross-validate the model to see whether this works.
However, the restricted range raises the possibility of a nonlinear relationship between the dependent variable ($y$) and the independent variables ($x_i$). Some additional indicators of this include:
Greater variation in residual values when $\hat{y}$ is in the middle of its range, compared to variation in residuals at either end of the range.
Theoretical reasons for specific non-linear relationships.
Evidence of model mis-specification (obtained in the usual ways).
Significance of quadratic or high-order terms in the $x_i$.
Consider a nonlinear re-expression of $y$ in case any of these conditions hold.
There are many ways to re-express $y$ to create more linear relationships with the $x_i$. For instance, any increasing function $f$ defined on the interval $[0,70]$ can be "folded" to create a symmetric increasing function via $y \to f(y) - f(70-y)$. If $f$ becomes arbitrarily large and negative as its argument approaches $0$, the folded version of $f$ will map $[0,70]$ into all the real numbers. Examples of such functions include the logarithm and any negative power. Using the logarithm is equivalent to the "logit link" recommended by @user603. Another way is to let $G$ be the inverse CDF of any probability distribution and define $f(y) = G(y/70)$. Using a Normal distribution gives the "probit" transformation.
One way to exploit families of transformations is to experiment: try a likely transformation, perform a quick regression of the transformed $y$ against the $x_i$, and test the residuals: they should appear to be independent of the predicted values of $y$ (homoscedastic and uncorrelated). These are signs of a linear relationship with the independent variables. It helps, too, if the residuals of the back-transformed predicted values tend to be small. This indicates the transformation has improved the fit. To resist the effects of outliers, use robust regression methods such as iteratively reweighted least squares.
|
How to model bounded target variable?
|
You don't necessarily have to do anything. It's possible the predictor will work fine. Even if the predictor extrapolates to values outside the range, possibly clamping the predictions to the range
|
How to model bounded target variable?
You don't necessarily have to do anything. It's possible the predictor will work fine. Even if the predictor extrapolates to values outside the range, possibly clamping the predictions to the range (that is, use $\max(0, \min(70, \hat{y}))$ instead of $\hat{y}$) will do well. Cross-validate the model to see whether this works.
However, the restricted range raises the possibility of a nonlinear relationship between the dependent variable ($y$) and the independent variables ($x_i$). Some additional indicators of this include:
Greater variation in residual values when $\hat{y}$ is in the middle of its range, compared to variation in residuals at either end of the range.
Theoretical reasons for specific non-linear relationships.
Evidence of model mis-specification (obtained in the usual ways).
Significance of quadratic or high-order terms in the $x_i$.
Consider a nonlinear re-expression of $y$ in case any of these conditions hold.
There are many ways to re-express $y$ to create more linear relationships with the $x_i$. For instance, any increasing function $f$ defined on the interval $[0,70]$ can be "folded" to create a symmetric increasing function via $y \to f(y) - f(70-y)$. If $f$ becomes arbitrarily large and negative as its argument approaches $0$, the folded version of $f$ will map $[0,70]$ into all the real numbers. Examples of such functions include the logarithm and any negative power. Using the logarithm is equivalent to the "logit link" recommended by @user603. Another way is to let $G$ be the inverse CDF of any probability distribution and define $f(y) = G(y/70)$. Using a Normal distribution gives the "probit" transformation.
One way to exploit families of transformations is to experiment: try a likely transformation, perform a quick regression of the transformed $y$ against the $x_i$, and test the residuals: they should appear to be independent of the predicted values of $y$ (homoscedastic and uncorrelated). These are signs of a linear relationship with the independent variables. It helps, too, if the residuals of the back-transformed predicted values tend to be small. This indicates the transformation has improved the fit. To resist the effects of outliers, use robust regression methods such as iteratively reweighted least squares.
|
How to model bounded target variable?
You don't necessarily have to do anything. It's possible the predictor will work fine. Even if the predictor extrapolates to values outside the range, possibly clamping the predictions to the range
|
13,236
|
How to model bounded target variable?
|
It is important to consider why are your values bounded in the 0-70 range. For example, if they are the number of correct answers on a 70-question test, then you should consider models for "number of successes" variables, such as overdispersed binomial regression. Other reasons might lead you to other solutions.
|
How to model bounded target variable?
|
It is important to consider why are your values bounded in the 0-70 range. For example, if they are the number of correct answers on a 70-question test, then you should consider models for "number of
|
How to model bounded target variable?
It is important to consider why are your values bounded in the 0-70 range. For example, if they are the number of correct answers on a 70-question test, then you should consider models for "number of successes" variables, such as overdispersed binomial regression. Other reasons might lead you to other solutions.
|
How to model bounded target variable?
It is important to consider why are your values bounded in the 0-70 range. For example, if they are the number of correct answers on a 70-question test, then you should consider models for "number of
|
13,237
|
How to model bounded target variable?
|
Data transformation: rescale your data to lie in $[0,1]$ and model it using a glm model with a logit link.
Edit: When you re-scale a vector (ie divide all the elements by the largest entry), as a rule, before you do that, screen (eyeballs) for outliers.
UPDATE
Assuming you have access to R, i would carry the modeling part with a robust glm routine, see $\verb+glmrob()+$ in package $\verb+robustbase+$.
|
How to model bounded target variable?
|
Data transformation: rescale your data to lie in $[0,1]$ and model it using a glm model with a logit link.
Edit: When you re-scale a vector (ie divide all the elements by the largest entry), as a rul
|
How to model bounded target variable?
Data transformation: rescale your data to lie in $[0,1]$ and model it using a glm model with a logit link.
Edit: When you re-scale a vector (ie divide all the elements by the largest entry), as a rule, before you do that, screen (eyeballs) for outliers.
UPDATE
Assuming you have access to R, i would carry the modeling part with a robust glm routine, see $\verb+glmrob()+$ in package $\verb+robustbase+$.
|
How to model bounded target variable?
Data transformation: rescale your data to lie in $[0,1]$ and model it using a glm model with a logit link.
Edit: When you re-scale a vector (ie divide all the elements by the largest entry), as a rul
|
13,238
|
ARIMA vs Kalman filter - how are they related
|
ARIMA is a class of models. These are stochastic processes that you can use to model some time series data.
There is another class of models called linear Gaussian state space models, sometimes just state space models. This is a strictly larger class (every ARIMA model is a state space model). A state space model involves dynamics for an unobserved stochastic process called the state, and a distribution for your actual observations, as a function of the state.
The Kalman filter is an algorithm (NOT a model), that is used to do two things in the context of state space models:
Compute the sequence of filtering distributions. This is the distribution of the current state, given all observations until now, for each time period. This gives us an estimate of the unobservable state in a way that doesn't depend on future data.
Compute the likelihood of the data. This allows us to perform maximum likelihood estimation and fit the model.
So, "ARIMA" and "Kalman filter" are not comparable because they are not the same kind of object at all (model vs algorithm). However, because the Kalman filter can be applied to any state space model, including ARIMA, it is typical in software to use the Kalman filter to fit an ARIMA model.
|
ARIMA vs Kalman filter - how are they related
|
ARIMA is a class of models. These are stochastic processes that you can use to model some time series data.
There is another class of models called linear Gaussian state space models, sometimes just s
|
ARIMA vs Kalman filter - how are they related
ARIMA is a class of models. These are stochastic processes that you can use to model some time series data.
There is another class of models called linear Gaussian state space models, sometimes just state space models. This is a strictly larger class (every ARIMA model is a state space model). A state space model involves dynamics for an unobserved stochastic process called the state, and a distribution for your actual observations, as a function of the state.
The Kalman filter is an algorithm (NOT a model), that is used to do two things in the context of state space models:
Compute the sequence of filtering distributions. This is the distribution of the current state, given all observations until now, for each time period. This gives us an estimate of the unobservable state in a way that doesn't depend on future data.
Compute the likelihood of the data. This allows us to perform maximum likelihood estimation and fit the model.
So, "ARIMA" and "Kalman filter" are not comparable because they are not the same kind of object at all (model vs algorithm). However, because the Kalman filter can be applied to any state space model, including ARIMA, it is typical in software to use the Kalman filter to fit an ARIMA model.
|
ARIMA vs Kalman filter - how are they related
ARIMA is a class of models. These are stochastic processes that you can use to model some time series data.
There is another class of models called linear Gaussian state space models, sometimes just s
|
13,239
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the explicit functional form of the regression equation?
|
First I show how you can specify a formula using aggregated data with proportions and weights. Then I show how you could specify a formula after dis-aggregating your data to individual observations.
Documentation inglm indicates that:
"For a binomial GLM prior weights are used to give the number of
trials when the response is the proportion of successes"
I create new columns total and proportion_disease in df for the 'number of trials' and 'proportion of successes' respectively.
library(dplyr)
df <- tibble(treatment_status = c("treatment", "no_treatment"),
disease = c(55, 42),
no_disease = c(67,34)) %>%
mutate(total = no_disease + disease,
proportion_disease = disease / total)
model_weighted <- glm(proportion_disease ~ treatment_status, data = df, family = binomial("logit"), weights = total)
The above weighted approach takes in aggregated data and will give the same solution as the cbind method but allows you to specify a formula. (Below is equivalent to Original Poster's method but cbind(c(55,42), c(67,34)) rather than cbind(c(55,67),c(42,34)) so that 'Disease' rather than 'Treatment' is the response variable.)
model_cbinded <- glm(cbind(disease, no_disease) ~ treatment_status, data = df, family = binomial("logit"))
You could also just dis-aggregate your data into individual observations and pass these into glm (allowing you to specify a formula as well).
df_expanded <- tibble(disease_status = c(1, 1, 0, 0),
treatment_status = rep(c("treatment", "control"), 2)) %>%
.[c(rep(1, 55), rep(2, 42), rep(3, 67), rep(4, 34)), ]
model_expanded <- glm(disease_status ~ treatment_status, data = df_expanded, family = binomial("logit"))
Let's compare these now by passing each model into summary. model_weighted and model_cbinded both produce the exact same results. model_expanded produces the same coefficients and standard errors, though outputs different degrees of freedom, deviance, AIC, etc. (corresponding with the number of rows/observations).
> lapply(list(model_weighted, model_cbinded, model_expanded), summary)
[[1]]
Call:
glm(formula = proportion_disease ~ treatment_status, family = binomial("logit"),
data = df, weights = total)
Deviance Residuals:
[1] 0 0
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment_statustreatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 1.9451e+00 on 1 degrees of freedom
Residual deviance: 1.0658e-14 on 0 degrees of freedom
AIC: 14.028
Number of Fisher Scoring iterations: 2
[[2]]
Call:
glm(formula = cbind(disease, no_disease) ~ treatment_status,
family = binomial("logit"), data = df)
Deviance Residuals:
[1] 0 0
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment_statustreatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 1.9451e+00 on 1 degrees of freedom
Residual deviance: 1.0658e-14 on 0 degrees of freedom
AIC: 14.028
Number of Fisher Scoring iterations: 2
[[3]]
Call:
glm(formula = disease_status ~ treatment_status, family = binomial("logit"),
data = df_expanded)
Deviance Residuals:
Min 1Q Median 3Q Max
-1.268 -1.095 -1.095 1.262 1.262
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment_statustreatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 274.41 on 197 degrees of freedom
Residual deviance: 272.46 on 196 degrees of freedom
AIC: 276.46
Number of Fisher Scoring iterations: 3
(See R bloggers for conversation on weights parameter in glm in the regression context.)
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the ex
|
First I show how you can specify a formula using aggregated data with proportions and weights. Then I show how you could specify a formula after dis-aggregating your data to individual observations.
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the explicit functional form of the regression equation?
First I show how you can specify a formula using aggregated data with proportions and weights. Then I show how you could specify a formula after dis-aggregating your data to individual observations.
Documentation inglm indicates that:
"For a binomial GLM prior weights are used to give the number of
trials when the response is the proportion of successes"
I create new columns total and proportion_disease in df for the 'number of trials' and 'proportion of successes' respectively.
library(dplyr)
df <- tibble(treatment_status = c("treatment", "no_treatment"),
disease = c(55, 42),
no_disease = c(67,34)) %>%
mutate(total = no_disease + disease,
proportion_disease = disease / total)
model_weighted <- glm(proportion_disease ~ treatment_status, data = df, family = binomial("logit"), weights = total)
The above weighted approach takes in aggregated data and will give the same solution as the cbind method but allows you to specify a formula. (Below is equivalent to Original Poster's method but cbind(c(55,42), c(67,34)) rather than cbind(c(55,67),c(42,34)) so that 'Disease' rather than 'Treatment' is the response variable.)
model_cbinded <- glm(cbind(disease, no_disease) ~ treatment_status, data = df, family = binomial("logit"))
You could also just dis-aggregate your data into individual observations and pass these into glm (allowing you to specify a formula as well).
df_expanded <- tibble(disease_status = c(1, 1, 0, 0),
treatment_status = rep(c("treatment", "control"), 2)) %>%
.[c(rep(1, 55), rep(2, 42), rep(3, 67), rep(4, 34)), ]
model_expanded <- glm(disease_status ~ treatment_status, data = df_expanded, family = binomial("logit"))
Let's compare these now by passing each model into summary. model_weighted and model_cbinded both produce the exact same results. model_expanded produces the same coefficients and standard errors, though outputs different degrees of freedom, deviance, AIC, etc. (corresponding with the number of rows/observations).
> lapply(list(model_weighted, model_cbinded, model_expanded), summary)
[[1]]
Call:
glm(formula = proportion_disease ~ treatment_status, family = binomial("logit"),
data = df, weights = total)
Deviance Residuals:
[1] 0 0
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment_statustreatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 1.9451e+00 on 1 degrees of freedom
Residual deviance: 1.0658e-14 on 0 degrees of freedom
AIC: 14.028
Number of Fisher Scoring iterations: 2
[[2]]
Call:
glm(formula = cbind(disease, no_disease) ~ treatment_status,
family = binomial("logit"), data = df)
Deviance Residuals:
[1] 0 0
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment_statustreatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 1.9451e+00 on 1 degrees of freedom
Residual deviance: 1.0658e-14 on 0 degrees of freedom
AIC: 14.028
Number of Fisher Scoring iterations: 2
[[3]]
Call:
glm(formula = disease_status ~ treatment_status, family = binomial("logit"),
data = df_expanded)
Deviance Residuals:
Min 1Q Median 3Q Max
-1.268 -1.095 -1.095 1.262 1.262
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment_statustreatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 274.41 on 197 degrees of freedom
Residual deviance: 272.46 on 196 degrees of freedom
AIC: 276.46
Number of Fisher Scoring iterations: 3
(See R bloggers for conversation on weights parameter in glm in the regression context.)
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the ex
First I show how you can specify a formula using aggregated data with proportions and weights. Then I show how you could specify a formula after dis-aggregating your data to individual observations.
|
13,240
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the explicit functional form of the regression equation?
|
Binomial distribution versus Bernoulli distribution
The binomial distribution can be viewed as multiple Bernoulli distributions with the same probability parameter $p$. Their probability distributions differ up to a constant.
For observations $x_i \in \lbrace 0,1 \rbrace$, where $k$ is the number of observations that are equal to $1$
$1$ Bernoulli experiment PMF $$f(x_1) = p^{x_1} (1-p)^{1-x_1}$$
$n$ Bernoulli experiments PMF $$f(x_1,x_2,\dots,x_n) = \prod p^{x_i} (1-p)^{1-x_i} = p^{k} (1-p)^{n-k}$$
Binomial distribution PMF $$f(x_1,x_2,\dots,x_n) = f(k,n) = {n \choose k} p^{k} (1-p)^{n-k}$$
The difference is that the Binomial distribution sort of 'ignores' the order of the observations $x_i$ and only looks at the total number of $x_i=1$ and $x_i=0$.
Influence of sample size on likelihood distribution and error
why simply using proportions is not sufficient
The maximum likelihood estimate is maximizing $p^k(1-p)^{n-k}$ and this happens at $p_{max} = k/n$ the proportion of observations with $x_i=1$. So indeed for finding the maximum likelihood the proportion is sufficient.
However, when we wish to estimate some expression for the error of the estimate (for instance standard error or confidence intervals) then the number of observations becomes important.
An intuitive view to see how the sample size matters might be the following: Let's look at the sample distribution of the outcome of the experiment as a function of the sample size. In the image below we plot the binomial distribution for $p=0.8$ with different size parameters $n$. On the left you see that the curves shift to the right for larger $n$, which is obvious as you would expect more counts when the sample size $n$ is increased. But the distance from the expected rate $p$ times $n$ is becoming relatively shorter. You see this on the right where we divide the outcome (the counts) by the total sample size $n$, which gives a relative rate. You see that the observed relative rate is more likely to be close to the true rate (0.8 in this graph) when the size $n$ is larger. (A related question is: How to estimate a probability of an event to occur based on its count?).
Input for the GLM function
I am wondering why R requires us to use the cbind function
You are not required to use the cbind function. There are 2/3 methods (two or three depending on how you look at it: two ways to present the data and the last one splits up in two ways to feed it to the glm function).
We can also use GLM as if it was doing a Bernoulli variable. In that case the data would consist of $55+67+42+34 = 198$ rows. One row for each single count (each count can be considered a Bernoulli distributed variable)
So the data would look like a long table
$$\begin{array}{rrr}
\text{ID} & \text{Observation of disease} & \text{Treatment}\\
1 & 1 & 1\\
2 & 1 & 1\\
3 & 1 & 1\\
\vdots & \vdots & \vdots \\
53 & 1 & 1\\
54 & 1 & 1\\
55 & 1 & 1\\
56 & 0 & 1\\
57 & 0 & 1\\
58 & 0 & 1\\
\vdots & \vdots & \vdots \\
120 & 0 & 1\\
121 & 0 & 1\\
122 & 0 & 1\\
123 & 1 & 0\\
124 & 1 & 0\\
125 & 1 & 0\\
\vdots & \vdots & \vdots \\
162 & 1 & 0\\
163 & 1 & 0\\
164 & 1 & 0\\
165 & 0 & 0\\
166 & 0 & 0\\
167 & 0 & 0\\
\vdots & \vdots & \vdots \\
196 & 0 & 0\\
197 & 0 & 0\\
198 & 0 & 0\\
\end{array}$$
data <- data.frame(ID = 1:198,
observation = c(rep(1,55),rep(0,67),rep(1,42),rep(0,34)),
treatment = c(rep(1,55+67), rep(0,42+34)))
glm1 <- glm(observation ~ treatment, family = binomial, data = data)
The previous method is often used when the independent variable is continuous. In the case of a categorical variable, we can group all the 1s and 0s for a category. In this case, the data is not 0s and 1s but the counts of 0s and 1s.
data <- data.frame(disease = c(55,42),
healthy = c(67,34),
treatment = c(1,0))
### the 'cbind method' gives glm the numbers in each categories
glm2 <- glm(cbind(disease,healthy) ~ treatment, family = binomial, data = data)
### this method gives glm the fraction and uses 'weight' to describe the number of data
glm3 <- glm(disease/(disease+healthy) ~ treatment, family = binomial, data = data, weight = disease+healthy)
The summaries of the above three different calls to glm give the same results. There is a difference in statistics like deviance and AIC, that is because the likelihood function is different by a factor $n \choose k$ but that is not important because the relevant measures in comparing models are the ratios of likelihood.
> summary(glm1)
Call:
glm(formula = observation ~ treatment, family = binomial, data = data)
Deviance Residuals:
Min 1Q Median 3Q Max
-1.268 -1.095 -1.095 1.262 1.262
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 274.41 on 197 degrees of freedom
Residual deviance: 272.46 on 196 degrees of freedom
AIC: 276.46
Number of Fisher Scoring iterations: 3
> summary(glm2)
Call:
glm(formula = cbind(disease, healthy) ~ treatment, family = binomial,
data = data)
Deviance Residuals:
[1] 0 0
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 1.9451e+00 on 1 degrees of freedom
Residual deviance: 1.0658e-14 on 0 degrees of freedom
AIC: 14.028
Number of Fisher Scoring iterations: 2
> summary(glm3)
Call:
glm(formula = disease/(disease + healthy) ~ treatment, family = binomial,
data = data, weights = disease + healthy)
Deviance Residuals:
[1] 0 0
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 1.9451e+00 on 1 degrees of freedom
Residual deviance: 1.0658e-14 on 0 degrees of freedom
AIC: 14.028
Number of Fisher Scoring iterations: 2
>
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the ex
|
Binomial distribution versus Bernoulli distribution
The binomial distribution can be viewed as multiple Bernoulli distributions with the same probability parameter $p$. Their probability distributions
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the explicit functional form of the regression equation?
Binomial distribution versus Bernoulli distribution
The binomial distribution can be viewed as multiple Bernoulli distributions with the same probability parameter $p$. Their probability distributions differ up to a constant.
For observations $x_i \in \lbrace 0,1 \rbrace$, where $k$ is the number of observations that are equal to $1$
$1$ Bernoulli experiment PMF $$f(x_1) = p^{x_1} (1-p)^{1-x_1}$$
$n$ Bernoulli experiments PMF $$f(x_1,x_2,\dots,x_n) = \prod p^{x_i} (1-p)^{1-x_i} = p^{k} (1-p)^{n-k}$$
Binomial distribution PMF $$f(x_1,x_2,\dots,x_n) = f(k,n) = {n \choose k} p^{k} (1-p)^{n-k}$$
The difference is that the Binomial distribution sort of 'ignores' the order of the observations $x_i$ and only looks at the total number of $x_i=1$ and $x_i=0$.
Influence of sample size on likelihood distribution and error
why simply using proportions is not sufficient
The maximum likelihood estimate is maximizing $p^k(1-p)^{n-k}$ and this happens at $p_{max} = k/n$ the proportion of observations with $x_i=1$. So indeed for finding the maximum likelihood the proportion is sufficient.
However, when we wish to estimate some expression for the error of the estimate (for instance standard error or confidence intervals) then the number of observations becomes important.
An intuitive view to see how the sample size matters might be the following: Let's look at the sample distribution of the outcome of the experiment as a function of the sample size. In the image below we plot the binomial distribution for $p=0.8$ with different size parameters $n$. On the left you see that the curves shift to the right for larger $n$, which is obvious as you would expect more counts when the sample size $n$ is increased. But the distance from the expected rate $p$ times $n$ is becoming relatively shorter. You see this on the right where we divide the outcome (the counts) by the total sample size $n$, which gives a relative rate. You see that the observed relative rate is more likely to be close to the true rate (0.8 in this graph) when the size $n$ is larger. (A related question is: How to estimate a probability of an event to occur based on its count?).
Input for the GLM function
I am wondering why R requires us to use the cbind function
You are not required to use the cbind function. There are 2/3 methods (two or three depending on how you look at it: two ways to present the data and the last one splits up in two ways to feed it to the glm function).
We can also use GLM as if it was doing a Bernoulli variable. In that case the data would consist of $55+67+42+34 = 198$ rows. One row for each single count (each count can be considered a Bernoulli distributed variable)
So the data would look like a long table
$$\begin{array}{rrr}
\text{ID} & \text{Observation of disease} & \text{Treatment}\\
1 & 1 & 1\\
2 & 1 & 1\\
3 & 1 & 1\\
\vdots & \vdots & \vdots \\
53 & 1 & 1\\
54 & 1 & 1\\
55 & 1 & 1\\
56 & 0 & 1\\
57 & 0 & 1\\
58 & 0 & 1\\
\vdots & \vdots & \vdots \\
120 & 0 & 1\\
121 & 0 & 1\\
122 & 0 & 1\\
123 & 1 & 0\\
124 & 1 & 0\\
125 & 1 & 0\\
\vdots & \vdots & \vdots \\
162 & 1 & 0\\
163 & 1 & 0\\
164 & 1 & 0\\
165 & 0 & 0\\
166 & 0 & 0\\
167 & 0 & 0\\
\vdots & \vdots & \vdots \\
196 & 0 & 0\\
197 & 0 & 0\\
198 & 0 & 0\\
\end{array}$$
data <- data.frame(ID = 1:198,
observation = c(rep(1,55),rep(0,67),rep(1,42),rep(0,34)),
treatment = c(rep(1,55+67), rep(0,42+34)))
glm1 <- glm(observation ~ treatment, family = binomial, data = data)
The previous method is often used when the independent variable is continuous. In the case of a categorical variable, we can group all the 1s and 0s for a category. In this case, the data is not 0s and 1s but the counts of 0s and 1s.
data <- data.frame(disease = c(55,42),
healthy = c(67,34),
treatment = c(1,0))
### the 'cbind method' gives glm the numbers in each categories
glm2 <- glm(cbind(disease,healthy) ~ treatment, family = binomial, data = data)
### this method gives glm the fraction and uses 'weight' to describe the number of data
glm3 <- glm(disease/(disease+healthy) ~ treatment, family = binomial, data = data, weight = disease+healthy)
The summaries of the above three different calls to glm give the same results. There is a difference in statistics like deviance and AIC, that is because the likelihood function is different by a factor $n \choose k$ but that is not important because the relevant measures in comparing models are the ratios of likelihood.
> summary(glm1)
Call:
glm(formula = observation ~ treatment, family = binomial, data = data)
Deviance Residuals:
Min 1Q Median 3Q Max
-1.268 -1.095 -1.095 1.262 1.262
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 274.41 on 197 degrees of freedom
Residual deviance: 272.46 on 196 degrees of freedom
AIC: 276.46
Number of Fisher Scoring iterations: 3
> summary(glm2)
Call:
glm(formula = cbind(disease, healthy) ~ treatment, family = binomial,
data = data)
Deviance Residuals:
[1] 0 0
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 1.9451e+00 on 1 degrees of freedom
Residual deviance: 1.0658e-14 on 0 degrees of freedom
AIC: 14.028
Number of Fisher Scoring iterations: 2
> summary(glm3)
Call:
glm(formula = disease/(disease + healthy) ~ treatment, family = binomial,
data = data, weights = disease + healthy)
Deviance Residuals:
[1] 0 0
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.2113 0.2307 0.916 0.360
treatment -0.4087 0.2938 -1.391 0.164
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 1.9451e+00 on 1 degrees of freedom
Residual deviance: 1.0658e-14 on 0 degrees of freedom
AIC: 14.028
Number of Fisher Scoring iterations: 2
>
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the ex
Binomial distribution versus Bernoulli distribution
The binomial distribution can be viewed as multiple Bernoulli distributions with the same probability parameter $p$. Their probability distributions
|
13,241
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the explicit functional form of the regression equation?
|
I found this discussion very helpful for the analysis I need to conduct for my thesis. I am not sure if I understand it right, that the multiple trials you are talking about are with the same sample?
In my case I have a control and a treatment group, and each respondent goes through 4 questions where he/she has to choose between train and plane. I now want to analyse the difference between control and treatment group over all four choices combined. So I think I could use the approach with a weighted model and the dependent variable "proportion_train" (which represents how often the train was chosen out of the four choices).
I am not sure about the interpretation of the coefficients of this model then. I know these are most likely the log-odds-ratios (or equivalently differences in log-odds). But do these log-odds-ratios show the probability combined over all trials (which I want to find out), or the per-trial probability?
Now I read somewhere else that I need to account for the correlation within the individuals by including random intercepts for the individual IDs - as the four questions were answered by the same individuals (but different individuals in control and treatment group of course).
None of you here included such a random intercept for the individuals, so I am wondering if it's necessary or not?
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the ex
|
I found this discussion very helpful for the analysis I need to conduct for my thesis. I am not sure if I understand it right, that the multiple trials you are talking about are with the same sample?
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the explicit functional form of the regression equation?
I found this discussion very helpful for the analysis I need to conduct for my thesis. I am not sure if I understand it right, that the multiple trials you are talking about are with the same sample?
In my case I have a control and a treatment group, and each respondent goes through 4 questions where he/she has to choose between train and plane. I now want to analyse the difference between control and treatment group over all four choices combined. So I think I could use the approach with a weighted model and the dependent variable "proportion_train" (which represents how often the train was chosen out of the four choices).
I am not sure about the interpretation of the coefficients of this model then. I know these are most likely the log-odds-ratios (or equivalently differences in log-odds). But do these log-odds-ratios show the probability combined over all trials (which I want to find out), or the per-trial probability?
Now I read somewhere else that I need to account for the correlation within the individuals by including random intercepts for the individual IDs - as the four questions were answered by the same individuals (but different individuals in control and treatment group of course).
None of you here included such a random intercept for the individuals, so I am wondering if it's necessary or not?
|
In using the cbind() function in R for a logistic regression on a $2 \times 2$ table, what is the ex
I found this discussion very helpful for the analysis I need to conduct for my thesis. I am not sure if I understand it right, that the multiple trials you are talking about are with the same sample?
|
13,242
|
How are the Error Function and Standard Normal distribution function related?
|
Because this comes up often in some systems (for instance, Mathematica insists on expressing the Normal CDF in terms of $\text{Erf}$), it's good to have a thread like this that documents the relationship.
By definition, the Error Function is
$$\text{Erf}(x) = \frac{2}{\sqrt{\pi}}\int_0^x e^{-t^2} \mathrm{d}t.$$
Writing $t^2 = z^2/2$ implies $t = z / \sqrt{2}$ (because $t$ is not negative), whence $\mathrm{d}t = \mathrm{d}z/\sqrt{2}$. The endpoints $t=0$ and $t=x$ become $z=0$ and $z=x\sqrt{2}$. To convert the resulting integral into something that looks like a cumulative distribution function (CDF), it must be expressed in terms of integrals that have lower limits of $-\infty$, thus:
$$\text{Erf}(x) = \frac{2}{\sqrt{2\pi}}\int_0^{x\sqrt{2}} e^{-z^2/2}\mathrm{d}z = 2\left(\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{x\sqrt{2}}e^{-z^2/2}\mathrm{d}z - \frac{1}{\sqrt{2\pi}}\int_{-\infty}^0 e^{-z^2/2}\mathrm{d}z\right).$$
Those integrals on the right hand size are both values of the CDF of the standard Normal distribution,
$$\Phi(x) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^x e^{-z^2/2} \mathrm{d}z.$$
Specifically,
$$\text{Erf}(x) = 2(\Phi(x\sqrt{2}) - \Phi(0)) = 2\left(\Phi(x\sqrt{2}) - \frac{1}{2}\right) = 2\Phi(x\sqrt{2}) - 1.$$
This shows how to express the Error Function in terms of the Normal CDF. Algebraic manipulation of that easily gives the Normal CDF in terms of the Error Function:
$$\Phi(x) = \frac{1 + \text{Erf}(x/\sqrt{2})}{2}.$$
This relationship (for real numbers, anyway) is exhibited in plots of the two functions. The graphs are identical curves. The coordinates of the Error Function on the left are converted to the coordinates of $\Phi$ on the right by multiplying the $x$ coordinates by $\sqrt{2}$, adding $1$ to the $y$ coordinates, and then dividing the $y$ coordinates by $2$, reflecting the relationship
$$\Phi(x\sqrt{2}) = \frac{\text{Erf}(x) + 1}{2}$$
in which the notation explicitly shows these three operations of multiplication, addition, and division.
|
How are the Error Function and Standard Normal distribution function related?
|
Because this comes up often in some systems (for instance, Mathematica insists on expressing the Normal CDF in terms of $\text{Erf}$), it's good to have a thread like this that documents the relations
|
How are the Error Function and Standard Normal distribution function related?
Because this comes up often in some systems (for instance, Mathematica insists on expressing the Normal CDF in terms of $\text{Erf}$), it's good to have a thread like this that documents the relationship.
By definition, the Error Function is
$$\text{Erf}(x) = \frac{2}{\sqrt{\pi}}\int_0^x e^{-t^2} \mathrm{d}t.$$
Writing $t^2 = z^2/2$ implies $t = z / \sqrt{2}$ (because $t$ is not negative), whence $\mathrm{d}t = \mathrm{d}z/\sqrt{2}$. The endpoints $t=0$ and $t=x$ become $z=0$ and $z=x\sqrt{2}$. To convert the resulting integral into something that looks like a cumulative distribution function (CDF), it must be expressed in terms of integrals that have lower limits of $-\infty$, thus:
$$\text{Erf}(x) = \frac{2}{\sqrt{2\pi}}\int_0^{x\sqrt{2}} e^{-z^2/2}\mathrm{d}z = 2\left(\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{x\sqrt{2}}e^{-z^2/2}\mathrm{d}z - \frac{1}{\sqrt{2\pi}}\int_{-\infty}^0 e^{-z^2/2}\mathrm{d}z\right).$$
Those integrals on the right hand size are both values of the CDF of the standard Normal distribution,
$$\Phi(x) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^x e^{-z^2/2} \mathrm{d}z.$$
Specifically,
$$\text{Erf}(x) = 2(\Phi(x\sqrt{2}) - \Phi(0)) = 2\left(\Phi(x\sqrt{2}) - \frac{1}{2}\right) = 2\Phi(x\sqrt{2}) - 1.$$
This shows how to express the Error Function in terms of the Normal CDF. Algebraic manipulation of that easily gives the Normal CDF in terms of the Error Function:
$$\Phi(x) = \frac{1 + \text{Erf}(x/\sqrt{2})}{2}.$$
This relationship (for real numbers, anyway) is exhibited in plots of the two functions. The graphs are identical curves. The coordinates of the Error Function on the left are converted to the coordinates of $\Phi$ on the right by multiplying the $x$ coordinates by $\sqrt{2}$, adding $1$ to the $y$ coordinates, and then dividing the $y$ coordinates by $2$, reflecting the relationship
$$\Phi(x\sqrt{2}) = \frac{\text{Erf}(x) + 1}{2}$$
in which the notation explicitly shows these three operations of multiplication, addition, and division.
|
How are the Error Function and Standard Normal distribution function related?
Because this comes up often in some systems (for instance, Mathematica insists on expressing the Normal CDF in terms of $\text{Erf}$), it's good to have a thread like this that documents the relations
|
13,243
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
|
"What makes the estimator work when the actual error distribution does not match the assumed error distribution?"
In principle the QMPLE does not "work", in the sense of being a "good" estimator. The theory developed around the QMLE is useful because it has led to misspecification tests.
What the QMLE certainly does is to consistently estimate the parameter vector which minimizes the Kullback-Leiber Divergence between the true distribution and the one specified. This sounds good, but minimizing this distance does not mean that the minimized distance won't be enormous.
Still, we read that there are many situations that the QMLE is a consistent estimator for the true parameter vector. This has to be assessed case-by-case, but let me give one very general situation, which shows that there is nothing inherent in the QMLE that makes it consistent for the true vector...
... Rather it is the fact that it coincides with another estimator that is always consistent (maintaining the ergodic-stationary sample assumption) : the old-fashioned, Method of Moments estimator.
In other words, when in doubt about the distribution, a strategy to consider is "always specify a distribution for which the Maximum Likelihood estimator for the parameters of interest coincides with the Method of Moments estimator": in this way no matter how off the mark is your distributional assumption, the estimator will at least be consistent.
You can take this strategy to ridiculous extremes: assume that you have a very large i.i.d. sample from a random variable, where all values are positive. Go on and assume that the random variable is normally distributed and apply maximum likelihood for the mean and variance: your QMLE will be consistent for the true values.
Of course this begs the question, why pretending to apply MLE since what we are essentially doing is relying and hiding behind the strengths of Method of Moments (which also guarantees asymptotic normality)?
In other more refined cases, QMLE may be shown to be consistent for the parameters of interest if we can say that we have specified correctly the conditional mean function but not the distribution (this is for example the case for Pooled Poisson QMLE - see Wooldridge).
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
|
"What makes the estimator work when the actual error distribution does not match the assumed error distribution?"
In principle the QMPLE does not "work", in the sense of being a "good" estimator. The
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
"What makes the estimator work when the actual error distribution does not match the assumed error distribution?"
In principle the QMPLE does not "work", in the sense of being a "good" estimator. The theory developed around the QMLE is useful because it has led to misspecification tests.
What the QMLE certainly does is to consistently estimate the parameter vector which minimizes the Kullback-Leiber Divergence between the true distribution and the one specified. This sounds good, but minimizing this distance does not mean that the minimized distance won't be enormous.
Still, we read that there are many situations that the QMLE is a consistent estimator for the true parameter vector. This has to be assessed case-by-case, but let me give one very general situation, which shows that there is nothing inherent in the QMLE that makes it consistent for the true vector...
... Rather it is the fact that it coincides with another estimator that is always consistent (maintaining the ergodic-stationary sample assumption) : the old-fashioned, Method of Moments estimator.
In other words, when in doubt about the distribution, a strategy to consider is "always specify a distribution for which the Maximum Likelihood estimator for the parameters of interest coincides with the Method of Moments estimator": in this way no matter how off the mark is your distributional assumption, the estimator will at least be consistent.
You can take this strategy to ridiculous extremes: assume that you have a very large i.i.d. sample from a random variable, where all values are positive. Go on and assume that the random variable is normally distributed and apply maximum likelihood for the mean and variance: your QMLE will be consistent for the true values.
Of course this begs the question, why pretending to apply MLE since what we are essentially doing is relying and hiding behind the strengths of Method of Moments (which also guarantees asymptotic normality)?
In other more refined cases, QMLE may be shown to be consistent for the parameters of interest if we can say that we have specified correctly the conditional mean function but not the distribution (this is for example the case for Pooled Poisson QMLE - see Wooldridge).
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
"What makes the estimator work when the actual error distribution does not match the assumed error distribution?"
In principle the QMPLE does not "work", in the sense of being a "good" estimator. The
|
13,244
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
|
The originating paper from Wedderburn in 74 is an excellent read regarding the subject of quasilikelihood. In particular he observed that for regular exponential families, the solutions to likelihood equations were obtained by solving a general score equation of the form:
$$ 0 = \sum_{i=1}^n \mathbf{S}(\beta, X_i, Y_i) = \mathbf{D}^{T} W \left( Y - g^{-1} (\mathbf{X}^T \beta)\right)
$$
Where $\mathbf{D} = \frac{\partial}{\partial \beta} g^{-1} ( \mathbf{X}^T \beta)$ and $W = \mathbf{V}^{-1}$. This notation originates in the work of McCullogh and Nelder in the originating text, "Generalized Linear Models". M&N describe solving these types of functions using the Gauss Newton type algorithm.
Interestingly, however, this formulation hearkened to a method-of-moments type estimator where one could simply sort of "set the thing they want to estimate" in the RHS of the parenthesized expression, and trust that the expression would converge to "that interesting thing". It was a proto form of estimating equations.
Estimating equations were no new concept. In fact, attempts as far back as 1870s and early 1900s to present EEs correctly derived limit theorems from EEs using Taylor expansions, but a lack of connection to a probabilistic model was a cause of contention among critical reviewers.
Wedderburn showed a few very important results: that using the first display in a general framework where the score equation $S$ can be replaced by a quasiscore, not corresponding to any probabilistic model, but instead answering a question of interest, yielded statistically cogent estimates. Reverse transforming a general score resulted in a general qMLE which comes from a likelihood that is correct up to a proportional constant. That proportional constant is called the "dispersion". A useful result from Wedderburn is that strong departures from probabilistic assumptions can result in large or small dispersions.
However, in contrast to the answer above, quasilikelihood has been used extensively. One very nice discussion in McCullogh and Nelder deals with population modeling of horseshoe crabs. Not unlike humans, their mating habits are simply bizarre: where many males may flock to a single female in unmeasured "clusters". From an ecologist perspective, actually observing these clusters is far beyond the scope of their work, but nonetheless arriving at predictions of population size from catch-and-release posed a significant challenge. It turns out that the this mating pattern results in a Poisson model with significant under-dispersion, that is to say the variance is proportional, but not equal to the mean.
Dispersions are considered nuisance parameters in the sense that we generally do not base inference about their value, and jointly estimating them in a single likelihood results in highly irregular likelihoods. Quasilikelihood is a very useful area of statistics, especially in light of the later work on generalized estimating equations.
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
|
The originating paper from Wedderburn in 74 is an excellent read regarding the subject of quasilikelihood. In particular he observed that for regular exponential families, the solutions to likelihood
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
The originating paper from Wedderburn in 74 is an excellent read regarding the subject of quasilikelihood. In particular he observed that for regular exponential families, the solutions to likelihood equations were obtained by solving a general score equation of the form:
$$ 0 = \sum_{i=1}^n \mathbf{S}(\beta, X_i, Y_i) = \mathbf{D}^{T} W \left( Y - g^{-1} (\mathbf{X}^T \beta)\right)
$$
Where $\mathbf{D} = \frac{\partial}{\partial \beta} g^{-1} ( \mathbf{X}^T \beta)$ and $W = \mathbf{V}^{-1}$. This notation originates in the work of McCullogh and Nelder in the originating text, "Generalized Linear Models". M&N describe solving these types of functions using the Gauss Newton type algorithm.
Interestingly, however, this formulation hearkened to a method-of-moments type estimator where one could simply sort of "set the thing they want to estimate" in the RHS of the parenthesized expression, and trust that the expression would converge to "that interesting thing". It was a proto form of estimating equations.
Estimating equations were no new concept. In fact, attempts as far back as 1870s and early 1900s to present EEs correctly derived limit theorems from EEs using Taylor expansions, but a lack of connection to a probabilistic model was a cause of contention among critical reviewers.
Wedderburn showed a few very important results: that using the first display in a general framework where the score equation $S$ can be replaced by a quasiscore, not corresponding to any probabilistic model, but instead answering a question of interest, yielded statistically cogent estimates. Reverse transforming a general score resulted in a general qMLE which comes from a likelihood that is correct up to a proportional constant. That proportional constant is called the "dispersion". A useful result from Wedderburn is that strong departures from probabilistic assumptions can result in large or small dispersions.
However, in contrast to the answer above, quasilikelihood has been used extensively. One very nice discussion in McCullogh and Nelder deals with population modeling of horseshoe crabs. Not unlike humans, their mating habits are simply bizarre: where many males may flock to a single female in unmeasured "clusters". From an ecologist perspective, actually observing these clusters is far beyond the scope of their work, but nonetheless arriving at predictions of population size from catch-and-release posed a significant challenge. It turns out that the this mating pattern results in a Poisson model with significant under-dispersion, that is to say the variance is proportional, but not equal to the mean.
Dispersions are considered nuisance parameters in the sense that we generally do not base inference about their value, and jointly estimating them in a single likelihood results in highly irregular likelihoods. Quasilikelihood is a very useful area of statistics, especially in light of the later work on generalized estimating equations.
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
The originating paper from Wedderburn in 74 is an excellent read regarding the subject of quasilikelihood. In particular he observed that for regular exponential families, the solutions to likelihood
|
13,245
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
|
I had a similar question as the original one posted here from Richard Hardy. My confusion was that the parameters estimated from quasi-ML may not exist in the unknown "true" distribution. In this case, what does "consistency" exactly mean? What do the estimated parameters converge to?
After checking some references (White (1982) should be one of the original articles but is gated. A helpful exposition I found is http://homepage.ntu.edu.tw/~ckuan/pdf/et01/ch9.pdf), my thoughts in plain English are as follows: after admitting that the distribution we assume is just an approximation to the unknown true one, the practical thing we can do is to find the parameter value to minimize their distance (Kullback-Leibler distance to be precise). The beauty of the theory is that, without the need to know the true distribution, the estimated parameters from quasi-ML converge to this distance-minimizing parameter (of course, there are other useful results from the theory such as asymptotic distribution of the estimated parameters etc. but they are not the focus of my question here).
Just as Alecos Papadopolous mentioned in his reply above, the minimized distance could still be large. So the distribution we assume could be a poor approximation to the true one. All that quasi-ML can do is making our assumed distribution as close to the unknown true one as possible. Hope my experience shared here might be helpful for others having similar confusions.
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
|
I had a similar question as the original one posted here from Richard Hardy. My confusion was that the parameters estimated from quasi-ML may not exist in the unknown "true" distribution. In this case
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
I had a similar question as the original one posted here from Richard Hardy. My confusion was that the parameters estimated from quasi-ML may not exist in the unknown "true" distribution. In this case, what does "consistency" exactly mean? What do the estimated parameters converge to?
After checking some references (White (1982) should be one of the original articles but is gated. A helpful exposition I found is http://homepage.ntu.edu.tw/~ckuan/pdf/et01/ch9.pdf), my thoughts in plain English are as follows: after admitting that the distribution we assume is just an approximation to the unknown true one, the practical thing we can do is to find the parameter value to minimize their distance (Kullback-Leibler distance to be precise). The beauty of the theory is that, without the need to know the true distribution, the estimated parameters from quasi-ML converge to this distance-minimizing parameter (of course, there are other useful results from the theory such as asymptotic distribution of the estimated parameters etc. but they are not the focus of my question here).
Just as Alecos Papadopolous mentioned in his reply above, the minimized distance could still be large. So the distribution we assume could be a poor approximation to the true one. All that quasi-ML can do is making our assumed distribution as close to the unknown true one as possible. Hope my experience shared here might be helpful for others having similar confusions.
|
Idea and intuition behind quasi maximum likelihood estimation (QMLE)
I had a similar question as the original one posted here from Richard Hardy. My confusion was that the parameters estimated from quasi-ML may not exist in the unknown "true" distribution. In this case
|
13,246
|
How to interpret the intercept term in a GLM?
|
The intercept term is the intercept in the linear part of the GLM equation, so your model for the mean is $E[Y] = g^{-1}(\mathbf{X \beta})$, where $g$ is your link function and $\mathbf{X\beta}$ is your linear model. This linear model contains an "intercept term", i.e.:
$\mathbf{X\beta} = c + X_1\beta_1+X_2\beta_2+\cdots$
In your case the intercept is significantly non-zero, but the variable is not, so it is saying that
$\mathbf{X\beta} = c \neq 0$
Because your link function is binomial, then
$g(\mu) = \ln\left(\frac{\mu}{1-\mu}\right)$
And so with just the intercept term, your fitted model for the mean is:
$E[Y] = \frac{1}{1+e^{-c}}$
You can see that if $c=0$ then this corresponds to simply a 50:50 chance of getting Y=1 or 0, i.e. $E[Y] = \frac{1}{1+1} = 0.5$
So your result is saying that you can't predict the outcome, but one class (1's or 0's) is more likely than the other.
|
How to interpret the intercept term in a GLM?
|
The intercept term is the intercept in the linear part of the GLM equation, so your model for the mean is $E[Y] = g^{-1}(\mathbf{X \beta})$, where $g$ is your link function and $\mathbf{X\beta}$ is yo
|
How to interpret the intercept term in a GLM?
The intercept term is the intercept in the linear part of the GLM equation, so your model for the mean is $E[Y] = g^{-1}(\mathbf{X \beta})$, where $g$ is your link function and $\mathbf{X\beta}$ is your linear model. This linear model contains an "intercept term", i.e.:
$\mathbf{X\beta} = c + X_1\beta_1+X_2\beta_2+\cdots$
In your case the intercept is significantly non-zero, but the variable is not, so it is saying that
$\mathbf{X\beta} = c \neq 0$
Because your link function is binomial, then
$g(\mu) = \ln\left(\frac{\mu}{1-\mu}\right)$
And so with just the intercept term, your fitted model for the mean is:
$E[Y] = \frac{1}{1+e^{-c}}$
You can see that if $c=0$ then this corresponds to simply a 50:50 chance of getting Y=1 or 0, i.e. $E[Y] = \frac{1}{1+1} = 0.5$
So your result is saying that you can't predict the outcome, but one class (1's or 0's) is more likely than the other.
|
How to interpret the intercept term in a GLM?
The intercept term is the intercept in the linear part of the GLM equation, so your model for the mean is $E[Y] = g^{-1}(\mathbf{X \beta})$, where $g$ is your link function and $\mathbf{X\beta}$ is yo
|
13,247
|
How to interpret the intercept term in a GLM?
|
It looks to me like there may be some problem with the data. It is odd that the parameter estimate for the coefficient would be 0.000. It looks like both your DV and your IV are dichotomous and that the proportions of your DV do not vary at all with your IV. Is this right?
The intercept, as I noted in my comment (and as @corone 's answer implies) is the value of the DV when the IV is 0. How was your IV coded? As is, though, the fact that the estimate for the coefficient is 0.000 implies that the IV makes no difference.
Therefore, the intercept of 2.708 is the estimated logit of the DV: that is, $\text{log}(\frac{p}{1-p})$ at all levels of the IV.
|
How to interpret the intercept term in a GLM?
|
It looks to me like there may be some problem with the data. It is odd that the parameter estimate for the coefficient would be 0.000. It looks like both your DV and your IV are dichotomous and that t
|
How to interpret the intercept term in a GLM?
It looks to me like there may be some problem with the data. It is odd that the parameter estimate for the coefficient would be 0.000. It looks like both your DV and your IV are dichotomous and that the proportions of your DV do not vary at all with your IV. Is this right?
The intercept, as I noted in my comment (and as @corone 's answer implies) is the value of the DV when the IV is 0. How was your IV coded? As is, though, the fact that the estimate for the coefficient is 0.000 implies that the IV makes no difference.
Therefore, the intercept of 2.708 is the estimated logit of the DV: that is, $\text{log}(\frac{p}{1-p})$ at all levels of the IV.
|
How to interpret the intercept term in a GLM?
It looks to me like there may be some problem with the data. It is odd that the parameter estimate for the coefficient would be 0.000. It looks like both your DV and your IV are dichotomous and that t
|
13,248
|
How to interpret the intercept term in a GLM?
|
In your case, the intercept is the grand mean of attacked_excluding_app, calculated for all data regardless of treatment. The significance test in the table of coefficients is testing whether it is significantly different from zero. Whether this is relevant depends on whether you have some a priori reason to expect it be zero or not.
For instance, imagine you had tested a drug and a placebo for their effect on blood pressure. For each subject, you record the change in their blood pressure by calculating (pressure after treatment - pressure before treatment) and treat this as the dependent variable in your analysis. You then find that the effect of treatment (drug vs. placebo) is non-significant but that the intercept is significantly > 0 - this would tell you that on average, your subjects' blood pressure increased between the two measurement times. This might be interesting and need further investigation.
|
How to interpret the intercept term in a GLM?
|
In your case, the intercept is the grand mean of attacked_excluding_app, calculated for all data regardless of treatment. The significance test in the table of coefficients is testing whether it is s
|
How to interpret the intercept term in a GLM?
In your case, the intercept is the grand mean of attacked_excluding_app, calculated for all data regardless of treatment. The significance test in the table of coefficients is testing whether it is significantly different from zero. Whether this is relevant depends on whether you have some a priori reason to expect it be zero or not.
For instance, imagine you had tested a drug and a placebo for their effect on blood pressure. For each subject, you record the change in their blood pressure by calculating (pressure after treatment - pressure before treatment) and treat this as the dependent variable in your analysis. You then find that the effect of treatment (drug vs. placebo) is non-significant but that the intercept is significantly > 0 - this would tell you that on average, your subjects' blood pressure increased between the two measurement times. This might be interesting and need further investigation.
|
How to interpret the intercept term in a GLM?
In your case, the intercept is the grand mean of attacked_excluding_app, calculated for all data regardless of treatment. The significance test in the table of coefficients is testing whether it is s
|
13,249
|
In regression analysis what's the difference between data-generation process and model?
|
We all have a good sense of what "model" might mean, although its technical definition will vary among disciplines. To compare this to DGP, I began by looking at the top five hits (counting two hits with the same author as one) in Googling "data generation process".
A paper on how the US Air Force actually creates data in logistics support.
Abstract of a paper published in Environment and Planning A concerning how "synthetic micropopulations" are created via computer "simulation models."
A Web page on "synthetic data generation"; that is, simulation "to explore the effects of certain data characteristics on ... models."
Abstract of a conference paper in data mining, asserting that "data in databases is the outcome of an underlying data generation process (dgp)."
A book chapter that characterizes the data of interest as "arising from some transformation $W_t$ of an underlying [stochastic] process $V_t$ ... some or all [of which] may be unobserved..."
These links exhibit three slightly different but closely related uses of the term "data generation process." The commonest is in a context of statistical simulation. The others refer to the actual means by which data are created in an ongoing situation (logistics) and to a probability model for an ongoing data creation procedure, intended not to be analyzed directly. In the last case the text is differentiating an unobservable stochastic process, which nevertheless is modeled mathematically, from the actual numbers that will be analyzed.
These suggest two slightly different answers are tenable:
In the context of simulation or creating "synthetic" data for analysis, the "data generation process" is a way to make data for subsequent study, usually by means of a computer's pseudo random number generator. The analysis will implicitly adopt some model that describes the mathematical properties of this DGP.
In the context of statistical analysis, we may want to distinguish a real-world phenomenon (the DGP) from the observations that will be analyzed. We have models for both the phenomenon and the observations as well as a model for how the two are connected.
In regression, then, the DGP would normally describe how a set of data $(\mathbf{X}, Y)_i$ = $(X_{1i}, X_{2i}, \dots, X_{pi}, Y_{i})$, $i=1, 2, \ldots, n$ is assumed to be produced. E.g., the $X_{ji}$ could be set by the experimenter or they could be observed in some way and then be presumed to cause or be related to the values of the $Y_i$. The model would describe the possible ways in which these data could be mathematically related; e.g., we might say that each $Y_{i}$ is a random variable with expectation $\mathbf{X} \mathbf{\beta}$ and variance $\sigma^2$ for unknown parameters $\beta$ and $\sigma$.
|
In regression analysis what's the difference between data-generation process and model?
|
We all have a good sense of what "model" might mean, although its technical definition will vary among disciplines. To compare this to DGP, I began by looking at the top five hits (counting two hits
|
In regression analysis what's the difference between data-generation process and model?
We all have a good sense of what "model" might mean, although its technical definition will vary among disciplines. To compare this to DGP, I began by looking at the top five hits (counting two hits with the same author as one) in Googling "data generation process".
A paper on how the US Air Force actually creates data in logistics support.
Abstract of a paper published in Environment and Planning A concerning how "synthetic micropopulations" are created via computer "simulation models."
A Web page on "synthetic data generation"; that is, simulation "to explore the effects of certain data characteristics on ... models."
Abstract of a conference paper in data mining, asserting that "data in databases is the outcome of an underlying data generation process (dgp)."
A book chapter that characterizes the data of interest as "arising from some transformation $W_t$ of an underlying [stochastic] process $V_t$ ... some or all [of which] may be unobserved..."
These links exhibit three slightly different but closely related uses of the term "data generation process." The commonest is in a context of statistical simulation. The others refer to the actual means by which data are created in an ongoing situation (logistics) and to a probability model for an ongoing data creation procedure, intended not to be analyzed directly. In the last case the text is differentiating an unobservable stochastic process, which nevertheless is modeled mathematically, from the actual numbers that will be analyzed.
These suggest two slightly different answers are tenable:
In the context of simulation or creating "synthetic" data for analysis, the "data generation process" is a way to make data for subsequent study, usually by means of a computer's pseudo random number generator. The analysis will implicitly adopt some model that describes the mathematical properties of this DGP.
In the context of statistical analysis, we may want to distinguish a real-world phenomenon (the DGP) from the observations that will be analyzed. We have models for both the phenomenon and the observations as well as a model for how the two are connected.
In regression, then, the DGP would normally describe how a set of data $(\mathbf{X}, Y)_i$ = $(X_{1i}, X_{2i}, \dots, X_{pi}, Y_{i})$, $i=1, 2, \ldots, n$ is assumed to be produced. E.g., the $X_{ji}$ could be set by the experimenter or they could be observed in some way and then be presumed to cause or be related to the values of the $Y_i$. The model would describe the possible ways in which these data could be mathematically related; e.g., we might say that each $Y_{i}$ is a random variable with expectation $\mathbf{X} \mathbf{\beta}$ and variance $\sigma^2$ for unknown parameters $\beta$ and $\sigma$.
|
In regression analysis what's the difference between data-generation process and model?
We all have a good sense of what "model" might mean, although its technical definition will vary among disciplines. To compare this to DGP, I began by looking at the top five hits (counting two hits
|
13,250
|
In regression analysis what's the difference between data-generation process and model?
|
Whuber's answer is excellent, but it is worth adding emphasis to the fact that a statistical model need not resemble the data generating model in every respect to be an appropriate model for inferential exploration of data. Liu and Meng explain that point with great clarity in their recent arXived paper (http://arxiv.org/abs/1510.08539):
Misconception 1. A probability model must describe the generation of
the data.
A more apt description of the model’s job (in inference) is
“Such and such probabilistic pattern produces data which resemble ours
in important ways.” To create replicas (i.e., controls) of the Mona
Lisa, one does not need to bring da Vinci back to life — a camera and
printer will suffice for most purposes. Of course, knowledge of da
Vinci’s painting style will improve the quality of our replicas, just
as scientific knowledge of the true data generating process helps us
design more meaningful controls. But for purposes of uncertainty
quantification, our model’s job is to specify a set of controls that
resemble (D,$\theta$). Nowhere is this point clearer than in
applications involving computer experiments where a probabilistic
pattern is used to describe data following a known (but highly
complicated) deterministic pattern (Kennedy and O’Hagan, 2001; Conti
et al., 2009). We need a descriptive model, not necessarily a
generative model. See Lehmann (1990), Breiman (2001) and Hansen and Yu
(2001) for more on this point.
|
In regression analysis what's the difference between data-generation process and model?
|
Whuber's answer is excellent, but it is worth adding emphasis to the fact that a statistical model need not resemble the data generating model in every respect to be an appropriate model for inferenti
|
In regression analysis what's the difference between data-generation process and model?
Whuber's answer is excellent, but it is worth adding emphasis to the fact that a statistical model need not resemble the data generating model in every respect to be an appropriate model for inferential exploration of data. Liu and Meng explain that point with great clarity in their recent arXived paper (http://arxiv.org/abs/1510.08539):
Misconception 1. A probability model must describe the generation of
the data.
A more apt description of the model’s job (in inference) is
“Such and such probabilistic pattern produces data which resemble ours
in important ways.” To create replicas (i.e., controls) of the Mona
Lisa, one does not need to bring da Vinci back to life — a camera and
printer will suffice for most purposes. Of course, knowledge of da
Vinci’s painting style will improve the quality of our replicas, just
as scientific knowledge of the true data generating process helps us
design more meaningful controls. But for purposes of uncertainty
quantification, our model’s job is to specify a set of controls that
resemble (D,$\theta$). Nowhere is this point clearer than in
applications involving computer experiments where a probabilistic
pattern is used to describe data following a known (but highly
complicated) deterministic pattern (Kennedy and O’Hagan, 2001; Conti
et al., 2009). We need a descriptive model, not necessarily a
generative model. See Lehmann (1990), Breiman (2001) and Hansen and Yu
(2001) for more on this point.
|
In regression analysis what's the difference between data-generation process and model?
Whuber's answer is excellent, but it is worth adding emphasis to the fact that a statistical model need not resemble the data generating model in every respect to be an appropriate model for inferenti
|
13,251
|
In regression analysis what's the difference between data-generation process and model?
|
The DGP is the true model. The model is what we have tried to, using our best skills, to represent the true state of nature. The DGP is influenced by "noise". Noise can be of many kinds:
One time interventions
Level shifts
Trends
Changes in Seasonality
Changes in Model Parameters
Changes in Variance
If you don't control for these 6 items than your ability to identify the true DGP is reduced.
|
In regression analysis what's the difference between data-generation process and model?
|
The DGP is the true model. The model is what we have tried to, using our best skills, to represent the true state of nature. The DGP is influenced by "noise". Noise can be of many kinds:
One time
|
In regression analysis what's the difference between data-generation process and model?
The DGP is the true model. The model is what we have tried to, using our best skills, to represent the true state of nature. The DGP is influenced by "noise". Noise can be of many kinds:
One time interventions
Level shifts
Trends
Changes in Seasonality
Changes in Model Parameters
Changes in Variance
If you don't control for these 6 items than your ability to identify the true DGP is reduced.
|
In regression analysis what's the difference between data-generation process and model?
The DGP is the true model. The model is what we have tried to, using our best skills, to represent the true state of nature. The DGP is influenced by "noise". Noise can be of many kinds:
One time
|
13,252
|
In regression analysis what's the difference between data-generation process and model?
|
DGP is the virtual reality and a unique recipe for simulation. A model is a collection of DGP or possible ways that the data could have been generated.
Read the first page of this mini course by Russell Davidson:
http://russell-davidson.arts.mcgill.ca/Aarhus/bootstrap_course.pdf
|
In regression analysis what's the difference between data-generation process and model?
|
DGP is the virtual reality and a unique recipe for simulation. A model is a collection of DGP or possible ways that the data could have been generated.
Read the first page of this mini course by Russe
|
In regression analysis what's the difference between data-generation process and model?
DGP is the virtual reality and a unique recipe for simulation. A model is a collection of DGP or possible ways that the data could have been generated.
Read the first page of this mini course by Russell Davidson:
http://russell-davidson.arts.mcgill.ca/Aarhus/bootstrap_course.pdf
|
In regression analysis what's the difference between data-generation process and model?
DGP is the virtual reality and a unique recipe for simulation. A model is a collection of DGP or possible ways that the data could have been generated.
Read the first page of this mini course by Russe
|
13,253
|
When are Monte Carlo methods preferred over temporal difference ones?
|
The main problem with TD learning and DP is that their step updates are biased on the initial conditions of the learning parameters. The bootstrapping process typically updates a function or lookup Q(s,a) on a successor value Q(s',a') using whatever the current estimates are in the latter. Clearly at the very start of learning these estimates contain no information from any real rewards or state transitions.
If learning works as intended, then the bias will reduce asymptotically over multiple iterations. However, the bias can cause significant problems, especially for off-policy methods (e.g. Q Learning) and when using function approximators. That combination is so likely to fail to converge that it is called the deadly triad in Sutton & Barto.
Monte Carlo control methods do not suffer from this bias, as each update is made using a true sample of what Q(s,a) should be. However, Monte Carlo methods can suffer from high variance, which means more samples are required to achieve the same degree of learning compared to TD.
In practice, TD learning appears to learn more efficiently if the problems with the deadly triad can be overcome. Recent results using experience replay and staged "frozen" copies of estimators provide work-arounds that address problems - e.g. that is how DQN learner for Atari games was built.
There is also a middle ground between TD and Monte Carlo. It is possible to construct a generalised method that combines trajectories of different lengths - from single-step TD to complete episode runs in Monte Carlo - and combine them. The most common variant of this is TD($\lambda$) learning, where $\lambda$ is a parameter from $0$ (effectively single-step TD learning) to $1$ (effectively Monte Carlo learning, but with a nice feature that it can be used in continuous problems). Typically, a value between $0$ and $1$ makes the most efficient learning agent - although like many hyperparameters, the best value to use depends on the problem.
If you are using a value-based method (as opposed to a policy-based one), then TD learning is generally used more in practice, or a TD/MC combination method such as TD(λ) can be even better.
In terms of "practical advantage" for MC? Monte Carlo learning is conceptually simple, robust and easy to implement, albeit often slower than TD. I would generally not use it for a learning controller engine (unless in a hurry to implement something for a simple environment), but I would seriously consider it for policy evaluation in order to compare multiple agents for instance - that is due to it being an unbiased measure, which is important for testing.
|
When are Monte Carlo methods preferred over temporal difference ones?
|
The main problem with TD learning and DP is that their step updates are biased on the initial conditions of the learning parameters. The bootstrapping process typically updates a function or lookup Q(
|
When are Monte Carlo methods preferred over temporal difference ones?
The main problem with TD learning and DP is that their step updates are biased on the initial conditions of the learning parameters. The bootstrapping process typically updates a function or lookup Q(s,a) on a successor value Q(s',a') using whatever the current estimates are in the latter. Clearly at the very start of learning these estimates contain no information from any real rewards or state transitions.
If learning works as intended, then the bias will reduce asymptotically over multiple iterations. However, the bias can cause significant problems, especially for off-policy methods (e.g. Q Learning) and when using function approximators. That combination is so likely to fail to converge that it is called the deadly triad in Sutton & Barto.
Monte Carlo control methods do not suffer from this bias, as each update is made using a true sample of what Q(s,a) should be. However, Monte Carlo methods can suffer from high variance, which means more samples are required to achieve the same degree of learning compared to TD.
In practice, TD learning appears to learn more efficiently if the problems with the deadly triad can be overcome. Recent results using experience replay and staged "frozen" copies of estimators provide work-arounds that address problems - e.g. that is how DQN learner for Atari games was built.
There is also a middle ground between TD and Monte Carlo. It is possible to construct a generalised method that combines trajectories of different lengths - from single-step TD to complete episode runs in Monte Carlo - and combine them. The most common variant of this is TD($\lambda$) learning, where $\lambda$ is a parameter from $0$ (effectively single-step TD learning) to $1$ (effectively Monte Carlo learning, but with a nice feature that it can be used in continuous problems). Typically, a value between $0$ and $1$ makes the most efficient learning agent - although like many hyperparameters, the best value to use depends on the problem.
If you are using a value-based method (as opposed to a policy-based one), then TD learning is generally used more in practice, or a TD/MC combination method such as TD(λ) can be even better.
In terms of "practical advantage" for MC? Monte Carlo learning is conceptually simple, robust and easy to implement, albeit often slower than TD. I would generally not use it for a learning controller engine (unless in a hurry to implement something for a simple environment), but I would seriously consider it for policy evaluation in order to compare multiple agents for instance - that is due to it being an unbiased measure, which is important for testing.
|
When are Monte Carlo methods preferred over temporal difference ones?
The main problem with TD learning and DP is that their step updates are biased on the initial conditions of the learning parameters. The bootstrapping process typically updates a function or lookup Q(
|
13,254
|
When are Monte Carlo methods preferred over temporal difference ones?
|
Essentially it depends on your environment.
TD exploits the Markov property, i.e. the future states of a process rely only upon the current state, and therefore it's usually more efficient to use TD in Markov environments.
MC does not exploit the Markov property as it bases rewards on the entire learning process, which lends itself to non-Markov environments.
|
When are Monte Carlo methods preferred over temporal difference ones?
|
Essentially it depends on your environment.
TD exploits the Markov property, i.e. the future states of a process rely only upon the current state, and therefore it's usually more efficient to use TD i
|
When are Monte Carlo methods preferred over temporal difference ones?
Essentially it depends on your environment.
TD exploits the Markov property, i.e. the future states of a process rely only upon the current state, and therefore it's usually more efficient to use TD in Markov environments.
MC does not exploit the Markov property as it bases rewards on the entire learning process, which lends itself to non-Markov environments.
|
When are Monte Carlo methods preferred over temporal difference ones?
Essentially it depends on your environment.
TD exploits the Markov property, i.e. the future states of a process rely only upon the current state, and therefore it's usually more efficient to use TD i
|
13,255
|
Understanding the Bayes risk
|
[Here is an excerpt from my own textbook, The Bayesian Choice (2007), that argues in favour of a decision-theoretic approach to Bayesian analysis, hence of using the Bayes risk.]
Except for the most trivial settings, it is generally
impossible to uniformly minimize (in $d$) the loss
function $\text{L}(\theta,d)$ when $\theta$ is unknown.
In order to derive an effective comparison criterion from
the loss function, the frequentist approach proposes to consider instead
the average loss (or frequentist risk)
\begin{eqnarray*}
R(\theta,\delta) & = & \mathbb{E}_\theta \lbrack \text{L} (\theta
,\delta(x))\rbrack \\
& = & \int_{\cal X} \text{L}(\theta,\delta(x))f(x|\theta) \,\text dx ,
\end{eqnarray*}
where $\delta(x)$ is the decision rule, i.e., the allocation of
a decision to each outcome $x\sim f(x|\theta)$ from the random
experiment.
The function $\delta$, from ${\mathcal X}$ in $\mathfrak{D}$, is usually called estimator (while the value $\delta(x)$ is called estimate of $\theta$). When there is no risk of confusion, we also denote the set of estimators by $\mathfrak{D}$.
The frequentist paradigm relies on this criterion
to compare estimators and, if possible, to select the best estimator,
the reasoning being that estimators are evaluated on their
long-run performance for all possible values of the parameter $\theta$.
Notice, however, that there are several difficulties associated with this approach.
The error (loss) is averaged over the different values of $x$
proportionally to the density $f(x|\theta)$. Therefore, it seems
that the observation $x$ is not taken into account any further. The
risk criterion evaluates procedures on their long-run performance
and not directly for the given observation, $x$. Such an evaluation
may be satisfactory for the statistician, but it is not so appealing
for a client, who wants optimal results for her data $x$, not that
of another's!
The frequentist analysis of the decision problem implicitly assumes
that this problem will be met again and again, for the frequency
evaluation to make sense. Indeed, $R(\theta,\delta)$ is
approximately the average loss over i.i.d. repetitions of the same
experiment, according to the Law of Large Numbers. However, on both
philosophical and practical grounds, there is a lot of controversy
over the very notion of repeatability of experiments (see Jeffreys
(1961)). For one thing, if new observations come to the
statistician, she should make use of them, and this could modify the
way the experiment is conducted, as in, for instance, medical
trials.
For a procedure $\delta$, the risk $R(\theta, \delta)$ is a function
of the parameter $\theta$. Therefore, the frequentist approach does
not induce a total ordering on the set of procedures. It is
generally impossible to compare decision procedures with this
criterion, since two crossing risk functions prevent comparison
between the corresponding estimators. At best, one may hope for a
procedure $\delta_0$ that uniformly minimizes $R(\theta,\delta)$,
but such cases rarely occur unless the space of decision procedures
is restricted. Best procedures can only be obtained by restricting
rather artificially the set of authorized procedures.
Example 2.4 - Consider $x_1$ and $x_2$, two observations from
$$
P_{\theta}(x = \theta-1) = P_{\theta}(x = \theta+1) = 0.5, \qquad
\theta\in\mathbb{R}.
$$
The parameter of interest is $\theta$ (i.e., $\mathfrak{D} = \Theta$) and
it is estimated by estimators $\delta$ under the loss
$$
\text{L}(\theta,\delta) = 1-\mathbb{I}_{\theta}(\delta),
$$
often called $0-1$ loss, which penalizes errors of estimation,
whatever their magnitude, by $1$. Considering the particular estimator
$$
\delta_0(x_1,x_2) = {x_1+x_2 \over 2},
$$
its risk function is
\begin{eqnarray*}
R(\theta,\delta_0) & = & 1-P_{\theta}(\delta_0(x_1,x_2) = \theta) \\
& = & 1-P_{\theta}(x_1 \ne x_2) = 0.5.
\end{eqnarray*}
This computation shows that the estimator $\delta_0$ is correct half
of the time. Actually, this estimator is always correct when
$x_1\ne x_2$, and always wrong otherwise. Now, the estimator
$\delta_1(x_1,x_2) = x_1+1$ also has a risk function equal to $0.5$,
as does $\delta_2(x_1,x_2) = x_2-1$. Therefore, $\delta_0$, $\delta_1$
and $\delta_2$ cannot be ranked under the $0-1$ loss. $\blacktriangleright$
On the contrary, the Bayesian approach to Decision Theory integrates
on the space $\Theta$ since $\theta$ is unknown, instead of
integrating on the space ${\cal X}$ as $x$ is known. It relies on
the posterior expected loss
\begin{eqnarray*}
\rho(\pi,d|x) & = & \mathbb{E}^\pi[L(\theta,d)|x] \\
& = & \int_{\Theta} \text{L}(\theta,d) \pi(\theta|x)\, \text d\theta,
\end{eqnarray*}
which averages the error (i.e., the loss) according to the posterior
distribution of the parameter $\theta$, conditionally on the observed
value} $x$. Given $x$, the average error resulting from decision $d$ is actually $\rho(\pi,d|x)$. The posterior expected loss is thus a function of $x$ but this dependence is not troublesome, as opposed to the frequentist
dependence of the risk on the parameter because $x$, contrary to $\theta$, is known.
|
Understanding the Bayes risk
|
[Here is an excerpt from my own textbook, The Bayesian Choice (2007), that argues in favour of a decision-theoretic approach to Bayesian analysis, hence of using the Bayes risk.]
Except for the most t
|
Understanding the Bayes risk
[Here is an excerpt from my own textbook, The Bayesian Choice (2007), that argues in favour of a decision-theoretic approach to Bayesian analysis, hence of using the Bayes risk.]
Except for the most trivial settings, it is generally
impossible to uniformly minimize (in $d$) the loss
function $\text{L}(\theta,d)$ when $\theta$ is unknown.
In order to derive an effective comparison criterion from
the loss function, the frequentist approach proposes to consider instead
the average loss (or frequentist risk)
\begin{eqnarray*}
R(\theta,\delta) & = & \mathbb{E}_\theta \lbrack \text{L} (\theta
,\delta(x))\rbrack \\
& = & \int_{\cal X} \text{L}(\theta,\delta(x))f(x|\theta) \,\text dx ,
\end{eqnarray*}
where $\delta(x)$ is the decision rule, i.e., the allocation of
a decision to each outcome $x\sim f(x|\theta)$ from the random
experiment.
The function $\delta$, from ${\mathcal X}$ in $\mathfrak{D}$, is usually called estimator (while the value $\delta(x)$ is called estimate of $\theta$). When there is no risk of confusion, we also denote the set of estimators by $\mathfrak{D}$.
The frequentist paradigm relies on this criterion
to compare estimators and, if possible, to select the best estimator,
the reasoning being that estimators are evaluated on their
long-run performance for all possible values of the parameter $\theta$.
Notice, however, that there are several difficulties associated with this approach.
The error (loss) is averaged over the different values of $x$
proportionally to the density $f(x|\theta)$. Therefore, it seems
that the observation $x$ is not taken into account any further. The
risk criterion evaluates procedures on their long-run performance
and not directly for the given observation, $x$. Such an evaluation
may be satisfactory for the statistician, but it is not so appealing
for a client, who wants optimal results for her data $x$, not that
of another's!
The frequentist analysis of the decision problem implicitly assumes
that this problem will be met again and again, for the frequency
evaluation to make sense. Indeed, $R(\theta,\delta)$ is
approximately the average loss over i.i.d. repetitions of the same
experiment, according to the Law of Large Numbers. However, on both
philosophical and practical grounds, there is a lot of controversy
over the very notion of repeatability of experiments (see Jeffreys
(1961)). For one thing, if new observations come to the
statistician, she should make use of them, and this could modify the
way the experiment is conducted, as in, for instance, medical
trials.
For a procedure $\delta$, the risk $R(\theta, \delta)$ is a function
of the parameter $\theta$. Therefore, the frequentist approach does
not induce a total ordering on the set of procedures. It is
generally impossible to compare decision procedures with this
criterion, since two crossing risk functions prevent comparison
between the corresponding estimators. At best, one may hope for a
procedure $\delta_0$ that uniformly minimizes $R(\theta,\delta)$,
but such cases rarely occur unless the space of decision procedures
is restricted. Best procedures can only be obtained by restricting
rather artificially the set of authorized procedures.
Example 2.4 - Consider $x_1$ and $x_2$, two observations from
$$
P_{\theta}(x = \theta-1) = P_{\theta}(x = \theta+1) = 0.5, \qquad
\theta\in\mathbb{R}.
$$
The parameter of interest is $\theta$ (i.e., $\mathfrak{D} = \Theta$) and
it is estimated by estimators $\delta$ under the loss
$$
\text{L}(\theta,\delta) = 1-\mathbb{I}_{\theta}(\delta),
$$
often called $0-1$ loss, which penalizes errors of estimation,
whatever their magnitude, by $1$. Considering the particular estimator
$$
\delta_0(x_1,x_2) = {x_1+x_2 \over 2},
$$
its risk function is
\begin{eqnarray*}
R(\theta,\delta_0) & = & 1-P_{\theta}(\delta_0(x_1,x_2) = \theta) \\
& = & 1-P_{\theta}(x_1 \ne x_2) = 0.5.
\end{eqnarray*}
This computation shows that the estimator $\delta_0$ is correct half
of the time. Actually, this estimator is always correct when
$x_1\ne x_2$, and always wrong otherwise. Now, the estimator
$\delta_1(x_1,x_2) = x_1+1$ also has a risk function equal to $0.5$,
as does $\delta_2(x_1,x_2) = x_2-1$. Therefore, $\delta_0$, $\delta_1$
and $\delta_2$ cannot be ranked under the $0-1$ loss. $\blacktriangleright$
On the contrary, the Bayesian approach to Decision Theory integrates
on the space $\Theta$ since $\theta$ is unknown, instead of
integrating on the space ${\cal X}$ as $x$ is known. It relies on
the posterior expected loss
\begin{eqnarray*}
\rho(\pi,d|x) & = & \mathbb{E}^\pi[L(\theta,d)|x] \\
& = & \int_{\Theta} \text{L}(\theta,d) \pi(\theta|x)\, \text d\theta,
\end{eqnarray*}
which averages the error (i.e., the loss) according to the posterior
distribution of the parameter $\theta$, conditionally on the observed
value} $x$. Given $x$, the average error resulting from decision $d$ is actually $\rho(\pi,d|x)$. The posterior expected loss is thus a function of $x$ but this dependence is not troublesome, as opposed to the frequentist
dependence of the risk on the parameter because $x$, contrary to $\theta$, is known.
|
Understanding the Bayes risk
[Here is an excerpt from my own textbook, The Bayesian Choice (2007), that argues in favour of a decision-theoretic approach to Bayesian analysis, hence of using the Bayes risk.]
Except for the most t
|
13,256
|
Understanding the Bayes risk
|
Quoting the classical Statistical Decision Theory by James O. Berger:
[...] We have already stated that decision rules will be evaluated in terms
of their risk functions $R(\theta, \delta)$. [...] The problem, as
pointed out earlier, is that different admissible decision rules will
have risks which are better for different $\theta$'s. To the rescue
comes the prior $\pi(\theta)$, which supposedly reflects which $\theta$'s are
the "likely" ones to occur. It seems very reasonable to "weight"
$R(\theta, \delta)$ by $\pi(\theta)$ and average.
Yes you can evaluate $R(\theta, \delta)$ for each $\theta$, but then you would implicitly assume that each possible value of $\theta$ is equally likely. In Bayesian scenario you pick prior $\pi(\theta)$ that reflects probabilities of observing different $\theta$'s and include such information.
|
Understanding the Bayes risk
|
Quoting the classical Statistical Decision Theory by James O. Berger:
[...] We have already stated that decision rules will be evaluated in terms
of their risk functions $R(\theta, \delta)$. [...]
|
Understanding the Bayes risk
Quoting the classical Statistical Decision Theory by James O. Berger:
[...] We have already stated that decision rules will be evaluated in terms
of their risk functions $R(\theta, \delta)$. [...] The problem, as
pointed out earlier, is that different admissible decision rules will
have risks which are better for different $\theta$'s. To the rescue
comes the prior $\pi(\theta)$, which supposedly reflects which $\theta$'s are
the "likely" ones to occur. It seems very reasonable to "weight"
$R(\theta, \delta)$ by $\pi(\theta)$ and average.
Yes you can evaluate $R(\theta, \delta)$ for each $\theta$, but then you would implicitly assume that each possible value of $\theta$ is equally likely. In Bayesian scenario you pick prior $\pi(\theta)$ that reflects probabilities of observing different $\theta$'s and include such information.
|
Understanding the Bayes risk
Quoting the classical Statistical Decision Theory by James O. Berger:
[...] We have already stated that decision rules will be evaluated in terms
of their risk functions $R(\theta, \delta)$. [...]
|
13,257
|
How to fit a mixed model with response variable between 0 and 1?
|
It makes sense to start with a simpler case of no random effects.
There are four ways to deal with continuous zero-to-one response variable that behaves like a fraction or a probability (this is our most canonical/upvoted/viewed thread on this topic, but unfortunately not all four options are discussed there):
If it is a fraction $p=m/n$ of two integers and all $n$s are known, then one can use standard logistic regression, aka binomial GLM. One way to code it in R is (assuming that n is a vector of $N$ values for each data point):
glm(p ~ a+b+c, myData, family="binomial", weights=n)
If $p$ is not a fraction of two integers, then one can use beta regression. This will only work if the observed $p$ is never equal to $0$ or $1$. If it is, then more complicated zero/one-inflated beta models are possible, but this becomes more involved (see this thread).
betareg(p ~ a+b+c, myData)
Logit transform the response and use linear regression. This is usually not advised.
lm(log(p/(1-p)) ~ a+b+c, myData)
Fit a binomial model but then compute standard errors taking over-dispersion into account. The standard errors can be computed in various ways:
(a) scaled standard errors via the overdispersion estimate (one, two). This is called "quasi-binomial" GLM.
(b) robust standard errors via the sandwich estimator (one, two, three, four). This is called "fractional logit" in econometrics.
The (a) and (b) are not identical (see this comment, and sections 3.4.1 and 3.4.2 in this book, and this SO post and also this one and this one), but tend to give similar results. Option (a) is implemented in glm as follows:
glm(p ~ a+b+c, myData, family="quasibinomial")
The same four ways are available with random effects.
Using weights argument (one, two):
glmer(p ~ a+b+c + (1|subject), myData, family="binomial", weights=n)
According to the second link above, it might be a good idea to model overdispersion, see there (and also #4 below).
Using beta mixed model:
glmmadmb(p ~ a+b+c + (1|subject), myData, family="beta")
or
glmmTMB(p ~ a+b+c + (1|subject), myData,
family=list(family="beta",link="logit"))
If there are exact zeros or ones in the response data, then one can use zero/one-inflated beta model in glmmTMB.
Using logit transform of the response:
lmer(log(p/(1-p)) ~ a+b+c + (1|subject), myData)
Accounting for overdispersion in the binomial model. This uses a different trick: adding a random effect for each data point:
myData$rowid = as.factor(1:nrow(myData))
glmer(p ~ a+b+c + (1|subject) + (1|rowid), myData, family="binomial",
glmerControl(optimizer="bobyqa"))
For some reason this does not work properly as glmer() complains about non-integer p and yields nonsense estimates. A solution that I came up with is to use fake constant weights=k and make sure that p*k is always integer. This requires rounding p but by selecting k that is large enough it should not matter much. The results do not seem to depend on the value of k.
k = 100
glmer(round(p*k)/k ~ a+b+c + (1|subject) + (1|rowid), myData,
family="binomial", weights=rowid*0+k, glmerControl(optimizer="bobyqa"))
Later update (Jan 2018): This might be an invalid approach. See discussion here. I have to investigate this more.
In my specific case option #1 is not available.
Option #2 is very slow and has issues with converging: glmmadmb takes five-ten minutes to run (and still complains that it did not converge!), whereas lmer works in a split-second and glmer takes a couple of seconds. Update: I tried glmmTMB as suggested in the comments by @BenBolker and it works almost as fast as glmer, without any convergence issues. So this is what I will be using.
Options #3 and #4 yield very similar estimates and very similar Wald confidence intervals (obtained with confint). I am not a big fan of #3 though because it is kind of cheating. And #4 feels somewhat hacky.
Huge thanks to @Aaron who pointed me towards #3 and #4 in his comment.
|
How to fit a mixed model with response variable between 0 and 1?
|
It makes sense to start with a simpler case of no random effects.
There are four ways to deal with continuous zero-to-one response variable that behaves like a fraction or a probability (this is our m
|
How to fit a mixed model with response variable between 0 and 1?
It makes sense to start with a simpler case of no random effects.
There are four ways to deal with continuous zero-to-one response variable that behaves like a fraction or a probability (this is our most canonical/upvoted/viewed thread on this topic, but unfortunately not all four options are discussed there):
If it is a fraction $p=m/n$ of two integers and all $n$s are known, then one can use standard logistic regression, aka binomial GLM. One way to code it in R is (assuming that n is a vector of $N$ values for each data point):
glm(p ~ a+b+c, myData, family="binomial", weights=n)
If $p$ is not a fraction of two integers, then one can use beta regression. This will only work if the observed $p$ is never equal to $0$ or $1$. If it is, then more complicated zero/one-inflated beta models are possible, but this becomes more involved (see this thread).
betareg(p ~ a+b+c, myData)
Logit transform the response and use linear regression. This is usually not advised.
lm(log(p/(1-p)) ~ a+b+c, myData)
Fit a binomial model but then compute standard errors taking over-dispersion into account. The standard errors can be computed in various ways:
(a) scaled standard errors via the overdispersion estimate (one, two). This is called "quasi-binomial" GLM.
(b) robust standard errors via the sandwich estimator (one, two, three, four). This is called "fractional logit" in econometrics.
The (a) and (b) are not identical (see this comment, and sections 3.4.1 and 3.4.2 in this book, and this SO post and also this one and this one), but tend to give similar results. Option (a) is implemented in glm as follows:
glm(p ~ a+b+c, myData, family="quasibinomial")
The same four ways are available with random effects.
Using weights argument (one, two):
glmer(p ~ a+b+c + (1|subject), myData, family="binomial", weights=n)
According to the second link above, it might be a good idea to model overdispersion, see there (and also #4 below).
Using beta mixed model:
glmmadmb(p ~ a+b+c + (1|subject), myData, family="beta")
or
glmmTMB(p ~ a+b+c + (1|subject), myData,
family=list(family="beta",link="logit"))
If there are exact zeros or ones in the response data, then one can use zero/one-inflated beta model in glmmTMB.
Using logit transform of the response:
lmer(log(p/(1-p)) ~ a+b+c + (1|subject), myData)
Accounting for overdispersion in the binomial model. This uses a different trick: adding a random effect for each data point:
myData$rowid = as.factor(1:nrow(myData))
glmer(p ~ a+b+c + (1|subject) + (1|rowid), myData, family="binomial",
glmerControl(optimizer="bobyqa"))
For some reason this does not work properly as glmer() complains about non-integer p and yields nonsense estimates. A solution that I came up with is to use fake constant weights=k and make sure that p*k is always integer. This requires rounding p but by selecting k that is large enough it should not matter much. The results do not seem to depend on the value of k.
k = 100
glmer(round(p*k)/k ~ a+b+c + (1|subject) + (1|rowid), myData,
family="binomial", weights=rowid*0+k, glmerControl(optimizer="bobyqa"))
Later update (Jan 2018): This might be an invalid approach. See discussion here. I have to investigate this more.
In my specific case option #1 is not available.
Option #2 is very slow and has issues with converging: glmmadmb takes five-ten minutes to run (and still complains that it did not converge!), whereas lmer works in a split-second and glmer takes a couple of seconds. Update: I tried glmmTMB as suggested in the comments by @BenBolker and it works almost as fast as glmer, without any convergence issues. So this is what I will be using.
Options #3 and #4 yield very similar estimates and very similar Wald confidence intervals (obtained with confint). I am not a big fan of #3 though because it is kind of cheating. And #4 feels somewhat hacky.
Huge thanks to @Aaron who pointed me towards #3 and #4 in his comment.
|
How to fit a mixed model with response variable between 0 and 1?
It makes sense to start with a simpler case of no random effects.
There are four ways to deal with continuous zero-to-one response variable that behaves like a fraction or a probability (this is our m
|
13,258
|
Compute and graph the LDA decision boundary
|
This particular figure in Hastie et al. was produced without computing equations of class boundaries. Instead, algorithm outlined by @ttnphns in the comments was used, see footnote 2 in section 4.3, page 110:
For this figure and many similar figures in the book we compute the decision boundaries by an exhaustive contouring method. We compute the decision rule on a fine lattice of points, and then use contouring algorithms to compute the boundaries.
However, I will proceed with describing how to obtain equations of LDA class boundaries.
Let us start with a simple 2D example. Here is the data from the Iris dataset; I discard petal measurements and only consider sepal length and sepal width. Three classes are marked with red, green and blue colours:
Let us denote class means (centroids) as $\boldsymbol\mu_1, \boldsymbol\mu_2, \boldsymbol\mu_3$. LDA assumes that all classes have the same within-class covariance; given the data, this shared covariance matrix is estimated (up to the scaling) as $\mathbf{W} = \sum_i (\mathbf{x}_i-\boldsymbol \mu_k)(\mathbf{x}_i-\boldsymbol \mu_k)^\top$, where the sum is over all data points and centroid of the respective class is subtracted from each point.
For each pair of classes (e.g. class $1$ and $2$) there is a class boundary between them. It is obvious that the boundary has to pass through the middle-point between the two class centroids $(\boldsymbol \mu_{1} + \boldsymbol \mu_{2})/2$. One of the central LDA results is that this boundary is a straight line orthogonal to $\mathbf{W}^{-1} \boldsymbol (\boldsymbol \mu_{1} - \boldsymbol \mu_{2})$. There are several ways to obtain this result, and even though it was not part of the question, I will briefly hint at three of them in the Appendix below.
Note that what is written above is already a precise specification of the boundary. If one wants to have a line equation in the standard form $y=ax+b$, then coefficients $a$ and $b$ can be computed and will be given by some messy formulas. I can hardly imagine a situation when this would be needed.
Let us now apply this formula to the Iris example. For each pair of classes I find a middle point and plot a line perpendicular to $\mathbf{W}^{-1}
\boldsymbol (\boldsymbol \mu_{i} - \boldsymbol \mu_{j})$:
Three lines intersect in one point, as should have been expected. Decision boundaries are given by rays starting from the intersection point:
Note that if the number of classes is $K\gg 2$, then there will be $K(K-1)/2$ pairs of classes and so a lot of lines, all intersecting in a tangled mess. To draw a nice picture like the one from the Hastie et al., one needs to keep only the necessary segments, and it is a separate algorithmic problem in itself (not related to LDA in any way, because one does not need it to do the classification; to classify a point, either check the Mahalanobis distance to each class and choose the one with the lowest distance, or use a series or pairwise LDAs).
In $D>2$ dimensions the formula stays exactly the same: boundary is orthogonal to $\mathbf{W}^{-1} \boldsymbol (\boldsymbol \mu_{1} - \boldsymbol \mu_{2})$ and passes through $(\boldsymbol \mu_{1} + \boldsymbol \mu_{2})/2$. However, in higher dimensions this is not a line anymore, but a hyperplane of $D-1$ dimensions. For illustration purposes, one can simply project the dataset to the first two discriminant axes, and thus reduce the problem to the 2D case (that I believe is what Hastie et al. did to produce that figure).
Appendix
How to see that the boundary is a straight line orthogonal to $\mathbf{W}^{-1} (\boldsymbol \mu_{1} - \boldsymbol \mu_{2})$? Here are several possible ways to obtain this result:
The fancy way: $\mathbf{W}^{-1}$ induces Mahalanobis metric on the plane; the boundary has to be orthogonal to $\boldsymbol \mu_{1} - \boldsymbol \mu_{2}$ in this metric, QED.
The standard Gaussian way: if both classes are described by Gaussian distributions, then the log-likelihood that a point $\mathbf x$ belongs to class $k$ is proportional to $(\mathbf x - \boldsymbol \mu_k)^\top \mathbf W^{-1}(\mathbf x - \boldsymbol \mu_k)$. On the boundary the likelihoods of belonging to classes $1$ and $2$ are equal; write it down, simplify, and you will immediately get to $\mathbf x^\top \mathbf W^{-1} (\boldsymbol \mu_{1} - \boldsymbol \mu_{2}) = \mathrm{const}$, QED.
The laboursome but intuitive way. Imagine that $\mathbf{W}$ is an identity matrix, i.e. all classes are spherical. Then the solution is obvious: boundary is simply orthogonal to $\boldsymbol \mu_1 - \boldsymbol \mu_2$. If classes are not spherical, then one can make them such by sphering. If the eigen-decomposition of $\mathbf{W}$ is $\mathbf{W} = \mathbf U \mathbf D \mathbf U^\top$, then matrix $\mathbf S = \mathbf D^{-1/2} \mathbf U^\top$ will do the trick (see e.g. here). So after applying $\mathbf S$, the boundary is orthogonal to $\mathbf S (\boldsymbol \mu_{1} - \boldsymbol \mu_{2})$. If we take this boundary, transform it back with $\mathbf S^{-1}$ and ask what is it now orthogonal to, the answer (left as an exercise) is: to $\mathbf S^\top \mathbf S \boldsymbol (\boldsymbol \mu_{1} - \boldsymbol \mu_{2})$. Plugging in the expression for $\mathbf S$, we get QED.
|
Compute and graph the LDA decision boundary
|
This particular figure in Hastie et al. was produced without computing equations of class boundaries. Instead, algorithm outlined by @ttnphns in the comments was used, see footnote 2 in section 4.3, p
|
Compute and graph the LDA decision boundary
This particular figure in Hastie et al. was produced without computing equations of class boundaries. Instead, algorithm outlined by @ttnphns in the comments was used, see footnote 2 in section 4.3, page 110:
For this figure and many similar figures in the book we compute the decision boundaries by an exhaustive contouring method. We compute the decision rule on a fine lattice of points, and then use contouring algorithms to compute the boundaries.
However, I will proceed with describing how to obtain equations of LDA class boundaries.
Let us start with a simple 2D example. Here is the data from the Iris dataset; I discard petal measurements and only consider sepal length and sepal width. Three classes are marked with red, green and blue colours:
Let us denote class means (centroids) as $\boldsymbol\mu_1, \boldsymbol\mu_2, \boldsymbol\mu_3$. LDA assumes that all classes have the same within-class covariance; given the data, this shared covariance matrix is estimated (up to the scaling) as $\mathbf{W} = \sum_i (\mathbf{x}_i-\boldsymbol \mu_k)(\mathbf{x}_i-\boldsymbol \mu_k)^\top$, where the sum is over all data points and centroid of the respective class is subtracted from each point.
For each pair of classes (e.g. class $1$ and $2$) there is a class boundary between them. It is obvious that the boundary has to pass through the middle-point between the two class centroids $(\boldsymbol \mu_{1} + \boldsymbol \mu_{2})/2$. One of the central LDA results is that this boundary is a straight line orthogonal to $\mathbf{W}^{-1} \boldsymbol (\boldsymbol \mu_{1} - \boldsymbol \mu_{2})$. There are several ways to obtain this result, and even though it was not part of the question, I will briefly hint at three of them in the Appendix below.
Note that what is written above is already a precise specification of the boundary. If one wants to have a line equation in the standard form $y=ax+b$, then coefficients $a$ and $b$ can be computed and will be given by some messy formulas. I can hardly imagine a situation when this would be needed.
Let us now apply this formula to the Iris example. For each pair of classes I find a middle point and plot a line perpendicular to $\mathbf{W}^{-1}
\boldsymbol (\boldsymbol \mu_{i} - \boldsymbol \mu_{j})$:
Three lines intersect in one point, as should have been expected. Decision boundaries are given by rays starting from the intersection point:
Note that if the number of classes is $K\gg 2$, then there will be $K(K-1)/2$ pairs of classes and so a lot of lines, all intersecting in a tangled mess. To draw a nice picture like the one from the Hastie et al., one needs to keep only the necessary segments, and it is a separate algorithmic problem in itself (not related to LDA in any way, because one does not need it to do the classification; to classify a point, either check the Mahalanobis distance to each class and choose the one with the lowest distance, or use a series or pairwise LDAs).
In $D>2$ dimensions the formula stays exactly the same: boundary is orthogonal to $\mathbf{W}^{-1} \boldsymbol (\boldsymbol \mu_{1} - \boldsymbol \mu_{2})$ and passes through $(\boldsymbol \mu_{1} + \boldsymbol \mu_{2})/2$. However, in higher dimensions this is not a line anymore, but a hyperplane of $D-1$ dimensions. For illustration purposes, one can simply project the dataset to the first two discriminant axes, and thus reduce the problem to the 2D case (that I believe is what Hastie et al. did to produce that figure).
Appendix
How to see that the boundary is a straight line orthogonal to $\mathbf{W}^{-1} (\boldsymbol \mu_{1} - \boldsymbol \mu_{2})$? Here are several possible ways to obtain this result:
The fancy way: $\mathbf{W}^{-1}$ induces Mahalanobis metric on the plane; the boundary has to be orthogonal to $\boldsymbol \mu_{1} - \boldsymbol \mu_{2}$ in this metric, QED.
The standard Gaussian way: if both classes are described by Gaussian distributions, then the log-likelihood that a point $\mathbf x$ belongs to class $k$ is proportional to $(\mathbf x - \boldsymbol \mu_k)^\top \mathbf W^{-1}(\mathbf x - \boldsymbol \mu_k)$. On the boundary the likelihoods of belonging to classes $1$ and $2$ are equal; write it down, simplify, and you will immediately get to $\mathbf x^\top \mathbf W^{-1} (\boldsymbol \mu_{1} - \boldsymbol \mu_{2}) = \mathrm{const}$, QED.
The laboursome but intuitive way. Imagine that $\mathbf{W}$ is an identity matrix, i.e. all classes are spherical. Then the solution is obvious: boundary is simply orthogonal to $\boldsymbol \mu_1 - \boldsymbol \mu_2$. If classes are not spherical, then one can make them such by sphering. If the eigen-decomposition of $\mathbf{W}$ is $\mathbf{W} = \mathbf U \mathbf D \mathbf U^\top$, then matrix $\mathbf S = \mathbf D^{-1/2} \mathbf U^\top$ will do the trick (see e.g. here). So after applying $\mathbf S$, the boundary is orthogonal to $\mathbf S (\boldsymbol \mu_{1} - \boldsymbol \mu_{2})$. If we take this boundary, transform it back with $\mathbf S^{-1}$ and ask what is it now orthogonal to, the answer (left as an exercise) is: to $\mathbf S^\top \mathbf S \boldsymbol (\boldsymbol \mu_{1} - \boldsymbol \mu_{2})$. Plugging in the expression for $\mathbf S$, we get QED.
|
Compute and graph the LDA decision boundary
This particular figure in Hastie et al. was produced without computing equations of class boundaries. Instead, algorithm outlined by @ttnphns in the comments was used, see footnote 2 in section 4.3, p
|
13,259
|
Compute and graph the LDA decision boundary
|
I want to start of by thanking @amoeba says Reinstate Monica & ttnphns for their contributions that have greatly helped me! I'm so grateful in fact, I'd want to buy them a drink or be able to return the favor somehow.
The only thing I'm going to add to their reply is my python implementation of drawing these Decision boundaries, I think it'll help others, theory and insight is great, but some understand better through code.
The code below is useful for visualization, I have used LDA for dimensionality reduction (10 000 dim to 2D) for 3 classes. The framework is sklearn. Only the code to plot the DB is written below, if you're interested in the training part of the classifier, sci-kit learn's documentation is VERY good. The code below assumes you have projected your training data to 2D and you have computed their means.
x_min, x_max = plt.xlim()
# xplot = np.linspace(x_min, x_max, 100) #to plot the whole lines and find the intersection
#x_l1 and x_l2 to only plot the relevant part of the lines [found the intersection by first plotting the data]
x_l1 = np.linspace(x_min, 0.272, 100)
x_l2 = np.linspace(0.272, x_max, 100)
cov = lda1_2features.covariance_
prec_m = np.linalg.inv(cov)
line1 = np.dot(prec_m, (mu1[0]-mu1[1]).T)#mu1 contains the coordinates of all the
# classes [in this example 3 classes)
midpoint1 = (mu1[1]+mu1[0])/2
plt.plot(midpoint1[0], midpoint1[1],
'p', color='magenta', markersize=10, markeredgecolor='grey')
rico1 = -line1[0]/line1[1]
cte1 = midpoint1[1]-(rico1)*midpoint1[0]
# plt.plot(xplot, (rico1*xplot)+cte1, '--b')
plt.plot(x_l1, (rico1*x_l1)+cte1, '--b')
line2 = np.dot(prec_m, (mu1[0]-mu1[2]).T)
midpoint2 = (mu1[2]+mu1[0])/2
plt.plot(midpoint2[0], midpoint2[1],
'p', color='magenta', markersize=10, markeredgecolor='grey')
rico2 = -line2[0]/line2[1]
cte2 = midpoint2[1]-(rico2)*midpoint2[0]
# plt.plot(xplot, (rico2*xplot)+cte2, '--r')
plt.plot(x_l2, (rico2*x_l2)+cte2, '--r')
line3 = np.dot(prec_m, (mu1[1]-mu1[2]).T)
midpoint3 = (mu1[2]+mu1[1])/2
plt.plot(midpoint3[0], midpoint3[1],
'p', color='magenta', markersize=10, markeredgecolor='grey')
rico3 = -line3[0]/line3[1]
cte3 = midpoint3[1]-(rico3)*midpoint3[0]
# plt.plot(xplot, (rico3*xplot)+cte3, '--g')
plt.plot(x_l1, (rico3*x_l1)+cte3, '--g')
plt.show()
2D subspace of classifier I with Decision boundaries, class centers(yellow star), cov_ellispses and midpoints(pentagons) plotted in one figure using matplotlib]
Sources;
scikit_lda_qda
scikit_lda
|
Compute and graph the LDA decision boundary
|
I want to start of by thanking @amoeba says Reinstate Monica & ttnphns for their contributions that have greatly helped me! I'm so grateful in fact, I'd want to buy them a drink or be able to return t
|
Compute and graph the LDA decision boundary
I want to start of by thanking @amoeba says Reinstate Monica & ttnphns for their contributions that have greatly helped me! I'm so grateful in fact, I'd want to buy them a drink or be able to return the favor somehow.
The only thing I'm going to add to their reply is my python implementation of drawing these Decision boundaries, I think it'll help others, theory and insight is great, but some understand better through code.
The code below is useful for visualization, I have used LDA for dimensionality reduction (10 000 dim to 2D) for 3 classes. The framework is sklearn. Only the code to plot the DB is written below, if you're interested in the training part of the classifier, sci-kit learn's documentation is VERY good. The code below assumes you have projected your training data to 2D and you have computed their means.
x_min, x_max = plt.xlim()
# xplot = np.linspace(x_min, x_max, 100) #to plot the whole lines and find the intersection
#x_l1 and x_l2 to only plot the relevant part of the lines [found the intersection by first plotting the data]
x_l1 = np.linspace(x_min, 0.272, 100)
x_l2 = np.linspace(0.272, x_max, 100)
cov = lda1_2features.covariance_
prec_m = np.linalg.inv(cov)
line1 = np.dot(prec_m, (mu1[0]-mu1[1]).T)#mu1 contains the coordinates of all the
# classes [in this example 3 classes)
midpoint1 = (mu1[1]+mu1[0])/2
plt.plot(midpoint1[0], midpoint1[1],
'p', color='magenta', markersize=10, markeredgecolor='grey')
rico1 = -line1[0]/line1[1]
cte1 = midpoint1[1]-(rico1)*midpoint1[0]
# plt.plot(xplot, (rico1*xplot)+cte1, '--b')
plt.plot(x_l1, (rico1*x_l1)+cte1, '--b')
line2 = np.dot(prec_m, (mu1[0]-mu1[2]).T)
midpoint2 = (mu1[2]+mu1[0])/2
plt.plot(midpoint2[0], midpoint2[1],
'p', color='magenta', markersize=10, markeredgecolor='grey')
rico2 = -line2[0]/line2[1]
cte2 = midpoint2[1]-(rico2)*midpoint2[0]
# plt.plot(xplot, (rico2*xplot)+cte2, '--r')
plt.plot(x_l2, (rico2*x_l2)+cte2, '--r')
line3 = np.dot(prec_m, (mu1[1]-mu1[2]).T)
midpoint3 = (mu1[2]+mu1[1])/2
plt.plot(midpoint3[0], midpoint3[1],
'p', color='magenta', markersize=10, markeredgecolor='grey')
rico3 = -line3[0]/line3[1]
cte3 = midpoint3[1]-(rico3)*midpoint3[0]
# plt.plot(xplot, (rico3*xplot)+cte3, '--g')
plt.plot(x_l1, (rico3*x_l1)+cte3, '--g')
plt.show()
2D subspace of classifier I with Decision boundaries, class centers(yellow star), cov_ellispses and midpoints(pentagons) plotted in one figure using matplotlib]
Sources;
scikit_lda_qda
scikit_lda
|
Compute and graph the LDA decision boundary
I want to start of by thanking @amoeba says Reinstate Monica & ttnphns for their contributions that have greatly helped me! I'm so grateful in fact, I'd want to buy them a drink or be able to return t
|
13,260
|
How to understand effect of RBF SVM
|
You can possibly start by looking at one of my answers here:
Non-linear SVM classification with RBF kernel
In that answer, I attempt to explain what a kernel function is attempting to do. Once you get a grasp of what it attempts to do, as a follow up, you can read my answer to a question on Quora :
https://www.quora.com/Machine-Learning/Why-does-the-RBF-radial-basis-function-kernel-map-into-infinite-dimensional-space/answer/Arun-Iyer-1
Reproducing the content of the answer on Quora, in case you don't have a Quora account.
Question: Why does the RBF (radial basis function) kernel map into infinite dimensional space?
Answer : Consider the polynomial kernel of degree 2 defined by, $$k(x, y) =
(x^Ty)^2$$ where $x, y \in \mathbb{R}^2$ and $x = (x_1, x_2), y = (y_1, y_2)$.
Thereby, the kernel function can be written as, $$k(x, y) =
(x_1y_1 + x_2y_2)^2 = x_{1}^2y_{1}^2 + 2x_1x_2y_1y_2 +
x_{2}^2y_{2}^2$$ Now, let us try to come up with a feature map
$\Phi$ such that the kernel function can be written as
$k(x, y) = \Phi(x)^T\Phi(y)$.
Consider the following feature map, $$\Phi(x) = (x_1^2,
\sqrt{2}x_1x_2, x_2^2)$$ Basically, this feature map is mapping
the points in $\mathbb{R}^2$ to points in
$\mathbb{R}^3$. Also, notice that, $$\Phi(x)^T\Phi(y) =
x_1^2y_1^2 + 2x_1x_2y_1y_2 + x_2^2y_2^2$$ which is essentially
our kernel function.
This means that our kernel function is actually computing the
inner/dot product of points in $\mathbb{R}^3$. That is, it
is implicitly mapping our points from $\mathbb{R}^2$ to
$\mathbb{R}^3$.
Exercise Question : If your points are in $\mathbb{R}^n$, a
polynomial kernel of degree 2 will map implicitly map it to some
vector space F. What is the dimension of this vector space F? Hint:
Everything I did above is a clue.
Now, coming to RBF.
Let us consider the RBF kernel again for points in
$\mathbb{R}^2$. Then, the kernel can be written as
$$k(x, y) = \exp(-\|x - y\|^2) = \exp(- (x_1 - y_1)^2 - (x_2 - y_2)^2)$$ $$= \exp(- x_1^2 + 2x_1y_1 - y_1^2 - x_2^2 + 2x_2y_2 - y_2^2) $$ $$ = \exp(-\|x\|^2) \exp(-\|y\|^2) \exp(2x^Ty)$$ (assuming gamma = 1). Using the
taylor series you can write this as, $$k(x, y) = \exp(-\|x\|^2) \exp(-\|y\|^2) \sum_{n = 0}^{\infty} \frac{(2x^Ty)^n}{n!}$$ Now,
if we were to come up with a feature map $\Phi$ just like
we did for the polynomial kernel, you would realize that the feature
map would map every point in our $\mathbb{R}^2$ to an
infinite vector. Thus, RBF implicitly maps every point to an infinite
dimensional space.
Exercise Question : Get the first few vector elements of the feature
map for RBF for the above case?
Now, from the above answer, we can conclude something:
It may be quite hard to predict in general what the mapping function
$\Phi$ looks like for arbitrary kernel. Though, for some cases like
polynomial and RBF we can see what it looks like.
Even when we know the mapping function, the exact effect that kernel will have on our set of points may be hard to predict. However, in certain cases we can say some things. For example, look at the $\Phi$ map given above for degree 2 polynomial kernel for $\mathbb{R}^2$. It looks like $\Phi(x) = (x_1^2,
\sqrt{2}x_1x_2, x_2^2)$. From this we can determine that this map collapses diametrically opposite quadrants i.e first and third quadrant are mapped to same set of points and second and fourth quadrant are mapped to the same set of points. Therefore, this kernel allows us to solve XOR problem! In general, however, it might be harder to predict such behaviour for multidimensional spaces. And it gets harder in the case of RBF kernels.
|
How to understand effect of RBF SVM
|
You can possibly start by looking at one of my answers here:
Non-linear SVM classification with RBF kernel
In that answer, I attempt to explain what a kernel function is attempting to do. Once you ge
|
How to understand effect of RBF SVM
You can possibly start by looking at one of my answers here:
Non-linear SVM classification with RBF kernel
In that answer, I attempt to explain what a kernel function is attempting to do. Once you get a grasp of what it attempts to do, as a follow up, you can read my answer to a question on Quora :
https://www.quora.com/Machine-Learning/Why-does-the-RBF-radial-basis-function-kernel-map-into-infinite-dimensional-space/answer/Arun-Iyer-1
Reproducing the content of the answer on Quora, in case you don't have a Quora account.
Question: Why does the RBF (radial basis function) kernel map into infinite dimensional space?
Answer : Consider the polynomial kernel of degree 2 defined by, $$k(x, y) =
(x^Ty)^2$$ where $x, y \in \mathbb{R}^2$ and $x = (x_1, x_2), y = (y_1, y_2)$.
Thereby, the kernel function can be written as, $$k(x, y) =
(x_1y_1 + x_2y_2)^2 = x_{1}^2y_{1}^2 + 2x_1x_2y_1y_2 +
x_{2}^2y_{2}^2$$ Now, let us try to come up with a feature map
$\Phi$ such that the kernel function can be written as
$k(x, y) = \Phi(x)^T\Phi(y)$.
Consider the following feature map, $$\Phi(x) = (x_1^2,
\sqrt{2}x_1x_2, x_2^2)$$ Basically, this feature map is mapping
the points in $\mathbb{R}^2$ to points in
$\mathbb{R}^3$. Also, notice that, $$\Phi(x)^T\Phi(y) =
x_1^2y_1^2 + 2x_1x_2y_1y_2 + x_2^2y_2^2$$ which is essentially
our kernel function.
This means that our kernel function is actually computing the
inner/dot product of points in $\mathbb{R}^3$. That is, it
is implicitly mapping our points from $\mathbb{R}^2$ to
$\mathbb{R}^3$.
Exercise Question : If your points are in $\mathbb{R}^n$, a
polynomial kernel of degree 2 will map implicitly map it to some
vector space F. What is the dimension of this vector space F? Hint:
Everything I did above is a clue.
Now, coming to RBF.
Let us consider the RBF kernel again for points in
$\mathbb{R}^2$. Then, the kernel can be written as
$$k(x, y) = \exp(-\|x - y\|^2) = \exp(- (x_1 - y_1)^2 - (x_2 - y_2)^2)$$ $$= \exp(- x_1^2 + 2x_1y_1 - y_1^2 - x_2^2 + 2x_2y_2 - y_2^2) $$ $$ = \exp(-\|x\|^2) \exp(-\|y\|^2) \exp(2x^Ty)$$ (assuming gamma = 1). Using the
taylor series you can write this as, $$k(x, y) = \exp(-\|x\|^2) \exp(-\|y\|^2) \sum_{n = 0}^{\infty} \frac{(2x^Ty)^n}{n!}$$ Now,
if we were to come up with a feature map $\Phi$ just like
we did for the polynomial kernel, you would realize that the feature
map would map every point in our $\mathbb{R}^2$ to an
infinite vector. Thus, RBF implicitly maps every point to an infinite
dimensional space.
Exercise Question : Get the first few vector elements of the feature
map for RBF for the above case?
Now, from the above answer, we can conclude something:
It may be quite hard to predict in general what the mapping function
$\Phi$ looks like for arbitrary kernel. Though, for some cases like
polynomial and RBF we can see what it looks like.
Even when we know the mapping function, the exact effect that kernel will have on our set of points may be hard to predict. However, in certain cases we can say some things. For example, look at the $\Phi$ map given above for degree 2 polynomial kernel for $\mathbb{R}^2$. It looks like $\Phi(x) = (x_1^2,
\sqrt{2}x_1x_2, x_2^2)$. From this we can determine that this map collapses diametrically opposite quadrants i.e first and third quadrant are mapped to same set of points and second and fourth quadrant are mapped to the same set of points. Therefore, this kernel allows us to solve XOR problem! In general, however, it might be harder to predict such behaviour for multidimensional spaces. And it gets harder in the case of RBF kernels.
|
How to understand effect of RBF SVM
You can possibly start by looking at one of my answers here:
Non-linear SVM classification with RBF kernel
In that answer, I attempt to explain what a kernel function is attempting to do. Once you ge
|
13,261
|
How to predict outcome with only positive cases as training?
|
This is called learning from positive and unlabeled data, or PU learning for short, and is an active niche of semi-supervised learning.
Briefly, it is important to use the unlabeled data in the learning process as it yields significantly improved models over so-called single-class classifiers that are trained exclusively on known positives. Unlabeled data can be incorporated in several ways, the predominant approaches being the following:
somehow infer a set of likely negatives from the unlabeled data and then train a supervised model to distinguish known positives from these inferred negatives.
treat the unlabeled set as negative and somehow account for the label noise that is known to be present.
I am active in this field, and rather than summarizing it here for you, I recommend reading two of my papers and the references therein to get an overview of the domain:
A state-of-the-art technique to learn models from positive and unlabeled data (formal publication available here): http://arxiv.org/abs/1402.3144
A technique to compute commonly used performance metrics without known negatives (under review, this is first of its kind): http://arxiv.org/abs/1504.06837
|
How to predict outcome with only positive cases as training?
|
This is called learning from positive and unlabeled data, or PU learning for short, and is an active niche of semi-supervised learning.
Briefly, it is important to use the unlabeled data in the learni
|
How to predict outcome with only positive cases as training?
This is called learning from positive and unlabeled data, or PU learning for short, and is an active niche of semi-supervised learning.
Briefly, it is important to use the unlabeled data in the learning process as it yields significantly improved models over so-called single-class classifiers that are trained exclusively on known positives. Unlabeled data can be incorporated in several ways, the predominant approaches being the following:
somehow infer a set of likely negatives from the unlabeled data and then train a supervised model to distinguish known positives from these inferred negatives.
treat the unlabeled set as negative and somehow account for the label noise that is known to be present.
I am active in this field, and rather than summarizing it here for you, I recommend reading two of my papers and the references therein to get an overview of the domain:
A state-of-the-art technique to learn models from positive and unlabeled data (formal publication available here): http://arxiv.org/abs/1402.3144
A technique to compute commonly used performance metrics without known negatives (under review, this is first of its kind): http://arxiv.org/abs/1504.06837
|
How to predict outcome with only positive cases as training?
This is called learning from positive and unlabeled data, or PU learning for short, and is an active niche of semi-supervised learning.
Briefly, it is important to use the unlabeled data in the learni
|
13,262
|
How to predict outcome with only positive cases as training?
|
I am assuming there aren't as many spam cases in your 18000 cases. To use a supervised learning approach to this, you need to have more than 1 category/class in your data. Since you know 2000 cases are spam, you can label the remaining 18000 cases as 'unknown category' and train any supervised learning model to predict if a case is in the spam or the unknown category. Then check your out of sample model accuracy to see how well the model performs to distinguish between the 2 categories. If it performs well, then my assumption of few spam cases in the 'unknown' category is warranted.
If it doesn't perform well, then you'll have to use an unsupervised learner(like kmeans, etc) to cluster and identify separate homogenous groups in your data. Then identify which clusters contain the most of the 2000 spam emails, and which ones do not, and label them as spam and non spam respectively. Next, you can proceed with modeling using a supervised learner like I described earlier.
|
How to predict outcome with only positive cases as training?
|
I am assuming there aren't as many spam cases in your 18000 cases. To use a supervised learning approach to this, you need to have more than 1 category/class in your data. Since you know 2000 cases ar
|
How to predict outcome with only positive cases as training?
I am assuming there aren't as many spam cases in your 18000 cases. To use a supervised learning approach to this, you need to have more than 1 category/class in your data. Since you know 2000 cases are spam, you can label the remaining 18000 cases as 'unknown category' and train any supervised learning model to predict if a case is in the spam or the unknown category. Then check your out of sample model accuracy to see how well the model performs to distinguish between the 2 categories. If it performs well, then my assumption of few spam cases in the 'unknown' category is warranted.
If it doesn't perform well, then you'll have to use an unsupervised learner(like kmeans, etc) to cluster and identify separate homogenous groups in your data. Then identify which clusters contain the most of the 2000 spam emails, and which ones do not, and label them as spam and non spam respectively. Next, you can proceed with modeling using a supervised learner like I described earlier.
|
How to predict outcome with only positive cases as training?
I am assuming there aren't as many spam cases in your 18000 cases. To use a supervised learning approach to this, you need to have more than 1 category/class in your data. Since you know 2000 cases ar
|
13,263
|
How to predict outcome with only positive cases as training?
|
What the OP is talking about is a one-class classification task, which is a very challenging one.
There are many papers on this task across different research fields. I also wrote one An Efficient Intrinsic Authorship Verification Scheme Based on Ensemble Learning. It is very easy to adapt it in order to classify spam/not spam, rather than authors. Give it a try and let me know if you need further details...
|
How to predict outcome with only positive cases as training?
|
What the OP is talking about is a one-class classification task, which is a very challenging one.
There are many papers on this task across different research fields. I also wrote one An Efficient In
|
How to predict outcome with only positive cases as training?
What the OP is talking about is a one-class classification task, which is a very challenging one.
There are many papers on this task across different research fields. I also wrote one An Efficient Intrinsic Authorship Verification Scheme Based on Ensemble Learning. It is very easy to adapt it in order to classify spam/not spam, rather than authors. Give it a try and let me know if you need further details...
|
How to predict outcome with only positive cases as training?
What the OP is talking about is a one-class classification task, which is a very challenging one.
There are many papers on this task across different research fields. I also wrote one An Efficient In
|
13,264
|
Regression tree algorithm with linear regression models in each leaf
|
While they work differently than your algorithm, I believe you'll find mob() and FTtree interesting. For Zeileis' mob see http://cran.r-project.org/web/packages/party/vignettes/MOB.pdf For FTtree,Gama's functional trees an implementation is available in Weka and thus RWeka. See http://cran.r-project.org/web/packages/RWeka/index.html for details.
|
Regression tree algorithm with linear regression models in each leaf
|
While they work differently than your algorithm, I believe you'll find mob() and FTtree interesting. For Zeileis' mob see http://cran.r-project.org/web/packages/party/vignettes/MOB.pdf For FTtree,Gama
|
Regression tree algorithm with linear regression models in each leaf
While they work differently than your algorithm, I believe you'll find mob() and FTtree interesting. For Zeileis' mob see http://cran.r-project.org/web/packages/party/vignettes/MOB.pdf For FTtree,Gama's functional trees an implementation is available in Weka and thus RWeka. See http://cran.r-project.org/web/packages/RWeka/index.html for details.
|
Regression tree algorithm with linear regression models in each leaf
While they work differently than your algorithm, I believe you'll find mob() and FTtree interesting. For Zeileis' mob see http://cran.r-project.org/web/packages/party/vignettes/MOB.pdf For FTtree,Gama
|
13,265
|
Regression tree algorithm with linear regression models in each leaf
|
RWeka package offers many regression methods. Among them, you can find M5P (M5 Prime), which is exactly tree based regression model with linear equations in leafs. For further details about M5 method, see publication.
An example code would be:
library(RWeka)
M5_model = M5P (Dep_var ~ ., data = train, control = Weka_control(N=F, M=10))
train_predicted = predict(M5_model, train)
test_predicted = predict(M5_model, test)
If you would like to use bagging ensemble with M5 method, try something like:
M5_bag = Bagging(Dep_var ~ ., data = train, control = Weka_control(P=100, I = 100, W = list("weka.classifiers.trees.M5P", M = 4)))
To see control options for M5P model, try:
WOW(M5P)
If you would like to optimize M5 method, there is a solution for that in caret package:
library(caret)
Optimization = train (Dep_var ~ .,data = train, method = 'M5')
|
Regression tree algorithm with linear regression models in each leaf
|
RWeka package offers many regression methods. Among them, you can find M5P (M5 Prime), which is exactly tree based regression model with linear equations in leafs. For further details about M5 method,
|
Regression tree algorithm with linear regression models in each leaf
RWeka package offers many regression methods. Among them, you can find M5P (M5 Prime), which is exactly tree based regression model with linear equations in leafs. For further details about M5 method, see publication.
An example code would be:
library(RWeka)
M5_model = M5P (Dep_var ~ ., data = train, control = Weka_control(N=F, M=10))
train_predicted = predict(M5_model, train)
test_predicted = predict(M5_model, test)
If you would like to use bagging ensemble with M5 method, try something like:
M5_bag = Bagging(Dep_var ~ ., data = train, control = Weka_control(P=100, I = 100, W = list("weka.classifiers.trees.M5P", M = 4)))
To see control options for M5P model, try:
WOW(M5P)
If you would like to optimize M5 method, there is a solution for that in caret package:
library(caret)
Optimization = train (Dep_var ~ .,data = train, method = 'M5')
|
Regression tree algorithm with linear regression models in each leaf
RWeka package offers many regression methods. Among them, you can find M5P (M5 Prime), which is exactly tree based regression model with linear equations in leafs. For further details about M5 method,
|
13,266
|
Regression tree algorithm with linear regression models in each leaf
|
I think this answers the short version of your question:
The Cubist package fits rule-based models (similar to trees) with
linear regression models in the terminal leaves, instance-based
corrections and boosting.
From Cran task views: Machine Learning
|
Regression tree algorithm with linear regression models in each leaf
|
I think this answers the short version of your question:
The Cubist package fits rule-based models (similar to trees) with
linear regression models in the terminal leaves, instance-based
correct
|
Regression tree algorithm with linear regression models in each leaf
I think this answers the short version of your question:
The Cubist package fits rule-based models (similar to trees) with
linear regression models in the terminal leaves, instance-based
corrections and boosting.
From Cran task views: Machine Learning
|
Regression tree algorithm with linear regression models in each leaf
I think this answers the short version of your question:
The Cubist package fits rule-based models (similar to trees) with
linear regression models in the terminal leaves, instance-based
correct
|
13,267
|
Stacking/ensembling models with caret
|
It looks like Max Kuhn actually started working on a package for ensembleling caret models, but hasn't had time to finish it yet. This is exactly what I was looking for. I hope the project gets finished one day!
edit: I wrote my own package to do this: caretEnsemble
|
Stacking/ensembling models with caret
|
It looks like Max Kuhn actually started working on a package for ensembleling caret models, but hasn't had time to finish it yet. This is exactly what I was looking for. I hope the project gets fini
|
Stacking/ensembling models with caret
It looks like Max Kuhn actually started working on a package for ensembleling caret models, but hasn't had time to finish it yet. This is exactly what I was looking for. I hope the project gets finished one day!
edit: I wrote my own package to do this: caretEnsemble
|
Stacking/ensembling models with caret
It looks like Max Kuhn actually started working on a package for ensembleling caret models, but hasn't had time to finish it yet. This is exactly what I was looking for. I hope the project gets fini
|
13,268
|
Stacking/ensembling models with caret
|
What you are looking for is called "model ensembling". A simple introductory tutorial with R code can be found here:
http://viksalgorithms.blogspot.jp/2012/01/intro-to-ensemble-learning-in-r.html
|
Stacking/ensembling models with caret
|
What you are looking for is called "model ensembling". A simple introductory tutorial with R code can be found here:
http://viksalgorithms.blogspot.jp/2012/01/intro-to-ensemble-learning-in-r.html
|
Stacking/ensembling models with caret
What you are looking for is called "model ensembling". A simple introductory tutorial with R code can be found here:
http://viksalgorithms.blogspot.jp/2012/01/intro-to-ensemble-learning-in-r.html
|
Stacking/ensembling models with caret
What you are looking for is called "model ensembling". A simple introductory tutorial with R code can be found here:
http://viksalgorithms.blogspot.jp/2012/01/intro-to-ensemble-learning-in-r.html
|
13,269
|
Stacking/ensembling models with caret
|
I'm not quite sure what you are looking for but this might help:
http://www.jstatsoft.org/v28/i05/paper
It is how to use multiple models in caret. The part you might be interested is section 5 on pg. 13.
|
Stacking/ensembling models with caret
|
I'm not quite sure what you are looking for but this might help:
http://www.jstatsoft.org/v28/i05/paper
It is how to use multiple models in caret. The part you might be interested is section 5 on pg.
|
Stacking/ensembling models with caret
I'm not quite sure what you are looking for but this might help:
http://www.jstatsoft.org/v28/i05/paper
It is how to use multiple models in caret. The part you might be interested is section 5 on pg. 13.
|
Stacking/ensembling models with caret
I'm not quite sure what you are looking for but this might help:
http://www.jstatsoft.org/v28/i05/paper
It is how to use multiple models in caret. The part you might be interested is section 5 on pg.
|
13,270
|
Calculating AUPR in R [closed]
|
As of July 2016, the package PRROC works great for computing both ROC AUC and PR AUC.
Assuming you already have a vector of probabilities (called probs) computed with your model and the true class labels are in your data frame as df$label (0 and 1) this code should work:
install.packages("PRROC")
require(PRROC)
fg <- probs[df$label == 1]
bg <- probs[df$label == 0]
# ROC Curve
roc <- roc.curve(scores.class0 = fg, scores.class1 = bg, curve = T)
plot(roc)
# PR Curve
pr <- pr.curve(scores.class0 = fg, scores.class1 = bg, curve = T)
plot(pr)
PS: The only disconcerting thing is you use scores.class0 = fg when fg is computed for label 1 and not 0.
Here are the example ROC and PR curves with the areas under them:
The bars on the right are the threshold probabilities at which a point on the curve is obtained.
Note that for a random classifier, ROC AUC will be close to 0.5 irrespective of the class imbalance. However, the PR AUC is tricky (see What is "baseline" in precision recall curve).
|
Calculating AUPR in R [closed]
|
As of July 2016, the package PRROC works great for computing both ROC AUC and PR AUC.
Assuming you already have a vector of probabilities (called probs) computed with your model and the true class lab
|
Calculating AUPR in R [closed]
As of July 2016, the package PRROC works great for computing both ROC AUC and PR AUC.
Assuming you already have a vector of probabilities (called probs) computed with your model and the true class labels are in your data frame as df$label (0 and 1) this code should work:
install.packages("PRROC")
require(PRROC)
fg <- probs[df$label == 1]
bg <- probs[df$label == 0]
# ROC Curve
roc <- roc.curve(scores.class0 = fg, scores.class1 = bg, curve = T)
plot(roc)
# PR Curve
pr <- pr.curve(scores.class0 = fg, scores.class1 = bg, curve = T)
plot(pr)
PS: The only disconcerting thing is you use scores.class0 = fg when fg is computed for label 1 and not 0.
Here are the example ROC and PR curves with the areas under them:
The bars on the right are the threshold probabilities at which a point on the curve is obtained.
Note that for a random classifier, ROC AUC will be close to 0.5 irrespective of the class imbalance. However, the PR AUC is tricky (see What is "baseline" in precision recall curve).
|
Calculating AUPR in R [closed]
As of July 2016, the package PRROC works great for computing both ROC AUC and PR AUC.
Assuming you already have a vector of probabilities (called probs) computed with your model and the true class lab
|
13,271
|
Calculating AUPR in R [closed]
|
AUPRC() is a function in the PerfMeas package which is much better than the pr.curve() function in PRROC package when the data is very large.
pr.curve() is a nightmare and takes forever to finish when you have vectors with millions of entries. PerfMeas takes seconds in comparison. PRROC is written in R and PerfMeas is written in C.
|
Calculating AUPR in R [closed]
|
AUPRC() is a function in the PerfMeas package which is much better than the pr.curve() function in PRROC package when the data is very large.
pr.curve() is a nightmare and takes forever to finish when
|
Calculating AUPR in R [closed]
AUPRC() is a function in the PerfMeas package which is much better than the pr.curve() function in PRROC package when the data is very large.
pr.curve() is a nightmare and takes forever to finish when you have vectors with millions of entries. PerfMeas takes seconds in comparison. PRROC is written in R and PerfMeas is written in C.
|
Calculating AUPR in R [closed]
AUPRC() is a function in the PerfMeas package which is much better than the pr.curve() function in PRROC package when the data is very large.
pr.curve() is a nightmare and takes forever to finish when
|
13,272
|
Calculating AUPR in R [closed]
|
A little googling returns one bioc package, qpgraph (qpPrecisionRecall), and a cran one, minet (auc.pr). I have no experience with them, though. Both have been devised to deal with biological networks.
|
Calculating AUPR in R [closed]
|
A little googling returns one bioc package, qpgraph (qpPrecisionRecall), and a cran one, minet (auc.pr). I have no experience with them, though. Both have been devised to deal with biological networks
|
Calculating AUPR in R [closed]
A little googling returns one bioc package, qpgraph (qpPrecisionRecall), and a cran one, minet (auc.pr). I have no experience with them, though. Both have been devised to deal with biological networks.
|
Calculating AUPR in R [closed]
A little googling returns one bioc package, qpgraph (qpPrecisionRecall), and a cran one, minet (auc.pr). I have no experience with them, though. Both have been devised to deal with biological networks
|
13,273
|
Calculating AUPR in R [closed]
|
Once you've got a precision recall curve from qpPrecisionRecall, e.g.:
pr <- qpPrecisionRecall(measurements, goldstandard)
you can calculate its AUC by doing this:
f <- approxfun(pr[, 1:2])
auc <- integrate(f, 0, 1)$value
the help page of qpPrecisionRecall gives you details on what data structure expects in its arguments.
|
Calculating AUPR in R [closed]
|
Once you've got a precision recall curve from qpPrecisionRecall, e.g.:
pr <- qpPrecisionRecall(measurements, goldstandard)
you can calculate its AUC by doing this:
f <- approxfun(pr[, 1:2])
auc <- in
|
Calculating AUPR in R [closed]
Once you've got a precision recall curve from qpPrecisionRecall, e.g.:
pr <- qpPrecisionRecall(measurements, goldstandard)
you can calculate its AUC by doing this:
f <- approxfun(pr[, 1:2])
auc <- integrate(f, 0, 1)$value
the help page of qpPrecisionRecall gives you details on what data structure expects in its arguments.
|
Calculating AUPR in R [closed]
Once you've got a precision recall curve from qpPrecisionRecall, e.g.:
pr <- qpPrecisionRecall(measurements, goldstandard)
you can calculate its AUC by doing this:
f <- approxfun(pr[, 1:2])
auc <- in
|
13,274
|
What are the differences between the Baum-Welch algorithm and Viterbi training?
|
The Baum-Welch algorithm and the Viterbi algorithm calculate different things.
If you know the transition probabilities for the hidden part of your model, and the emission probabilities for the visible outputs of your model, then the Viterbi algorithm gives you the most likely complete sequence of hidden states conditional on both your outputs and your model specification.
The Baum-Welch algorithm gives you both the most likely hidden transition probabilities as well as the most likely set of emission probabilities given only the observed states of the model (and, usually, an upper bound on the number of hidden states). You also get the "pointwise" highest likelihood points in the hidden states, which is often slightly different from the single hidden sequence that is overall most likely.
If you know your model and just want the latent states, then there is no reason to use the Baum-Welch algorithm. If you don't know your model, then you can't be using the Viterbi algorithm.
Edited to add: See Peter Smit's comment; there's some overlap/vagueness in nomenclature. Some poking around led me to a chapter by Luis Javier Rodrıguez and Ines Torres in "Pattern Recognition and Image Analysis" (ISBN 978-3-540-40217-6, pp 845-857) which discusses the speed versus accuracy trade-offs of the two algorithms.
Briefly, the Baum-Welch algorithm is essentially the Expectation-Maximization (EM) algorithm applied to an HMM; as a strict EM-type algorithm you're guaranteed to converge to at least a local maximum, and so for unimodal problems find the MLE. It requires two passes over your data for each step, though, and the complexity gets very big in the length of the data and number of training samples. However, you do end up with the full conditional likelihood for your hidden parameters.
The Viterbi training algorithm (as opposed to the "Viterbi algorithm") approximates the MLE to achieve a gain in speed at the cost of accuracy. It segments the data and then applies the Viterbi algorithm (as I understood it) to get the most likely state sequence in the segment, then uses that most likely state sequence to re-estimate the hidden parameters. This, unlike the Baum-Welch algorithm, doesn't give the full conditional likelihood of the hidden parameters, and so ends up reducing the accuracy while saving significant (the chapter reports 1 to 2 orders of magnitude) computational time.
|
What are the differences between the Baum-Welch algorithm and Viterbi training?
|
The Baum-Welch algorithm and the Viterbi algorithm calculate different things.
If you know the transition probabilities for the hidden part of your model, and the emission probabilities for the visibl
|
What are the differences between the Baum-Welch algorithm and Viterbi training?
The Baum-Welch algorithm and the Viterbi algorithm calculate different things.
If you know the transition probabilities for the hidden part of your model, and the emission probabilities for the visible outputs of your model, then the Viterbi algorithm gives you the most likely complete sequence of hidden states conditional on both your outputs and your model specification.
The Baum-Welch algorithm gives you both the most likely hidden transition probabilities as well as the most likely set of emission probabilities given only the observed states of the model (and, usually, an upper bound on the number of hidden states). You also get the "pointwise" highest likelihood points in the hidden states, which is often slightly different from the single hidden sequence that is overall most likely.
If you know your model and just want the latent states, then there is no reason to use the Baum-Welch algorithm. If you don't know your model, then you can't be using the Viterbi algorithm.
Edited to add: See Peter Smit's comment; there's some overlap/vagueness in nomenclature. Some poking around led me to a chapter by Luis Javier Rodrıguez and Ines Torres in "Pattern Recognition and Image Analysis" (ISBN 978-3-540-40217-6, pp 845-857) which discusses the speed versus accuracy trade-offs of the two algorithms.
Briefly, the Baum-Welch algorithm is essentially the Expectation-Maximization (EM) algorithm applied to an HMM; as a strict EM-type algorithm you're guaranteed to converge to at least a local maximum, and so for unimodal problems find the MLE. It requires two passes over your data for each step, though, and the complexity gets very big in the length of the data and number of training samples. However, you do end up with the full conditional likelihood for your hidden parameters.
The Viterbi training algorithm (as opposed to the "Viterbi algorithm") approximates the MLE to achieve a gain in speed at the cost of accuracy. It segments the data and then applies the Viterbi algorithm (as I understood it) to get the most likely state sequence in the segment, then uses that most likely state sequence to re-estimate the hidden parameters. This, unlike the Baum-Welch algorithm, doesn't give the full conditional likelihood of the hidden parameters, and so ends up reducing the accuracy while saving significant (the chapter reports 1 to 2 orders of magnitude) computational time.
|
What are the differences between the Baum-Welch algorithm and Viterbi training?
The Baum-Welch algorithm and the Viterbi algorithm calculate different things.
If you know the transition probabilities for the hidden part of your model, and the emission probabilities for the visibl
|
13,275
|
What are the differences between the Baum-Welch algorithm and Viterbi training?
|
Forward-backward is used when you want to count 'invisible things'. For example, when using E-M to improve a model via unsupervised data. I think that Petrov's paper is an example. In the technique I'm thinking of, you first train a model with annotated data with fairly coarse annotations (e.g. a tag for 'Verb'). Then you arbitrarily split the probability mass for that state in two slightly unequal quantities, and retrain, running forward-backward to maximize likelihood by redistributing mass between the two states.
|
What are the differences between the Baum-Welch algorithm and Viterbi training?
|
Forward-backward is used when you want to count 'invisible things'. For example, when using E-M to improve a model via unsupervised data. I think that Petrov's paper is an example. In the technique I'
|
What are the differences between the Baum-Welch algorithm and Viterbi training?
Forward-backward is used when you want to count 'invisible things'. For example, when using E-M to improve a model via unsupervised data. I think that Petrov's paper is an example. In the technique I'm thinking of, you first train a model with annotated data with fairly coarse annotations (e.g. a tag for 'Verb'). Then you arbitrarily split the probability mass for that state in two slightly unequal quantities, and retrain, running forward-backward to maximize likelihood by redistributing mass between the two states.
|
What are the differences between the Baum-Welch algorithm and Viterbi training?
Forward-backward is used when you want to count 'invisible things'. For example, when using E-M to improve a model via unsupervised data. I think that Petrov's paper is an example. In the technique I'
|
13,276
|
Are there any circumstances where stepwise regression should be used?
|
I am not aware of situations, in which stepwise regression would be the preferred approach. It may be okay (particularly in its step-down version starting from the full model) with bootstrapping of the whole stepwise process on extremely large datasets with $n>>p$. Here $n$ is the number of observations in an continuous outcome (or number of records with an event in survival analysis) $p$ is the number of candidate predictors including all considered interactions - i.e. when any even small effects become very clear and it does not matter so much how your do your model building (that would mean that $n$ would be much larger than $p$ than by substantially more than the sometimes quoted factor of 20).
Of course the reason most people are tempted to do something like stepwise regression is,
because it is not computationally intensive (if you do not do the proper bootstrapping, but then your results are pretty unreliable),
because it provides clear cut "is in the model" versus "is not in the model" statements (which are very unreliable in standard stepwise regression; something that proper bootstrapping will usually make clear so that these statements will usually not be so clear) and
because often $n$ is smaller, close to or just a bit larger than $p$.
I.e. a method like stepwise regression would (if it had good operating characteristics) be especially attractive in those situations, when it does not have good operating characteristics.
|
Are there any circumstances where stepwise regression should be used?
|
I am not aware of situations, in which stepwise regression would be the preferred approach. It may be okay (particularly in its step-down version starting from the full model) with bootstrapping of th
|
Are there any circumstances where stepwise regression should be used?
I am not aware of situations, in which stepwise regression would be the preferred approach. It may be okay (particularly in its step-down version starting from the full model) with bootstrapping of the whole stepwise process on extremely large datasets with $n>>p$. Here $n$ is the number of observations in an continuous outcome (or number of records with an event in survival analysis) $p$ is the number of candidate predictors including all considered interactions - i.e. when any even small effects become very clear and it does not matter so much how your do your model building (that would mean that $n$ would be much larger than $p$ than by substantially more than the sometimes quoted factor of 20).
Of course the reason most people are tempted to do something like stepwise regression is,
because it is not computationally intensive (if you do not do the proper bootstrapping, but then your results are pretty unreliable),
because it provides clear cut "is in the model" versus "is not in the model" statements (which are very unreliable in standard stepwise regression; something that proper bootstrapping will usually make clear so that these statements will usually not be so clear) and
because often $n$ is smaller, close to or just a bit larger than $p$.
I.e. a method like stepwise regression would (if it had good operating characteristics) be especially attractive in those situations, when it does not have good operating characteristics.
|
Are there any circumstances where stepwise regression should be used?
I am not aware of situations, in which stepwise regression would be the preferred approach. It may be okay (particularly in its step-down version starting from the full model) with bootstrapping of th
|
13,277
|
Are there any circumstances where stepwise regression should be used?
|
Two cases in which I would not object to seeing step-wise regression are
Exploratory data analysis
Predictive models
In both these very important use cases, you are not so concerned about traditional statistical inference, so the fact that p-values, etc., are no longer valid is of little concern.
For example, if a research paper said "In our pilot study, we used step-wise regression to find 3 interesting variables out of 1000. In a follow-up study with new data, we showed these 3 interesting variables were strongly correlated with the outcome of interest", I would have no problem with the use of step-wise regression. Similarly, "We used step-wise regression to build a predictive model. This out-preformed alternative model X in our hold-out data set in regards to MSE" is totally fine with me as well.
To be clear, I am not saying that step-wise regression is the best way to approach these problems. But it is easy and may give you satisfactory solutions.
EDIT:
In the comments, there is a question of whether stepwise AIC can actually be useful for prediction. Here's a simulation that shows it doing much better than linear regression with all the covariates, and nearly as well as elastic nets with the penalty chosen by cross-validation.
I wouldn't take this simulation as the end of the discussion; it's not too hard to come up with a scenario in which step-wise AIC will preform worse. But it's really not an unreasonable scenario, and exactly the type of situation that elastic nets are designed for (high correlation of covariates with very few large effects)!
library(leaps)
library(glmnet)
nRows <- 1000
nCols <- 500
# Seed set For reproducibility.
# Try changing for investigation of reliability of results
set.seed(1)
# Creating heavily correlated covariates
x_firstHalf <- matrix(rnorm(nRows * nCols / 2), nrow = nRows)
x_secondHalf <- x_firstHalf + 0.5 *
matrix(rnorm(nRows * nCols / 2), nrow = nRows)
x_mat <- cbind(x_firstHalf, x_secondHalf) + rnorm(nRows)
# Creating beta's. Most will be of very small magnitude
p_large = 0.01
betas <- rnorm(nCols, sd = 0.01) +
rnorm(nCols, sd = 4) * rbinom(nCols, size = 1, prob = p_large)
y <- x_mat %*% betas + rnorm(nRows, sd = 4)
all_data <- data.frame(y, x_mat)
colnames(all_data) <- c('y', paste('x', 1:nCols, sep = '_'))
# Holding out 25% of data for validation
holdout_index <- 1:(nRows * .25)
train_data <- all_data[-holdout_index, ]
validate_data <- all_data[holdout_index, ]
mean_fit <- lm(y ~ 0, data = train_data)
full_fit <- lm(y ~ ., data = train_data)
step_fit <- step(mean_fit,
scope = list(lower = mean_fit, upper = full_fit),
direction = "forward", steps = 20, trace = 0)
glmnet_cvRes <- cv.glmnet(x = as.matrix(train_data[,-1]),
y = as.numeric(train_data$y) )
full_pred <- predict(full_fit, validate_data)
step_pred <- predict(step_fit, validate_data)
glmnet_pred <- predict(glmnet_cvRes, as.matrix(validate_data[,-1]), s='lambda.min')
sd(full_pred - validate_data$y) # [1] 6.426117
sd(step_pred - validate_data$y) # [1] 4.233672
sd(glmnet_pred - validate_data$y) # [1] 4.127171
# Note that stepwise AIC does considerably better than using all covariates
# in linear regression, and not that much worse than penalized methods
# with cross validation!!
Side note:
I'm really not a fan of stepwise regression for many, many reasons, so I feel somewhat awkward having taken this stance in defense of it. But I merely think it's important to be precise about exactly what I don't like about it.
|
Are there any circumstances where stepwise regression should be used?
|
Two cases in which I would not object to seeing step-wise regression are
Exploratory data analysis
Predictive models
In both these very important use cases, you are not so concerned about traditiona
|
Are there any circumstances where stepwise regression should be used?
Two cases in which I would not object to seeing step-wise regression are
Exploratory data analysis
Predictive models
In both these very important use cases, you are not so concerned about traditional statistical inference, so the fact that p-values, etc., are no longer valid is of little concern.
For example, if a research paper said "In our pilot study, we used step-wise regression to find 3 interesting variables out of 1000. In a follow-up study with new data, we showed these 3 interesting variables were strongly correlated with the outcome of interest", I would have no problem with the use of step-wise regression. Similarly, "We used step-wise regression to build a predictive model. This out-preformed alternative model X in our hold-out data set in regards to MSE" is totally fine with me as well.
To be clear, I am not saying that step-wise regression is the best way to approach these problems. But it is easy and may give you satisfactory solutions.
EDIT:
In the comments, there is a question of whether stepwise AIC can actually be useful for prediction. Here's a simulation that shows it doing much better than linear regression with all the covariates, and nearly as well as elastic nets with the penalty chosen by cross-validation.
I wouldn't take this simulation as the end of the discussion; it's not too hard to come up with a scenario in which step-wise AIC will preform worse. But it's really not an unreasonable scenario, and exactly the type of situation that elastic nets are designed for (high correlation of covariates with very few large effects)!
library(leaps)
library(glmnet)
nRows <- 1000
nCols <- 500
# Seed set For reproducibility.
# Try changing for investigation of reliability of results
set.seed(1)
# Creating heavily correlated covariates
x_firstHalf <- matrix(rnorm(nRows * nCols / 2), nrow = nRows)
x_secondHalf <- x_firstHalf + 0.5 *
matrix(rnorm(nRows * nCols / 2), nrow = nRows)
x_mat <- cbind(x_firstHalf, x_secondHalf) + rnorm(nRows)
# Creating beta's. Most will be of very small magnitude
p_large = 0.01
betas <- rnorm(nCols, sd = 0.01) +
rnorm(nCols, sd = 4) * rbinom(nCols, size = 1, prob = p_large)
y <- x_mat %*% betas + rnorm(nRows, sd = 4)
all_data <- data.frame(y, x_mat)
colnames(all_data) <- c('y', paste('x', 1:nCols, sep = '_'))
# Holding out 25% of data for validation
holdout_index <- 1:(nRows * .25)
train_data <- all_data[-holdout_index, ]
validate_data <- all_data[holdout_index, ]
mean_fit <- lm(y ~ 0, data = train_data)
full_fit <- lm(y ~ ., data = train_data)
step_fit <- step(mean_fit,
scope = list(lower = mean_fit, upper = full_fit),
direction = "forward", steps = 20, trace = 0)
glmnet_cvRes <- cv.glmnet(x = as.matrix(train_data[,-1]),
y = as.numeric(train_data$y) )
full_pred <- predict(full_fit, validate_data)
step_pred <- predict(step_fit, validate_data)
glmnet_pred <- predict(glmnet_cvRes, as.matrix(validate_data[,-1]), s='lambda.min')
sd(full_pred - validate_data$y) # [1] 6.426117
sd(step_pred - validate_data$y) # [1] 4.233672
sd(glmnet_pred - validate_data$y) # [1] 4.127171
# Note that stepwise AIC does considerably better than using all covariates
# in linear regression, and not that much worse than penalized methods
# with cross validation!!
Side note:
I'm really not a fan of stepwise regression for many, many reasons, so I feel somewhat awkward having taken this stance in defense of it. But I merely think it's important to be precise about exactly what I don't like about it.
|
Are there any circumstances where stepwise regression should be used?
Two cases in which I would not object to seeing step-wise regression are
Exploratory data analysis
Predictive models
In both these very important use cases, you are not so concerned about traditiona
|
13,278
|
Advantages of Particle Swarm Optimization over Bayesian Optimization for hyperparameter tuning?
|
As the lead developer of Optunity I'll add my two cents.
We have done extensive benchmarks comparing Optunity with the most popular Bayesian solvers (e.g., hyperopt, SMAC, bayesopt) on real-world problems, and the results indicate that PSO is in fact not less efficient in many practical cases. In our benchmark, which consists of tuning SVM classifiers on various datasets, Optunity is actually more efficient than hyperopt and SMAC, but slightly less efficient than BayesOpt. I would love to share the results here, but I'm going to wait until Optunity is finally published in JMLR (under review for over a year now, so don't hold your breath ...).
As you indicate, increased efficiency is a commonly used selling point for Bayesian optimization, but in practice it only holds water if the assumptions of the underlying surrogate models hold, which is far from trivial. In our experiments, Optunity's very simple PSO solver is often competitive with complex Bayesian approaches in terms of number of function evaluations. Bayesian solvers work very well when provided with good priors, but with an uninformative prior there is virtually no structural benefit over metaheuristic methods like PSO in terms of efficiency.
A big selling point for PSO is the fact it's embarassingly parallel. Bayesian optimization is often hard to parallelize, due to its inherently sequential nature (hyperopt's implementation being the only real exception). Given opportunities to distribute, which is becoming the norm, Optunity quickly takes the lead in wall-clock time to obtain good solutions.
Another key difference between Optunity and most other dedicated hyperparameter optimization libraries is the target audience: Optunity has the simplest interface and is targetted towards non-machine learning experts, whereas most other libraries require some understanding of Bayesian optimization to use effectively (i.e., they are targetted towards specialists).
The reason we made the library is that despite the fact dedicated hyperparameter optimization methods exist, they lack adoption in practice. Most people are still either not tuning at all, doing it manually, or via naive approaches like grid or random search. In our opinion, a key reason for this is the fact that existing libraries prior to developing Optunity were too difficult to use in terms of installation, documentation, API and often limited to a single environment.
|
Advantages of Particle Swarm Optimization over Bayesian Optimization for hyperparameter tuning?
|
As the lead developer of Optunity I'll add my two cents.
We have done extensive benchmarks comparing Optunity with the most popular Bayesian solvers (e.g., hyperopt, SMAC, bayesopt) on real-world pro
|
Advantages of Particle Swarm Optimization over Bayesian Optimization for hyperparameter tuning?
As the lead developer of Optunity I'll add my two cents.
We have done extensive benchmarks comparing Optunity with the most popular Bayesian solvers (e.g., hyperopt, SMAC, bayesopt) on real-world problems, and the results indicate that PSO is in fact not less efficient in many practical cases. In our benchmark, which consists of tuning SVM classifiers on various datasets, Optunity is actually more efficient than hyperopt and SMAC, but slightly less efficient than BayesOpt. I would love to share the results here, but I'm going to wait until Optunity is finally published in JMLR (under review for over a year now, so don't hold your breath ...).
As you indicate, increased efficiency is a commonly used selling point for Bayesian optimization, but in practice it only holds water if the assumptions of the underlying surrogate models hold, which is far from trivial. In our experiments, Optunity's very simple PSO solver is often competitive with complex Bayesian approaches in terms of number of function evaluations. Bayesian solvers work very well when provided with good priors, but with an uninformative prior there is virtually no structural benefit over metaheuristic methods like PSO in terms of efficiency.
A big selling point for PSO is the fact it's embarassingly parallel. Bayesian optimization is often hard to parallelize, due to its inherently sequential nature (hyperopt's implementation being the only real exception). Given opportunities to distribute, which is becoming the norm, Optunity quickly takes the lead in wall-clock time to obtain good solutions.
Another key difference between Optunity and most other dedicated hyperparameter optimization libraries is the target audience: Optunity has the simplest interface and is targetted towards non-machine learning experts, whereas most other libraries require some understanding of Bayesian optimization to use effectively (i.e., they are targetted towards specialists).
The reason we made the library is that despite the fact dedicated hyperparameter optimization methods exist, they lack adoption in practice. Most people are still either not tuning at all, doing it manually, or via naive approaches like grid or random search. In our opinion, a key reason for this is the fact that existing libraries prior to developing Optunity were too difficult to use in terms of installation, documentation, API and often limited to a single environment.
|
Advantages of Particle Swarm Optimization over Bayesian Optimization for hyperparameter tuning?
As the lead developer of Optunity I'll add my two cents.
We have done extensive benchmarks comparing Optunity with the most popular Bayesian solvers (e.g., hyperopt, SMAC, bayesopt) on real-world pro
|
13,279
|
Advantages of Particle Swarm Optimization over Bayesian Optimization for hyperparameter tuning?
|
The answer is problem-dependent and cannot be given without additional context.
Typically, the answer would go as follows. Bayesian Optimization is more suitable for low-dimensional problems with the computational budget up to say 10x-100x the number of variables. PSO can be quite efficient for much larger budgets but is not state-of-the-art in its niche.
|
Advantages of Particle Swarm Optimization over Bayesian Optimization for hyperparameter tuning?
|
The answer is problem-dependent and cannot be given without additional context.
Typically, the answer would go as follows. Bayesian Optimization is more suitable for low-dimensional problems with the
|
Advantages of Particle Swarm Optimization over Bayesian Optimization for hyperparameter tuning?
The answer is problem-dependent and cannot be given without additional context.
Typically, the answer would go as follows. Bayesian Optimization is more suitable for low-dimensional problems with the computational budget up to say 10x-100x the number of variables. PSO can be quite efficient for much larger budgets but is not state-of-the-art in its niche.
|
Advantages of Particle Swarm Optimization over Bayesian Optimization for hyperparameter tuning?
The answer is problem-dependent and cannot be given without additional context.
Typically, the answer would go as follows. Bayesian Optimization is more suitable for low-dimensional problems with the
|
13,280
|
Attainable correlations for lognormal random variables
|
I'll start by providing the definition of comonotonicity and countermonotonicity. Then, I'll mention why this is relevant to compute the minimum and maximum possible correlation coefficient between two random variables. And finally, I'll compute these bounds for the lognormal random variables $X_1$ and $X_2$.
Comonotonicity and countermonotonicity
The random variables $X_1, \ldots, X_d$ are said to be comonotonic if their copula is the Fréchet upper bound $M(u_1, \ldots, u_d) = \min(u_1, \ldots, u_d)$, which is the strongest type of "positive" dependence.
It can be shown that $X_1, \ldots, X_d$ are comonotonic if and only if
$$
(X_1, \ldots, X_d) \stackrel{\mathrm{d}}{=} (h_1(Z), \ldots, h_d(Z)),
$$
where $Z$ is some random variable, $h_1, \ldots, h_d$ are increasing functions, and
$\stackrel{\mathrm{d}}{=}$ denotes equality in distribution.
So, comonotonic random variables are only functions of a single random variable.
The random variables $X_1, X_2$ are said to be countermonotonic if their copula is the Fréchet lower bound $W(u_1, u_2) = \max(0, u_1 + u_2 - 1)$, which is the strongest type of "negative" dependence in the bivariate case. Countermonotonocity doesn't generalize to higher dimensions.
It can be shown that $X_1, X_2$ are countermonotonic if and only if
$$
(X_1, X_2) \stackrel{\mathrm{d}}{=} (h_1(Z), h_2(Z)),
$$
where $Z$ is some random variable, and $h_1$ and $h_2$ are respectively an increasing and a decreasing function, or vice versa.
Attainable correlation
Let $X_1$ and $X_2$ be two random variables with strictly positive and finite variances, and let $\rho_{\min}$ and $\rho_{\max}$ denote the minimum and maximum possible correlation coefficient between $X_1$ and $X_2$.
Then, it can be shown that
${\rm \rho}(X_1, X_2) = \rho_{\min}$ if and only if $X_1$ and $X_2$ are countermonotonic;
${\rm \rho}(X_1, X_2) = \rho_{\max}$ if and only if $X_1$ and $X_2$ are comonotonic.
Attainable correlation for lognormal random variables
To obtain $\rho_{\max}$ we use the fact that the maximum correlation is attained if and only if $X_1$ and $X_2$ are comonotonic. The random variables $X_1 = e^{Z}$ and $X_2 = e^{\sigma Z}$ where $Z \sim {\rm N} (0, 1)$ are comonotonic since the exponential function is a (strictly) increasing function, and thus $\rho_{\max} = {\rm corr} \left (e^Z, e^{\sigma Z} \right )$.
Using the properties of lognormal random variables, we have
${\rm E}(e^Z) = e^{1/2}$,
${\rm E}(e^{\sigma Z}) = e^{\sigma^2/2}$,
${\rm var}(e^Z) = e(e - 1)$,
${\rm var}(e^{\sigma Z}) = e^{\sigma^2}(e^{\sigma^2} - 1)$, and the covariance is
\begin{align}
{\rm cov}\left (e^Z, e^{\sigma Z}\right )
&= {\rm E}\left (e^{(\sigma + 1) Z}\right ) - {\rm E}\left (e^{\sigma Z}\right ){\rm E}\left (e^Z\right ) \\
&= e^{(\sigma + 1)^2/2} - e^{(\sigma^2 + 1)/2} \\
&= e^{(\sigma^2 + 1)/2} ( e^{\sigma} -1 ).
\end{align}
Thus,
\begin{align}
\rho_{\max}
& = \frac{ e^{(\sigma^2 + 1)/2} ( e^{\sigma} -1 ) }
{ \sqrt{ e(e - 1) e^{\sigma^2}(e^{\sigma^2} - 1) } } \\
& = \frac{ ( e^{\sigma} -1 ) }
{ \sqrt{ (e - 1) (e^{\sigma^2} - 1) } }.
\end{align}
Similar computations with $X_2 = e^{-\sigma Z}$ yield
\begin{align}
\rho_{\min}
& = \frac{ ( e^{-\sigma} -1 ) }
{ \sqrt{ (e - 1) (e^{\sigma^2} - 1) } }.
\end{align}
Comment
This example shows that it is possible to have a pair of random variable that are strongly dependent — comonotonicity and countermonotonicity are the strongest kind of dependence — but that have a very low correlation.
The following chart shows these bounds as a function of $\sigma$.
This is the R code I used to produce the above chart.
curve((exp(x)-1)/sqrt((exp(1) - 1)*(exp(x^2) - 1)), from = 0, to = 5,
ylim = c(-1, 1), col = 2, lwd = 2, main = "Lognormal attainable correlation",
xlab = expression(sigma), ylab = "Correlation", cex.lab = 1.2)
curve((exp(-x)-1)/sqrt((exp(1) - 1)*(exp(x^2) - 1)), col = 4, lwd = 2, add = TRUE)
legend(x = "bottomright", col = c(2, 4), lwd = c(2, 2), inset = 0.02,
legend = c("Correlation upper bound", "Correlation lower bound"))
abline(h = 0, lty = 2)
|
Attainable correlations for lognormal random variables
|
I'll start by providing the definition of comonotonicity and countermonotonicity. Then, I'll mention why this is relevant to compute the minimum and maximum possible correlation coefficient between tw
|
Attainable correlations for lognormal random variables
I'll start by providing the definition of comonotonicity and countermonotonicity. Then, I'll mention why this is relevant to compute the minimum and maximum possible correlation coefficient between two random variables. And finally, I'll compute these bounds for the lognormal random variables $X_1$ and $X_2$.
Comonotonicity and countermonotonicity
The random variables $X_1, \ldots, X_d$ are said to be comonotonic if their copula is the Fréchet upper bound $M(u_1, \ldots, u_d) = \min(u_1, \ldots, u_d)$, which is the strongest type of "positive" dependence.
It can be shown that $X_1, \ldots, X_d$ are comonotonic if and only if
$$
(X_1, \ldots, X_d) \stackrel{\mathrm{d}}{=} (h_1(Z), \ldots, h_d(Z)),
$$
where $Z$ is some random variable, $h_1, \ldots, h_d$ are increasing functions, and
$\stackrel{\mathrm{d}}{=}$ denotes equality in distribution.
So, comonotonic random variables are only functions of a single random variable.
The random variables $X_1, X_2$ are said to be countermonotonic if their copula is the Fréchet lower bound $W(u_1, u_2) = \max(0, u_1 + u_2 - 1)$, which is the strongest type of "negative" dependence in the bivariate case. Countermonotonocity doesn't generalize to higher dimensions.
It can be shown that $X_1, X_2$ are countermonotonic if and only if
$$
(X_1, X_2) \stackrel{\mathrm{d}}{=} (h_1(Z), h_2(Z)),
$$
where $Z$ is some random variable, and $h_1$ and $h_2$ are respectively an increasing and a decreasing function, or vice versa.
Attainable correlation
Let $X_1$ and $X_2$ be two random variables with strictly positive and finite variances, and let $\rho_{\min}$ and $\rho_{\max}$ denote the minimum and maximum possible correlation coefficient between $X_1$ and $X_2$.
Then, it can be shown that
${\rm \rho}(X_1, X_2) = \rho_{\min}$ if and only if $X_1$ and $X_2$ are countermonotonic;
${\rm \rho}(X_1, X_2) = \rho_{\max}$ if and only if $X_1$ and $X_2$ are comonotonic.
Attainable correlation for lognormal random variables
To obtain $\rho_{\max}$ we use the fact that the maximum correlation is attained if and only if $X_1$ and $X_2$ are comonotonic. The random variables $X_1 = e^{Z}$ and $X_2 = e^{\sigma Z}$ where $Z \sim {\rm N} (0, 1)$ are comonotonic since the exponential function is a (strictly) increasing function, and thus $\rho_{\max} = {\rm corr} \left (e^Z, e^{\sigma Z} \right )$.
Using the properties of lognormal random variables, we have
${\rm E}(e^Z) = e^{1/2}$,
${\rm E}(e^{\sigma Z}) = e^{\sigma^2/2}$,
${\rm var}(e^Z) = e(e - 1)$,
${\rm var}(e^{\sigma Z}) = e^{\sigma^2}(e^{\sigma^2} - 1)$, and the covariance is
\begin{align}
{\rm cov}\left (e^Z, e^{\sigma Z}\right )
&= {\rm E}\left (e^{(\sigma + 1) Z}\right ) - {\rm E}\left (e^{\sigma Z}\right ){\rm E}\left (e^Z\right ) \\
&= e^{(\sigma + 1)^2/2} - e^{(\sigma^2 + 1)/2} \\
&= e^{(\sigma^2 + 1)/2} ( e^{\sigma} -1 ).
\end{align}
Thus,
\begin{align}
\rho_{\max}
& = \frac{ e^{(\sigma^2 + 1)/2} ( e^{\sigma} -1 ) }
{ \sqrt{ e(e - 1) e^{\sigma^2}(e^{\sigma^2} - 1) } } \\
& = \frac{ ( e^{\sigma} -1 ) }
{ \sqrt{ (e - 1) (e^{\sigma^2} - 1) } }.
\end{align}
Similar computations with $X_2 = e^{-\sigma Z}$ yield
\begin{align}
\rho_{\min}
& = \frac{ ( e^{-\sigma} -1 ) }
{ \sqrt{ (e - 1) (e^{\sigma^2} - 1) } }.
\end{align}
Comment
This example shows that it is possible to have a pair of random variable that are strongly dependent — comonotonicity and countermonotonicity are the strongest kind of dependence — but that have a very low correlation.
The following chart shows these bounds as a function of $\sigma$.
This is the R code I used to produce the above chart.
curve((exp(x)-1)/sqrt((exp(1) - 1)*(exp(x^2) - 1)), from = 0, to = 5,
ylim = c(-1, 1), col = 2, lwd = 2, main = "Lognormal attainable correlation",
xlab = expression(sigma), ylab = "Correlation", cex.lab = 1.2)
curve((exp(-x)-1)/sqrt((exp(1) - 1)*(exp(x^2) - 1)), col = 4, lwd = 2, add = TRUE)
legend(x = "bottomright", col = c(2, 4), lwd = c(2, 2), inset = 0.02,
legend = c("Correlation upper bound", "Correlation lower bound"))
abline(h = 0, lty = 2)
|
Attainable correlations for lognormal random variables
I'll start by providing the definition of comonotonicity and countermonotonicity. Then, I'll mention why this is relevant to compute the minimum and maximum possible correlation coefficient between tw
|
13,281
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when $(x,y) \sim N(0,1)\times N(0,1)$?
|
You're referring to a transformation from a pair of independent variates $(X,Y)$ to the polar representation $(R,\theta)$ (radius and angle), and then looking at the marginal distribution of $\theta$.
I'm going to offer a somewhat intuitive explanation (though a mathematical derivation of the density does essentially what I describe informally).
Note that if you scale the two variables, X and Y by some common scale (e.g. go from U(-1,1) to U(-10,10) or from N(0,1) to N(0,20) on both variables at the same time) that makes no difference to the distribution of the angle (it only affects the scale of the distribution of the radius). So let's just consider the unit cases.
First consider what's going on with the uniform case. Note that the distribution is uniform over the unit square, so that the probability density in a region that's contained within $[-1,1]^2$ is proportional to the area of the region. Specifically, look at the density associated with an element of angle, $d\theta$ near the horizontal (near angle $\theta=0$) and on the diagonal (near angle $\theta=\pi/4$):
Clearly the probability element $df_\theta$ (i.e. area) corresponding to an element of angle ($d\theta$) is larger when the angle is near one of the diagonals. Indeed consider inscribing a circle inside the square; the area spanned by a given tiny angle within the circle is constant, and then the part outside the circle grows as we approach the diagonal, where it at its maximum.
This completely accounts for the pattern you see in the simulations.
Indeed, we can see that the density must be proportional to the length of the segment from the center of the square to its edge; simple trigonometry is sufficient to derive the density from there and then it's easy to find the constant required to make the density integrate to 1.
[Edit: added this next bit to discuss the radius, since the question has changed since my original answer.]
Note that if we had a uniform distribution over the unit circle (i.e. the one we inscribed in the square before) then the density of the radius for that would be proportional to the radius (consider the area of a small annular element of width $dr$ at radius $r$ - i.e. between $r$ and $r+dr$ - has area proportional to $r$). Then as we pass outside the circle, new annular regions with larger radius only get density contributions from the part in the square, so the density decreases (initially quite rapidly, then more slowly) between $1$ and $\sqrt 2$. (Again, fairly simple geometrical notions are sufficient to get the functional form of the density if it is needed.)
By contrast, if the joint distribution is rotationally symmetric about the origin then the probability element at some angle doesn't depend on the angle (this is essentially a tautology!). The bivariate distribution of two independent standard Gaussians is rotationally symmetric about the origin:
(code for this image based on Elan Cohen's code here but there's a nice alternative here, and something between the two here)
Consequently the volume contained in some angle $d\theta$ is the same for every $\theta$, so the density associated with the angle is uniform on $[0,2\pi)$.
[The polar trick typically used for integrating the normal density over the real line can be used to figure out that the density of the squared radius is negative exponential, and from there the density of the radius is simple to identify by a simple transformation argument from the distribution function]
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when
|
You're referring to a transformation from a pair of independent variates $(X,Y)$ to the polar representation $(R,\theta)$ (radius and angle), and then looking at the marginal distribution of $\theta$.
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when $(x,y) \sim N(0,1)\times N(0,1)$?
You're referring to a transformation from a pair of independent variates $(X,Y)$ to the polar representation $(R,\theta)$ (radius and angle), and then looking at the marginal distribution of $\theta$.
I'm going to offer a somewhat intuitive explanation (though a mathematical derivation of the density does essentially what I describe informally).
Note that if you scale the two variables, X and Y by some common scale (e.g. go from U(-1,1) to U(-10,10) or from N(0,1) to N(0,20) on both variables at the same time) that makes no difference to the distribution of the angle (it only affects the scale of the distribution of the radius). So let's just consider the unit cases.
First consider what's going on with the uniform case. Note that the distribution is uniform over the unit square, so that the probability density in a region that's contained within $[-1,1]^2$ is proportional to the area of the region. Specifically, look at the density associated with an element of angle, $d\theta$ near the horizontal (near angle $\theta=0$) and on the diagonal (near angle $\theta=\pi/4$):
Clearly the probability element $df_\theta$ (i.e. area) corresponding to an element of angle ($d\theta$) is larger when the angle is near one of the diagonals. Indeed consider inscribing a circle inside the square; the area spanned by a given tiny angle within the circle is constant, and then the part outside the circle grows as we approach the diagonal, where it at its maximum.
This completely accounts for the pattern you see in the simulations.
Indeed, we can see that the density must be proportional to the length of the segment from the center of the square to its edge; simple trigonometry is sufficient to derive the density from there and then it's easy to find the constant required to make the density integrate to 1.
[Edit: added this next bit to discuss the radius, since the question has changed since my original answer.]
Note that if we had a uniform distribution over the unit circle (i.e. the one we inscribed in the square before) then the density of the radius for that would be proportional to the radius (consider the area of a small annular element of width $dr$ at radius $r$ - i.e. between $r$ and $r+dr$ - has area proportional to $r$). Then as we pass outside the circle, new annular regions with larger radius only get density contributions from the part in the square, so the density decreases (initially quite rapidly, then more slowly) between $1$ and $\sqrt 2$. (Again, fairly simple geometrical notions are sufficient to get the functional form of the density if it is needed.)
By contrast, if the joint distribution is rotationally symmetric about the origin then the probability element at some angle doesn't depend on the angle (this is essentially a tautology!). The bivariate distribution of two independent standard Gaussians is rotationally symmetric about the origin:
(code for this image based on Elan Cohen's code here but there's a nice alternative here, and something between the two here)
Consequently the volume contained in some angle $d\theta$ is the same for every $\theta$, so the density associated with the angle is uniform on $[0,2\pi)$.
[The polar trick typically used for integrating the normal density over the real line can be used to figure out that the density of the squared radius is negative exponential, and from there the density of the radius is simple to identify by a simple transformation argument from the distribution function]
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when
You're referring to a transformation from a pair of independent variates $(X,Y)$ to the polar representation $(R,\theta)$ (radius and angle), and then looking at the marginal distribution of $\theta$.
|
13,282
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when $(x,y) \sim N(0,1)\times N(0,1)$?
|
To complete the fairly good answers given by Glen and Michael, I'll just compute the density of $\theta$ when the distribution of $(X,Y)$ is uniform on the square $[-1,1]\times[-1,1]$. This uniform density is $1 \over 4$ on this square, $0$ elsewhere -- that is, the probability of sampling a point in a given region of the square is $1 \over 4$ the area of this region.
The region of interest for our question is the red sector on this drawing:
It’s a triangle delimited by the angle $\theta$ and $\theta + d\theta$. The probability of sampling a point in this triangle is the probability of sampling a value between $\theta$ and $\theta + d\theta$ — which is the density of $\theta$.
I’ll make the computation for $\theta\in \left[ -{\pi \over 4}, {\pi\over 4}\right]$ -- the whole density can be obtained by extending it by $\pi\over 2$ periodicity.
Elementary trigonometry show that the lower side has length $1\over \cos\theta$. The upper size has length
$$ {1\over \cos(\theta + d\theta)} = {1\over \cos\theta} + {\sin \theta \over \cos^2\theta} d\theta.$$
(We’ll see that the precise value of the derivative doesn’t really matter here!)
Now the area of a triangle with two sides of lengthes $a$ and $b$ forming an angle $\alpha$ is ${1\over 2}ab\sin\alpha$, hence in our case
$$ {1\over 2} \left({1\over \cos\theta} \right) \left({1\over \cos\theta} + {\sin \theta \over \cos^2\theta} d\theta\right) \sin d\theta = {d\theta \over 2\cos^2 \theta}$$
(we neglect higher powers of $d\theta$ and use $\sin d \theta= d\theta$).
Thus the density of $\theta$ is
$$ {1\over 8 \cos^2 \theta}$$
for $\theta$ in $\left[-{\pi\over 4},{\pi\over 4}\right]$, and is $\pi\over 2$ periodic.
Verification:
x <- runif(1e6, -1, 1)
y <- runif(1e6, -1, 1)
hist( atan2(y,x), freq=FALSE, breaks=100)
theta <- seq(-pi, pi, length=500)
lines(theta, 0.125/cos((theta + pi/4)%%(pi/2) - pi/4)**2, col="red" )
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when
|
To complete the fairly good answers given by Glen and Michael, I'll just compute the density of $\theta$ when the distribution of $(X,Y)$ is uniform on the square $[-1,1]\times[-1,1]$. This uniform de
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when $(x,y) \sim N(0,1)\times N(0,1)$?
To complete the fairly good answers given by Glen and Michael, I'll just compute the density of $\theta$ when the distribution of $(X,Y)$ is uniform on the square $[-1,1]\times[-1,1]$. This uniform density is $1 \over 4$ on this square, $0$ elsewhere -- that is, the probability of sampling a point in a given region of the square is $1 \over 4$ the area of this region.
The region of interest for our question is the red sector on this drawing:
It’s a triangle delimited by the angle $\theta$ and $\theta + d\theta$. The probability of sampling a point in this triangle is the probability of sampling a value between $\theta$ and $\theta + d\theta$ — which is the density of $\theta$.
I’ll make the computation for $\theta\in \left[ -{\pi \over 4}, {\pi\over 4}\right]$ -- the whole density can be obtained by extending it by $\pi\over 2$ periodicity.
Elementary trigonometry show that the lower side has length $1\over \cos\theta$. The upper size has length
$$ {1\over \cos(\theta + d\theta)} = {1\over \cos\theta} + {\sin \theta \over \cos^2\theta} d\theta.$$
(We’ll see that the precise value of the derivative doesn’t really matter here!)
Now the area of a triangle with two sides of lengthes $a$ and $b$ forming an angle $\alpha$ is ${1\over 2}ab\sin\alpha$, hence in our case
$$ {1\over 2} \left({1\over \cos\theta} \right) \left({1\over \cos\theta} + {\sin \theta \over \cos^2\theta} d\theta\right) \sin d\theta = {d\theta \over 2\cos^2 \theta}$$
(we neglect higher powers of $d\theta$ and use $\sin d \theta= d\theta$).
Thus the density of $\theta$ is
$$ {1\over 8 \cos^2 \theta}$$
for $\theta$ in $\left[-{\pi\over 4},{\pi\over 4}\right]$, and is $\pi\over 2$ periodic.
Verification:
x <- runif(1e6, -1, 1)
y <- runif(1e6, -1, 1)
hist( atan2(y,x), freq=FALSE, breaks=100)
theta <- seq(-pi, pi, length=500)
lines(theta, 0.125/cos((theta + pi/4)%%(pi/2) - pi/4)**2, col="red" )
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when
To complete the fairly good answers given by Glen and Michael, I'll just compute the density of $\theta$ when the distribution of $(X,Y)$ is uniform on the square $[-1,1]\times[-1,1]$. This uniform de
|
13,283
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when $(x,y) \sim N(0,1)\times N(0,1)$?
|
I will answer the question about the normal case leading to the uniform distribution. It is well known that if $X$ and $Y$ are independent and normally distributed the contours of constant probability density is a circle in the $x-y$ plane. The radius $R= \sqrt{X^2+ Y^2}$ has the Rayleigh distribution. For a good discussion of this, see the Wikipedia article titled Rayleigh distribution.
Now let us look at the random variables $X$ and $Y$ using polar coordinates.
$X = r\cos(\theta)$, $Y = r \sin(\theta)$. note that $X^2 +Y^2= r^2$. If $\theta$ is uniform on $(0,2 \pi)$ and $r$ has a Rayleigh distribution $X$ and $Y$ will be independent normals each with $0$ mean and common variance. The converse is also true. The proof of the converse is what I think the OP wants as the answer to the second part of the question.
Here is a sketch of the proof. Without loss of generality, we can assume that $X$ is distributed $N(0,1)$ and $Y$ is distributed $N(0,1)$ and independent of each other.
Then the joint density $f(x,y) = (1/2 \pi)\exp[(-[x^2 +y^2])/2]$. Use the transformation to polar coordinates to get $g(r, \theta)$. Since $x = r \sin(\theta)$ and $y = r \cos(\theta)$. So $r= \sqrt{x^2 + y^2}$ and $\theta = \arctan(x/y)$. Compute the Jacobian of the transformation and make the appropriate substitution into $f(x,y)$. as a result $g(r, \theta)$ will be $r \exp[(-r^2)/(2 \pi)]$ for $r\geq0$ and $0\leq\theta\leq 2 \pi$. This shows that $r$ and theta are independent with $r$ having a Rayleigh distribution and theta has the constant density $1/(2 \pi)$.
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when
|
I will answer the question about the normal case leading to the uniform distribution. It is well known that if $X$ and $Y$ are independent and normally distributed the contours of constant probabilit
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when $(x,y) \sim N(0,1)\times N(0,1)$?
I will answer the question about the normal case leading to the uniform distribution. It is well known that if $X$ and $Y$ are independent and normally distributed the contours of constant probability density is a circle in the $x-y$ plane. The radius $R= \sqrt{X^2+ Y^2}$ has the Rayleigh distribution. For a good discussion of this, see the Wikipedia article titled Rayleigh distribution.
Now let us look at the random variables $X$ and $Y$ using polar coordinates.
$X = r\cos(\theta)$, $Y = r \sin(\theta)$. note that $X^2 +Y^2= r^2$. If $\theta$ is uniform on $(0,2 \pi)$ and $r$ has a Rayleigh distribution $X$ and $Y$ will be independent normals each with $0$ mean and common variance. The converse is also true. The proof of the converse is what I think the OP wants as the answer to the second part of the question.
Here is a sketch of the proof. Without loss of generality, we can assume that $X$ is distributed $N(0,1)$ and $Y$ is distributed $N(0,1)$ and independent of each other.
Then the joint density $f(x,y) = (1/2 \pi)\exp[(-[x^2 +y^2])/2]$. Use the transformation to polar coordinates to get $g(r, \theta)$. Since $x = r \sin(\theta)$ and $y = r \cos(\theta)$. So $r= \sqrt{x^2 + y^2}$ and $\theta = \arctan(x/y)$. Compute the Jacobian of the transformation and make the appropriate substitution into $f(x,y)$. as a result $g(r, \theta)$ will be $r \exp[(-r^2)/(2 \pi)]$ for $r\geq0$ and $0\leq\theta\leq 2 \pi$. This shows that $r$ and theta are independent with $r$ having a Rayleigh distribution and theta has the constant density $1/(2 \pi)$.
|
How is $\theta$, the polar coordinate, distributed when $(x,y) \sim U(-1,1) \times U(-1,1)$ vs. when
I will answer the question about the normal case leading to the uniform distribution. It is well known that if $X$ and $Y$ are independent and normally distributed the contours of constant probabilit
|
13,284
|
Is Correlation Transitive? [duplicate]
|
We may prove that if the correlations are sufficiently close to 1, then $X$ and $Z$ must be positively correlated.
Let’s assume $C(x,y)$ is the correlation coefficient between $x$ and $y$. Like wise we have $C(x,z)$ and $C(y,z)$. Here is an equation which comes from solving correlation equation mathematically :
$$C(x,y) = C(y,z) C(z,x) - \sqrt{ (1 - C(y,z)^2 ) (1 - C(z,x)^2 ) }$$
Now if we want C(x,y) to be more than zero , we basically want the RHS of above equation to be positive. Hence, you need to solve for :
$$C(y,z) C(z,x) > \sqrt{ (1 - C(y,z)^2 ) (1 - C(z,x)^2 ) }$$
We can actually solve the above equation for both C(y,z) > 0 and C(y,z) < 0 together by squaring both sides. This will finally give the result as C(x,y) is a non zero number if following equation holds true:
$$C(y,z) ^ 2 + C(z,x) ^ 2 > 1$$
Wow, this is an equation for a circle. Hence the following plot will explain everything :
If the two known correlation are in the A zone, the third correlation will be positive. If they lie in the B zone, the third correlation will be negative. Inside the circle, we cannot say anything about the relationship. A very interesting insight here is that even if $C(y,z)$ and $C(z,x)$ are 0.5, $C(x,y)$ can actually also be negative.
|
Is Correlation Transitive? [duplicate]
|
We may prove that if the correlations are sufficiently close to 1, then $X$ and $Z$ must be positively correlated.
Let’s assume $C(x,y)$ is the correlation coefficient between $x$ and $y$. Like wise w
|
Is Correlation Transitive? [duplicate]
We may prove that if the correlations are sufficiently close to 1, then $X$ and $Z$ must be positively correlated.
Let’s assume $C(x,y)$ is the correlation coefficient between $x$ and $y$. Like wise we have $C(x,z)$ and $C(y,z)$. Here is an equation which comes from solving correlation equation mathematically :
$$C(x,y) = C(y,z) C(z,x) - \sqrt{ (1 - C(y,z)^2 ) (1 - C(z,x)^2 ) }$$
Now if we want C(x,y) to be more than zero , we basically want the RHS of above equation to be positive. Hence, you need to solve for :
$$C(y,z) C(z,x) > \sqrt{ (1 - C(y,z)^2 ) (1 - C(z,x)^2 ) }$$
We can actually solve the above equation for both C(y,z) > 0 and C(y,z) < 0 together by squaring both sides. This will finally give the result as C(x,y) is a non zero number if following equation holds true:
$$C(y,z) ^ 2 + C(z,x) ^ 2 > 1$$
Wow, this is an equation for a circle. Hence the following plot will explain everything :
If the two known correlation are in the A zone, the third correlation will be positive. If they lie in the B zone, the third correlation will be negative. Inside the circle, we cannot say anything about the relationship. A very interesting insight here is that even if $C(y,z)$ and $C(z,x)$ are 0.5, $C(x,y)$ can actually also be negative.
|
Is Correlation Transitive? [duplicate]
We may prove that if the correlations are sufficiently close to 1, then $X$ and $Z$ must be positively correlated.
Let’s assume $C(x,y)$ is the correlation coefficient between $x$ and $y$. Like wise w
|
13,285
|
Is Correlation Transitive? [duplicate]
|
Here is a great post by Terence Tao on the topic. Words from the man himself:
I came across the (important) point that correlation is not necessarily transitive: if $X$ correlates with $Y$, and $Y$ correlates with $Z$, then this does not imply that $X$ correlates with $Z$.
|
Is Correlation Transitive? [duplicate]
|
Here is a great post by Terence Tao on the topic. Words from the man himself:
I came across the (important) point that correlation is not necessarily transitive: if $X$ correlates with $Y$, and $Y$
|
Is Correlation Transitive? [duplicate]
Here is a great post by Terence Tao on the topic. Words from the man himself:
I came across the (important) point that correlation is not necessarily transitive: if $X$ correlates with $Y$, and $Y$ correlates with $Z$, then this does not imply that $X$ correlates with $Z$.
|
Is Correlation Transitive? [duplicate]
Here is a great post by Terence Tao on the topic. Words from the man himself:
I came across the (important) point that correlation is not necessarily transitive: if $X$ correlates with $Y$, and $Y$
|
13,286
|
Why are “time series” called such?
|
Why is it "Time Series", not "Time Sequence"?
This inconsistency bugged me too the first time I saw it! But note that outside mathematics, people often use "series" to refer to what mathematicians might call a sequence.
For example, the Oxford English dictionary online gives the main definition of "series" as a "number of events, objects, or people of a similar or related kind coming one after another". This is what is happening in a time series: you have a sequence of observations coming one after the other. This is equivalent to the usage of the word in such phrases as "TV series" (one episode after another), "series circuit" (the current flows through each component successively), the World Series (a sequence of baseball games one after the other) and so on.
The etymology of "series" comes from the early 17th century, "from Latin, literally 'row, chain', from serere 'join, connect'", which is quite instructive. It didn't originally have the meaning of summation, but I can't find separate citations that establish when the word "series" was first used for the sum of the terms in a sequence. In fact it's quite common, particularly in older mathematics textbooks, to see the word "series" used where you might prefer "sequence", and "sum of series" where you might prefer "series". I don't know when this terminology was standardised in its present form. Here's an extract on arithmetic and geometric progressions from Daboll's Schoolmaster's assistant, improved and enlarged being a plain practical system of arithmetic: adapted to the United States - Nathan Daboll's 1814 update to his 1799 original Daboll's schoolmaster's assistant: being a plain, practical system of arithmetic, adapted to the United States, which was one of the most popular mathematics education books in the US throughout much of the 19th century.
The whole of Daboll's Schoolmaster's Assistant is available at archive.org and makes fascinating reading; it is the mathematics textbook that Herman Melville refers to in Moby-Dick (1851) and according to The Historical Roots of Elementary Mathematics by Bunt, Jones and Bedient (Dover Books, 1988) was predominant in American schools until 1850. At some point I may check some later standard texts; I do not think the hard distinction between "sequence" and "series" in mathematics arose until rather later.
Is time the independent variable?
This is basically the right idea: for instance when you plot a time series, we normally show the observations on the vertical axis while the horizontal axis represents time elapsed. And certainly it's true you wouldn't regard time as a dependent variable, since that would make no sense from a causation point of view. Your observations depend on time, and not vice versa.
But note that "time" is usually referred to by an index number to signify the position of the observation ($X_1, X_2, X_3, ...$) rather than by a particular year/date/time - we don't generally see things like $X_\text{1 Jan 1998}, X_\text{2 Jan 1998}, X_\text{3 Jan 1998},...$. Also the time series $X_1, X_2, X_3, ...$ is considered univariate, meaning "one variable". This is in contrast to performing a bivariate ("two variable") regression analysis of your observed values, $X$, against time, $t$. There you would consider your data set as built out of two variables $X_1, X_2, X_3, ...$ against $t_1, t_2, t_3, ...$. In a time series, time is generally represented just by the index number (position in the sequence), not a separate variable in its own right.
|
Why are “time series” called such?
|
Why is it "Time Series", not "Time Sequence"?
This inconsistency bugged me too the first time I saw it! But note that outside mathematics, people often use "series" to refer to what mathematicians mig
|
Why are “time series” called such?
Why is it "Time Series", not "Time Sequence"?
This inconsistency bugged me too the first time I saw it! But note that outside mathematics, people often use "series" to refer to what mathematicians might call a sequence.
For example, the Oxford English dictionary online gives the main definition of "series" as a "number of events, objects, or people of a similar or related kind coming one after another". This is what is happening in a time series: you have a sequence of observations coming one after the other. This is equivalent to the usage of the word in such phrases as "TV series" (one episode after another), "series circuit" (the current flows through each component successively), the World Series (a sequence of baseball games one after the other) and so on.
The etymology of "series" comes from the early 17th century, "from Latin, literally 'row, chain', from serere 'join, connect'", which is quite instructive. It didn't originally have the meaning of summation, but I can't find separate citations that establish when the word "series" was first used for the sum of the terms in a sequence. In fact it's quite common, particularly in older mathematics textbooks, to see the word "series" used where you might prefer "sequence", and "sum of series" where you might prefer "series". I don't know when this terminology was standardised in its present form. Here's an extract on arithmetic and geometric progressions from Daboll's Schoolmaster's assistant, improved and enlarged being a plain practical system of arithmetic: adapted to the United States - Nathan Daboll's 1814 update to his 1799 original Daboll's schoolmaster's assistant: being a plain, practical system of arithmetic, adapted to the United States, which was one of the most popular mathematics education books in the US throughout much of the 19th century.
The whole of Daboll's Schoolmaster's Assistant is available at archive.org and makes fascinating reading; it is the mathematics textbook that Herman Melville refers to in Moby-Dick (1851) and according to The Historical Roots of Elementary Mathematics by Bunt, Jones and Bedient (Dover Books, 1988) was predominant in American schools until 1850. At some point I may check some later standard texts; I do not think the hard distinction between "sequence" and "series" in mathematics arose until rather later.
Is time the independent variable?
This is basically the right idea: for instance when you plot a time series, we normally show the observations on the vertical axis while the horizontal axis represents time elapsed. And certainly it's true you wouldn't regard time as a dependent variable, since that would make no sense from a causation point of view. Your observations depend on time, and not vice versa.
But note that "time" is usually referred to by an index number to signify the position of the observation ($X_1, X_2, X_3, ...$) rather than by a particular year/date/time - we don't generally see things like $X_\text{1 Jan 1998}, X_\text{2 Jan 1998}, X_\text{3 Jan 1998},...$. Also the time series $X_1, X_2, X_3, ...$ is considered univariate, meaning "one variable". This is in contrast to performing a bivariate ("two variable") regression analysis of your observed values, $X$, against time, $t$. There you would consider your data set as built out of two variables $X_1, X_2, X_3, ...$ against $t_1, t_2, t_3, ...$. In a time series, time is generally represented just by the index number (position in the sequence), not a separate variable in its own right.
|
Why are “time series” called such?
Why is it "Time Series", not "Time Sequence"?
This inconsistency bugged me too the first time I saw it! But note that outside mathematics, people often use "series" to refer to what mathematicians mig
|
13,287
|
Why are “time series” called such?
|
"Series" is:
a group or a number of related or similar things
(http://dictionary.reference.com/browse/series)
a number of things or events that are arranged or happen one after the
other (http://www.merriam-webster.com/dictionary/series)
A number of objects or events arranged or coming one after the other
in succession (http://www.thefreedictionary.com/series)
A number of events, objects, or people of a similar or related kind
coming one after another
(http://www.oxforddictionaries.com/definition/english/series)
Time series is a sequence of values "coming one after another". Series does not have to be a sum like in mathematics.
|
Why are “time series” called such?
|
"Series" is:
a group or a number of related or similar things
(http://dictionary.reference.com/browse/series)
a number of things or events that are arranged or happen one after the
other (http://www.
|
Why are “time series” called such?
"Series" is:
a group or a number of related or similar things
(http://dictionary.reference.com/browse/series)
a number of things or events that are arranged or happen one after the
other (http://www.merriam-webster.com/dictionary/series)
A number of objects or events arranged or coming one after the other
in succession (http://www.thefreedictionary.com/series)
A number of events, objects, or people of a similar or related kind
coming one after another
(http://www.oxforddictionaries.com/definition/english/series)
Time series is a sequence of values "coming one after another". Series does not have to be a sum like in mathematics.
|
Why are “time series” called such?
"Series" is:
a group or a number of related or similar things
(http://dictionary.reference.com/browse/series)
a number of things or events that are arranged or happen one after the
other (http://www.
|
13,288
|
Why are “time series” called such?
|
The accepted answer is informative (I upvoted it myself), but it assumes that the "series" term in Time Series is really a misnomer and should be "sequence" instead. For the first few decades in the development of time series analysis, 1920s and 1930s, time series was synonymous with ARMA time series. An MA time series is indeed a sum of a sequence of white noise innovations. An AR time series, if covariance stationary, is also a sum of a sequence of white noise innovations. It may well be that the name "series" in time series was very appropriately assigned to time series, when these were synonymous with ARMA time series, but as other types of time series were discovered, which did not have a similar representation as a sum, nobody went back to revise the term because it's been used for decades and it may have just stuck in the statistics community. (https://www.statistics.su.se/english/research/time-series-analysis/a-brief-history-of-time-series-analysis-1.259451)
|
Why are “time series” called such?
|
The accepted answer is informative (I upvoted it myself), but it assumes that the "series" term in Time Series is really a misnomer and should be "sequence" instead. For the first few decades in the d
|
Why are “time series” called such?
The accepted answer is informative (I upvoted it myself), but it assumes that the "series" term in Time Series is really a misnomer and should be "sequence" instead. For the first few decades in the development of time series analysis, 1920s and 1930s, time series was synonymous with ARMA time series. An MA time series is indeed a sum of a sequence of white noise innovations. An AR time series, if covariance stationary, is also a sum of a sequence of white noise innovations. It may well be that the name "series" in time series was very appropriately assigned to time series, when these were synonymous with ARMA time series, but as other types of time series were discovered, which did not have a similar representation as a sum, nobody went back to revise the term because it's been used for decades and it may have just stuck in the statistics community. (https://www.statistics.su.se/english/research/time-series-analysis/a-brief-history-of-time-series-analysis-1.259451)
|
Why are “time series” called such?
The accepted answer is informative (I upvoted it myself), but it assumes that the "series" term in Time Series is really a misnomer and should be "sequence" instead. For the first few decades in the d
|
13,289
|
Calculating $R^2$ in mixed models using Nakagawa & Schielzeth's (2013) R2glmm method
|
I am answering by pasting Douglas Bates's reply in the R-Sig-ME mailing list, on 17 Dec 2014 on the question of how to calculate an $R^2$ statistic for generalized linear mixed models, which I believe is required reading for anyone interested in such a thing. Bates is the original author of the lme4package for R and co-author of nlme, as well as co-author of a well-known book on mixed models, and CV will benefit from having the text in an answer, rather than just a link to it.
I must admit to getting a little twitchy when people speak of the "R2 for
GLMMs". R2 for a linear model is well-defined and has many desirable
properties. For other models one can define different quantities that
reflect some but not all of these properties. But this is not calculating
an R2 in the sense of obtaining a number having all the properties that the
R2 for linear models does. Usually there are several different ways that
such a quantity could be defined. Especially for GLMs and GLMMs before you
can define "proportion of response variance explained" you first need to
define what you mean by "response variance". The whole point of GLMs and
GLMMs is that a simple sum of squares of deviations does not meaningfully
reflect the variability in the response because the variance of an
individual response depends on its mean.
Confusion about what constitutes R2 or degrees of freedom of any of the
other quantities associated with linear models as applied to other models
comes from confusing the formula with the concept. Although formulas are
derived from models the derivation often involves quite sophisticated
mathematics. To avoid a potentially confusing derivation and just "cut to
the chase" it is easier to present the formulas. But the formula is not
the concept. Generalizing a formula is not equivalent to generalizing the
concept. And those formulas are almost never used in practice, especially
for generalized linear models, analysis of variance and random effects. I
have a "meta-theorem" that the only quantity actually calculated according
to the formulas given in introductory texts is the sample mean.
It may seem that I am being a grumpy old man about this, and perhaps I am,
but the danger is that people expect an "R2-like" quantity to have all the
properties of an R2 for linear models. It can't. There is no way to
generalize all the properties to a much more complicated model like a GLMM.
I was once on the committee reviewing a thesis proposal for Ph.D.
candidacy. The proposal was to examine I think 9 different formulas that
could be considered ways of computing an R2 for a nonlinear regression
model to decide which one was "best". Of course, this would be done
through a simulation study with only a couple of different models and only
a few different sets of parameter values for each. My suggestion that this
was an entirely meaningless exercise was not greeted warmly.
|
Calculating $R^2$ in mixed models using Nakagawa & Schielzeth's (2013) R2glmm method
|
I am answering by pasting Douglas Bates's reply in the R-Sig-ME mailing list, on 17 Dec 2014 on the question of how to calculate an $R^2$ statistic for generalized linear mixed models, which I believe
|
Calculating $R^2$ in mixed models using Nakagawa & Schielzeth's (2013) R2glmm method
I am answering by pasting Douglas Bates's reply in the R-Sig-ME mailing list, on 17 Dec 2014 on the question of how to calculate an $R^2$ statistic for generalized linear mixed models, which I believe is required reading for anyone interested in such a thing. Bates is the original author of the lme4package for R and co-author of nlme, as well as co-author of a well-known book on mixed models, and CV will benefit from having the text in an answer, rather than just a link to it.
I must admit to getting a little twitchy when people speak of the "R2 for
GLMMs". R2 for a linear model is well-defined and has many desirable
properties. For other models one can define different quantities that
reflect some but not all of these properties. But this is not calculating
an R2 in the sense of obtaining a number having all the properties that the
R2 for linear models does. Usually there are several different ways that
such a quantity could be defined. Especially for GLMs and GLMMs before you
can define "proportion of response variance explained" you first need to
define what you mean by "response variance". The whole point of GLMs and
GLMMs is that a simple sum of squares of deviations does not meaningfully
reflect the variability in the response because the variance of an
individual response depends on its mean.
Confusion about what constitutes R2 or degrees of freedom of any of the
other quantities associated with linear models as applied to other models
comes from confusing the formula with the concept. Although formulas are
derived from models the derivation often involves quite sophisticated
mathematics. To avoid a potentially confusing derivation and just "cut to
the chase" it is easier to present the formulas. But the formula is not
the concept. Generalizing a formula is not equivalent to generalizing the
concept. And those formulas are almost never used in practice, especially
for generalized linear models, analysis of variance and random effects. I
have a "meta-theorem" that the only quantity actually calculated according
to the formulas given in introductory texts is the sample mean.
It may seem that I am being a grumpy old man about this, and perhaps I am,
but the danger is that people expect an "R2-like" quantity to have all the
properties of an R2 for linear models. It can't. There is no way to
generalize all the properties to a much more complicated model like a GLMM.
I was once on the committee reviewing a thesis proposal for Ph.D.
candidacy. The proposal was to examine I think 9 different formulas that
could be considered ways of computing an R2 for a nonlinear regression
model to decide which one was "best". Of course, this would be done
through a simulation study with only a couple of different models and only
a few different sets of parameter values for each. My suggestion that this
was an entirely meaningless exercise was not greeted warmly.
|
Calculating $R^2$ in mixed models using Nakagawa & Schielzeth's (2013) R2glmm method
I am answering by pasting Douglas Bates's reply in the R-Sig-ME mailing list, on 17 Dec 2014 on the question of how to calculate an $R^2$ statistic for generalized linear mixed models, which I believe
|
13,290
|
Calculating $R^2$ in mixed models using Nakagawa & Schielzeth's (2013) R2glmm method
|
After browsing the literature I came across the following paper which compares several different methods for calculating $R^2$ values for mixed models, where the $R^2$(MVP) methods is equivalent to the method proposed by Nakagawa and Schielzeth.
Lahuis, D et al (2014) Explained Variance Measures for Multilevel Models. Organizational Research Methods.
Overall, most of the measures (Formula , Formula , $R^2$ (OLS), and $R^2$ (MVP)) exhibited acceptable levels of bias, consistency, and efficiency across all conditions and models. In addition, the difference in mean bias values for these measures was small. Formula and Formula were the least biased in the random-intercept models and Formula and $R^2$ (MVP) were the least biased in the random-slope models. In terms of efficiency, the Formula and $R^2$ (MVP) had the lowest standard deviation values in the random-intercept model. $R^2$ (MVP) and $R^2$ (OLS) had the lowest standard deviations in the random-slope model. In general, Formula was not an efficient estimator.
|
Calculating $R^2$ in mixed models using Nakagawa & Schielzeth's (2013) R2glmm method
|
After browsing the literature I came across the following paper which compares several different methods for calculating $R^2$ values for mixed models, where the $R^2$(MVP) methods is equivalent to th
|
Calculating $R^2$ in mixed models using Nakagawa & Schielzeth's (2013) R2glmm method
After browsing the literature I came across the following paper which compares several different methods for calculating $R^2$ values for mixed models, where the $R^2$(MVP) methods is equivalent to the method proposed by Nakagawa and Schielzeth.
Lahuis, D et al (2014) Explained Variance Measures for Multilevel Models. Organizational Research Methods.
Overall, most of the measures (Formula , Formula , $R^2$ (OLS), and $R^2$ (MVP)) exhibited acceptable levels of bias, consistency, and efficiency across all conditions and models. In addition, the difference in mean bias values for these measures was small. Formula and Formula were the least biased in the random-intercept models and Formula and $R^2$ (MVP) were the least biased in the random-slope models. In terms of efficiency, the Formula and $R^2$ (MVP) had the lowest standard deviation values in the random-intercept model. $R^2$ (MVP) and $R^2$ (OLS) had the lowest standard deviations in the random-slope model. In general, Formula was not an efficient estimator.
|
Calculating $R^2$ in mixed models using Nakagawa & Schielzeth's (2013) R2glmm method
After browsing the literature I came across the following paper which compares several different methods for calculating $R^2$ values for mixed models, where the $R^2$(MVP) methods is equivalent to th
|
13,291
|
Ways to reduce high dimensional data for visualization
|
I had some seven-dimensional data myself. Although I finally settled for a small selection of 3-dimensional slice-throughs, one option is the Parallel Coordinates Plot. This works for an arbitrary number of dimensions! From Wikipedia:
Parallel coordinates is a common way of visualizing high-dimensional geometry and analyzing multivariate data.
To show a set of points in an n-dimensional space, a backdrop is drawn consisting of n parallel lines, typically vertical and equally spaced. A point in n-dimensional space is represented as a polyline with vertices on the parallel axes; the position of the vertex on the ith axis corresponds to the ith coordinate of the point.
|
Ways to reduce high dimensional data for visualization
|
I had some seven-dimensional data myself. Although I finally settled for a small selection of 3-dimensional slice-throughs, one option is the Parallel Coordinates Plot. This works for an arbitrary num
|
Ways to reduce high dimensional data for visualization
I had some seven-dimensional data myself. Although I finally settled for a small selection of 3-dimensional slice-throughs, one option is the Parallel Coordinates Plot. This works for an arbitrary number of dimensions! From Wikipedia:
Parallel coordinates is a common way of visualizing high-dimensional geometry and analyzing multivariate data.
To show a set of points in an n-dimensional space, a backdrop is drawn consisting of n parallel lines, typically vertical and equally spaced. A point in n-dimensional space is represented as a polyline with vertices on the parallel axes; the position of the vertex on the ith axis corresponds to the ith coordinate of the point.
|
Ways to reduce high dimensional data for visualization
I had some seven-dimensional data myself. Although I finally settled for a small selection of 3-dimensional slice-throughs, one option is the Parallel Coordinates Plot. This works for an arbitrary num
|
13,292
|
Ways to reduce high dimensional data for visualization
|
Pairs plots: This is not a method of dimensionality reduction, but it is a really good way to get a quick overview of where some meaningful relationships might lie. In R, the base package contains the pairs() function, which is good for continuous data (it converts everything to continuous). A better function is ggpairs(), from the GGally package:
library(GGally)
ggpairs(iris, colour='Species')
|
Ways to reduce high dimensional data for visualization
|
Pairs plots: This is not a method of dimensionality reduction, but it is a really good way to get a quick overview of where some meaningful relationships might lie. In R, the base package contains the
|
Ways to reduce high dimensional data for visualization
Pairs plots: This is not a method of dimensionality reduction, but it is a really good way to get a quick overview of where some meaningful relationships might lie. In R, the base package contains the pairs() function, which is good for continuous data (it converts everything to continuous). A better function is ggpairs(), from the GGally package:
library(GGally)
ggpairs(iris, colour='Species')
|
Ways to reduce high dimensional data for visualization
Pairs plots: This is not a method of dimensionality reduction, but it is a really good way to get a quick overview of where some meaningful relationships might lie. In R, the base package contains the
|
13,293
|
Ways to reduce high dimensional data for visualization
|
Principal Component Analysis is generally a good choice for dimension reduction in most cases, I am not sure it will suit for your particular problem, but it will find the orthogonal dimensions along which most variation of data samples are captured. If you develop in R, you can use prcomp() to simply convert your original matrix of data points to the PCA form.
|
Ways to reduce high dimensional data for visualization
|
Principal Component Analysis is generally a good choice for dimension reduction in most cases, I am not sure it will suit for your particular problem, but it will find the orthogonal dimensions along
|
Ways to reduce high dimensional data for visualization
Principal Component Analysis is generally a good choice for dimension reduction in most cases, I am not sure it will suit for your particular problem, but it will find the orthogonal dimensions along which most variation of data samples are captured. If you develop in R, you can use prcomp() to simply convert your original matrix of data points to the PCA form.
|
Ways to reduce high dimensional data for visualization
Principal Component Analysis is generally a good choice for dimension reduction in most cases, I am not sure it will suit for your particular problem, but it will find the orthogonal dimensions along
|
13,294
|
Ways to reduce high dimensional data for visualization
|
Here are a couple of ways of portraying 3-D data with ggplot2. You can combine approaches (facet grids, colors, shapes, etc.) to increase the dimensionality of your graphic.
doInstall <- TRUE # Change to FALSE if you don't want packages installed.
toInstall <- c("ggplot2")
if(doInstall){install.packages(toInstall, repos = "http://cran.r-project.org")}
lapply(toInstall, library, character.only = TRUE)
# Air passenger data. ts converted to long matrix:
myData <- data.frame(Year = c(floor(time(AirPassengers) + .01)),
Month = c(cycle(AirPassengers)),
Value = c(AirPassengers))
# Easy conversion code from: http://stackoverflow.com/a/4973859/479554
# Convert month numbers to names, using a built-in constant:
myData$Month <- factor(myData$Month)
levels(myData$Month) <- month.abb
# One possibility:
zp1 <- ggplot(myData,
aes(x = Year, y = Value, colour = Month))
zp1 <- zp1 + geom_line()
print(zp1) # This is fine, if you can differentiate between the colors
# Another possibility:
zp2 <- ggplot(myData,
aes(x = Year, y = Value))
zp2 <- zp2 + geom_line()
zp2 <- zp2 + facet_wrap(~ Month)
print(zp2) # This is fine, but it's hard to compare across facets
# A third possibility; plotting reference lines across each facet:
referenceLines <- myData # \/ Rename
colnames(referenceLines)[2] <- "groupVar"
zp3 <- ggplot(myData,
aes(x = Year, y = Value))
zp3 <- zp3 + geom_line(data = referenceLines, # Plotting the "underlayer"
aes(x = Year, y = Value, group = groupVar),
colour = "GRAY", alpha = 1/2, size = 1/2)
zp3 <- zp3 + geom_line(size = 1) # Drawing the "overlayer"
zp3 <- zp3 + facet_wrap(~ Month)
zp3 <- zp3 + theme_bw()
print(zp3)
|
Ways to reduce high dimensional data for visualization
|
Here are a couple of ways of portraying 3-D data with ggplot2. You can combine approaches (facet grids, colors, shapes, etc.) to increase the dimensionality of your graphic.
doInstall <- TRUE # Chang
|
Ways to reduce high dimensional data for visualization
Here are a couple of ways of portraying 3-D data with ggplot2. You can combine approaches (facet grids, colors, shapes, etc.) to increase the dimensionality of your graphic.
doInstall <- TRUE # Change to FALSE if you don't want packages installed.
toInstall <- c("ggplot2")
if(doInstall){install.packages(toInstall, repos = "http://cran.r-project.org")}
lapply(toInstall, library, character.only = TRUE)
# Air passenger data. ts converted to long matrix:
myData <- data.frame(Year = c(floor(time(AirPassengers) + .01)),
Month = c(cycle(AirPassengers)),
Value = c(AirPassengers))
# Easy conversion code from: http://stackoverflow.com/a/4973859/479554
# Convert month numbers to names, using a built-in constant:
myData$Month <- factor(myData$Month)
levels(myData$Month) <- month.abb
# One possibility:
zp1 <- ggplot(myData,
aes(x = Year, y = Value, colour = Month))
zp1 <- zp1 + geom_line()
print(zp1) # This is fine, if you can differentiate between the colors
# Another possibility:
zp2 <- ggplot(myData,
aes(x = Year, y = Value))
zp2 <- zp2 + geom_line()
zp2 <- zp2 + facet_wrap(~ Month)
print(zp2) # This is fine, but it's hard to compare across facets
# A third possibility; plotting reference lines across each facet:
referenceLines <- myData # \/ Rename
colnames(referenceLines)[2] <- "groupVar"
zp3 <- ggplot(myData,
aes(x = Year, y = Value))
zp3 <- zp3 + geom_line(data = referenceLines, # Plotting the "underlayer"
aes(x = Year, y = Value, group = groupVar),
colour = "GRAY", alpha = 1/2, size = 1/2)
zp3 <- zp3 + geom_line(size = 1) # Drawing the "overlayer"
zp3 <- zp3 + facet_wrap(~ Month)
zp3 <- zp3 + theme_bw()
print(zp3)
|
Ways to reduce high dimensional data for visualization
Here are a couple of ways of portraying 3-D data with ggplot2. You can combine approaches (facet grids, colors, shapes, etc.) to increase the dimensionality of your graphic.
doInstall <- TRUE # Chang
|
13,295
|
Ways to reduce high dimensional data for visualization
|
For the two-dimensional problem, I wonder if you could plot a map of your trace points with some symbol at the (x,y) coordinates. Then this symbol would either change color or oscillate around its fixed position (corresponding to $p=p_{mean}$ for example). I can see both being relatively easy to do in matplotlib. The one where the symbol oscillate makes me think of a raster plot like this one:
This plot shows the velocity profiles at different axial locations, giving you a 2D map of the flowfield. The vertical lines represent 0 velocity. The regions without dots are not part of the computational domain. Of course this is not easily extensible to 3D data...
|
Ways to reduce high dimensional data for visualization
|
For the two-dimensional problem, I wonder if you could plot a map of your trace points with some symbol at the (x,y) coordinates. Then this symbol would either change color or oscillate around its fix
|
Ways to reduce high dimensional data for visualization
For the two-dimensional problem, I wonder if you could plot a map of your trace points with some symbol at the (x,y) coordinates. Then this symbol would either change color or oscillate around its fixed position (corresponding to $p=p_{mean}$ for example). I can see both being relatively easy to do in matplotlib. The one where the symbol oscillate makes me think of a raster plot like this one:
This plot shows the velocity profiles at different axial locations, giving you a 2D map of the flowfield. The vertical lines represent 0 velocity. The regions without dots are not part of the computational domain. Of course this is not easily extensible to 3D data...
|
Ways to reduce high dimensional data for visualization
For the two-dimensional problem, I wonder if you could plot a map of your trace points with some symbol at the (x,y) coordinates. Then this symbol would either change color or oscillate around its fix
|
13,296
|
Constrained linear regression through a specified point
|
If $(x_0,y_0)$ is the point through which the regression line must pass, fit the model $y−y_0=\beta (x−x_0)+\varepsilon$, i.e., a linear regression with "no intercept" on a translated data set. In $R$, this might look like lm( I(y-y0) ~ I(x-x0) + 0). Note the + 0 at the end which indicates to lm that no intercept term should be fit.
Depending on how easily you are convinced, there are multiple ways to demonstrate that this does, indeed, yield the correct answer. If you want to establish it formally, one simple method is to use Lagrange multipliers.
Whether or not it is actually a good idea to force a regression line to go through a particular point is a separate matter and is problem dependent. Generally, I would personally caution against this, unless there is a very good reason (e.g., very strong theoretical considerations). For one thing, fitting the full model can provide a means for measuring lack of fit. As a second matter, if you are mostly interested in evaluating model explanatory power for values of $x$ and $y$ "far away" from $(x_0,y_0)$, then the relevance of the fixed point becomes suspect.
|
Constrained linear regression through a specified point
|
If $(x_0,y_0)$ is the point through which the regression line must pass, fit the model $y−y_0=\beta (x−x_0)+\varepsilon$, i.e., a linear regression with "no intercept" on a translated data set. In $R$
|
Constrained linear regression through a specified point
If $(x_0,y_0)$ is the point through which the regression line must pass, fit the model $y−y_0=\beta (x−x_0)+\varepsilon$, i.e., a linear regression with "no intercept" on a translated data set. In $R$, this might look like lm( I(y-y0) ~ I(x-x0) + 0). Note the + 0 at the end which indicates to lm that no intercept term should be fit.
Depending on how easily you are convinced, there are multiple ways to demonstrate that this does, indeed, yield the correct answer. If you want to establish it formally, one simple method is to use Lagrange multipliers.
Whether or not it is actually a good idea to force a regression line to go through a particular point is a separate matter and is problem dependent. Generally, I would personally caution against this, unless there is a very good reason (e.g., very strong theoretical considerations). For one thing, fitting the full model can provide a means for measuring lack of fit. As a second matter, if you are mostly interested in evaluating model explanatory power for values of $x$ and $y$ "far away" from $(x_0,y_0)$, then the relevance of the fixed point becomes suspect.
|
Constrained linear regression through a specified point
If $(x_0,y_0)$ is the point through which the regression line must pass, fit the model $y−y_0=\beta (x−x_0)+\varepsilon$, i.e., a linear regression with "no intercept" on a translated data set. In $R$
|
13,297
|
Changing null hypothesis in linear regression
|
set.seed(20); y = rnorm(20); x = y + rnorm(20, 0, 0.2) # generate correlated data
summary(lm(y ~ x)) # original model
summary(lm(y ~ x, offset= 1.00*x)) # testing against slope=1
summary(lm(y-x ~ x)) # testing against slope=1
Outputs:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.01532 0.04728 0.324 0.75
x 0.91424 0.04128 22.148 1.64e-14 ***
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.01532 0.04728 0.324 0.7497
x -0.08576 0.04128 -2.078 0.0523 .
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.01532 0.04728 0.324 0.7497
x -0.08576 0.04128 -2.078 0.0523 .
|
Changing null hypothesis in linear regression
|
set.seed(20); y = rnorm(20); x = y + rnorm(20, 0, 0.2) # generate correlated data
summary(lm(y ~ x)) # original model
summary(lm(y ~ x, offset= 1.00*x)) # testing against slope=1
sum
|
Changing null hypothesis in linear regression
set.seed(20); y = rnorm(20); x = y + rnorm(20, 0, 0.2) # generate correlated data
summary(lm(y ~ x)) # original model
summary(lm(y ~ x, offset= 1.00*x)) # testing against slope=1
summary(lm(y-x ~ x)) # testing against slope=1
Outputs:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.01532 0.04728 0.324 0.75
x 0.91424 0.04128 22.148 1.64e-14 ***
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.01532 0.04728 0.324 0.7497
x -0.08576 0.04128 -2.078 0.0523 .
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.01532 0.04728 0.324 0.7497
x -0.08576 0.04128 -2.078 0.0523 .
|
Changing null hypothesis in linear regression
set.seed(20); y = rnorm(20); x = y + rnorm(20, 0, 0.2) # generate correlated data
summary(lm(y ~ x)) # original model
summary(lm(y ~ x, offset= 1.00*x)) # testing against slope=1
sum
|
13,298
|
Changing null hypothesis in linear regression
|
Your hypothesis can be expressed as $R\beta=r$ where $\beta$ is your regression coefficients and $R$ is restriction matrix with $r$ the restrictions. If our model is
$$y=\beta_0+\beta_1x+u$$
then for hypothesis $\beta_1=0$, $R=[0,1]$ and $r=1$.
For these type of hypotheses you can use linearHypothesis function from package car:
set.seed(20); y = rnorm(20); x = y + rnorm(20, 0, 0.2) # generate correlated data
mod <- lm(y ~ x)) # original model
> linearHypothesis(mod,matrix(c(0,1),nrow=1),rhs=c(1))
Linear hypothesis test
Hypothesis:
x = 1
Model 1: restricted model
Model 2: y ~ x
Res.Df RSS Df Sum of Sq F Pr(>F)
1 19 0.96022
2 18 0.77450 1 0.18572 4.3162 0.05234 .
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
|
Changing null hypothesis in linear regression
|
Your hypothesis can be expressed as $R\beta=r$ where $\beta$ is your regression coefficients and $R$ is restriction matrix with $r$ the restrictions. If our model is
$$y=\beta_0+\beta_1x+u$$
then for
|
Changing null hypothesis in linear regression
Your hypothesis can be expressed as $R\beta=r$ where $\beta$ is your regression coefficients and $R$ is restriction matrix with $r$ the restrictions. If our model is
$$y=\beta_0+\beta_1x+u$$
then for hypothesis $\beta_1=0$, $R=[0,1]$ and $r=1$.
For these type of hypotheses you can use linearHypothesis function from package car:
set.seed(20); y = rnorm(20); x = y + rnorm(20, 0, 0.2) # generate correlated data
mod <- lm(y ~ x)) # original model
> linearHypothesis(mod,matrix(c(0,1),nrow=1),rhs=c(1))
Linear hypothesis test
Hypothesis:
x = 1
Model 1: restricted model
Model 2: y ~ x
Res.Df RSS Df Sum of Sq F Pr(>F)
1 19 0.96022
2 18 0.77450 1 0.18572 4.3162 0.05234 .
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
|
Changing null hypothesis in linear regression
Your hypothesis can be expressed as $R\beta=r$ where $\beta$ is your regression coefficients and $R$ is restriction matrix with $r$ the restrictions. If our model is
$$y=\beta_0+\beta_1x+u$$
then for
|
13,299
|
Changing null hypothesis in linear regression
|
It seems you're still trying to reject a null hypothesis. There are loads of problems with that, not the least of which is that it's possible that you don't have enough power to see that you're different from 1. It sounds like you don't care that the slope is 0.07 different from 1. But what if you can't really tell? What if you're actually estimating a slope that varies wildly and may actually be quite far from 1 with something like a confidence interval of ±0.4. Your best tactic here is not changing the null hypothesis but actually speaking reasonably about an interval estimate. If you apply the command confint() to your model you can get a 95% confidence interval around your slope. Then you can use this to discuss the slope you did get. If 1 is within the confidence interval you can state that it is within the range of values you believe likely to contain the true value. But more importantly you can also state what that range of values is.
|
Changing null hypothesis in linear regression
|
It seems you're still trying to reject a null hypothesis. There are loads of problems with that, not the least of which is that it's possible that you don't have enough power to see that you're diffe
|
Changing null hypothesis in linear regression
It seems you're still trying to reject a null hypothesis. There are loads of problems with that, not the least of which is that it's possible that you don't have enough power to see that you're different from 1. It sounds like you don't care that the slope is 0.07 different from 1. But what if you can't really tell? What if you're actually estimating a slope that varies wildly and may actually be quite far from 1 with something like a confidence interval of ±0.4. Your best tactic here is not changing the null hypothesis but actually speaking reasonably about an interval estimate. If you apply the command confint() to your model you can get a 95% confidence interval around your slope. Then you can use this to discuss the slope you did get. If 1 is within the confidence interval you can state that it is within the range of values you believe likely to contain the true value. But more importantly you can also state what that range of values is.
|
Changing null hypothesis in linear regression
It seems you're still trying to reject a null hypothesis. There are loads of problems with that, not the least of which is that it's possible that you don't have enough power to see that you're diffe
|
13,300
|
Changing null hypothesis in linear regression
|
The point of testing is that you want to reject your null hypothesis, not confirm it. The fact that there is no significant difference, is in no way a proof of the absence of a significant difference. For that, you'll have to define what effect size you deem reasonable to reject the null.
Testing whether your slope is significantly different from 1 is not that difficult, you just test whether the difference $slope - 1$ differs significantly from zero. By hand this would be something like :
set.seed(20); y = rnorm(20); x = y + rnorm(20, 0, 0.2)
model <- lm(y~x)
coefx <- coef(summary(model))[2,1]
seslope <- coef(summary(model))[2,2]
DF <- model$df.residual
# normal test
p <- (1 - pt(coefx/seslope,DF) )*2
# test whether different from 1
p2 <- (1 - pt(abs(coefx-1)/seslope,DF) )*2
Now you should be aware of the fact that the effect size for which a difference becomes significant, is
> qt(0.975,DF)*seslope
[1] 0.08672358
provided that we have a decent estimator of the standard error on the slope. Hence, if you decide that a significant difference should only be detected from 0.1, you can calculate the necessary DF as follows :
optimize(
function(x)abs(qt(0.975,x)*seslope - 0.1),
interval=c(5,500)
)
$minimum
[1] 6.2593
Mind you, this is pretty dependent on the estimate of the seslope. To get a better estimate on seslope, you could do a resampling of your data. A naive way would be :
n <- length(y)
seslope2 <-
mean(
replicate(n,{
id <- sample(seq.int(n),1)
model <- lm(y[-id]~x[-id])
coef(summary(model))[2,2]
})
)
putting seslope2 in the optimization function, returns :
$minimum
[1] 6.954609
All this will tell you that your dataset will return a significant result faster than you deem necessary, and that you only need 7 degrees of freedom (in this case 9 observations) if you want to be sure that non-significant means what you want it means.
|
Changing null hypothesis in linear regression
|
The point of testing is that you want to reject your null hypothesis, not confirm it. The fact that there is no significant difference, is in no way a proof of the absence of a significant difference.
|
Changing null hypothesis in linear regression
The point of testing is that you want to reject your null hypothesis, not confirm it. The fact that there is no significant difference, is in no way a proof of the absence of a significant difference. For that, you'll have to define what effect size you deem reasonable to reject the null.
Testing whether your slope is significantly different from 1 is not that difficult, you just test whether the difference $slope - 1$ differs significantly from zero. By hand this would be something like :
set.seed(20); y = rnorm(20); x = y + rnorm(20, 0, 0.2)
model <- lm(y~x)
coefx <- coef(summary(model))[2,1]
seslope <- coef(summary(model))[2,2]
DF <- model$df.residual
# normal test
p <- (1 - pt(coefx/seslope,DF) )*2
# test whether different from 1
p2 <- (1 - pt(abs(coefx-1)/seslope,DF) )*2
Now you should be aware of the fact that the effect size for which a difference becomes significant, is
> qt(0.975,DF)*seslope
[1] 0.08672358
provided that we have a decent estimator of the standard error on the slope. Hence, if you decide that a significant difference should only be detected from 0.1, you can calculate the necessary DF as follows :
optimize(
function(x)abs(qt(0.975,x)*seslope - 0.1),
interval=c(5,500)
)
$minimum
[1] 6.2593
Mind you, this is pretty dependent on the estimate of the seslope. To get a better estimate on seslope, you could do a resampling of your data. A naive way would be :
n <- length(y)
seslope2 <-
mean(
replicate(n,{
id <- sample(seq.int(n),1)
model <- lm(y[-id]~x[-id])
coef(summary(model))[2,2]
})
)
putting seslope2 in the optimization function, returns :
$minimum
[1] 6.954609
All this will tell you that your dataset will return a significant result faster than you deem necessary, and that you only need 7 degrees of freedom (in this case 9 observations) if you want to be sure that non-significant means what you want it means.
|
Changing null hypothesis in linear regression
The point of testing is that you want to reject your null hypothesis, not confirm it. The fact that there is no significant difference, is in no way a proof of the absence of a significant difference.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.