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
|
|---|---|---|---|---|---|---|
7,101
|
Are all simulation methods some form of Monte Carlo?
|
There are superb answer though, Feynman's landmark paper, that also touches upon what is a "simulation" from quantum perspective, really worth mentioning here: Simulating physics with computers.
are all simulation methods in essence Monte Carlo methods?
Feynman distinguishes 3 types of simulations: (1) Simulating time (2) Simulating probabilities (3) And simulating quantum states. Putting simulating quantum states a side as physics question. Actually (1) & (2) might be only realistically simulated by only Monte Carlo methods, i.e., the methods relying on law of large numbers (ergodicity) in randomised fashion. Even if we consider, classical molecular dynamics, i.e., generating deterministic trajectories, the simulated observables in this case relies on ergodicity. Hence, the entire point of doing simulation again boils down to computing probabilistic objects (observables) out of these deterministically generated trajectories. Consequently, usefulness of "non Monte Carlo" simulations are again achieved by Monte Carlo type methods.
|
Are all simulation methods some form of Monte Carlo?
|
There are superb answer though, Feynman's landmark paper, that also touches upon what is a "simulation" from quantum perspective, really worth mentioning here: Simulating physics with computers.
are
|
Are all simulation methods some form of Monte Carlo?
There are superb answer though, Feynman's landmark paper, that also touches upon what is a "simulation" from quantum perspective, really worth mentioning here: Simulating physics with computers.
are all simulation methods in essence Monte Carlo methods?
Feynman distinguishes 3 types of simulations: (1) Simulating time (2) Simulating probabilities (3) And simulating quantum states. Putting simulating quantum states a side as physics question. Actually (1) & (2) might be only realistically simulated by only Monte Carlo methods, i.e., the methods relying on law of large numbers (ergodicity) in randomised fashion. Even if we consider, classical molecular dynamics, i.e., generating deterministic trajectories, the simulated observables in this case relies on ergodicity. Hence, the entire point of doing simulation again boils down to computing probabilistic objects (observables) out of these deterministically generated trajectories. Consequently, usefulness of "non Monte Carlo" simulations are again achieved by Monte Carlo type methods.
|
Are all simulation methods some form of Monte Carlo?
There are superb answer though, Feynman's landmark paper, that also touches upon what is a "simulation" from quantum perspective, really worth mentioning here: Simulating physics with computers.
are
|
7,102
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an increase in Type I errors?
|
Certainly you can go on fishing expeditions, as long as you admit that it's a fishing expedition and treat it as such. A nicer name for such is "exploratory data analysis".
A better analogy might be shooting at a target:
You can shoot at a target and celebrate if you hit the bulls eye.
You can shoot without a target in order to test the properties of your gun.
But it's cheating to shoot at a wall and then paint a target around the bullet hole.
One way to avoid some of the problems with this is to do the exploration in a training data set and then test it on a separate "test" data set.
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an i
|
Certainly you can go on fishing expeditions, as long as you admit that it's a fishing expedition and treat it as such. A nicer name for such is "exploratory data analysis".
A better analogy might be
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an increase in Type I errors?
Certainly you can go on fishing expeditions, as long as you admit that it's a fishing expedition and treat it as such. A nicer name for such is "exploratory data analysis".
A better analogy might be shooting at a target:
You can shoot at a target and celebrate if you hit the bulls eye.
You can shoot without a target in order to test the properties of your gun.
But it's cheating to shoot at a wall and then paint a target around the bullet hole.
One way to avoid some of the problems with this is to do the exploration in a training data set and then test it on a separate "test" data set.
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an i
Certainly you can go on fishing expeditions, as long as you admit that it's a fishing expedition and treat it as such. A nicer name for such is "exploratory data analysis".
A better analogy might be
|
7,103
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an increase in Type I errors?
|
The problem with fishing expeditions is this: if you test enough hypotheses, one of them will be confirmed with a low p value. Let me give a concrete example.
Imagine you have are doing an epidemiological study. You have found 1000 patients that suffer from a rare condition. You want to know what they have in common. So you start testing - you want to see whether a particular characteristic is overrepresented in this sample. Initially you test for gender, race, certain pertinent family history (father died of heart disease before age 50, …) but eventually, as you are having trouble finding anything that "sticks", you start to add all kinds of other factors that just might relate to the disease:
is vegetarian
has traveled to Canada
finished college
is married
has children
has cats
has dogs
drinks at least 5 glasses of red wine per week
…
Now here is the thing. If I select enough "random" hypotheses, it starts to become likely that at least one of these will result in a p value less than 0.05 - because the very essence of p value is "the probability of being wrong to reject the null hypothesis when there is no effect". Put differently - on average, for every 20 bogus hypotheses you test, one of them will give you a p of < 0.05.
This is SO very well summarized in the XKCD cartoon http://xkcd.com/882/ :
The tragedy is that even if an individual author does not perform 20 different hypothesis tests on a sample in order to look for significance, there might be 19 other authors doing the same thing; and the one who "finds" a correlation now has an interesting paper to write, and one that is likely to get accepted for publication…
This leads to an unfortunate tendency for irreproducible findings. The best way to guard against this as an individual author is to set the bar higher. Instead of testing for the individual factor, ask yourself "if I test N hypotheses, what is the probability of coming up with at least one false positive". When you are really testing "fishing hypotheses" you could think about making a Bonferroni correction to guard against this - but people frequently don't.
There were some interesting papers by Dr Ioannides - profiled in the Atlantic Monthly specifically on this subject.
See also this earlier question with several insightful answers.
update to better respond to all aspects of your question:
If you are afraid you might be "fishing", but you really don't know what hypothesis to formulate, you could definitely split your data in "exploration", "replication" and "confirmation" sections. In principle this should limit your exposure to the risks outlined earlier: if you have a p value of 0.05 in the exploration data and you get a similar value in the replication and confirmation data, your risk of being wrong drops. A nice example of "doing it right" was shown in the British Medical Journal (a very respected publication with an Impact Factor of 17+)
Exploration and confirmation of factors associated with uncomplicated pregnancy in nulliparous women: prospective cohort study, Chappell et al
Here is the relevant paragraph:
We divided the dataset of 5628 women into three parts: an exploration
dataset of two thirds of the women from Australia and New Zealand,
chosen at random (n=2129); a local replication dataset of the
remaining third of women from Australia and New Zealand (n=1067); and
an external, geographically distinct confirmation dataset of 2432
European women from the United Kingdom and Republic of Ireland.
Going back a little bit in the literature, there is a good paper by Altman et al entitle "Prognosis and prognostic research: validating a prognostic model" which goes into a lot more depth, and suggests ways to make sure you don't fall into this error. The "main points" from the article:
Unvalidated models should not be used in clinical practice
When validating a prognostic model, calibration and discrimination should be evaluated
Validation should be done on a different data from that used to develop the model, preferably from patients in other centres
Models may not perform well in practice because of deficiencies in the development methods or because the new sample is too different from the original
Note in particular the suggestion that validation be done (I paraphrase) with data from other sources - i.e. it is not enough to split your data arbitrarily into subsets, but you should do what you can to prove that "learning" on set from one set of experiments can be applied to data from a different set of experiments. That's a higher bar, but it further reduces the risk that a systematic bias in your setup creates "results" that cannot be independently verified.
It's a very important subject - thank you for asking the question!
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an i
|
The problem with fishing expeditions is this: if you test enough hypotheses, one of them will be confirmed with a low p value. Let me give a concrete example.
Imagine you have are doing an epidemiolo
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an increase in Type I errors?
The problem with fishing expeditions is this: if you test enough hypotheses, one of them will be confirmed with a low p value. Let me give a concrete example.
Imagine you have are doing an epidemiological study. You have found 1000 patients that suffer from a rare condition. You want to know what they have in common. So you start testing - you want to see whether a particular characteristic is overrepresented in this sample. Initially you test for gender, race, certain pertinent family history (father died of heart disease before age 50, …) but eventually, as you are having trouble finding anything that "sticks", you start to add all kinds of other factors that just might relate to the disease:
is vegetarian
has traveled to Canada
finished college
is married
has children
has cats
has dogs
drinks at least 5 glasses of red wine per week
…
Now here is the thing. If I select enough "random" hypotheses, it starts to become likely that at least one of these will result in a p value less than 0.05 - because the very essence of p value is "the probability of being wrong to reject the null hypothesis when there is no effect". Put differently - on average, for every 20 bogus hypotheses you test, one of them will give you a p of < 0.05.
This is SO very well summarized in the XKCD cartoon http://xkcd.com/882/ :
The tragedy is that even if an individual author does not perform 20 different hypothesis tests on a sample in order to look for significance, there might be 19 other authors doing the same thing; and the one who "finds" a correlation now has an interesting paper to write, and one that is likely to get accepted for publication…
This leads to an unfortunate tendency for irreproducible findings. The best way to guard against this as an individual author is to set the bar higher. Instead of testing for the individual factor, ask yourself "if I test N hypotheses, what is the probability of coming up with at least one false positive". When you are really testing "fishing hypotheses" you could think about making a Bonferroni correction to guard against this - but people frequently don't.
There were some interesting papers by Dr Ioannides - profiled in the Atlantic Monthly specifically on this subject.
See also this earlier question with several insightful answers.
update to better respond to all aspects of your question:
If you are afraid you might be "fishing", but you really don't know what hypothesis to formulate, you could definitely split your data in "exploration", "replication" and "confirmation" sections. In principle this should limit your exposure to the risks outlined earlier: if you have a p value of 0.05 in the exploration data and you get a similar value in the replication and confirmation data, your risk of being wrong drops. A nice example of "doing it right" was shown in the British Medical Journal (a very respected publication with an Impact Factor of 17+)
Exploration and confirmation of factors associated with uncomplicated pregnancy in nulliparous women: prospective cohort study, Chappell et al
Here is the relevant paragraph:
We divided the dataset of 5628 women into three parts: an exploration
dataset of two thirds of the women from Australia and New Zealand,
chosen at random (n=2129); a local replication dataset of the
remaining third of women from Australia and New Zealand (n=1067); and
an external, geographically distinct confirmation dataset of 2432
European women from the United Kingdom and Republic of Ireland.
Going back a little bit in the literature, there is a good paper by Altman et al entitle "Prognosis and prognostic research: validating a prognostic model" which goes into a lot more depth, and suggests ways to make sure you don't fall into this error. The "main points" from the article:
Unvalidated models should not be used in clinical practice
When validating a prognostic model, calibration and discrimination should be evaluated
Validation should be done on a different data from that used to develop the model, preferably from patients in other centres
Models may not perform well in practice because of deficiencies in the development methods or because the new sample is too different from the original
Note in particular the suggestion that validation be done (I paraphrase) with data from other sources - i.e. it is not enough to split your data arbitrarily into subsets, but you should do what you can to prove that "learning" on set from one set of experiments can be applied to data from a different set of experiments. That's a higher bar, but it further reduces the risk that a systematic bias in your setup creates "results" that cannot be independently verified.
It's a very important subject - thank you for asking the question!
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an i
The problem with fishing expeditions is this: if you test enough hypotheses, one of them will be confirmed with a low p value. Let me give a concrete example.
Imagine you have are doing an epidemiolo
|
7,104
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an increase in Type I errors?
|
The question asks if there are other problems than type I error inflation that come with fishing expeditions.
A type I error occurs when you reject the null hypothesis (typically of no effect) when it is true. A generalization, related to type I errors but not quite the same, is that even when the null is false (i.e., there is some effect) fishing expeditions will lead to overestimates of the size (and hence importance) of the effects found. In other words, when you aren't looking at a particular variable, but look at everything and focus your attention on whatever is the largest effect, the effects you find may not be $0$, but are biased to appear larger than they are. An example of this can be seen in my answer to: Algorithms for automatic model selection.
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an i
|
The question asks if there are other problems than type I error inflation that come with fishing expeditions.
A type I error occurs when you reject the null hypothesis (typically of no effect) when
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an increase in Type I errors?
The question asks if there are other problems than type I error inflation that come with fishing expeditions.
A type I error occurs when you reject the null hypothesis (typically of no effect) when it is true. A generalization, related to type I errors but not quite the same, is that even when the null is false (i.e., there is some effect) fishing expeditions will lead to overestimates of the size (and hence importance) of the effects found. In other words, when you aren't looking at a particular variable, but look at everything and focus your attention on whatever is the largest effect, the effects you find may not be $0$, but are biased to appear larger than they are. An example of this can be seen in my answer to: Algorithms for automatic model selection.
|
Is it possible to change a hypothesis to match observed data (aka fishing expedition) and avoid an i
The question asks if there are other problems than type I error inflation that come with fishing expeditions.
A type I error occurs when you reject the null hypothesis (typically of no effect) when
|
7,105
|
What algorithms need feature scaling, beside from SVM?
|
In general, algorithms that exploit distances or similarities (e.g. in the form of scalar product) between data samples, such as k-NN and SVM, are sensitive to feature transformations.
Graphical-model based classifiers, such as Fisher LDA or Naive Bayes, as well as Decision trees and Tree-based ensemble methods (RF, XGB) are invariant to feature scaling, but still, it might be a good idea to rescale/standardize your data.
|
What algorithms need feature scaling, beside from SVM?
|
In general, algorithms that exploit distances or similarities (e.g. in the form of scalar product) between data samples, such as k-NN and SVM, are sensitive to feature transformations.
Graphical-model
|
What algorithms need feature scaling, beside from SVM?
In general, algorithms that exploit distances or similarities (e.g. in the form of scalar product) between data samples, such as k-NN and SVM, are sensitive to feature transformations.
Graphical-model based classifiers, such as Fisher LDA or Naive Bayes, as well as Decision trees and Tree-based ensemble methods (RF, XGB) are invariant to feature scaling, but still, it might be a good idea to rescale/standardize your data.
|
What algorithms need feature scaling, beside from SVM?
In general, algorithms that exploit distances or similarities (e.g. in the form of scalar product) between data samples, such as k-NN and SVM, are sensitive to feature transformations.
Graphical-model
|
7,106
|
What algorithms need feature scaling, beside from SVM?
|
Here is a list I found on http://www.dataschool.io/comparing-supervised-learning-algorithms/ indicating which classifier needs feature scaling:
Full table:
In k-means clustering you also need to normalize your input.
In addition to considering whether the classifier exploits distances or similarities as Yell Bond mentioned, Stochastic Gradient Descent is also sensitive to feature scaling (since the learning rate in the update equation of Stochastic Gradient Descent is the same for every parameter {1}):
References:
{1} Elkan, Charles. "Log-linear models and conditional random fields." Tutorial notes at CIKM 8 (2008). https://scholar.google.com/scholar?cluster=5802800304608191219&hl=en&as_sdt=0,22 ; https://pdfs.semanticscholar.org/b971/0868004ec688c4ca87aa1fec7ffb7a2d01d8.pdf
|
What algorithms need feature scaling, beside from SVM?
|
Here is a list I found on http://www.dataschool.io/comparing-supervised-learning-algorithms/ indicating which classifier needs feature scaling:
Full table:
In k-means clustering you also need to nor
|
What algorithms need feature scaling, beside from SVM?
Here is a list I found on http://www.dataschool.io/comparing-supervised-learning-algorithms/ indicating which classifier needs feature scaling:
Full table:
In k-means clustering you also need to normalize your input.
In addition to considering whether the classifier exploits distances or similarities as Yell Bond mentioned, Stochastic Gradient Descent is also sensitive to feature scaling (since the learning rate in the update equation of Stochastic Gradient Descent is the same for every parameter {1}):
References:
{1} Elkan, Charles. "Log-linear models and conditional random fields." Tutorial notes at CIKM 8 (2008). https://scholar.google.com/scholar?cluster=5802800304608191219&hl=en&as_sdt=0,22 ; https://pdfs.semanticscholar.org/b971/0868004ec688c4ca87aa1fec7ffb7a2d01d8.pdf
|
What algorithms need feature scaling, beside from SVM?
Here is a list I found on http://www.dataschool.io/comparing-supervised-learning-algorithms/ indicating which classifier needs feature scaling:
Full table:
In k-means clustering you also need to nor
|
7,107
|
What algorithms need feature scaling, beside from SVM?
|
Adding to the excellent (but too short) answer by Yell Bond. Look at what happens with a linear regression model, we write it with only two predictors but the issue do not depend on that.
$$
Y_i = \beta_0 + \beta_1 x_i + \beta_2 z_i + \epsilon_i
$$
$i=1, \dots, n$. Now if you, say, center and scale the predictors to get
$$
x_i^* = (x_i - \bar{x})/\text{sd}(x) \\
z_i^* = (z_i - \bar{z})/\text{sd}(z)
$$
and instead fit the model (using ordinary least squares)
$$
Y_i = \beta_0^* + \beta_1^* x_i^* + \beta_2^* z_i^* + \epsilon_i
$$
Then the fitted parameters (betas) will change, but they change in a way that you can calculate by simple algebra from the transformation applied. So if we call the estimated betas from the model using transformed predictors for $\beta_{1,2}^*$ and the denote the betas from the untransformed model with $\hat{\beta}_{1,2}$, we can calculate one set of betas from the other one, knowing the means and standard deviations of the predictors. The realtionship between the transformed and untransformed parameters is the same as between their estimates, when based on OLS. Some algebra will give the relationship as
$$
\beta_0=\beta_0^* - \frac{\beta_1^* \bar{x}}{\text{sd(x)}} -\frac{\beta_2^*\bar{z}}{\text{sd(z)}},\quad \beta_1 =\frac{\beta_1^*}{\text{sd(x)}},\quad \beta_2=\frac{\beta_2^*}{\text{sd(z)}}
$$
So standardization is not a necessary part of modelling. (It might still be done for other reasons, which we do not cover here). This answer depends also upon us using ordinary least squares. For some other fitting methods, such as ridge or lasso, standardization is important, because we loose this invariance we have with least squares. This is easy to see: both lasso and ridge do regularization based on the size of the betas, so any transformation which change the relative sizes of the betas will change the result!
And this discussion for the case of linear regression tells you what you should look after in other cases: Is there invariance, or is it not? Generally, methods which depends on distance measures among the predictors will not show invariance, so standardization is important. Another example will be clustering.
|
What algorithms need feature scaling, beside from SVM?
|
Adding to the excellent (but too short) answer by Yell Bond. Look at what happens with a linear regression model, we write it with only two predictors but the issue do not depend on that.
$$
Y_i =
|
What algorithms need feature scaling, beside from SVM?
Adding to the excellent (but too short) answer by Yell Bond. Look at what happens with a linear regression model, we write it with only two predictors but the issue do not depend on that.
$$
Y_i = \beta_0 + \beta_1 x_i + \beta_2 z_i + \epsilon_i
$$
$i=1, \dots, n$. Now if you, say, center and scale the predictors to get
$$
x_i^* = (x_i - \bar{x})/\text{sd}(x) \\
z_i^* = (z_i - \bar{z})/\text{sd}(z)
$$
and instead fit the model (using ordinary least squares)
$$
Y_i = \beta_0^* + \beta_1^* x_i^* + \beta_2^* z_i^* + \epsilon_i
$$
Then the fitted parameters (betas) will change, but they change in a way that you can calculate by simple algebra from the transformation applied. So if we call the estimated betas from the model using transformed predictors for $\beta_{1,2}^*$ and the denote the betas from the untransformed model with $\hat{\beta}_{1,2}$, we can calculate one set of betas from the other one, knowing the means and standard deviations of the predictors. The realtionship between the transformed and untransformed parameters is the same as between their estimates, when based on OLS. Some algebra will give the relationship as
$$
\beta_0=\beta_0^* - \frac{\beta_1^* \bar{x}}{\text{sd(x)}} -\frac{\beta_2^*\bar{z}}{\text{sd(z)}},\quad \beta_1 =\frac{\beta_1^*}{\text{sd(x)}},\quad \beta_2=\frac{\beta_2^*}{\text{sd(z)}}
$$
So standardization is not a necessary part of modelling. (It might still be done for other reasons, which we do not cover here). This answer depends also upon us using ordinary least squares. For some other fitting methods, such as ridge or lasso, standardization is important, because we loose this invariance we have with least squares. This is easy to see: both lasso and ridge do regularization based on the size of the betas, so any transformation which change the relative sizes of the betas will change the result!
And this discussion for the case of linear regression tells you what you should look after in other cases: Is there invariance, or is it not? Generally, methods which depends on distance measures among the predictors will not show invariance, so standardization is important. Another example will be clustering.
|
What algorithms need feature scaling, beside from SVM?
Adding to the excellent (but too short) answer by Yell Bond. Look at what happens with a linear regression model, we write it with only two predictors but the issue do not depend on that.
$$
Y_i =
|
7,108
|
Why does "explaining away" make intuitive sense?
|
Clarification and notation
if C occurs, one of P(A) or P(B) increases, but the other decreases
This isn't correct. You have (implicitly and reasonably) assumed that A is (marginally) independent of B and also that A and B are the only causes of C. This implies that A and B are indeed dependent conditional on C, their joint effect. These facts are consistent because explaining away is about P(A | C), which is not the same distribution as P(A). The conditioning bar notation is important here.
However, my current intuition tells me that both P(A) and P(B) should increase if C occurs since C occurring makes it more likely that any of the causes for C occurred.
You are having the 'inference from semi-controlled demolition' (see below for details). To begin with, you already believe that C indicates that either A or B happened so you can't get any more certain that either A or B happened when you see C. But how about A and B given C? Well, this possible but less likely than either A and not B or B and not A. That is the 'explaining away' and what you want the intuition for.
Intuition
Let's move to a continuous model so we can visualise things more easily and think about correlation as a particular form of non-independence. Assume that reading scores (A) and math scores (B) are independently distributed in the general population. Now assume that a school will admit (C) a student with a combined reading and math score over some threshold. (It doesn't matter what that threshold is as long as it's at least a bit selective).
Here's a concrete example: Assume independent unit normally distributed reading and math scores and a sample of students, summarised below. When a student's reading and math score are together over the admission threshold (here 1.5) the student is shown as a red dot.
Because good math scores offset bad reading scores and vice versa, the population of admitted students will be such that reading and math are now dependent and negatively correlated (-0.65 here). This is also true in the non-admitted population (-0.19 here).
So, when you meet an randomly chosen student and you hear about her high math score then you should expect her to have gotten a lower reading score - the math score 'explains away' her admission. Of course she could also have a high reading score -- this certainly happens in the plot -- but it's less likely. And none of this affects our earlier assumption of no correlation, negative or positive, between math and reading scores in the general population.
Intuition check
Moving back to a discrete example closer to your original. Consider the best (and perhaps only) cartoon about 'explaining away'.
The government plot is A, the terrorist plot is B, and treat the general destruction as C, ignoring the fact there are two towers. If it is clear why the audience are being quite rational when they doubt the speaker's theory, then you understand 'explaining away'.
|
Why does "explaining away" make intuitive sense?
|
Clarification and notation
if C occurs, one of P(A) or P(B) increases, but the other decreases
This isn't correct. You have (implicitly and reasonably) assumed that A is (marginally) independent o
|
Why does "explaining away" make intuitive sense?
Clarification and notation
if C occurs, one of P(A) or P(B) increases, but the other decreases
This isn't correct. You have (implicitly and reasonably) assumed that A is (marginally) independent of B and also that A and B are the only causes of C. This implies that A and B are indeed dependent conditional on C, their joint effect. These facts are consistent because explaining away is about P(A | C), which is not the same distribution as P(A). The conditioning bar notation is important here.
However, my current intuition tells me that both P(A) and P(B) should increase if C occurs since C occurring makes it more likely that any of the causes for C occurred.
You are having the 'inference from semi-controlled demolition' (see below for details). To begin with, you already believe that C indicates that either A or B happened so you can't get any more certain that either A or B happened when you see C. But how about A and B given C? Well, this possible but less likely than either A and not B or B and not A. That is the 'explaining away' and what you want the intuition for.
Intuition
Let's move to a continuous model so we can visualise things more easily and think about correlation as a particular form of non-independence. Assume that reading scores (A) and math scores (B) are independently distributed in the general population. Now assume that a school will admit (C) a student with a combined reading and math score over some threshold. (It doesn't matter what that threshold is as long as it's at least a bit selective).
Here's a concrete example: Assume independent unit normally distributed reading and math scores and a sample of students, summarised below. When a student's reading and math score are together over the admission threshold (here 1.5) the student is shown as a red dot.
Because good math scores offset bad reading scores and vice versa, the population of admitted students will be such that reading and math are now dependent and negatively correlated (-0.65 here). This is also true in the non-admitted population (-0.19 here).
So, when you meet an randomly chosen student and you hear about her high math score then you should expect her to have gotten a lower reading score - the math score 'explains away' her admission. Of course she could also have a high reading score -- this certainly happens in the plot -- but it's less likely. And none of this affects our earlier assumption of no correlation, negative or positive, between math and reading scores in the general population.
Intuition check
Moving back to a discrete example closer to your original. Consider the best (and perhaps only) cartoon about 'explaining away'.
The government plot is A, the terrorist plot is B, and treat the general destruction as C, ignoring the fact there are two towers. If it is clear why the audience are being quite rational when they doubt the speaker's theory, then you understand 'explaining away'.
|
Why does "explaining away" make intuitive sense?
Clarification and notation
if C occurs, one of P(A) or P(B) increases, but the other decreases
This isn't correct. You have (implicitly and reasonably) assumed that A is (marginally) independent o
|
7,109
|
Why does "explaining away" make intuitive sense?
|
I think your intuition is ok but your understanding of "explain away" reasoning is wrong.
In the article you linked to
"Explaining away" is a common pattern of reasoning in which the
confirmation of one cause of an observed or believed event reduces the
need to invoke alternative causes
(emphasis added)
This is quite different from your:
I use "explain away" reasoning, if $C$ occurs, one of $P(A)$ or $P(B)$
increases, but the other decreases since I don't need alternative
reasons to explain why $C$ occurred.
You don't just need $C$ to occur it also needs to have been explained away by confirmation of $A$ or $B$ before you reduce the probability of the other possible explanation
Think of it another way. The ground is shaking. You observe $B$, the giant is wandering around. This explains away $C$, so it seems unlikely that there is now an earthquake - you settle for the giant explanation. But observing the giant was key - until you had this as the likely explanation of the earthquake, nothing had been explained away. When all you had was $C$, in fact both $P(A|C)$ and $P(B|C)$ are > $P(A)$ and $P(B)$ respectively, as per @Glen_b's answer.
|
Why does "explaining away" make intuitive sense?
|
I think your intuition is ok but your understanding of "explain away" reasoning is wrong.
In the article you linked to
"Explaining away" is a common pattern of reasoning in which the
confirmation o
|
Why does "explaining away" make intuitive sense?
I think your intuition is ok but your understanding of "explain away" reasoning is wrong.
In the article you linked to
"Explaining away" is a common pattern of reasoning in which the
confirmation of one cause of an observed or believed event reduces the
need to invoke alternative causes
(emphasis added)
This is quite different from your:
I use "explain away" reasoning, if $C$ occurs, one of $P(A)$ or $P(B)$
increases, but the other decreases since I don't need alternative
reasons to explain why $C$ occurred.
You don't just need $C$ to occur it also needs to have been explained away by confirmation of $A$ or $B$ before you reduce the probability of the other possible explanation
Think of it another way. The ground is shaking. You observe $B$, the giant is wandering around. This explains away $C$, so it seems unlikely that there is now an earthquake - you settle for the giant explanation. But observing the giant was key - until you had this as the likely explanation of the earthquake, nothing had been explained away. When all you had was $C$, in fact both $P(A|C)$ and $P(B|C)$ are > $P(A)$ and $P(B)$ respectively, as per @Glen_b's answer.
|
Why does "explaining away" make intuitive sense?
I think your intuition is ok but your understanding of "explain away" reasoning is wrong.
In the article you linked to
"Explaining away" is a common pattern of reasoning in which the
confirmation o
|
7,110
|
Why does "explaining away" make intuitive sense?
|
In the absence of specific additional information that changes the conditional probability of $A$ or $B$, Bayes rule tells you
$P(A|C) = \frac{P(C|A)P(A)}{P(C)}$ and similarly for $P(B|C)$
If $\frac{P(C|A)}{P(C)}$ and $\frac{P(C|B)}{P(C)}$ are both bigger than 1 (which you'd expect if the word 'explanation' is really to mean anything), then both $A$ and $B$ will be more conditionally more probable than they were before $C$ was observed.
It will be of interest to see if one becomes relatively more likely after observing $C$ compared to before.
$\frac{P(A|C)}{P(B|C)} = \frac{P(C|A)P(A)}{P(C|B)P(B)}$
That is, the relative probability of the two after observing $C$ is the relative probability before ($P(A)/P(B)$) times the ratio of the conditional probabilities of observing $C$ given the two 'explanations'.
|
Why does "explaining away" make intuitive sense?
|
In the absence of specific additional information that changes the conditional probability of $A$ or $B$, Bayes rule tells you
$P(A|C) = \frac{P(C|A)P(A)}{P(C)}$ and similarly for $P(B|C)$
If $\frac{
|
Why does "explaining away" make intuitive sense?
In the absence of specific additional information that changes the conditional probability of $A$ or $B$, Bayes rule tells you
$P(A|C) = \frac{P(C|A)P(A)}{P(C)}$ and similarly for $P(B|C)$
If $\frac{P(C|A)}{P(C)}$ and $\frac{P(C|B)}{P(C)}$ are both bigger than 1 (which you'd expect if the word 'explanation' is really to mean anything), then both $A$ and $B$ will be more conditionally more probable than they were before $C$ was observed.
It will be of interest to see if one becomes relatively more likely after observing $C$ compared to before.
$\frac{P(A|C)}{P(B|C)} = \frac{P(C|A)P(A)}{P(C|B)P(B)}$
That is, the relative probability of the two after observing $C$ is the relative probability before ($P(A)/P(B)$) times the ratio of the conditional probabilities of observing $C$ given the two 'explanations'.
|
Why does "explaining away" make intuitive sense?
In the absence of specific additional information that changes the conditional probability of $A$ or $B$, Bayes rule tells you
$P(A|C) = \frac{P(C|A)P(A)}{P(C)}$ and similarly for $P(B|C)$
If $\frac{
|
7,111
|
Why does "explaining away" make intuitive sense?
|
You're asking for intuition. What does it mean that $A$ and $B$ are independent? It means that if I tell you that I've just seen the monster, your opinion about the occurrence or not of the earthquake doesn't change; and conversely. If you think that both $P(C\mid A)$ and $P(C\mid B)$ are high, and I tell you that the ground is shaking and there is no monster in the town, wouldn't that change your opinion about the occurrence of the earthquake, making it more probable?
|
Why does "explaining away" make intuitive sense?
|
You're asking for intuition. What does it mean that $A$ and $B$ are independent? It means that if I tell you that I've just seen the monster, your opinion about the occurrence or not of the earthquake
|
Why does "explaining away" make intuitive sense?
You're asking for intuition. What does it mean that $A$ and $B$ are independent? It means that if I tell you that I've just seen the monster, your opinion about the occurrence or not of the earthquake doesn't change; and conversely. If you think that both $P(C\mid A)$ and $P(C\mid B)$ are high, and I tell you that the ground is shaking and there is no monster in the town, wouldn't that change your opinion about the occurrence of the earthquake, making it more probable?
|
Why does "explaining away" make intuitive sense?
You're asking for intuition. What does it mean that $A$ and $B$ are independent? It means that if I tell you that I've just seen the monster, your opinion about the occurrence or not of the earthquake
|
7,112
|
Why does "explaining away" make intuitive sense?
|
From the linked abstract, it appears that "explaining away" is discussing a learning mechanism, a common way that humans reason, not a formal method of logic or probability. It's a human-like way of reasoning that's not formally correct, just as inductive reasoning is not formally correct (as opposed to deductive reasoning). So I think the formal logic and probability answers are very good, but not applicable. (Note that the abstract is in a Machine Intelligence context.)
Your giants example is very good for this. We believe that earthquakes or giants can cause the ground to shake. But we also believe that giants do not exist -- or are extremely unlikely to exist. The ground shakes. We will not investigate whether a giant is walking around, but rather we'll inquire as to whether an earthquake happened. Hearing that an earthquake did in fact happen, we are even more convinced that earthquakes are an adequate explanation of shaking ground and that giants are even more certain not to exist or are at least even more highly unlikely to exist.
We would only accept that a giant caused the ground to shake only if: 1) we actually witnessed the giant and were willing to believe that we were not being fooled and that our previous assumption that giants were highly-unlikely or impossible was wrong, or 2) we could totally eliminate the possibility of an earthquake and also eliminate all possibilities D, E, F, G, ... that we previously had not thought of but that now seem more likely than a giant.
In the giant case, it makes sense. This learning mechanism (an explanation we find likely becomes even more likely and causes other explanations to become less likely, each time that explanation works) is reasonable in general, but will burn us, too. For example, the ideas that the earth orbits the sun, or that ulcers are caused by bacteria had a hard time gaining traction because of "explaining away", which in this case we'd call confirmation bias.
The fact that the abstract is in a Machine Intelligence setting also makes me thing this is discussing a learning mechanism commonly used by humans (and other animals, I imagine) that could benefit learning systems even though it can also be highly flawed. The AI community tried formal systems for years without getting closer to human-like intelligence and I believe that pragmatics has won out over formalism and "explaining away" is something that we do and thus that AI needs to do.
|
Why does "explaining away" make intuitive sense?
|
From the linked abstract, it appears that "explaining away" is discussing a learning mechanism, a common way that humans reason, not a formal method of logic or probability. It's a human-like way of r
|
Why does "explaining away" make intuitive sense?
From the linked abstract, it appears that "explaining away" is discussing a learning mechanism, a common way that humans reason, not a formal method of logic or probability. It's a human-like way of reasoning that's not formally correct, just as inductive reasoning is not formally correct (as opposed to deductive reasoning). So I think the formal logic and probability answers are very good, but not applicable. (Note that the abstract is in a Machine Intelligence context.)
Your giants example is very good for this. We believe that earthquakes or giants can cause the ground to shake. But we also believe that giants do not exist -- or are extremely unlikely to exist. The ground shakes. We will not investigate whether a giant is walking around, but rather we'll inquire as to whether an earthquake happened. Hearing that an earthquake did in fact happen, we are even more convinced that earthquakes are an adequate explanation of shaking ground and that giants are even more certain not to exist or are at least even more highly unlikely to exist.
We would only accept that a giant caused the ground to shake only if: 1) we actually witnessed the giant and were willing to believe that we were not being fooled and that our previous assumption that giants were highly-unlikely or impossible was wrong, or 2) we could totally eliminate the possibility of an earthquake and also eliminate all possibilities D, E, F, G, ... that we previously had not thought of but that now seem more likely than a giant.
In the giant case, it makes sense. This learning mechanism (an explanation we find likely becomes even more likely and causes other explanations to become less likely, each time that explanation works) is reasonable in general, but will burn us, too. For example, the ideas that the earth orbits the sun, or that ulcers are caused by bacteria had a hard time gaining traction because of "explaining away", which in this case we'd call confirmation bias.
The fact that the abstract is in a Machine Intelligence setting also makes me thing this is discussing a learning mechanism commonly used by humans (and other animals, I imagine) that could benefit learning systems even though it can also be highly flawed. The AI community tried formal systems for years without getting closer to human-like intelligence and I believe that pragmatics has won out over formalism and "explaining away" is something that we do and thus that AI needs to do.
|
Why does "explaining away" make intuitive sense?
From the linked abstract, it appears that "explaining away" is discussing a learning mechanism, a common way that humans reason, not a formal method of logic or probability. It's a human-like way of r
|
7,113
|
Why does "explaining away" make intuitive sense?
|
I think an easier way to think of it is: If there is any variable $C$ $(0<P(C)<1)$ such that the occurrence of $C$ increases the probability of both $A$ and $B$, then $A$ and $B$ cannot be independent. In your example, you actually chose variables that you intuitively understand to be dependent, not independent. That is, the event that there is an earthquake and a giant stomping around aren't independent, since they both are more likely to occur when the floor is shaking. Here is another example: Let C be the event that it rains, and A be the event that you use an umbrella, and B the event that you wear rainboots. Clearly A and B are not independent because when C occurs, you are more likely to both wear galoshes and carry and umbrella. But if you lived in an area that never, ever rained, then A and B could potentially be independent--neither the umbrella nor galoshes are being used as rain gear, so perhaps you wear the galoshes in the garden and use the umbrella to catch fish. They are only able to be independent because they don't share a cause.
Here is a proof: Suppose $A$ and $B$ are independent and also conditionally independent given $C$.
$P(AB) = P(A)P(B) = P(A|C)P(B|C)P(C)^2$ since $A$ is independent of $B$
$P(AB) = P(AB|C)P(C) = P(A|C)P(B|C)P(C)$ since $A$ is cond. independent of $B$ given $C$.
It follows from 1 and 2 that $P(C) = P(C)^2$ hence $P(C) = 0$ or $P(C) = 1$.
|
Why does "explaining away" make intuitive sense?
|
I think an easier way to think of it is: If there is any variable $C$ $(0<P(C)<1)$ such that the occurrence of $C$ increases the probability of both $A$ and $B$, then $A$ and $B$ cannot be independent
|
Why does "explaining away" make intuitive sense?
I think an easier way to think of it is: If there is any variable $C$ $(0<P(C)<1)$ such that the occurrence of $C$ increases the probability of both $A$ and $B$, then $A$ and $B$ cannot be independent. In your example, you actually chose variables that you intuitively understand to be dependent, not independent. That is, the event that there is an earthquake and a giant stomping around aren't independent, since they both are more likely to occur when the floor is shaking. Here is another example: Let C be the event that it rains, and A be the event that you use an umbrella, and B the event that you wear rainboots. Clearly A and B are not independent because when C occurs, you are more likely to both wear galoshes and carry and umbrella. But if you lived in an area that never, ever rained, then A and B could potentially be independent--neither the umbrella nor galoshes are being used as rain gear, so perhaps you wear the galoshes in the garden and use the umbrella to catch fish. They are only able to be independent because they don't share a cause.
Here is a proof: Suppose $A$ and $B$ are independent and also conditionally independent given $C$.
$P(AB) = P(A)P(B) = P(A|C)P(B|C)P(C)^2$ since $A$ is independent of $B$
$P(AB) = P(AB|C)P(C) = P(A|C)P(B|C)P(C)$ since $A$ is cond. independent of $B$ given $C$.
It follows from 1 and 2 that $P(C) = P(C)^2$ hence $P(C) = 0$ or $P(C) = 1$.
|
Why does "explaining away" make intuitive sense?
I think an easier way to think of it is: If there is any variable $C$ $(0<P(C)<1)$ such that the occurrence of $C$ increases the probability of both $A$ and $B$, then $A$ and $B$ cannot be independent
|
7,114
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
The linear régression coefficients of $y = ax + b$ are $a = cov(x,y)/var(x)$ and $b = mean(y) - a \cdot mean(x)$.
So all you really need is an incremental method to compute $cov(x,y)$. From this value and the variance of $x$ and the mean of both $y$ and $x$ you can compute the parameters $a$ and $b$.
As you will see in the pseudo code given below incremental computation of $cov(x,y)$ is very similar to incremental computation of $var(x)$. This shouldn't be a surprise because $var(x) = cov(x,x)$.
Here is the pseudo code you are probably looking for:
init(): meanX = 0, meanY = 0, varX = 0, covXY = 0, n = 0
update(x,y):
n += 1
dx = x - meanX
dy = y - meanY
varX += (((n-1)/n)*dx*dx - varX)/n
covXY += (((n-1)/n)*dx*dy - covXY)/n
meanX += dx/n
meanY += dy/n
getA(): return covXY/varX
getB(): return meanY - getA()*meanX
I found this question while searching for an equivalent algorithm incrementally computing a multi variate regression as $R = (X'X)^{-1}X'Y $ so that $ XR = Y+\epsilon $
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
The linear régression coefficients of $y = ax + b$ are $a = cov(x,y)/var(x)$ and $b = mean(y) - a \cdot mean(x)$.
So all you really need is an incremental method to compute $cov(x,y)$. From this value
|
Are there algorithms for computing "running" linear or logistic regression parameters?
The linear régression coefficients of $y = ax + b$ are $a = cov(x,y)/var(x)$ and $b = mean(y) - a \cdot mean(x)$.
So all you really need is an incremental method to compute $cov(x,y)$. From this value and the variance of $x$ and the mean of both $y$ and $x$ you can compute the parameters $a$ and $b$.
As you will see in the pseudo code given below incremental computation of $cov(x,y)$ is very similar to incremental computation of $var(x)$. This shouldn't be a surprise because $var(x) = cov(x,x)$.
Here is the pseudo code you are probably looking for:
init(): meanX = 0, meanY = 0, varX = 0, covXY = 0, n = 0
update(x,y):
n += 1
dx = x - meanX
dy = y - meanY
varX += (((n-1)/n)*dx*dx - varX)/n
covXY += (((n-1)/n)*dx*dy - covXY)/n
meanX += dx/n
meanY += dy/n
getA(): return covXY/varX
getB(): return meanY - getA()*meanX
I found this question while searching for an equivalent algorithm incrementally computing a multi variate regression as $R = (X'X)^{-1}X'Y $ so that $ XR = Y+\epsilon $
|
Are there algorithms for computing "running" linear or logistic regression parameters?
The linear régression coefficients of $y = ax + b$ are $a = cov(x,y)/var(x)$ and $b = mean(y) - a \cdot mean(x)$.
So all you really need is an incremental method to compute $cov(x,y)$. From this value
|
7,115
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
For your two specific examples:
Linear Regression
The paper "Online Linear Regression and Its Application to Model-Based Reinforcement Learning" by Alexander Strehl and Michael Littman describes an algorithm called "KWIK Linear Regression" (see algorithm 1) which provides an approximation to the linear regression solution using incremental updates. Note that this is not regularised (i.e. it is not Ridge Regression). I'm pretty sure that the method of Strehl & Littman cannot extend to that setting.
Logistic Regression
This thread sheds some light on the matter. Quoting:
Even without a regularization constraint, logistic regression is a nonlinear optimization problem. Already this does not have an analytic solution, which is usually a prerequisite to deriving an update solution. With a regularization constraint, it becomes a constrained optimization problem. This introduces a whole new set of non-analytic complications on top of the ones that the unconstrained problem already had.
There are however other online (or incremental) methods for regression that you might want to look at, for example Locally Weighted Projection Regression (LWPR)
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
For your two specific examples:
Linear Regression
The paper "Online Linear Regression and Its Application to Model-Based Reinforcement Learning" by Alexander Strehl and Michael Littman describes an al
|
Are there algorithms for computing "running" linear or logistic regression parameters?
For your two specific examples:
Linear Regression
The paper "Online Linear Regression and Its Application to Model-Based Reinforcement Learning" by Alexander Strehl and Michael Littman describes an algorithm called "KWIK Linear Regression" (see algorithm 1) which provides an approximation to the linear regression solution using incremental updates. Note that this is not regularised (i.e. it is not Ridge Regression). I'm pretty sure that the method of Strehl & Littman cannot extend to that setting.
Logistic Regression
This thread sheds some light on the matter. Quoting:
Even without a regularization constraint, logistic regression is a nonlinear optimization problem. Already this does not have an analytic solution, which is usually a prerequisite to deriving an update solution. With a regularization constraint, it becomes a constrained optimization problem. This introduces a whole new set of non-analytic complications on top of the ones that the unconstrained problem already had.
There are however other online (or incremental) methods for regression that you might want to look at, for example Locally Weighted Projection Regression (LWPR)
|
Are there algorithms for computing "running" linear or logistic regression parameters?
For your two specific examples:
Linear Regression
The paper "Online Linear Regression and Its Application to Model-Based Reinforcement Learning" by Alexander Strehl and Michael Littman describes an al
|
7,116
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
As a general principle:
0) you keep the sufficient statistics and the current ML estimates
1) when you get new data, update the sufficient statistics and the estimates
2) When you don't have sufficient statistics you'll need to use all of the data.
3) Typically you don't have closed-form solutions; use the previous MLEs as the starting point, use some convenient optimization method to find the new optimum from there. You may need to experiment a bit to find which approaches make the best tradeoffs for your particular kinds of problem instances.
If your problem has a special structure, you can probably exploit it.
A couple of potential references that may or may not have some value:
McMahan, H. B. and M. Streeter (2012),
Open Problem: Better Bounds for Online Logistic Regression,
JMLR: Workshop and Conference Proceedings, vol 23, 44.1–44.3
Penny, W.D. and S.J. Roberts (1999),
Dynamic Logistic Regression,
Proceedings IJCNN '99
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
As a general principle:
0) you keep the sufficient statistics and the current ML estimates
1) when you get new data, update the sufficient statistics and the estimates
2) When you don't have sufficien
|
Are there algorithms for computing "running" linear or logistic regression parameters?
As a general principle:
0) you keep the sufficient statistics and the current ML estimates
1) when you get new data, update the sufficient statistics and the estimates
2) When you don't have sufficient statistics you'll need to use all of the data.
3) Typically you don't have closed-form solutions; use the previous MLEs as the starting point, use some convenient optimization method to find the new optimum from there. You may need to experiment a bit to find which approaches make the best tradeoffs for your particular kinds of problem instances.
If your problem has a special structure, you can probably exploit it.
A couple of potential references that may or may not have some value:
McMahan, H. B. and M. Streeter (2012),
Open Problem: Better Bounds for Online Logistic Regression,
JMLR: Workshop and Conference Proceedings, vol 23, 44.1–44.3
Penny, W.D. and S.J. Roberts (1999),
Dynamic Logistic Regression,
Proceedings IJCNN '99
|
Are there algorithms for computing "running" linear or logistic regression parameters?
As a general principle:
0) you keep the sufficient statistics and the current ML estimates
1) when you get new data, update the sufficient statistics and the estimates
2) When you don't have sufficien
|
7,117
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
Adding to tdc's answer, there are no known methods to compute exact estimates of the coefficients at any point in time with just constant time per iteration. However, there are some alternatives which are reasonable and interesting.
The first model to look at is the online learning setting. In this setting, the world first announces a value of x, your algorithm predicts a value for y, the world announces the true value y', and your algorithm suffers a loss l(y,y'). For this setting it is known that simple algorithms (gradient descent and exponentiated gradient, among others) achieve sublinear regret. This means that as you see more examples the number of extra mistakes your algorithm makes (when compared to the best possible linear predictor) does not grow with the number of examples. This works even in adversarial settings. There is a good paper explaining one popular strategy to prove these regret bounds. Shai Shalev-Schwartz's lecture notes are also useful.
There is an extension of the online learning setting called the bandit setting where your algorithm is only given a number representing how wrong it was (and no pointer to the right answer). Impressively, many results from online learning carry over to this setting, except here one is forced to explore as well as exploit, which leads to all sorts of interesting challenges.
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
Adding to tdc's answer, there are no known methods to compute exact estimates of the coefficients at any point in time with just constant time per iteration. However, there are some alternatives which
|
Are there algorithms for computing "running" linear or logistic regression parameters?
Adding to tdc's answer, there are no known methods to compute exact estimates of the coefficients at any point in time with just constant time per iteration. However, there are some alternatives which are reasonable and interesting.
The first model to look at is the online learning setting. In this setting, the world first announces a value of x, your algorithm predicts a value for y, the world announces the true value y', and your algorithm suffers a loss l(y,y'). For this setting it is known that simple algorithms (gradient descent and exponentiated gradient, among others) achieve sublinear regret. This means that as you see more examples the number of extra mistakes your algorithm makes (when compared to the best possible linear predictor) does not grow with the number of examples. This works even in adversarial settings. There is a good paper explaining one popular strategy to prove these regret bounds. Shai Shalev-Schwartz's lecture notes are also useful.
There is an extension of the online learning setting called the bandit setting where your algorithm is only given a number representing how wrong it was (and no pointer to the right answer). Impressively, many results from online learning carry over to this setting, except here one is forced to explore as well as exploit, which leads to all sorts of interesting challenges.
|
Are there algorithms for computing "running" linear or logistic regression parameters?
Adding to tdc's answer, there are no known methods to compute exact estimates of the coefficients at any point in time with just constant time per iteration. However, there are some alternatives which
|
7,118
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
You can use some standard Kalman Filter package in R for this - sspir, dlm, kfas, etc. I feel that KF is a much more developed area than online-learning, so it may be more practical. You may use a model
$$y_t = \beta_t\cdot x_t + \varepsilon_t, \\ \beta_t = \beta_{t-1}+ \eta_t$$ to allow your regression coefficients to slowly vary with time and KF will re-estimate them on each step (with constant time cost) based on most recent data. Alternatively, you can set them constant $$\beta_t = \beta_{t-1}$$ and KF will still re-estimate them on each step but this time assuming they are constant and just incorporating new observed data to produce better and better estimates of same coefficients values.
You can formulate similar model for logistic regression, $$y_t = logit(\beta_t\cdot x_t + \varepsilon_t), \\ \beta_t = \beta_{t-1}+ \eta_t$$ as it will be non-linear, you will need to use non-linear filtering method from above packages - EKF or UKF.
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
You can use some standard Kalman Filter package in R for this - sspir, dlm, kfas, etc. I feel that KF is a much more developed area than online-learning, so it may be more practical. You may use a mod
|
Are there algorithms for computing "running" linear or logistic regression parameters?
You can use some standard Kalman Filter package in R for this - sspir, dlm, kfas, etc. I feel that KF is a much more developed area than online-learning, so it may be more practical. You may use a model
$$y_t = \beta_t\cdot x_t + \varepsilon_t, \\ \beta_t = \beta_{t-1}+ \eta_t$$ to allow your regression coefficients to slowly vary with time and KF will re-estimate them on each step (with constant time cost) based on most recent data. Alternatively, you can set them constant $$\beta_t = \beta_{t-1}$$ and KF will still re-estimate them on each step but this time assuming they are constant and just incorporating new observed data to produce better and better estimates of same coefficients values.
You can formulate similar model for logistic regression, $$y_t = logit(\beta_t\cdot x_t + \varepsilon_t), \\ \beta_t = \beta_{t-1}+ \eta_t$$ as it will be non-linear, you will need to use non-linear filtering method from above packages - EKF or UKF.
|
Are there algorithms for computing "running" linear or logistic regression parameters?
You can use some standard Kalman Filter package in R for this - sspir, dlm, kfas, etc. I feel that KF is a much more developed area than online-learning, so it may be more practical. You may use a mod
|
7,119
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
Other answers have pointed to the world of machine learning, and that is certainly one place where this problem has been addressed.
However, another approach that may be better suited to your needs is the use of the QR factorization with with low rank updates. Approaches to doing this and using it to solve least squares problems are given in:
Updating the QR factorization and the least squares problem by Hammerling and Lucas.
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
Other answers have pointed to the world of machine learning, and that is certainly one place where this problem has been addressed.
However, another approach that may be better suited to your needs
|
Are there algorithms for computing "running" linear or logistic regression parameters?
Other answers have pointed to the world of machine learning, and that is certainly one place where this problem has been addressed.
However, another approach that may be better suited to your needs is the use of the QR factorization with with low rank updates. Approaches to doing this and using it to solve least squares problems are given in:
Updating the QR factorization and the least squares problem by Hammerling and Lucas.
|
Are there algorithms for computing "running" linear or logistic regression parameters?
Other answers have pointed to the world of machine learning, and that is certainly one place where this problem has been addressed.
However, another approach that may be better suited to your needs
|
7,120
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
This is to add to @chmike answer.
The method appears to be similar to B. P. Welford’s online algorithm for standard deviation which also calculates the mean. John Cook gives a good explanation here. Tony Finch in 2009 provides a method for an exponential moving average and standard deviation:
diff := x – mean
incr := alpha * diff
mean := mean + incr
variance := (1 - alpha) * (variance + diff * incr)
Peering at the previously posted answer and expanding upon it to include a exponential moving window:
init():
meanX = 0, meanY = 0, varX = 0, covXY = 0, n = 0,
meanXY = 0, varY = 0, desiredAlpha=0.01 #additional variables for correlation
update(x,y):
n += 1
alpha=max(desiredAlpha,1/n) #to handle initial conditions
dx = x - meanX
dy = y - meanY
dxy = (x*y) - meanXY #needed for cor
varX += ((1-alpha)*dx*dx - varX)*alpha
varY += ((1-alpha)*dy*dy - varY)*alpha #needed for corXY
covXY += ((1-alpha)*dx*dy - covXY)*alpha
#alternate method: varX = (1-alpha)*(varX+dx*dx*alpha)
#alternate method: varY = (1-alpha)*(varY+dy*dy*alpha) #needed for corXY
#alternate method: covXY = (1-alpha)*(covXY+dx*dy*alpha)
meanX += dx * alpha
meanY += dy * alpha
meanXY += dxy * alpha
getA(): return covXY/varX
getB(): return meanY - getA()*meanX
corXY(): return (meanXY - meanX * meanY) / ( sqrt(varX) * sqrt(varY) )
In the above "code", desiredAlpha could be set to 0 and if so, the code would operate without exponential weighting. It can be suggested to set desiredAlpha to 1/desiredWindowSize as suggested by Modified_moving_average for a moving window size.
Side question: of the alternative calculations above, any comments on which is better from a precision standpoint?
References:
chmike (2013) https://stats.stackexchange.com/a/79845/70282
Cook, John (n.d.) Accurately computing running variance http://www.johndcook.com/blog/standard_deviation/
Finch, Tony. (2009) Incremental calculation of weighted mean and variance. https://fanf2.user.srcf.net/hermes/doc/antiforgery/stats.pdf
Wikipedia. (n.d) Welford’s online algorithm https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm
|
Are there algorithms for computing "running" linear or logistic regression parameters?
|
This is to add to @chmike answer.
The method appears to be similar to B. P. Welford’s online algorithm for standard deviation which also calculates the mean. John Cook gives a good explanation here.
|
Are there algorithms for computing "running" linear or logistic regression parameters?
This is to add to @chmike answer.
The method appears to be similar to B. P. Welford’s online algorithm for standard deviation which also calculates the mean. John Cook gives a good explanation here. Tony Finch in 2009 provides a method for an exponential moving average and standard deviation:
diff := x – mean
incr := alpha * diff
mean := mean + incr
variance := (1 - alpha) * (variance + diff * incr)
Peering at the previously posted answer and expanding upon it to include a exponential moving window:
init():
meanX = 0, meanY = 0, varX = 0, covXY = 0, n = 0,
meanXY = 0, varY = 0, desiredAlpha=0.01 #additional variables for correlation
update(x,y):
n += 1
alpha=max(desiredAlpha,1/n) #to handle initial conditions
dx = x - meanX
dy = y - meanY
dxy = (x*y) - meanXY #needed for cor
varX += ((1-alpha)*dx*dx - varX)*alpha
varY += ((1-alpha)*dy*dy - varY)*alpha #needed for corXY
covXY += ((1-alpha)*dx*dy - covXY)*alpha
#alternate method: varX = (1-alpha)*(varX+dx*dx*alpha)
#alternate method: varY = (1-alpha)*(varY+dy*dy*alpha) #needed for corXY
#alternate method: covXY = (1-alpha)*(covXY+dx*dy*alpha)
meanX += dx * alpha
meanY += dy * alpha
meanXY += dxy * alpha
getA(): return covXY/varX
getB(): return meanY - getA()*meanX
corXY(): return (meanXY - meanX * meanY) / ( sqrt(varX) * sqrt(varY) )
In the above "code", desiredAlpha could be set to 0 and if so, the code would operate without exponential weighting. It can be suggested to set desiredAlpha to 1/desiredWindowSize as suggested by Modified_moving_average for a moving window size.
Side question: of the alternative calculations above, any comments on which is better from a precision standpoint?
References:
chmike (2013) https://stats.stackexchange.com/a/79845/70282
Cook, John (n.d.) Accurately computing running variance http://www.johndcook.com/blog/standard_deviation/
Finch, Tony. (2009) Incremental calculation of weighted mean and variance. https://fanf2.user.srcf.net/hermes/doc/antiforgery/stats.pdf
Wikipedia. (n.d) Welford’s online algorithm https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm
|
Are there algorithms for computing "running" linear or logistic regression parameters?
This is to add to @chmike answer.
The method appears to be similar to B. P. Welford’s online algorithm for standard deviation which also calculates the mean. John Cook gives a good explanation here.
|
7,121
|
How to sample from a discrete distribution? [duplicate]
|
Sure. Here's an R function that will sample from that distribution n times, with replacement:
sampleDist = function(n) {
sample(x = c(1,2,3,4), n, replace = T, prob = c(0.1, 0.4, 0.2, 0.3))
}
# > sampleDist(10)
# [1] 4 2 2 2 2 2 4 1 2 2
If you want to go a little lower level, you can see the actual algorithm used by checking out the R source (written in C):
/* Unequal probability sampling; with-replacement case
* n are the lengths of p and perm. p contains probabilities, perm
* contains the actual outcomes, and ans contains an array of values
* that were sampled.
*/
static void ProbSampleReplace(int n, double *p, int *perm, int nans, int *ans)
{
double rU;
int i, j;
int nm1 = n - 1;
/* record element identities */
for (i = 0; i < n; i++)
perm[i] = i + 1;
/* sort the probabilities into descending order */
revsort(p, perm, n);
/* compute cumulative probabilities */
for (i = 1 ; i < n; i++)
p[i] += p[i - 1];
/* compute the sample */
for (i = 0; i < nans; i++) {
rU = unif_rand();
for (j = 0; j < nm1; j++) {
if (rU <= p[j])
break;
}
ans[i] = perm[j];
}
}
|
How to sample from a discrete distribution? [duplicate]
|
Sure. Here's an R function that will sample from that distribution n times, with replacement:
sampleDist = function(n) {
sample(x = c(1,2,3,4), n, replace = T, prob = c(0.1, 0.4, 0.2, 0.3))
}
|
How to sample from a discrete distribution? [duplicate]
Sure. Here's an R function that will sample from that distribution n times, with replacement:
sampleDist = function(n) {
sample(x = c(1,2,3,4), n, replace = T, prob = c(0.1, 0.4, 0.2, 0.3))
}
# > sampleDist(10)
# [1] 4 2 2 2 2 2 4 1 2 2
If you want to go a little lower level, you can see the actual algorithm used by checking out the R source (written in C):
/* Unequal probability sampling; with-replacement case
* n are the lengths of p and perm. p contains probabilities, perm
* contains the actual outcomes, and ans contains an array of values
* that were sampled.
*/
static void ProbSampleReplace(int n, double *p, int *perm, int nans, int *ans)
{
double rU;
int i, j;
int nm1 = n - 1;
/* record element identities */
for (i = 0; i < n; i++)
perm[i] = i + 1;
/* sort the probabilities into descending order */
revsort(p, perm, n);
/* compute cumulative probabilities */
for (i = 1 ; i < n; i++)
p[i] += p[i - 1];
/* compute the sample */
for (i = 0; i < nans; i++) {
rU = unif_rand();
for (j = 0; j < nm1; j++) {
if (rU <= p[j])
break;
}
ans[i] = perm[j];
}
}
|
How to sample from a discrete distribution? [duplicate]
Sure. Here's an R function that will sample from that distribution n times, with replacement:
sampleDist = function(n) {
sample(x = c(1,2,3,4), n, replace = T, prob = c(0.1, 0.4, 0.2, 0.3))
}
|
7,122
|
How to sample from a discrete distribution? [duplicate]
|
In response to a question in comments, here's an outline of a few potentially* faster ways to do discrete distributions than the cdf method.
* I say "potentially" because for some discrete cases a well implemented inverse-cdf approach can be very fast. The general case is harder to make fast without introducing additional tricks.
For the case of four different outcomes as in the example in the question, the naive version of the inverse cdf approach (or effectively equivalent approaches) are fine; but if there are hundreds (or thousands, or millions) of categories it can become slow without being a bit smarter (you certainly don't want to be sequentially searching through the cdf until you find the first category in which the cdf exceeds a random uniform). There are some faster approaches than that.
[You could see the first few things I mention below s having a connection to faster-than-sequential approaches to locating a value using an index and so are in a way just a "smarter version of using the cdf". One can of course look at "standard" approaches to solve related problems like "searching a sorted file", and end up with methods with much faster than sequential performance; if you can call suitable functions, such standard approaches may often be all you need.]
Anyway, to some efficient approaches for generating from discrete distributions.
1) the "Table method". Instead of being $O(n)$ for $n$ categories, once set up, the "simple" version of this in (a) (if the distribution is suitable) is $O(1)$.
a) Simple approach - assuming rational probabilities (done on the above data example):
- set up an array with 10 cells, containing a '1', four '2's, two '3's and three '4's. Sample that using a discrete uniform (easy to do from a continuous uniform), and you get simple fast code.
b) More complex case - doesn't need 'nice' probabilities. Use $2^k$ cells, or rather, you'll end up using a few less than that. So for example, consider the following:
x 0 1 2 3 4 5 6
P(X=x) 0.4581 0.0032 0.1985 0.3298 0.0022 0.0080 0.0002
(We could have 10000 cells and use the previous exact approach, of course, but what if these probabilities are irrational, say?)
Let's use $k=8$. Multiply the probabilities by $2^k$ and truncate to find out how many of each cell type we need:
x 0 1 2 3 4 5 6 Tot
P(X=x) 0.4581 0.0032 0.1985 0.3298 0.0022 0.0080 0.0002 1.0000
[256p(x)] 117 0 50 84 0 2 0 253
Then the last 3 cells are basically "generate instead from this other distribution" (i.e. p(x) - \frac{\lfloor 256 p(x)\rfloor}{256} normalized to a p.m.f.):
x* 0 1 2 3 4 5 6 Tot
P(X=x*) 0.091200 0.273067 0.272000 0.142933 0.187733 0.016000 0.017067 1.000000
The "spillover" table can be done by any reasonable method (you only get here about 1% of the time, it doesn't need to be as fast). So $\frac{253}{256}$ of the time we generate a random uniform, use its first 8 bits to pick a random cell, and output the value in the cell; after the initial setup all of this can be made very fast. The other $\frac{3}{256}$ of the time we hit a cell that says "generate from the second table". Almost always, you generate a
single uniform on $(0,1)$ and get a discrete random number from a multiply, a truncation and the cost of accessing an array element.
2) "Squaring the histogram" method; this is kind of related to (1), but each cell can actually generate either one of two values, depending on a (continuous) uniform. So you generate a discrete value from 1 to n, then within each one, check whether to generate its main value or its second value. It works with bounded random variables. There's no spillover table, and it generally uses much smaller tables than method (1). Usually, it's set up so that the choice of 1:n uses the first few bits of a uniform random number, and the remainder of it tells you which of the two values for that bin to output.
Perhaps the easiest way to outline the method is to do it on the above example:
Think of the distribution as a histogram with 4 bins:
We cut off the tops of the tallest bars and put them in the shorter ones, 'squaring it off'. The average 'height' of a bar will be 0.25. So we cut 0.15 off the second bar and put it in the first and 0.05 off the fourth and put it in the third:
Its always possible to organize this in such a way that no bin ends up with more than 2 colors, though one color may end up in several bins.
So now you choose one of the 4 bins at random (requires 2 random bits off the top of a uniform). You then use the remaining bits to specify a uniformly distributed vertical position and compare with the break between colors to work out which of two values to output. While very fast it's usually not quite as fast as the 'table' method.
--
These methods can be adapted to deal with unbounded variables, where again, it's 'mostly fast'.
A reference: http://www.jstatsoft.org/v11/i03/paper
The relatively slow part of these is creating the tables of values; they're suitable when you know what you're going to be generating ("we need to sample values from this distribution many times in the future") rather than trying to create it as you go. "We need to sample a million values from this ASAP, but we'll never need to do it again" creates different priorities; in many situations some of the "standard computing approaches" to looking up sorted values (i.e. to doing the cdf method more quickly) may actually be about your best choice.
There are still other fast approaches to generating from discrete distributions. Carefully coded, you can do some very fast generation. For example:
3) the rejection method ("accept-reject") can be done with discrete distributions; if you have a discrete majorizing function ("envelope") which is a scaled-up discrete pmf that you can already generate from in a fast way, it adapts directly, and in some cases can be very fast. More generally you can take advantage of being able to generate from continuous distributions (for example by discretizing the result back to a discrete envelope).
Here imagine that we have some discrete probability function $f$ for which we don't have a convenient cdf (or inverse-cdf) -- indeed in this illustration we didn't even have the normalizing constant, so our plot is unnormalized:
Now we need to find some convenient-to-generate-from discrete probability function $g$, which can be multiplied by a constant $c$ and be everywhere at least as large as $f$ (we need to be sure that this remains true for all $x$ values). That is, $c.g(x)\geq f(x)$ for all the possible $x$ values.
Sometimes a suitable $g$ is easily identified, but one useful option is to take a mixture of a discrete uniform for the left part, and a distribution with at least as heavy a tail as $f$ on the right. Two reasonably convenient choices for that are a geometric distribution (when the tail isn't decreasing slower than exponentially) and something like a discretized Pareto or discretized half-Cauchy distribution, obtained by taking $\lfloor X\rfloor$ for some Pareto or half-Cauchy random variate $X$ (in either case for when the pmf is decreasing slower than exponentially).
(For that matter, the geometric itself can be generated by discretizing an exponential.)
In this case, a discrete uniform on the left and a geometric on the right work quite well:
(Reminder: what is plotted here is an unnormalized pmf, so the y-axis doesn't represent probability but something proportional to probability)
Then the procedure is a matter of simulating a proposed value $x$ from $g$, simulating a uniform, $U$ on $(0,c.g(x))$ and if $U<f$, accepting that proposed $x$ (otherwise rejecting it and generating a new proposed $x$).
|
How to sample from a discrete distribution? [duplicate]
|
In response to a question in comments, here's an outline of a few potentially* faster ways to do discrete distributions than the cdf method.
* I say "potentially" because for some discrete cases a wel
|
How to sample from a discrete distribution? [duplicate]
In response to a question in comments, here's an outline of a few potentially* faster ways to do discrete distributions than the cdf method.
* I say "potentially" because for some discrete cases a well implemented inverse-cdf approach can be very fast. The general case is harder to make fast without introducing additional tricks.
For the case of four different outcomes as in the example in the question, the naive version of the inverse cdf approach (or effectively equivalent approaches) are fine; but if there are hundreds (or thousands, or millions) of categories it can become slow without being a bit smarter (you certainly don't want to be sequentially searching through the cdf until you find the first category in which the cdf exceeds a random uniform). There are some faster approaches than that.
[You could see the first few things I mention below s having a connection to faster-than-sequential approaches to locating a value using an index and so are in a way just a "smarter version of using the cdf". One can of course look at "standard" approaches to solve related problems like "searching a sorted file", and end up with methods with much faster than sequential performance; if you can call suitable functions, such standard approaches may often be all you need.]
Anyway, to some efficient approaches for generating from discrete distributions.
1) the "Table method". Instead of being $O(n)$ for $n$ categories, once set up, the "simple" version of this in (a) (if the distribution is suitable) is $O(1)$.
a) Simple approach - assuming rational probabilities (done on the above data example):
- set up an array with 10 cells, containing a '1', four '2's, two '3's and three '4's. Sample that using a discrete uniform (easy to do from a continuous uniform), and you get simple fast code.
b) More complex case - doesn't need 'nice' probabilities. Use $2^k$ cells, or rather, you'll end up using a few less than that. So for example, consider the following:
x 0 1 2 3 4 5 6
P(X=x) 0.4581 0.0032 0.1985 0.3298 0.0022 0.0080 0.0002
(We could have 10000 cells and use the previous exact approach, of course, but what if these probabilities are irrational, say?)
Let's use $k=8$. Multiply the probabilities by $2^k$ and truncate to find out how many of each cell type we need:
x 0 1 2 3 4 5 6 Tot
P(X=x) 0.4581 0.0032 0.1985 0.3298 0.0022 0.0080 0.0002 1.0000
[256p(x)] 117 0 50 84 0 2 0 253
Then the last 3 cells are basically "generate instead from this other distribution" (i.e. p(x) - \frac{\lfloor 256 p(x)\rfloor}{256} normalized to a p.m.f.):
x* 0 1 2 3 4 5 6 Tot
P(X=x*) 0.091200 0.273067 0.272000 0.142933 0.187733 0.016000 0.017067 1.000000
The "spillover" table can be done by any reasonable method (you only get here about 1% of the time, it doesn't need to be as fast). So $\frac{253}{256}$ of the time we generate a random uniform, use its first 8 bits to pick a random cell, and output the value in the cell; after the initial setup all of this can be made very fast. The other $\frac{3}{256}$ of the time we hit a cell that says "generate from the second table". Almost always, you generate a
single uniform on $(0,1)$ and get a discrete random number from a multiply, a truncation and the cost of accessing an array element.
2) "Squaring the histogram" method; this is kind of related to (1), but each cell can actually generate either one of two values, depending on a (continuous) uniform. So you generate a discrete value from 1 to n, then within each one, check whether to generate its main value or its second value. It works with bounded random variables. There's no spillover table, and it generally uses much smaller tables than method (1). Usually, it's set up so that the choice of 1:n uses the first few bits of a uniform random number, and the remainder of it tells you which of the two values for that bin to output.
Perhaps the easiest way to outline the method is to do it on the above example:
Think of the distribution as a histogram with 4 bins:
We cut off the tops of the tallest bars and put them in the shorter ones, 'squaring it off'. The average 'height' of a bar will be 0.25. So we cut 0.15 off the second bar and put it in the first and 0.05 off the fourth and put it in the third:
Its always possible to organize this in such a way that no bin ends up with more than 2 colors, though one color may end up in several bins.
So now you choose one of the 4 bins at random (requires 2 random bits off the top of a uniform). You then use the remaining bits to specify a uniformly distributed vertical position and compare with the break between colors to work out which of two values to output. While very fast it's usually not quite as fast as the 'table' method.
--
These methods can be adapted to deal with unbounded variables, where again, it's 'mostly fast'.
A reference: http://www.jstatsoft.org/v11/i03/paper
The relatively slow part of these is creating the tables of values; they're suitable when you know what you're going to be generating ("we need to sample values from this distribution many times in the future") rather than trying to create it as you go. "We need to sample a million values from this ASAP, but we'll never need to do it again" creates different priorities; in many situations some of the "standard computing approaches" to looking up sorted values (i.e. to doing the cdf method more quickly) may actually be about your best choice.
There are still other fast approaches to generating from discrete distributions. Carefully coded, you can do some very fast generation. For example:
3) the rejection method ("accept-reject") can be done with discrete distributions; if you have a discrete majorizing function ("envelope") which is a scaled-up discrete pmf that you can already generate from in a fast way, it adapts directly, and in some cases can be very fast. More generally you can take advantage of being able to generate from continuous distributions (for example by discretizing the result back to a discrete envelope).
Here imagine that we have some discrete probability function $f$ for which we don't have a convenient cdf (or inverse-cdf) -- indeed in this illustration we didn't even have the normalizing constant, so our plot is unnormalized:
Now we need to find some convenient-to-generate-from discrete probability function $g$, which can be multiplied by a constant $c$ and be everywhere at least as large as $f$ (we need to be sure that this remains true for all $x$ values). That is, $c.g(x)\geq f(x)$ for all the possible $x$ values.
Sometimes a suitable $g$ is easily identified, but one useful option is to take a mixture of a discrete uniform for the left part, and a distribution with at least as heavy a tail as $f$ on the right. Two reasonably convenient choices for that are a geometric distribution (when the tail isn't decreasing slower than exponentially) and something like a discretized Pareto or discretized half-Cauchy distribution, obtained by taking $\lfloor X\rfloor$ for some Pareto or half-Cauchy random variate $X$ (in either case for when the pmf is decreasing slower than exponentially).
(For that matter, the geometric itself can be generated by discretizing an exponential.)
In this case, a discrete uniform on the left and a geometric on the right work quite well:
(Reminder: what is plotted here is an unnormalized pmf, so the y-axis doesn't represent probability but something proportional to probability)
Then the procedure is a matter of simulating a proposed value $x$ from $g$, simulating a uniform, $U$ on $(0,c.g(x))$ and if $U<f$, accepting that proposed $x$ (otherwise rejecting it and generating a new proposed $x$).
|
How to sample from a discrete distribution? [duplicate]
In response to a question in comments, here's an outline of a few potentially* faster ways to do discrete distributions than the cdf method.
* I say "potentially" because for some discrete cases a wel
|
7,123
|
How to sample from a discrete distribution? [duplicate]
|
In python you could do something like
from scipy.stats import rv_discrete
x=[1,2,3,4]
px=[0.1,0.4,0.2,0.3]
sample=rv_discrete(values=(x,px)).rvs(size=10)
Which would give you 10 samples from the distribution. You could repeat this then find the proportions of samples that are 2.
|
How to sample from a discrete distribution? [duplicate]
|
In python you could do something like
from scipy.stats import rv_discrete
x=[1,2,3,4]
px=[0.1,0.4,0.2,0.3]
sample=rv_discrete(values=(x,px)).rvs(size=10)
Which would give you 10 sam
|
How to sample from a discrete distribution? [duplicate]
In python you could do something like
from scipy.stats import rv_discrete
x=[1,2,3,4]
px=[0.1,0.4,0.2,0.3]
sample=rv_discrete(values=(x,px)).rvs(size=10)
Which would give you 10 samples from the distribution. You could repeat this then find the proportions of samples that are 2.
|
How to sample from a discrete distribution? [duplicate]
In python you could do something like
from scipy.stats import rv_discrete
x=[1,2,3,4]
px=[0.1,0.4,0.2,0.3]
sample=rv_discrete(values=(x,px)).rvs(size=10)
Which would give you 10 sam
|
7,124
|
How to sample from a discrete distribution? [duplicate]
|
Yes it is possible and fairly easy, exactly how depends on what tool(s) you are using.
In R it would be sample(1:4, n, prob=c(0.1,0.4,0.2,0.3), replace=TRUE) where n is the number of values you want to sample.
In tools without an equivalent function you can still generate a uniform value and then your RV will equal 1 if it is below 0.1, 2 if it is between 0.1 and 0.5, 3 if between 0.5 and 0.7, and 4 if greater than 0.7 (that is the idea of mapping to the cumulative).
For your example you could also sample uniformly from a set with one 1, four 2's, two 3's, and three 4's to get the same probabilities.
|
How to sample from a discrete distribution? [duplicate]
|
Yes it is possible and fairly easy, exactly how depends on what tool(s) you are using.
In R it would be sample(1:4, n, prob=c(0.1,0.4,0.2,0.3), replace=TRUE) where n is the number of values you want t
|
How to sample from a discrete distribution? [duplicate]
Yes it is possible and fairly easy, exactly how depends on what tool(s) you are using.
In R it would be sample(1:4, n, prob=c(0.1,0.4,0.2,0.3), replace=TRUE) where n is the number of values you want to sample.
In tools without an equivalent function you can still generate a uniform value and then your RV will equal 1 if it is below 0.1, 2 if it is between 0.1 and 0.5, 3 if between 0.5 and 0.7, and 4 if greater than 0.7 (that is the idea of mapping to the cumulative).
For your example you could also sample uniformly from a set with one 1, four 2's, two 3's, and three 4's to get the same probabilities.
|
How to sample from a discrete distribution? [duplicate]
Yes it is possible and fairly easy, exactly how depends on what tool(s) you are using.
In R it would be sample(1:4, n, prob=c(0.1,0.4,0.2,0.3), replace=TRUE) where n is the number of values you want t
|
7,125
|
How to sample from a discrete distribution? [duplicate]
|
In Stata:
In Mata use rdiscrete() as documented at http://www.stata.com/help.cgi?mf_runiform
In Stata itself, there are various ways. Here's one:
. gen rnd = runiform()
. gen y = cond(rnd <= 0.1, 1, cond(rnd <= .5, 2, cond(rnd <= .7, 3, 4)))
|
How to sample from a discrete distribution? [duplicate]
|
In Stata:
In Mata use rdiscrete() as documented at http://www.stata.com/help.cgi?mf_runiform
In Stata itself, there are various ways. Here's one:
. gen rnd = runiform()
. gen y = cond(rnd <= 0.1, 1
|
How to sample from a discrete distribution? [duplicate]
In Stata:
In Mata use rdiscrete() as documented at http://www.stata.com/help.cgi?mf_runiform
In Stata itself, there are various ways. Here's one:
. gen rnd = runiform()
. gen y = cond(rnd <= 0.1, 1, cond(rnd <= .5, 2, cond(rnd <= .7, 3, 4)))
|
How to sample from a discrete distribution? [duplicate]
In Stata:
In Mata use rdiscrete() as documented at http://www.stata.com/help.cgi?mf_runiform
In Stata itself, there are various ways. Here's one:
. gen rnd = runiform()
. gen y = cond(rnd <= 0.1, 1
|
7,126
|
Gradient of Hinge loss
|
To get the gradient we differentiate the loss with respect to $i$th component of $w$.
Rewrite hinge loss in terms of $w$ as $f(g(w))$ where $f(z)=\max(0,1-y\ z)$ and $g(w)=\mathbf{x}\cdot \mathbf{w}$
Using chain rule we get
$$\frac{\partial}{\partial w_i} f(g(w))=\frac{\partial f}{\partial z} \frac{\partial g}{\partial w_i} $$
First derivative term is evaluated at $g(w)=x\cdot w$ becoming $-y$ when $\mathbf{x}\cdot w<1$, and 0 when $\mathbf{x}\cdot w>1$. Second derivative term becomes $x_i$. So in the end you get
$$
\frac{\partial f(g(w))}{\partial w_i} =
\begin{cases}
-y\ x_i &\text{if } y\ \mathbf{x}\cdot \mathbf{w} < 1 \\
0&\text{if } y\ \mathbf{x}\cdot \mathbf{w} > 1
\end{cases}
$$
Since $i$ ranges over the components of $x$, you can view the above as a vector quantity, and write $\frac{\partial}{\partial w}$ as shorthand for $(\frac{\partial}{\partial w_1},\frac{\partial}{\partial w_2},\ldots)$
|
Gradient of Hinge loss
|
To get the gradient we differentiate the loss with respect to $i$th component of $w$.
Rewrite hinge loss in terms of $w$ as $f(g(w))$ where $f(z)=\max(0,1-y\ z)$ and $g(w)=\mathbf{x}\cdot \mathbf{w}$
|
Gradient of Hinge loss
To get the gradient we differentiate the loss with respect to $i$th component of $w$.
Rewrite hinge loss in terms of $w$ as $f(g(w))$ where $f(z)=\max(0,1-y\ z)$ and $g(w)=\mathbf{x}\cdot \mathbf{w}$
Using chain rule we get
$$\frac{\partial}{\partial w_i} f(g(w))=\frac{\partial f}{\partial z} \frac{\partial g}{\partial w_i} $$
First derivative term is evaluated at $g(w)=x\cdot w$ becoming $-y$ when $\mathbf{x}\cdot w<1$, and 0 when $\mathbf{x}\cdot w>1$. Second derivative term becomes $x_i$. So in the end you get
$$
\frac{\partial f(g(w))}{\partial w_i} =
\begin{cases}
-y\ x_i &\text{if } y\ \mathbf{x}\cdot \mathbf{w} < 1 \\
0&\text{if } y\ \mathbf{x}\cdot \mathbf{w} > 1
\end{cases}
$$
Since $i$ ranges over the components of $x$, you can view the above as a vector quantity, and write $\frac{\partial}{\partial w}$ as shorthand for $(\frac{\partial}{\partial w_1},\frac{\partial}{\partial w_2},\ldots)$
|
Gradient of Hinge loss
To get the gradient we differentiate the loss with respect to $i$th component of $w$.
Rewrite hinge loss in terms of $w$ as $f(g(w))$ where $f(z)=\max(0,1-y\ z)$ and $g(w)=\mathbf{x}\cdot \mathbf{w}$
|
7,127
|
Gradient of Hinge loss
|
This is 3 years late, but still may be relevant for someone...
Let $S$ denote a sample of points $x_i \in R^d$ and the set of corresponding labels $y_i \in \{-1,1\}$. We search to find a hyperplane $w$ that would minimize the total hinge-loss:
\begin{equation}
w^* = \underset{w}{\text{argmin }} L^{hinge}_S(w) = \underset{w}{\text{argmin }} \sum_i{l_{hinge}(w,x_i,y_i)}= \underset{w}{\text{argmin }} \sum_i{\max{\{0,1-y_iw\cdot x}\}}
\end{equation}
To find $w^*$ take derivative of the total hinge loss . Gradient of each component is:
$$
\frac{\partial{l_{hinge}}}{\partial w}=
\begin{cases}
0 & y_iw\cdot x \geq 1 \\
-y_ix & y_iw\cdot x < 1
\end{cases}
$$
The gradient of the sum is a sum of gradients.
$$
\frac{\partial{L_S^{hinge}}}{\partial{w}}=\sum_i{\frac{\partial{l_{hinge}}}{\partial w}}
$$
Python example, which uses GD to find hinge-loss optimal separatinig hyperplane follows (its probably not the most efficient code, but it works)
import numpy as np
import matplotlib.pyplot as plt
def hinge_loss(w,x,y):
""" evaluates hinge loss and its gradient at w
rows of x are data points
y is a vector of labels
"""
loss,grad = 0,0
for (x_,y_) in zip(x,y):
v = y_*np.dot(w,x_)
loss += max(0,1-v)
grad += 0 if v > 1 else -y_*x_
return (loss,grad)
def grad_descent(x,y,w,step,thresh=0.001):
grad = np.inf
ws = np.zeros((2,0))
ws = np.hstack((ws,w.reshape(2,1)))
step_num = 1
delta = np.inf
loss0 = np.inf
while np.abs(delta)>thresh:
loss,grad = hinge_loss(w,x,y)
delta = loss0-loss
loss0 = loss
grad_dir = grad/np.linalg.norm(grad)
w = w-step*grad_dir/step_num
ws = np.hstack((ws,w.reshape((2,1))))
step_num += 1
return np.sum(ws,1)/np.size(ws,1)
def test1():
# sample data points
x1 = np.array((0,1,3,4,1))
x2 = np.array((1,2,0,1,1))
x = np.vstack((x1,x2)).T
# sample labels
y = np.array((1,1,-1,-1,-1))
w = grad_descent(x,y,np.array((0,0)),0.1)
loss, grad = hinge_loss(w,x,y)
plot_test(x,y,w)
def plot_test(x,y,w):
plt.figure()
x1, x2 = x[:,0], x[:,1]
x1_min, x1_max = np.min(x1)*.7, np.max(x1)*1.3
x2_min, x2_max = np.min(x2)*.7, np.max(x2)*1.3
gridpoints = 2000
x1s = np.linspace(x1_min, x1_max, gridpoints)
x2s = np.linspace(x2_min, x2_max, gridpoints)
gridx1, gridx2 = np.meshgrid(x1s,x2s)
grid_pts = np.c_[gridx1.ravel(), gridx2.ravel()]
predictions = np.array([np.sign(np.dot(w,x_)) for x_ in grid_pts]).reshape((gridpoints,gridpoints))
plt.contourf(gridx1, gridx2, predictions, cmap=plt.cm.Paired)
plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Paired)
plt.title('total hinge loss: %g' % hinge_loss(w,x,y)[0])
plt.show()
if __name__ == '__main__':
np.set_printoptions(precision=3)
test1()
|
Gradient of Hinge loss
|
This is 3 years late, but still may be relevant for someone...
Let $S$ denote a sample of points $x_i \in R^d$ and the set of corresponding labels $y_i \in \{-1,1\}$. We search to find a hyperplane $w
|
Gradient of Hinge loss
This is 3 years late, but still may be relevant for someone...
Let $S$ denote a sample of points $x_i \in R^d$ and the set of corresponding labels $y_i \in \{-1,1\}$. We search to find a hyperplane $w$ that would minimize the total hinge-loss:
\begin{equation}
w^* = \underset{w}{\text{argmin }} L^{hinge}_S(w) = \underset{w}{\text{argmin }} \sum_i{l_{hinge}(w,x_i,y_i)}= \underset{w}{\text{argmin }} \sum_i{\max{\{0,1-y_iw\cdot x}\}}
\end{equation}
To find $w^*$ take derivative of the total hinge loss . Gradient of each component is:
$$
\frac{\partial{l_{hinge}}}{\partial w}=
\begin{cases}
0 & y_iw\cdot x \geq 1 \\
-y_ix & y_iw\cdot x < 1
\end{cases}
$$
The gradient of the sum is a sum of gradients.
$$
\frac{\partial{L_S^{hinge}}}{\partial{w}}=\sum_i{\frac{\partial{l_{hinge}}}{\partial w}}
$$
Python example, which uses GD to find hinge-loss optimal separatinig hyperplane follows (its probably not the most efficient code, but it works)
import numpy as np
import matplotlib.pyplot as plt
def hinge_loss(w,x,y):
""" evaluates hinge loss and its gradient at w
rows of x are data points
y is a vector of labels
"""
loss,grad = 0,0
for (x_,y_) in zip(x,y):
v = y_*np.dot(w,x_)
loss += max(0,1-v)
grad += 0 if v > 1 else -y_*x_
return (loss,grad)
def grad_descent(x,y,w,step,thresh=0.001):
grad = np.inf
ws = np.zeros((2,0))
ws = np.hstack((ws,w.reshape(2,1)))
step_num = 1
delta = np.inf
loss0 = np.inf
while np.abs(delta)>thresh:
loss,grad = hinge_loss(w,x,y)
delta = loss0-loss
loss0 = loss
grad_dir = grad/np.linalg.norm(grad)
w = w-step*grad_dir/step_num
ws = np.hstack((ws,w.reshape((2,1))))
step_num += 1
return np.sum(ws,1)/np.size(ws,1)
def test1():
# sample data points
x1 = np.array((0,1,3,4,1))
x2 = np.array((1,2,0,1,1))
x = np.vstack((x1,x2)).T
# sample labels
y = np.array((1,1,-1,-1,-1))
w = grad_descent(x,y,np.array((0,0)),0.1)
loss, grad = hinge_loss(w,x,y)
plot_test(x,y,w)
def plot_test(x,y,w):
plt.figure()
x1, x2 = x[:,0], x[:,1]
x1_min, x1_max = np.min(x1)*.7, np.max(x1)*1.3
x2_min, x2_max = np.min(x2)*.7, np.max(x2)*1.3
gridpoints = 2000
x1s = np.linspace(x1_min, x1_max, gridpoints)
x2s = np.linspace(x2_min, x2_max, gridpoints)
gridx1, gridx2 = np.meshgrid(x1s,x2s)
grid_pts = np.c_[gridx1.ravel(), gridx2.ravel()]
predictions = np.array([np.sign(np.dot(w,x_)) for x_ in grid_pts]).reshape((gridpoints,gridpoints))
plt.contourf(gridx1, gridx2, predictions, cmap=plt.cm.Paired)
plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Paired)
plt.title('total hinge loss: %g' % hinge_loss(w,x,y)[0])
plt.show()
if __name__ == '__main__':
np.set_printoptions(precision=3)
test1()
|
Gradient of Hinge loss
This is 3 years late, but still may be relevant for someone...
Let $S$ denote a sample of points $x_i \in R^d$ and the set of corresponding labels $y_i \in \{-1,1\}$. We search to find a hyperplane $w
|
7,128
|
Gradient of Hinge loss
|
I fixed your code. The main problem is your definition of hinge and d_hinge functions. These should be applied one sample at a time. Instead your definition aggregates all the samples before taking the maximum.
#Run standard gradient descent
gradient_descent<-function(fw, dfw, n, lr=0.01)
{
#Date to be used
x<-t(matrix(c(1,3,6,1,4,2,1,5,4,1,6,1), nrow=3))
y<-t(t(c(1,1,-1,-1)))
w<-matrix(0, nrow=ncol(x))
print(sprintf("loss: %f,x.w: %s",sum(mapply(function(xr,yr) fw(w,xr,yr), split(x,row(x)),split(y,row(y)))),paste(x%*%w, collapse=',')))
#update the weights 'n' times
for (i in 1:n)
{
w<-w-lr*dfw(w,x,y)
print(sprintf("loss: %f,x.w: %s",sum(mapply(function(xr,yr) fw(w,xr,yr), split(x,row(x)),split(y,row(y)))),paste(x%*%w,collapse=',')))
}
}
#Hinge loss
hinge<-function(w,xr,yr) max(1-yr*xr%*%w, 0)
d_hinge<-function(w,x,y){ dw<- apply(mapply(function(xr,yr) -yr * xr * (yr * xr %*% w < 1),split(x,row(x)),split(y,row(y))),1,sum); dw}
gradient_descent(hinge, d_hinge, 100, lr=0.01)
I need n=10000 to converge.
[1] "loss: 0.090000,x.w: 1.08999999999995,0.909999999999905,-1.19000000000008,-1.69000000000011"
[1] "loss: 0.100000,x.w: 1.33999999999995,1.1199999999999,-0.900000000000075,-1.42000000000011"
[1] "loss: 0.230000,x.w: 0.939999999999948,0.829999999999905,-1.32000000000007,-1.77000000000011"
[1] "loss: 0.370000,x.w: 1.64999999999995,1.2899999999999,-0.630000000000075,-1.25000000000011"
[1] "loss: 0.000000,x.w: 1.24999999999995,0.999999999999905,-1.05000000000008,-1.60000000000011"
[1] "loss: 0.240000,x.w: 1.49999999999995,1.2099999999999,-0.760000000000075,-1.33000000000011"
[1] "loss: 0.080000,x.w: 1.09999999999995,0.919999999999905,-1.18000000000007,-1.68000000000011"
[1] "loss: 0.110000,x.w: 1.34999999999995,1.1299999999999,-0.890000000000075,-1.41000000000011"
[1] "loss: 0.210000,x.w: 0.949999999999948,0.839999999999905,-1.31000000000007,-1.76000000000011"
[1] "loss: 0.380000,x.w: 1.65999999999995,1.2999999999999,-0.620000000000074,-1.24000000000011"
[1] "loss: 0.000000,x.w: 1.25999999999995,1.0099999999999,-1.04000000000008,-1.59000000000011"
[1] "loss: 0.000000,x.w: 1.25999999999995,1.0099999999999,-1.04000000000008,-1.59000000000011"
|
Gradient of Hinge loss
|
I fixed your code. The main problem is your definition of hinge and d_hinge functions. These should be applied one sample at a time. Instead your definition aggregates all the samples before taking th
|
Gradient of Hinge loss
I fixed your code. The main problem is your definition of hinge and d_hinge functions. These should be applied one sample at a time. Instead your definition aggregates all the samples before taking the maximum.
#Run standard gradient descent
gradient_descent<-function(fw, dfw, n, lr=0.01)
{
#Date to be used
x<-t(matrix(c(1,3,6,1,4,2,1,5,4,1,6,1), nrow=3))
y<-t(t(c(1,1,-1,-1)))
w<-matrix(0, nrow=ncol(x))
print(sprintf("loss: %f,x.w: %s",sum(mapply(function(xr,yr) fw(w,xr,yr), split(x,row(x)),split(y,row(y)))),paste(x%*%w, collapse=',')))
#update the weights 'n' times
for (i in 1:n)
{
w<-w-lr*dfw(w,x,y)
print(sprintf("loss: %f,x.w: %s",sum(mapply(function(xr,yr) fw(w,xr,yr), split(x,row(x)),split(y,row(y)))),paste(x%*%w,collapse=',')))
}
}
#Hinge loss
hinge<-function(w,xr,yr) max(1-yr*xr%*%w, 0)
d_hinge<-function(w,x,y){ dw<- apply(mapply(function(xr,yr) -yr * xr * (yr * xr %*% w < 1),split(x,row(x)),split(y,row(y))),1,sum); dw}
gradient_descent(hinge, d_hinge, 100, lr=0.01)
I need n=10000 to converge.
[1] "loss: 0.090000,x.w: 1.08999999999995,0.909999999999905,-1.19000000000008,-1.69000000000011"
[1] "loss: 0.100000,x.w: 1.33999999999995,1.1199999999999,-0.900000000000075,-1.42000000000011"
[1] "loss: 0.230000,x.w: 0.939999999999948,0.829999999999905,-1.32000000000007,-1.77000000000011"
[1] "loss: 0.370000,x.w: 1.64999999999995,1.2899999999999,-0.630000000000075,-1.25000000000011"
[1] "loss: 0.000000,x.w: 1.24999999999995,0.999999999999905,-1.05000000000008,-1.60000000000011"
[1] "loss: 0.240000,x.w: 1.49999999999995,1.2099999999999,-0.760000000000075,-1.33000000000011"
[1] "loss: 0.080000,x.w: 1.09999999999995,0.919999999999905,-1.18000000000007,-1.68000000000011"
[1] "loss: 0.110000,x.w: 1.34999999999995,1.1299999999999,-0.890000000000075,-1.41000000000011"
[1] "loss: 0.210000,x.w: 0.949999999999948,0.839999999999905,-1.31000000000007,-1.76000000000011"
[1] "loss: 0.380000,x.w: 1.65999999999995,1.2999999999999,-0.620000000000074,-1.24000000000011"
[1] "loss: 0.000000,x.w: 1.25999999999995,1.0099999999999,-1.04000000000008,-1.59000000000011"
[1] "loss: 0.000000,x.w: 1.25999999999995,1.0099999999999,-1.04000000000008,-1.59000000000011"
|
Gradient of Hinge loss
I fixed your code. The main problem is your definition of hinge and d_hinge functions. These should be applied one sample at a time. Instead your definition aggregates all the samples before taking th
|
7,129
|
What is Bayes' theorem all about?
|
Bayes' theorem is a relatively simple, but fundamental result of probability theory that allows for the calculation of certain conditional probabilities. Conditional probabilities are just those probabilities that reflect the influence of one event on the probability of another.
Simply put, in its most famous form, it states that the probability of a hypothesis given new data (P(H|D); called the posterior probability) is equal to the following equation: the probability of the observed data given the hypothesis (P(D|H); called the conditional probability), times the probability of the theory being true prior to new evidence (P(H); called the prior probability of H), divided by the probability of seeing that data, period (P(D); called the marginal probability of D).
Formally, the equation looks like this:
The significance of Bayes theorem is largely due to its proper use being a point of contention between schools of thought on probability. To a subjective Bayesian (that interprets probability as being subjective degrees of belief) Bayes' theorem provides the cornerstone for theory testing, theory selection and other practices, by plugging their subjective probability judgments into the equation, and running with it. To a frequentist (that interprets probability as limiting relative frequencies), this use of Bayes' theorem is an abuse, and they strive to instead use meaningful (non-subjective) priors (as do objective Bayesians under yet another interpretation of probability).
|
What is Bayes' theorem all about?
|
Bayes' theorem is a relatively simple, but fundamental result of probability theory that allows for the calculation of certain conditional probabilities. Conditional probabilities are just those prob
|
What is Bayes' theorem all about?
Bayes' theorem is a relatively simple, but fundamental result of probability theory that allows for the calculation of certain conditional probabilities. Conditional probabilities are just those probabilities that reflect the influence of one event on the probability of another.
Simply put, in its most famous form, it states that the probability of a hypothesis given new data (P(H|D); called the posterior probability) is equal to the following equation: the probability of the observed data given the hypothesis (P(D|H); called the conditional probability), times the probability of the theory being true prior to new evidence (P(H); called the prior probability of H), divided by the probability of seeing that data, period (P(D); called the marginal probability of D).
Formally, the equation looks like this:
The significance of Bayes theorem is largely due to its proper use being a point of contention between schools of thought on probability. To a subjective Bayesian (that interprets probability as being subjective degrees of belief) Bayes' theorem provides the cornerstone for theory testing, theory selection and other practices, by plugging their subjective probability judgments into the equation, and running with it. To a frequentist (that interprets probability as limiting relative frequencies), this use of Bayes' theorem is an abuse, and they strive to instead use meaningful (non-subjective) priors (as do objective Bayesians under yet another interpretation of probability).
|
What is Bayes' theorem all about?
Bayes' theorem is a relatively simple, but fundamental result of probability theory that allows for the calculation of certain conditional probabilities. Conditional probabilities are just those prob
|
7,130
|
What is Bayes' theorem all about?
|
I'm sorry, but there seems to be some confusion here:
Bayes' theorem is not up for discussion of the neverending Bayesian-Frequentist debate. It is a theorem that is consistent with both schools of thought (given that it is consistent with Kolmogorov's probability axioms).
Of course, Bayes' theorem is the core of Bayesian statistics, but the theorem itself is universal. The clash between frequentists and Bayesians mostly pertains to how prior distributions can be defined or not.
So, if the question is about Bayes' theorem (and not Bayesian statistics):
Bayes' theorem defines how one can calculate specific conditional probabilities. Imagine for instance that you know: the probability of somebody having symptom A, given that they have disease X p(A|X); the probability of somebody in general having disease X p(X); the probability of somebody in general having symptom A p(A). with these 3 pieces of information you can calculate the probability of somebody having disease X, given that they have sympotm A p(X|A).
|
What is Bayes' theorem all about?
|
I'm sorry, but there seems to be some confusion here:
Bayes' theorem is not up for discussion of the neverending Bayesian-Frequentist debate. It is a theorem that is consistent with both schools of t
|
What is Bayes' theorem all about?
I'm sorry, but there seems to be some confusion here:
Bayes' theorem is not up for discussion of the neverending Bayesian-Frequentist debate. It is a theorem that is consistent with both schools of thought (given that it is consistent with Kolmogorov's probability axioms).
Of course, Bayes' theorem is the core of Bayesian statistics, but the theorem itself is universal. The clash between frequentists and Bayesians mostly pertains to how prior distributions can be defined or not.
So, if the question is about Bayes' theorem (and not Bayesian statistics):
Bayes' theorem defines how one can calculate specific conditional probabilities. Imagine for instance that you know: the probability of somebody having symptom A, given that they have disease X p(A|X); the probability of somebody in general having disease X p(X); the probability of somebody in general having symptom A p(A). with these 3 pieces of information you can calculate the probability of somebody having disease X, given that they have sympotm A p(X|A).
|
What is Bayes' theorem all about?
I'm sorry, but there seems to be some confusion here:
Bayes' theorem is not up for discussion of the neverending Bayesian-Frequentist debate. It is a theorem that is consistent with both schools of t
|
7,131
|
What is Bayes' theorem all about?
|
Bayes' theorem is a way to rotate a conditional probability $P(A|B)$ to another conditional probability $P(B|A)$.
A stumbling block for some is the meaning of $P(B|A)$. This is a way to reduce the space of possible events by considering only those events where $A$ definitely happens (or is true). So for instance the probability that a thrown, fair, dice lands showing six, $P(\mbox{dice lands six})$, is 1/6, however the probability that a dice lands six given that it landed an even number, $P(\mbox{dice lands six}|\mbox{dice lands even})$, is 1/3.
You can derive Bayes' theorem yourself as follows. Start with the ratio definition of a conditional probability:
$P(B|A) = \frac{P(AB)}{P(A)}$
where $P(AB)$ is the joint probability of $A$ and $B$ and $P(A)$ is the marginal probability of $A$.
Currently the formula makes no reference to $P(A|B)$, so let's write down the definition of this too:
$P(A|B) = \frac{P(BA)}{P(B)}$
The little trick for making this work is seeing that $P(AB) = P(BA)$ (since a Boolean algebra is underneath all of this, you can easily prove this with a truth table by showing $AB = BA$), so we can write:
$P(A|B) = \frac{P(AB)}{P(B)}$
Now to slot this into the formula for $P(B|A)$, just rewrite the formula above so $P(AB)$ is on the left:
$P(AB) = P(A|B)P(B)$
and hey presto:
$P(B|A) = \frac{P(A|B)P(B)}{P(A)}$
As for what the point is to rotating a conditional probability in this way, consider the common example of trying to infer the probability that someone has a disease given that they have a symptom, i.e., we know that they have a symptom - we can just see it - but we cannot be certain whether they have a disease and have to infer it. I'll start with the formula and work back.
$P(\mbox{disease}|\mbox{symptom}) = \frac{P(\mbox{symptom}|\mbox{disease})P(\mbox{disease})}{P(\mbox{symptom})}$
So to work it out, you need to know the prior probability of the symptom, the prior probability of the disease (i.e., how common or rare are the symptom and disease) and also the probability that someone has a symptom given we know someone has a disease (e.g., via expensive time consuming lab tests).
It can get a lot more complicated than this, e.g., if you have multiple diseases and symptoms, but the idea is the same. Even more generally, Bayes' theorem often makes an appearance if you have a probability theory of relationships between causes (e.g., diseases) and effects (e.g., symptoms) and you need to reason backwards (e.g., you see some symptoms from which you want to infer the underlying disease).
|
What is Bayes' theorem all about?
|
Bayes' theorem is a way to rotate a conditional probability $P(A|B)$ to another conditional probability $P(B|A)$.
A stumbling block for some is the meaning of $P(B|A)$. This is a way to reduce the sp
|
What is Bayes' theorem all about?
Bayes' theorem is a way to rotate a conditional probability $P(A|B)$ to another conditional probability $P(B|A)$.
A stumbling block for some is the meaning of $P(B|A)$. This is a way to reduce the space of possible events by considering only those events where $A$ definitely happens (or is true). So for instance the probability that a thrown, fair, dice lands showing six, $P(\mbox{dice lands six})$, is 1/6, however the probability that a dice lands six given that it landed an even number, $P(\mbox{dice lands six}|\mbox{dice lands even})$, is 1/3.
You can derive Bayes' theorem yourself as follows. Start with the ratio definition of a conditional probability:
$P(B|A) = \frac{P(AB)}{P(A)}$
where $P(AB)$ is the joint probability of $A$ and $B$ and $P(A)$ is the marginal probability of $A$.
Currently the formula makes no reference to $P(A|B)$, so let's write down the definition of this too:
$P(A|B) = \frac{P(BA)}{P(B)}$
The little trick for making this work is seeing that $P(AB) = P(BA)$ (since a Boolean algebra is underneath all of this, you can easily prove this with a truth table by showing $AB = BA$), so we can write:
$P(A|B) = \frac{P(AB)}{P(B)}$
Now to slot this into the formula for $P(B|A)$, just rewrite the formula above so $P(AB)$ is on the left:
$P(AB) = P(A|B)P(B)$
and hey presto:
$P(B|A) = \frac{P(A|B)P(B)}{P(A)}$
As for what the point is to rotating a conditional probability in this way, consider the common example of trying to infer the probability that someone has a disease given that they have a symptom, i.e., we know that they have a symptom - we can just see it - but we cannot be certain whether they have a disease and have to infer it. I'll start with the formula and work back.
$P(\mbox{disease}|\mbox{symptom}) = \frac{P(\mbox{symptom}|\mbox{disease})P(\mbox{disease})}{P(\mbox{symptom})}$
So to work it out, you need to know the prior probability of the symptom, the prior probability of the disease (i.e., how common or rare are the symptom and disease) and also the probability that someone has a symptom given we know someone has a disease (e.g., via expensive time consuming lab tests).
It can get a lot more complicated than this, e.g., if you have multiple diseases and symptoms, but the idea is the same. Even more generally, Bayes' theorem often makes an appearance if you have a probability theory of relationships between causes (e.g., diseases) and effects (e.g., symptoms) and you need to reason backwards (e.g., you see some symptoms from which you want to infer the underlying disease).
|
What is Bayes' theorem all about?
Bayes' theorem is a way to rotate a conditional probability $P(A|B)$ to another conditional probability $P(B|A)$.
A stumbling block for some is the meaning of $P(B|A)$. This is a way to reduce the sp
|
7,132
|
What is Bayes' theorem all about?
|
There are two main schools of thought is Statistics: frequentist and Bayesian.
Bayes theorem is to do with the latter and can be seen as a way of understanding how the probability that a theory is true is affected by a new piece of evidence. This is known as conditional probability. You might want to look at this to get a handle on the math.
|
What is Bayes' theorem all about?
|
There are two main schools of thought is Statistics: frequentist and Bayesian.
Bayes theorem is to do with the latter and can be seen as a way of understanding how the probability that a theory is tr
|
What is Bayes' theorem all about?
There are two main schools of thought is Statistics: frequentist and Bayesian.
Bayes theorem is to do with the latter and can be seen as a way of understanding how the probability that a theory is true is affected by a new piece of evidence. This is known as conditional probability. You might want to look at this to get a handle on the math.
|
What is Bayes' theorem all about?
There are two main schools of thought is Statistics: frequentist and Bayesian.
Bayes theorem is to do with the latter and can be seen as a way of understanding how the probability that a theory is tr
|
7,133
|
What is Bayes' theorem all about?
|
Let me give you a very very intuitional insight. Suppose you are tossing a coin 10 times and you get 8 heads and 2 tails. The question that would come to your mind is whether this coin is biased towards heads or not.
Now if you go by conventional definitions or the frequentist approach of probability you might say that the coin is unbiased and this is an exceptional occurrence. Hence you would conclude that the possibility of getting a head next toss is also 50%.
But suppose you are a Bayesian. You would actually think that since you have got exceptionally high number of heads, the coin has a bias towards the head side. There are methods to calculate this possible bias. You would calculate them and then when you toss the coin next time, you would definitely call a heads.
So, Bayesian probability is about the belief that you develop based on the data you observe. I hope that was simple enough.
|
What is Bayes' theorem all about?
|
Let me give you a very very intuitional insight. Suppose you are tossing a coin 10 times and you get 8 heads and 2 tails. The question that would come to your mind is whether this coin is biased towa
|
What is Bayes' theorem all about?
Let me give you a very very intuitional insight. Suppose you are tossing a coin 10 times and you get 8 heads and 2 tails. The question that would come to your mind is whether this coin is biased towards heads or not.
Now if you go by conventional definitions or the frequentist approach of probability you might say that the coin is unbiased and this is an exceptional occurrence. Hence you would conclude that the possibility of getting a head next toss is also 50%.
But suppose you are a Bayesian. You would actually think that since you have got exceptionally high number of heads, the coin has a bias towards the head side. There are methods to calculate this possible bias. You would calculate them and then when you toss the coin next time, you would definitely call a heads.
So, Bayesian probability is about the belief that you develop based on the data you observe. I hope that was simple enough.
|
What is Bayes' theorem all about?
Let me give you a very very intuitional insight. Suppose you are tossing a coin 10 times and you get 8 heads and 2 tails. The question that would come to your mind is whether this coin is biased towa
|
7,134
|
What is Bayes' theorem all about?
|
Bayes' theorem relates two ideas: probability and likelihood. Probability says: given this model, these are the outcomes. So: given a fair coin, I'll get heads 50% of the time. Likelihood says: given these outcomes, this is what we can say about the model. So: if you toss a coin 100 times and get 88 heads (to pick up on a previous example and make it more extreme), then the likelihood that the fair coin model is correct is not so high.
One of the standard examples used to illustrate Bayes' theorem is the idea of testing for a disease: if you take a test that's 95% accurate for a disease that 1 in 10000 of the population have, and you test positive, what are the chances that you have the disease?
The naive answer is 95%, but this ignores the issue that 5% of the tests on 9999 out of 10000 people will give a false positive. So your odds of having the disease are far lower than 95%.
My use of the vague phrase "what are the chances" is deliberate. To use the probability/likelihood language: the probability that the test is accurate is 95%, but what you want to know is the likelihood that you have the disease.
Slightly off topic: The other classic example which Bayes theorem is used to solve in all the textbooks is the Monty Hall problem: You're on a quiz show. There is a prize behind one of three doors. You choose door one. The host opens door three to reveal no prize. Should you change to door two given the chance?
I like the rewording of the question (courtesy of the reference below): you're on a quiz show. There is a prize behind one of a million doors. You choose door one. The host opens all the other doors except door 104632 to reveal no prize. Should you change to door 104632?
My favourite book which discusses Bayes' theorem, very much from the Bayesian perspective, is "Information Theory, Inference and Learning Algorithms ", by David J. C. MacKay. It's a Cambridge University Press book, ISBN-13: 9780521642989. My answer is (I hope) a distillation of the kind of discussions made in the book. (Usual rules apply: I have no affiliations with the author, I just like the book).
|
What is Bayes' theorem all about?
|
Bayes' theorem relates two ideas: probability and likelihood. Probability says: given this model, these are the outcomes. So: given a fair coin, I'll get heads 50% of the time. Likelihood says: given
|
What is Bayes' theorem all about?
Bayes' theorem relates two ideas: probability and likelihood. Probability says: given this model, these are the outcomes. So: given a fair coin, I'll get heads 50% of the time. Likelihood says: given these outcomes, this is what we can say about the model. So: if you toss a coin 100 times and get 88 heads (to pick up on a previous example and make it more extreme), then the likelihood that the fair coin model is correct is not so high.
One of the standard examples used to illustrate Bayes' theorem is the idea of testing for a disease: if you take a test that's 95% accurate for a disease that 1 in 10000 of the population have, and you test positive, what are the chances that you have the disease?
The naive answer is 95%, but this ignores the issue that 5% of the tests on 9999 out of 10000 people will give a false positive. So your odds of having the disease are far lower than 95%.
My use of the vague phrase "what are the chances" is deliberate. To use the probability/likelihood language: the probability that the test is accurate is 95%, but what you want to know is the likelihood that you have the disease.
Slightly off topic: The other classic example which Bayes theorem is used to solve in all the textbooks is the Monty Hall problem: You're on a quiz show. There is a prize behind one of three doors. You choose door one. The host opens door three to reveal no prize. Should you change to door two given the chance?
I like the rewording of the question (courtesy of the reference below): you're on a quiz show. There is a prize behind one of a million doors. You choose door one. The host opens all the other doors except door 104632 to reveal no prize. Should you change to door 104632?
My favourite book which discusses Bayes' theorem, very much from the Bayesian perspective, is "Information Theory, Inference and Learning Algorithms ", by David J. C. MacKay. It's a Cambridge University Press book, ISBN-13: 9780521642989. My answer is (I hope) a distillation of the kind of discussions made in the book. (Usual rules apply: I have no affiliations with the author, I just like the book).
|
What is Bayes' theorem all about?
Bayes' theorem relates two ideas: probability and likelihood. Probability says: given this model, these are the outcomes. So: given a fair coin, I'll get heads 50% of the time. Likelihood says: given
|
7,135
|
What is Bayes' theorem all about?
|
Bayes theorem in its most obvious form is simply a re-statement of two things:
the joint probability is symmetric in its arguments $P(HD|I)=P(DH|I)$
the product rule $P(HD|I)=P(H|I)P(D|HI)$
So by using the symmetry:
$$P(HD|I)=P(H|I)P(D|HI)=P(D|I)P(H|DI)$$
Now if $P(D|I) \neq 0$ you can divide both sides by $P(D|I)$ to get:
$$P(H|DI)=P(H|I)\frac{P(D|HI)}{P(D|I)}$$
So this is it? How can something so simple be so awesome? As with most things "its the journey that's more important than the destination". Bayes theorem rocks because of the arguments that lead to it.
What is missing from this is that the product rule and sum rule $P(H|I)=1-P(\overline{H}|I)$, can be derived using deductive logic based on axioms of consistent reasoning.
Now the "rule" in deductive logic is that if you have a relationship "A implies B" then you also have "Not B implies Not A". So we have "consistent reasoning implies Bayes theorem". This means "Not Bayes theorem implies Not consistent reasoning". i.e. if your result isn't equivalent to a Bayesian result for some prior and likelihood then you are reasoning inconsistently.
This result is called Cox's theorem and was proved in "Algebra of Probable inference" in the 1940's. A more recent derivation is given in Proability theory: The logic of science.
|
What is Bayes' theorem all about?
|
Bayes theorem in its most obvious form is simply a re-statement of two things:
the joint probability is symmetric in its arguments $P(HD|I)=P(DH|I)$
the product rule $P(HD|I)=P(H|I)P(D|HI)$
So by us
|
What is Bayes' theorem all about?
Bayes theorem in its most obvious form is simply a re-statement of two things:
the joint probability is symmetric in its arguments $P(HD|I)=P(DH|I)$
the product rule $P(HD|I)=P(H|I)P(D|HI)$
So by using the symmetry:
$$P(HD|I)=P(H|I)P(D|HI)=P(D|I)P(H|DI)$$
Now if $P(D|I) \neq 0$ you can divide both sides by $P(D|I)$ to get:
$$P(H|DI)=P(H|I)\frac{P(D|HI)}{P(D|I)}$$
So this is it? How can something so simple be so awesome? As with most things "its the journey that's more important than the destination". Bayes theorem rocks because of the arguments that lead to it.
What is missing from this is that the product rule and sum rule $P(H|I)=1-P(\overline{H}|I)$, can be derived using deductive logic based on axioms of consistent reasoning.
Now the "rule" in deductive logic is that if you have a relationship "A implies B" then you also have "Not B implies Not A". So we have "consistent reasoning implies Bayes theorem". This means "Not Bayes theorem implies Not consistent reasoning". i.e. if your result isn't equivalent to a Bayesian result for some prior and likelihood then you are reasoning inconsistently.
This result is called Cox's theorem and was proved in "Algebra of Probable inference" in the 1940's. A more recent derivation is given in Proability theory: The logic of science.
|
What is Bayes' theorem all about?
Bayes theorem in its most obvious form is simply a re-statement of two things:
the joint probability is symmetric in its arguments $P(HD|I)=P(DH|I)$
the product rule $P(HD|I)=P(H|I)P(D|HI)$
So by us
|
7,136
|
What is Bayes' theorem all about?
|
I really like Kevin Murphy's intro the to Bayes Theorem
http://www.cs.ubc.ca/~murphyk/Bayes/bayesrule.html
The quote here is from an economist article:
http://www.cs.ubc.ca/~murphyk/Bayes/economist.html
The essence of the Bayesian approach is to provide a mathematical rule explaining how you should change your existing beliefs in the light of new evidence. In other words, it allows scientists to combine new data with their existing knowledge or expertise. The canonical example is to imagine that a precocious newborn observes his first sunset, and wonders whether the sun will rise again or not. He assigns equal prior probabilities to both possible outcomes, and represents this by placing one white and one black marble into a bag. The following day, when the sun rises, the child places another white marble in the bag. The probability that a marble plucked randomly from the bag will be white (ie, the child's degree of belief in future sunrises) has thus gone from a half to two-thirds. After sunrise the next day, the child adds another white marble, and the probability (and thus the degree of belief) goes from two-thirds to three-quarters. And so on. Gradually, the initial belief that the sun is just as likely as not to rise each morning is modified to become a near-certainty that the sun will always rise.
|
What is Bayes' theorem all about?
|
I really like Kevin Murphy's intro the to Bayes Theorem
http://www.cs.ubc.ca/~murphyk/Bayes/bayesrule.html
The quote here is from an economist article:
http://www.cs.ubc.ca/~murphyk/Bayes/economist.ht
|
What is Bayes' theorem all about?
I really like Kevin Murphy's intro the to Bayes Theorem
http://www.cs.ubc.ca/~murphyk/Bayes/bayesrule.html
The quote here is from an economist article:
http://www.cs.ubc.ca/~murphyk/Bayes/economist.html
The essence of the Bayesian approach is to provide a mathematical rule explaining how you should change your existing beliefs in the light of new evidence. In other words, it allows scientists to combine new data with their existing knowledge or expertise. The canonical example is to imagine that a precocious newborn observes his first sunset, and wonders whether the sun will rise again or not. He assigns equal prior probabilities to both possible outcomes, and represents this by placing one white and one black marble into a bag. The following day, when the sun rises, the child places another white marble in the bag. The probability that a marble plucked randomly from the bag will be white (ie, the child's degree of belief in future sunrises) has thus gone from a half to two-thirds. After sunrise the next day, the child adds another white marble, and the probability (and thus the degree of belief) goes from two-thirds to three-quarters. And so on. Gradually, the initial belief that the sun is just as likely as not to rise each morning is modified to become a near-certainty that the sun will always rise.
|
What is Bayes' theorem all about?
I really like Kevin Murphy's intro the to Bayes Theorem
http://www.cs.ubc.ca/~murphyk/Bayes/bayesrule.html
The quote here is from an economist article:
http://www.cs.ubc.ca/~murphyk/Bayes/economist.ht
|
7,137
|
Introduction to causal analysis
|
Pearl recently published a new book, aimed for beginners: Causal Inference in Statistics: A Primer. If you have never seen causality with directed acyclic graphs before, this is where you should start. And you should do all the study questions of the book —— this will help you get acquainted with the new tools and notation.
Pearl is also releasing a book aimed for the general audience, The Book of Why which will be available May 2018.
Also aimed for beginners, Miguel Hernán has just started a new causal inference course on edX Causal Diagrams: Draw Your Assumptions Before Your Conclusions.
In the Handbook of Causal Analysis for Social Research, there's also a very good text by Felix Elwert, Chapter 13, which is a very friendly introduction to graphical models.
Other two good papers with "gentle introductions" (as Pearl likes to say) to causal graphs are Pearl (2003) and Pearl (2009). The first paper comes with discussions as well.
As other people have mentioned, Morgan and Winship is a very good textbook --- for social scientists a very friendly yet comprehensive introduction --- and it covers both graphical models and potential outcomes.
There's a recent book by Imbens and Rubin, which covers to a greater extent some parts of randomized experiments, but there's nothing on DAGS --- it will only expose you to the potential outcomes framework, so you need to supplement it with other books, as the one mentioned above.
Among economists, the graduate and undergraduate books by Angrist and Pischke are popular. But it's important to notice they focus on common strategies/tricks --- instrumental variables, differences-in-differences, RDD etc. So you can get a flavor of a more applied perspective, but with only that you won't get the bigger picture about identification problems.
If you are interested in causal discovery and want a more Machine Learning oriented approach, Peters, Janzing and Scholkopf have a new book out Elements of Causal inference, the pdf is free.
It's worth mentioning here the "Causality in Statistics Education" prize. On its webpage you can find slides and other materials for several classes that won the prize for each year since its beginning on 2013. In this vein is also worth noticing VanderWeele's book.
Finally, as obviously already mentioned, there's Pearl's now classic book. The readings of the more preliminary materials cited above will help you reading it.
|
Introduction to causal analysis
|
Pearl recently published a new book, aimed for beginners: Causal Inference in Statistics: A Primer. If you have never seen causality with directed acyclic graphs before, this is where you should start
|
Introduction to causal analysis
Pearl recently published a new book, aimed for beginners: Causal Inference in Statistics: A Primer. If you have never seen causality with directed acyclic graphs before, this is where you should start. And you should do all the study questions of the book —— this will help you get acquainted with the new tools and notation.
Pearl is also releasing a book aimed for the general audience, The Book of Why which will be available May 2018.
Also aimed for beginners, Miguel Hernán has just started a new causal inference course on edX Causal Diagrams: Draw Your Assumptions Before Your Conclusions.
In the Handbook of Causal Analysis for Social Research, there's also a very good text by Felix Elwert, Chapter 13, which is a very friendly introduction to graphical models.
Other two good papers with "gentle introductions" (as Pearl likes to say) to causal graphs are Pearl (2003) and Pearl (2009). The first paper comes with discussions as well.
As other people have mentioned, Morgan and Winship is a very good textbook --- for social scientists a very friendly yet comprehensive introduction --- and it covers both graphical models and potential outcomes.
There's a recent book by Imbens and Rubin, which covers to a greater extent some parts of randomized experiments, but there's nothing on DAGS --- it will only expose you to the potential outcomes framework, so you need to supplement it with other books, as the one mentioned above.
Among economists, the graduate and undergraduate books by Angrist and Pischke are popular. But it's important to notice they focus on common strategies/tricks --- instrumental variables, differences-in-differences, RDD etc. So you can get a flavor of a more applied perspective, but with only that you won't get the bigger picture about identification problems.
If you are interested in causal discovery and want a more Machine Learning oriented approach, Peters, Janzing and Scholkopf have a new book out Elements of Causal inference, the pdf is free.
It's worth mentioning here the "Causality in Statistics Education" prize. On its webpage you can find slides and other materials for several classes that won the prize for each year since its beginning on 2013. In this vein is also worth noticing VanderWeele's book.
Finally, as obviously already mentioned, there's Pearl's now classic book. The readings of the more preliminary materials cited above will help you reading it.
|
Introduction to causal analysis
Pearl recently published a new book, aimed for beginners: Causal Inference in Statistics: A Primer. If you have never seen causality with directed acyclic graphs before, this is where you should start
|
7,138
|
Introduction to causal analysis
|
Try Morgan and Winship (2007) for a social science take or Hernan and Robins (forthcoming) for an epidemiological take. Although still in progress, this looks like it's going to be very good.
Morgan and Winship is particularly good on what must be assumed for causal interpretations of regression-type models.
Pearl (2000) is in no sense introductory, although ultimately a very good read. You may find some of his website and specific articles useful, particularly on interpreting structural equation models. They are mostly available as technical reports.
Update: Pearl, Glymour and Jewell's (2017) Causal Inference in Statistics: A Primer, is introductory though. And very good too.
|
Introduction to causal analysis
|
Try Morgan and Winship (2007) for a social science take or Hernan and Robins (forthcoming) for an epidemiological take. Although still in progress, this looks like it's going to be very good.
Morgan
|
Introduction to causal analysis
Try Morgan and Winship (2007) for a social science take or Hernan and Robins (forthcoming) for an epidemiological take. Although still in progress, this looks like it's going to be very good.
Morgan and Winship is particularly good on what must be assumed for causal interpretations of regression-type models.
Pearl (2000) is in no sense introductory, although ultimately a very good read. You may find some of his website and specific articles useful, particularly on interpreting structural equation models. They are mostly available as technical reports.
Update: Pearl, Glymour and Jewell's (2017) Causal Inference in Statistics: A Primer, is introductory though. And very good too.
|
Introduction to causal analysis
Try Morgan and Winship (2007) for a social science take or Hernan and Robins (forthcoming) for an epidemiological take. Although still in progress, this looks like it's going to be very good.
Morgan
|
7,139
|
Introduction to causal analysis
|
I have very high expectations for Austin Nichols' forthcoming book Causal Inference: Measuring the Effect of x on y. The expected publication date is 2013. In the mean time, his handout and paper provide a nice overview of panel methods, instrumental variables, propensity score matching/reweighting, and regression discontinuity. The comparisons between all these estimators (and RCTs) are especially useful, as well as the Stata mini-tutorials (that can be skipped if you're not a Stata user). Curated references are provided if you want to dig deeper. Unfortunately, there's not very much on structural equations here, though that is also true of the Morgan and Winship book. Their ARS paper is a shorter, though somewhat dated, overview.
I found Pearl to be an interesting, but difficult, introduction to this material. If it was my first exposure to these ideas, I don't know if I would have walked away after reading it knowing how to apply any of the methods very well.
Finally, here are video presentations and slides by economist James Heckman and Pearl from the 2012 Causal Inference Symposium at University of Michigan. Lots of stuff on structural models here.
|
Introduction to causal analysis
|
I have very high expectations for Austin Nichols' forthcoming book Causal Inference: Measuring the Effect of x on y. The expected publication date is 2013. In the mean time, his handout and paper pro
|
Introduction to causal analysis
I have very high expectations for Austin Nichols' forthcoming book Causal Inference: Measuring the Effect of x on y. The expected publication date is 2013. In the mean time, his handout and paper provide a nice overview of panel methods, instrumental variables, propensity score matching/reweighting, and regression discontinuity. The comparisons between all these estimators (and RCTs) are especially useful, as well as the Stata mini-tutorials (that can be skipped if you're not a Stata user). Curated references are provided if you want to dig deeper. Unfortunately, there's not very much on structural equations here, though that is also true of the Morgan and Winship book. Their ARS paper is a shorter, though somewhat dated, overview.
I found Pearl to be an interesting, but difficult, introduction to this material. If it was my first exposure to these ideas, I don't know if I would have walked away after reading it knowing how to apply any of the methods very well.
Finally, here are video presentations and slides by economist James Heckman and Pearl from the 2012 Causal Inference Symposium at University of Michigan. Lots of stuff on structural models here.
|
Introduction to causal analysis
I have very high expectations for Austin Nichols' forthcoming book Causal Inference: Measuring the Effect of x on y. The expected publication date is 2013. In the mean time, his handout and paper pro
|
7,140
|
Introduction to causal analysis
|
Cosma Shalizi's textbook Advanced Data Analysis from an Elementary Point of View has an excellent coverage of causation. (The textbook is still in draft form, and is available online as a pdf, so it has the added benefit of being free.)
You should decide, though, whether you are interested in methods for (a) estimating the size of causal effects, or (b) learning the structure of causal networks (i.e. learning which variables influence which others). There are many references for (a), I think Pearl's Causality is the best. There are few introductory references for (b); I think Cosma's textbook is the best, but it is not comprehensive.
CMU hosted some great introductory talks on causal structure learning in 2013. Richard Scheines presented a tutorial on causal inference using Tetrad, a long and gentle introduction to the basic concepts. Frederick Eberhardt presented All of Causal Discovery, a fast-paced overview of the state of the art. One or both of them may be helpful; Frederick's talk should give you plenty of ideas about where to go next.
|
Introduction to causal analysis
|
Cosma Shalizi's textbook Advanced Data Analysis from an Elementary Point of View has an excellent coverage of causation. (The textbook is still in draft form, and is available online as a pdf, so it h
|
Introduction to causal analysis
Cosma Shalizi's textbook Advanced Data Analysis from an Elementary Point of View has an excellent coverage of causation. (The textbook is still in draft form, and is available online as a pdf, so it has the added benefit of being free.)
You should decide, though, whether you are interested in methods for (a) estimating the size of causal effects, or (b) learning the structure of causal networks (i.e. learning which variables influence which others). There are many references for (a), I think Pearl's Causality is the best. There are few introductory references for (b); I think Cosma's textbook is the best, but it is not comprehensive.
CMU hosted some great introductory talks on causal structure learning in 2013. Richard Scheines presented a tutorial on causal inference using Tetrad, a long and gentle introduction to the basic concepts. Frederick Eberhardt presented All of Causal Discovery, a fast-paced overview of the state of the art. One or both of them may be helpful; Frederick's talk should give you plenty of ideas about where to go next.
|
Introduction to causal analysis
Cosma Shalizi's textbook Advanced Data Analysis from an Elementary Point of View has an excellent coverage of causation. (The textbook is still in draft form, and is available online as a pdf, so it h
|
7,141
|
Introduction to causal analysis
|
I'd recommend:
Data Analysis Using Regression and Multilevel/Hierarchical Models (Gelman & Hill)
Chapter9 and Chapter10 are about causal inference and publicly accessible.
Gelman is known to be a great author who describes complex concepts thoroughly.
Also consider his web blog: http://andrewgelman.com/ there are lots of materials about causal inference.
You don't get the full picture of all possible methods, but you'd probably get a very elaborate explanation about what is going on.
PS:
Gelman's 8 schools treatment effect analysis became a classic example of bayesian statistics of hierarchical modelling.
|
Introduction to causal analysis
|
I'd recommend:
Data Analysis Using Regression and Multilevel/Hierarchical Models (Gelman & Hill)
Chapter9 and Chapter10 are about causal inference and publicly accessible.
Gelman is known to be a gre
|
Introduction to causal analysis
I'd recommend:
Data Analysis Using Regression and Multilevel/Hierarchical Models (Gelman & Hill)
Chapter9 and Chapter10 are about causal inference and publicly accessible.
Gelman is known to be a great author who describes complex concepts thoroughly.
Also consider his web blog: http://andrewgelman.com/ there are lots of materials about causal inference.
You don't get the full picture of all possible methods, but you'd probably get a very elaborate explanation about what is going on.
PS:
Gelman's 8 schools treatment effect analysis became a classic example of bayesian statistics of hierarchical modelling.
|
Introduction to causal analysis
I'd recommend:
Data Analysis Using Regression and Multilevel/Hierarchical Models (Gelman & Hill)
Chapter9 and Chapter10 are about causal inference and publicly accessible.
Gelman is known to be a gre
|
7,142
|
What is a Highest Density Region (HDR)?
|
I recommend Rob Hyndman's 1996 article "Computing and Graphing Highest Density Regions" in The American Statistician. Here is the definition of the HDR, taken from that article:
Let $f(x)$ be the density function of a random variable $X$. Then the
$100(1-\alpha)\%$ HDR is the subset $R(f_\alpha)$ of the sample space
of $X$ such that
$$R(f_\alpha) = \{x\colon f(x)\geq f_\alpha\},$$
where $f_\alpha$ is the largest constant such that
$$P\big(X\in R(f_\alpha)\big)\geq 1-\alpha.$$
Figure 1 from that article illustrates the difference between the 75% HDR (so $\alpha=0.25$) and various other 75% Probability Regions for a mixture of two normals ($c_q$ is the $q$-th quantile, $\mu$ the mean and $\sigma$ the standard deviation of the density):
The idea in one dimension is to take a horizontal line and shift it up (to $y=f_\alpha$) until the area above it and under the density is $1-\alpha$. Then the HDR $R_\alpha$ is the projection to the $x$ axis of this area.
Of course, all this works with any density, whether Bayesian posterior or other.
Here is a link to R code, which is the hdrcdepackage (and to the article on JSTOR).
|
What is a Highest Density Region (HDR)?
|
I recommend Rob Hyndman's 1996 article "Computing and Graphing Highest Density Regions" in The American Statistician. Here is the definition of the HDR, taken from that article:
Let $f(x)$ be the den
|
What is a Highest Density Region (HDR)?
I recommend Rob Hyndman's 1996 article "Computing and Graphing Highest Density Regions" in The American Statistician. Here is the definition of the HDR, taken from that article:
Let $f(x)$ be the density function of a random variable $X$. Then the
$100(1-\alpha)\%$ HDR is the subset $R(f_\alpha)$ of the sample space
of $X$ such that
$$R(f_\alpha) = \{x\colon f(x)\geq f_\alpha\},$$
where $f_\alpha$ is the largest constant such that
$$P\big(X\in R(f_\alpha)\big)\geq 1-\alpha.$$
Figure 1 from that article illustrates the difference between the 75% HDR (so $\alpha=0.25$) and various other 75% Probability Regions for a mixture of two normals ($c_q$ is the $q$-th quantile, $\mu$ the mean and $\sigma$ the standard deviation of the density):
The idea in one dimension is to take a horizontal line and shift it up (to $y=f_\alpha$) until the area above it and under the density is $1-\alpha$. Then the HDR $R_\alpha$ is the projection to the $x$ axis of this area.
Of course, all this works with any density, whether Bayesian posterior or other.
Here is a link to R code, which is the hdrcdepackage (and to the article on JSTOR).
|
What is a Highest Density Region (HDR)?
I recommend Rob Hyndman's 1996 article "Computing and Graphing Highest Density Regions" in The American Statistician. Here is the definition of the HDR, taken from that article:
Let $f(x)$ be the den
|
7,143
|
What is a Highest Density Region (HDR)?
|
A highest posterior density [interval] is basically the shortest interval on a posterior density for some given confidence level. A highest density region is probably the same idea applied to any arbitrary density, so not necessarily a posterior distribution.
If $1-\alpha$ is your confidence level, you can always find two quantiles $q_{1-\alpha/2 + c}$, $q_{\alpha/2 -c}$ that will give you a working interval. There are a bunch though, and they all have different lengths. You want the shortest.
If your density $f(\cdot)$ is unimodal, then the shortest interval will happen at the two quantiles $a$ and $b$ such that $f(a) = f(b)$.
|
What is a Highest Density Region (HDR)?
|
A highest posterior density [interval] is basically the shortest interval on a posterior density for some given confidence level. A highest density region is probably the same idea applied to any arbi
|
What is a Highest Density Region (HDR)?
A highest posterior density [interval] is basically the shortest interval on a posterior density for some given confidence level. A highest density region is probably the same idea applied to any arbitrary density, so not necessarily a posterior distribution.
If $1-\alpha$ is your confidence level, you can always find two quantiles $q_{1-\alpha/2 + c}$, $q_{\alpha/2 -c}$ that will give you a working interval. There are a bunch though, and they all have different lengths. You want the shortest.
If your density $f(\cdot)$ is unimodal, then the shortest interval will happen at the two quantiles $a$ and $b$ such that $f(a) = f(b)$.
|
What is a Highest Density Region (HDR)?
A highest posterior density [interval] is basically the shortest interval on a posterior density for some given confidence level. A highest density region is probably the same idea applied to any arbi
|
7,144
|
What is a Highest Density Region (HDR)?
|
Hyndman (1996):
The region covering the sample space for a given probability 1-α, should have the smallest possible volume.
Every point inside the region should have probability density at least as large as every point outside the region.
such regions are called highest density regions (HDR’s)
One of the most distinctive property of HDR’s is that of all possible regions of probability coverage, the HDR has the smallest region possible in the sample space. “Smallest” mean with respect to some simple measure such as the usual Lebesgue measure; in the one-dimensional continuous case that would be the shortest interval, and in the two-dimensional case that would be the smallest area of the surface. In Bayesian analysis a similar approach is called the highest posterior density region (HPD) and the posterior density is used as a measure.
HPD is one of the methods for defining a credible interval in Bayesian statistics.
A credible interval is an interval within which an unobserved parameter value falls with a particular probability. It is an interval in the domain of a posterior probability distribution or a predictive distribution. The generalisation to multivariate problems is the credible region.
Credible intervals are not unique on a posterior distribution. Methods for defining a suitable credible interval include:
Choosing the narrowest interval, which for a unimodal distribution will involve choosing those values of highest probability density including the mode (the maximum a posteriori). This is sometimes called the highest posterior density interval (HPDI).
Choosing the interval where the probability of being below the interval is as likely as being above it. This interval will include the median. This is sometimes called the equal-tailed interval.
Assuming that the mean exists, choosing the interval for which the mean is the central point.
|
What is a Highest Density Region (HDR)?
|
Hyndman (1996):
The region covering the sample space for a given probability 1-α, should have the smallest possible volume.
Every point inside the region should have probability density at least as l
|
What is a Highest Density Region (HDR)?
Hyndman (1996):
The region covering the sample space for a given probability 1-α, should have the smallest possible volume.
Every point inside the region should have probability density at least as large as every point outside the region.
such regions are called highest density regions (HDR’s)
One of the most distinctive property of HDR’s is that of all possible regions of probability coverage, the HDR has the smallest region possible in the sample space. “Smallest” mean with respect to some simple measure such as the usual Lebesgue measure; in the one-dimensional continuous case that would be the shortest interval, and in the two-dimensional case that would be the smallest area of the surface. In Bayesian analysis a similar approach is called the highest posterior density region (HPD) and the posterior density is used as a measure.
HPD is one of the methods for defining a credible interval in Bayesian statistics.
A credible interval is an interval within which an unobserved parameter value falls with a particular probability. It is an interval in the domain of a posterior probability distribution or a predictive distribution. The generalisation to multivariate problems is the credible region.
Credible intervals are not unique on a posterior distribution. Methods for defining a suitable credible interval include:
Choosing the narrowest interval, which for a unimodal distribution will involve choosing those values of highest probability density including the mode (the maximum a posteriori). This is sometimes called the highest posterior density interval (HPDI).
Choosing the interval where the probability of being below the interval is as likely as being above it. This interval will include the median. This is sometimes called the equal-tailed interval.
Assuming that the mean exists, choosing the interval for which the mean is the central point.
|
What is a Highest Density Region (HDR)?
Hyndman (1996):
The region covering the sample space for a given probability 1-α, should have the smallest possible volume.
Every point inside the region should have probability density at least as l
|
7,145
|
What is a Highest Density Region (HDR)?
|
I don't have enough reputation to comment, but I think the current top answer by @StephanKolassa may contain a mistake?
"The idea in one dimension is to take a horizontal line and shift it up (to 𝑦=𝑓𝛼) until the area above it and under the density is 1−𝛼. Then the HDR 𝑅𝛼 is the projection to the 𝑥 axis of this area."[emphasis added]
In the figure, this would imply that all the area between the horizontal dotted line and the density curve equals 1-alpha. But I think the text from Rob Hyndman's article implies a different area, which is above the x-axis and under the density for the values in x such that f(x) >= f_a. This would be all the area between the two sets of vertical dotted lines in the figure. Small difference, but threw me for a while when thinking about it.
|
What is a Highest Density Region (HDR)?
|
I don't have enough reputation to comment, but I think the current top answer by @StephanKolassa may contain a mistake?
"The idea in one dimension is to take a horizontal line and shift it up (to 𝑦=𝑓𝛼
|
What is a Highest Density Region (HDR)?
I don't have enough reputation to comment, but I think the current top answer by @StephanKolassa may contain a mistake?
"The idea in one dimension is to take a horizontal line and shift it up (to 𝑦=𝑓𝛼) until the area above it and under the density is 1−𝛼. Then the HDR 𝑅𝛼 is the projection to the 𝑥 axis of this area."[emphasis added]
In the figure, this would imply that all the area between the horizontal dotted line and the density curve equals 1-alpha. But I think the text from Rob Hyndman's article implies a different area, which is above the x-axis and under the density for the values in x such that f(x) >= f_a. This would be all the area between the two sets of vertical dotted lines in the figure. Small difference, but threw me for a while when thinking about it.
|
What is a Highest Density Region (HDR)?
I don't have enough reputation to comment, but I think the current top answer by @StephanKolassa may contain a mistake?
"The idea in one dimension is to take a horizontal line and shift it up (to 𝑦=𝑓𝛼
|
7,146
|
What is a Highest Density Region (HDR)?
|
This should be the answer for this question:
Highest density regions are often the most appropriate subset to use to summarize a
region, and are capable of exposing the most striking features of the data than most alternative methods (Hyndman, 1996)
Hyndman further argues that highest-density regions (HDR) are a “more effective summary of the forecast distribution than other common forecast region” because of its flexibility “to convey both multimodularity and asymmetry in the forecast density”
This should be the answer. Not sure why you start off with a mathematical definition and talk about 100(1−α)%. All I want to know is what is meant by the term HDR (high density region). A classic example of complicating things when not asked :)
|
What is a Highest Density Region (HDR)?
|
This should be the answer for this question:
Highest density regions are often the most appropriate subset to use to summarize a
region, and are capable of exposing the most striking features of the d
|
What is a Highest Density Region (HDR)?
This should be the answer for this question:
Highest density regions are often the most appropriate subset to use to summarize a
region, and are capable of exposing the most striking features of the data than most alternative methods (Hyndman, 1996)
Hyndman further argues that highest-density regions (HDR) are a “more effective summary of the forecast distribution than other common forecast region” because of its flexibility “to convey both multimodularity and asymmetry in the forecast density”
This should be the answer. Not sure why you start off with a mathematical definition and talk about 100(1−α)%. All I want to know is what is meant by the term HDR (high density region). A classic example of complicating things when not asked :)
|
What is a Highest Density Region (HDR)?
This should be the answer for this question:
Highest density regions are often the most appropriate subset to use to summarize a
region, and are capable of exposing the most striking features of the d
|
7,147
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
|
Assuming that the decisions of invited persons to come to the wedding are independent, the number of guests that will come to the wedding can be modeled as the sum of Bernoulli random variables that have not necessarily identical probabilities of success.
This corresponds to the Poisson binomial distribution.
Let $X$ be a random variable corresponding to the total number of persons that will come to your wedding out of $N$ invited persons.
The expected number of participants is indeed the sum of individual ''show-up'' probabilities $p_i$, that is
$$
E(X) = \sum_{i = 1}^N p_i .
$$
The derivation of confidence intervals isn't straightforward given the form of the probability mass function. However, they are easy to approximate with Monte Carlo simulations.
The following figure shows an example of the distribution of the number of participants to the wedding based on 10000 simulated scenarios (right) using some fake show-up probabilities for the 230 invited persons (left). The R code used to run this simulation is shown below; it provides approximations of confidence intervals.
## Parameters
N <- 230 # Number of potential guests
nb.sim <- 10000 # Number of simulations
## Create example of groups of guests with same show-up probability
set.seed(345)
tmp <- hist(rbeta(N, 3, 2), breaks = seq(0, 1, length.out = 21))
p <- tmp$breaks[-1] # Group show-up probabilities
n <- tmp$counts # Number of person per group
## Generate number of guests by group
guest.mat <- matrix(NA, nrow = nb.sim, ncol = length(p))
for (j in 1:length(p)) {
guest.mat[, j] <- rbinom(nb.sim, n[j], p[j])
}
## Number of guest per scenario
nb.guests <- apply(guest.mat, 1, sum)
## Result summary
par(mfrow = c(1, 2))
barplot(n, names.arg = p, xlab = "Probability group", ylab = "Group size")
hist(nb.guests, breaks = 21, probability = TRUE, main = "", xlab = "Guests")
par(mfrow = c(1, 1))
## Theoretical mean and variance
c(sum(n * p), sum(n * p * (1-p)))
#[1] 148.8500 43.8475
## Sample mean and variance
c(mean(nb.guests), var(nb.guests))
#[1] 148.86270 43.23657
## Sample quantiles
quantile(nb.guests, probs = c(0.01, 0.05, 0.5, 0.95, 0.99))
#1% 5% 50% 95% 99%
#133.99 138.00 149.00 160.00 164.00
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
|
Assuming that the decisions of invited persons to come to the wedding are independent, the number of guests that will come to the wedding can be modeled as the sum of Bernoulli random variables that h
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
Assuming that the decisions of invited persons to come to the wedding are independent, the number of guests that will come to the wedding can be modeled as the sum of Bernoulli random variables that have not necessarily identical probabilities of success.
This corresponds to the Poisson binomial distribution.
Let $X$ be a random variable corresponding to the total number of persons that will come to your wedding out of $N$ invited persons.
The expected number of participants is indeed the sum of individual ''show-up'' probabilities $p_i$, that is
$$
E(X) = \sum_{i = 1}^N p_i .
$$
The derivation of confidence intervals isn't straightforward given the form of the probability mass function. However, they are easy to approximate with Monte Carlo simulations.
The following figure shows an example of the distribution of the number of participants to the wedding based on 10000 simulated scenarios (right) using some fake show-up probabilities for the 230 invited persons (left). The R code used to run this simulation is shown below; it provides approximations of confidence intervals.
## Parameters
N <- 230 # Number of potential guests
nb.sim <- 10000 # Number of simulations
## Create example of groups of guests with same show-up probability
set.seed(345)
tmp <- hist(rbeta(N, 3, 2), breaks = seq(0, 1, length.out = 21))
p <- tmp$breaks[-1] # Group show-up probabilities
n <- tmp$counts # Number of person per group
## Generate number of guests by group
guest.mat <- matrix(NA, nrow = nb.sim, ncol = length(p))
for (j in 1:length(p)) {
guest.mat[, j] <- rbinom(nb.sim, n[j], p[j])
}
## Number of guest per scenario
nb.guests <- apply(guest.mat, 1, sum)
## Result summary
par(mfrow = c(1, 2))
barplot(n, names.arg = p, xlab = "Probability group", ylab = "Group size")
hist(nb.guests, breaks = 21, probability = TRUE, main = "", xlab = "Guests")
par(mfrow = c(1, 1))
## Theoretical mean and variance
c(sum(n * p), sum(n * p * (1-p)))
#[1] 148.8500 43.8475
## Sample mean and variance
c(mean(nb.guests), var(nb.guests))
#[1] 148.86270 43.23657
## Sample quantiles
quantile(nb.guests, probs = c(0.01, 0.05, 0.5, 0.95, 0.99))
#1% 5% 50% 95% 99%
#133.99 138.00 149.00 160.00 164.00
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
Assuming that the decisions of invited persons to come to the wedding are independent, the number of guests that will come to the wedding can be modeled as the sum of Bernoulli random variables that h
|
7,148
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
|
As has been pointed out, the expectations simply add.
However, knowing the expectation isn't much use, you also need some sense of the likely variation around it.
There are three things you need to be concerned about:
variation in the individuals around their expectation (a person with 60% chance of coming doesn't actually achieve their expectation; they're always either above or below it)
dependence between people. Couples that might both come will tend to either both attend or neither. Young children won't attend without their parents. In some cases, some people may avoid coming if they know another person will be there.
error in estimation of the probabilities. Those probabilities are just guesses; you might want to consider the effect of somewhat different guesses (maybe someone else's assessments of those numbers)
The first is amenable to calculation, either by normal approximation or via simulation. The second might be simulated under various assumptions, either specific to the people, or by considering some distribution of dependencies. (The third item is more difficult.)
Edited to address followup questions in comments:
If I understand your phrasing correctly, for the family of 4, you have a 50% chance each of either 4 people or none coming. That's an expected number of 2, certainly, but you'd want to have some idea of the variability around the expectation as well, in which case you probably want to keep the actual situation of 50% of 0/50% of 4.
If you can partition everyone into independent groups, a good first approximation (with lots of such groups) would be then to add the means and variances across independent groups and then treat the sum as normal (perhaps with continuity correction). More accurate approach would be to simulate the process or to compute the distribution exactly via numerical convolution; while both approaches are straightforward, this is an unnecessary level of precision for this particular application, since there's so many layers of approximation already - it's like being told the dimensions of a room to the nearest foot and then calculating how much paint you'll need to the nearest milliliter - the additional precision is pointless.
So imagine (for simplicity) we had four groups:
1) group A (1 individual) - 70% chance of attendance
2) group B (1 individual) - 60% chance of attendance
3) group C (family of 4) - 0: 0.5 4: 0.5 (if anyone stays home, none will come)
4) group D (couple of 2) - 0: 0.4 1: 0.1 2: 0.5 (i.e. 50% chance of both, plus 10% chance exactly one will come, e.g. if the other has work commitments or is ill)
Then we get the following means and variances:
mean variance
A 0.7 0.21
B 0.6 0.24
C 2.0 4.0
D 1.1 0.89
Tot 4.4 5.34
So a normal approximation will be pretty rough in this case, but would suggest that more than 7 people would be pretty unlikely (on the order of 5%), and 6 or less would occur roughly 75-80% of the time.
[A more accurate approach would be to simulate the process, but on the full problem rather than the cut down example this is probably unnecessary since there's so many layers of approximation already.]
Once you have your combined distribution that incorporates such group-dependencies, you might then wish to apply any sources of overall joint dependency (such as severe weather) -- or you may wish to simply insure against or even ignore such eventualities, depending on circumstances.
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
|
As has been pointed out, the expectations simply add.
However, knowing the expectation isn't much use, you also need some sense of the likely variation around it.
There are three things you need to be
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
As has been pointed out, the expectations simply add.
However, knowing the expectation isn't much use, you also need some sense of the likely variation around it.
There are three things you need to be concerned about:
variation in the individuals around their expectation (a person with 60% chance of coming doesn't actually achieve their expectation; they're always either above or below it)
dependence between people. Couples that might both come will tend to either both attend or neither. Young children won't attend without their parents. In some cases, some people may avoid coming if they know another person will be there.
error in estimation of the probabilities. Those probabilities are just guesses; you might want to consider the effect of somewhat different guesses (maybe someone else's assessments of those numbers)
The first is amenable to calculation, either by normal approximation or via simulation. The second might be simulated under various assumptions, either specific to the people, or by considering some distribution of dependencies. (The third item is more difficult.)
Edited to address followup questions in comments:
If I understand your phrasing correctly, for the family of 4, you have a 50% chance each of either 4 people or none coming. That's an expected number of 2, certainly, but you'd want to have some idea of the variability around the expectation as well, in which case you probably want to keep the actual situation of 50% of 0/50% of 4.
If you can partition everyone into independent groups, a good first approximation (with lots of such groups) would be then to add the means and variances across independent groups and then treat the sum as normal (perhaps with continuity correction). More accurate approach would be to simulate the process or to compute the distribution exactly via numerical convolution; while both approaches are straightforward, this is an unnecessary level of precision for this particular application, since there's so many layers of approximation already - it's like being told the dimensions of a room to the nearest foot and then calculating how much paint you'll need to the nearest milliliter - the additional precision is pointless.
So imagine (for simplicity) we had four groups:
1) group A (1 individual) - 70% chance of attendance
2) group B (1 individual) - 60% chance of attendance
3) group C (family of 4) - 0: 0.5 4: 0.5 (if anyone stays home, none will come)
4) group D (couple of 2) - 0: 0.4 1: 0.1 2: 0.5 (i.e. 50% chance of both, plus 10% chance exactly one will come, e.g. if the other has work commitments or is ill)
Then we get the following means and variances:
mean variance
A 0.7 0.21
B 0.6 0.24
C 2.0 4.0
D 1.1 0.89
Tot 4.4 5.34
So a normal approximation will be pretty rough in this case, but would suggest that more than 7 people would be pretty unlikely (on the order of 5%), and 6 or less would occur roughly 75-80% of the time.
[A more accurate approach would be to simulate the process, but on the full problem rather than the cut down example this is probably unnecessary since there's so many layers of approximation already.]
Once you have your combined distribution that incorporates such group-dependencies, you might then wish to apply any sources of overall joint dependency (such as severe weather) -- or you may wish to simply insure against or even ignore such eventualities, depending on circumstances.
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
As has been pointed out, the expectations simply add.
However, knowing the expectation isn't much use, you also need some sense of the likely variation around it.
There are three things you need to be
|
7,149
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
|
(Ignore my earlier comment on this - I just realised I was confusing the expectation with something else.) Given that you're essentially trying to find the expectation of the number of people showing up, you can theoretically add the probability of each person showing up to do so.
This is because we can consider someone showing up as taking either the value $0$ or $1$, and because the expectation is a linear operator.
However, this only gives you the expected value - without further assumptions it would seem difficult to estimate things like variance of people showing up, particularly since it's pretty fair to assume that person A showing up is not necessarily independent of person B showing up.
That aside, here's a vaguely relevant BBC article.
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
|
(Ignore my earlier comment on this - I just realised I was confusing the expectation with something else.) Given that you're essentially trying to find the expectation of the number of people showing
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
(Ignore my earlier comment on this - I just realised I was confusing the expectation with something else.) Given that you're essentially trying to find the expectation of the number of people showing up, you can theoretically add the probability of each person showing up to do so.
This is because we can consider someone showing up as taking either the value $0$ or $1$, and because the expectation is a linear operator.
However, this only gives you the expected value - without further assumptions it would seem difficult to estimate things like variance of people showing up, particularly since it's pretty fair to assume that person A showing up is not necessarily independent of person B showing up.
That aside, here's a vaguely relevant BBC article.
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
(Ignore my earlier comment on this - I just realised I was confusing the expectation with something else.) Given that you're essentially trying to find the expectation of the number of people showing
|
7,150
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
|
For large numbers, 80% is what you'd expect. This may be a situation where a detailed analysis as you propose only adds errors to the calculations.
For example, is Marc's potential attendance really 1/3 of Joseph's? And is Joseph's really 30%, or might it be 25%? Things happen when you reach large numbers that simply make 80% more valid than all this analysis. I just came back from a wedding. 550 invited. 452 attended. For purposes of planning the hall and starting to talk to the caterer, the initial estimate of 440 was fine.
May I offer a line from my toast to the couple? "Remember, if your wife is happy, but you are not happy, you are still far happier than if your wife is unhappy, but you are happy."
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
|
For large numbers, 80% is what you'd expect. This may be a situation where a detailed analysis as you propose only adds errors to the calculations.
For example, is Marc's potential attendance really 1
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
For large numbers, 80% is what you'd expect. This may be a situation where a detailed analysis as you propose only adds errors to the calculations.
For example, is Marc's potential attendance really 1/3 of Joseph's? And is Joseph's really 30%, or might it be 25%? Things happen when you reach large numbers that simply make 80% more valid than all this analysis. I just came back from a wedding. 550 invited. 452 attended. For purposes of planning the hall and starting to talk to the caterer, the initial estimate of 440 was fine.
May I offer a line from my toast to the couple? "Remember, if your wife is happy, but you are not happy, you are still far happier than if your wife is unhappy, but you are happy."
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
For large numbers, 80% is what you'd expect. This may be a situation where a detailed analysis as you propose only adds errors to the calculations.
For example, is Marc's potential attendance really 1
|
7,151
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
|
As a statistician who just got married, I'll tell you that JoeTaxpayer has the right answer. The 80% figure strikes me as a little high, though could be accurate if most of the people are local (ours was a destination wedding and we landed closer to 65%).
But nonetheless, you're assuming a lot of variability in the prior probabilities that people attend, I think more than really exists. Assuming you don't invite people who actively dislike you, you should assume that just about everybody will come for whom it is within their means and they don't have a conflict (in a broad sense), but at least 10-20% WILL have something that keeps them from attending. For those who have to travel, that increases the time and money required so figure 30-35% of travelers won't attend (depending on distance). Otherwise, keep the probabilities constant (even if your parents say "oh so-and-so won't fly all the way to Austin, we just want to invite them..."). If you're having a fun reception, especially with an open bar, people generally won't skip that unless they have to.
Anyway, congratulations on getting married. Now as to the probability that you stay married, this is always a good read: http://users.nber.org/~bstevens/papers/Marital_Stability.pdf
:-)
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
|
As a statistician who just got married, I'll tell you that JoeTaxpayer has the right answer. The 80% figure strikes me as a little high, though could be accurate if most of the people are local (ours
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
As a statistician who just got married, I'll tell you that JoeTaxpayer has the right answer. The 80% figure strikes me as a little high, though could be accurate if most of the people are local (ours was a destination wedding and we landed closer to 65%).
But nonetheless, you're assuming a lot of variability in the prior probabilities that people attend, I think more than really exists. Assuming you don't invite people who actively dislike you, you should assume that just about everybody will come for whom it is within their means and they don't have a conflict (in a broad sense), but at least 10-20% WILL have something that keeps them from attending. For those who have to travel, that increases the time and money required so figure 30-35% of travelers won't attend (depending on distance). Otherwise, keep the probabilities constant (even if your parents say "oh so-and-so won't fly all the way to Austin, we just want to invite them..."). If you're having a fun reception, especially with an open bar, people generally won't skip that unless they have to.
Anyway, congratulations on getting married. Now as to the probability that you stay married, this is always a good read: http://users.nber.org/~bstevens/papers/Marital_Stability.pdf
:-)
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
As a statistician who just got married, I'll tell you that JoeTaxpayer has the right answer. The 80% figure strikes me as a little high, though could be accurate if most of the people are local (ours
|
7,152
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
|
Add up all probabilities, that's your expected number of people to come.
You have i=1..N events, each has probability $P_i$. The expected number of people to come is $\sum_i1_iP_i$, where $1_i$ - indicator variable equal to one if a person shows up, and zero otherwise.
Of course, we're assuming that whether someone comes or not does not depend on other people's attendance. This assumption is simply wrong. Consider couples, they're highly correlated.
Since you do not have data on correlations, the best you can do is to handle couples as a unit, i.e. $2\times1_iP_i$, where $P_i$ is the probability the couple will show up.
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
|
Add up all probabilities, that's your expected number of people to come.
You have i=1..N events, each has probability $P_i$. The expected number of people to come is $\sum_i1_iP_i$, where $1_i$ - indi
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
Add up all probabilities, that's your expected number of people to come.
You have i=1..N events, each has probability $P_i$. The expected number of people to come is $\sum_i1_iP_i$, where $1_i$ - indicator variable equal to one if a person shows up, and zero otherwise.
Of course, we're assuming that whether someone comes or not does not depend on other people's attendance. This assumption is simply wrong. Consider couples, they're highly correlated.
Since you do not have data on correlations, the best you can do is to handle couples as a unit, i.e. $2\times1_iP_i$, where $P_i$ is the probability the couple will show up.
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
Add up all probabilities, that's your expected number of people to come.
You have i=1..N events, each has probability $P_i$. The expected number of people to come is $\sum_i1_iP_i$, where $1_i$ - indi
|
7,153
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
|
For my wedding, I made two lists -- likely to attend (80%) and unlikely to attend (20%). Regardless of any more refined assessment for any reason, I assigned everyone invited to one of the two groups. I was off by 2 people. N = 1. Purely heuristic.
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
|
For my wedding, I made two lists -- likely to attend (80%) and unlikely to attend (20%). Regardless of any more refined assessment for any reason, I assigned everyone invited to one of the two groups.
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
For my wedding, I made two lists -- likely to attend (80%) and unlikely to attend (20%). Regardless of any more refined assessment for any reason, I assigned everyone invited to one of the two groups. I was off by 2 people. N = 1. Purely heuristic.
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
For my wedding, I made two lists -- likely to attend (80%) and unlikely to attend (20%). Regardless of any more refined assessment for any reason, I assigned everyone invited to one of the two groups.
|
7,154
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
|
I notice that no one has pointed out that you do not need to divide by 100. Your percentages can be viewed as expected portions of a person to show up, with the understanding that, like Schrödinger's cat, you will not get parts of a person in attendance or not in attendance, but the attendance state of each person will be entirely resolved at the moment of the event.
Since the range of your percentages run from 0% (none of the person showing up) to 100% (all of the person showing up), in your two examples involving 10 and 20 people, you summed the expected value for the portion of each person to show up, and got a number whose units were "people".
The prominent equation in QuantIbex's superb answer shows that summing the percentages results in the expected number of people at the event, no division involved.
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
|
I notice that no one has pointed out that you do not need to divide by 100. Your percentages can be viewed as expected portions of a person to show up, with the understanding that, like Schrödinger's
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each person and add them?
I notice that no one has pointed out that you do not need to divide by 100. Your percentages can be viewed as expected portions of a person to show up, with the understanding that, like Schrödinger's cat, you will not get parts of a person in attendance or not in attendance, but the attendance state of each person will be entirely resolved at the moment of the event.
Since the range of your percentages run from 0% (none of the person showing up) to 100% (all of the person showing up), in your two examples involving 10 and 20 people, you summed the expected value for the portion of each person to show up, and got a number whose units were "people".
The prominent equation in QuantIbex's superb answer shows that summing the percentages results in the expected number of people at the event, no division involved.
|
Help me calculate how many people will come to my wedding! Can I attribute a percentage to each pers
I notice that no one has pointed out that you do not need to divide by 100. Your percentages can be viewed as expected portions of a person to show up, with the understanding that, like Schrödinger's
|
7,155
|
Test accuracy higher than training. How to interpret?
|
I think a first step is to check whether the reported training and test performance are in fact correct.
Is the splitting during the 5-fold cross validation done in a way that yields statistically independent cv train/test sets? E.g. if there are repeated measurements in the data, do they always end up in the same set?
95.83% accuracy in a 5-fold cv of 150 samples is in line with 5 wrong out of 130 training samples for the 5 surrogate models, or 25 wrong cases for 5 * 130 training samples.
98.21% test accuracy is more difficult to explain: during one run of the cv, each case should be tested once. So the possibly reported numbers should be in steps of 100%/150. 98.21% corresponds to 2.68 wrong cases (2 and 3 wrong out of 150 test cases gives 98.67 and 98.00% accuracy, respectively).
If you can extract your model, calculate the reported accuracies externally.
What are the reported accuracies for random input?
Do an external cross validation: split your data, and hand over only the training part to the program. Predict the "external" test data and calculate accuracy. Is this in line with the program's output?
Make sure the reported "test accuracy" comes from independent data (double/nested cross validation): if your program does data driven optimization (e.g. choosing the "best" features by comparing many models), this is more like at training error (goodness of fit) than like a generalization error.
I agree with @mbq that training error is hardly ever useful in machine learning. But you may be in one of the few situations where it actually is useful: If the program selects a "best" model by comparing accuracies, but has only training errors to choose from, you need to check whether the training error actually allows a sensible choice.
@mbq outlined the best-case scenario for indistinguishable models. However, worse scenarios happen as well: just like test accuracy, training accuracy is also subject to variance but has an optimistic bias compared to the generalization accuracy that is usually of interest. This can lead to a situation where models cannot be distinguished although they really have different performance. But their training (or internal cv) accuracies are too close to distinguish them because of their optimistic bias. E.g. iterative feature selection methods can be subject to such problems that may even persist for the internal cross validation accuracies (depending on how that cross validation is implemented).
So if such an issue could arise, I think it is a good idea to check whether a sensible choice can possibly result from the accuracies the program uses for the decision. This would mean checking that the internal cv accuracy (which is supposedly used for selection of the best model) is not or not too much optimistically biased with respect to an externally done cv with statistically independent splitting. Again, synthetic and/or random data can help finding out what the program actually does.
A second step is to have a look whether the observed differences for statistically independent splits are meaningful, as @mbq pointed out already.
I suggest you calculate what difference in accuracy you need to observe with your given sample size in order to have a statistically meaningful difference.
If your observed variation is less, you cannot decide which algorithm is better with your given data set: further optimization does not make sense.
|
Test accuracy higher than training. How to interpret?
|
I think a first step is to check whether the reported training and test performance are in fact correct.
Is the splitting during the 5-fold cross validation done in a way that yields statistically in
|
Test accuracy higher than training. How to interpret?
I think a first step is to check whether the reported training and test performance are in fact correct.
Is the splitting during the 5-fold cross validation done in a way that yields statistically independent cv train/test sets? E.g. if there are repeated measurements in the data, do they always end up in the same set?
95.83% accuracy in a 5-fold cv of 150 samples is in line with 5 wrong out of 130 training samples for the 5 surrogate models, or 25 wrong cases for 5 * 130 training samples.
98.21% test accuracy is more difficult to explain: during one run of the cv, each case should be tested once. So the possibly reported numbers should be in steps of 100%/150. 98.21% corresponds to 2.68 wrong cases (2 and 3 wrong out of 150 test cases gives 98.67 and 98.00% accuracy, respectively).
If you can extract your model, calculate the reported accuracies externally.
What are the reported accuracies for random input?
Do an external cross validation: split your data, and hand over only the training part to the program. Predict the "external" test data and calculate accuracy. Is this in line with the program's output?
Make sure the reported "test accuracy" comes from independent data (double/nested cross validation): if your program does data driven optimization (e.g. choosing the "best" features by comparing many models), this is more like at training error (goodness of fit) than like a generalization error.
I agree with @mbq that training error is hardly ever useful in machine learning. But you may be in one of the few situations where it actually is useful: If the program selects a "best" model by comparing accuracies, but has only training errors to choose from, you need to check whether the training error actually allows a sensible choice.
@mbq outlined the best-case scenario for indistinguishable models. However, worse scenarios happen as well: just like test accuracy, training accuracy is also subject to variance but has an optimistic bias compared to the generalization accuracy that is usually of interest. This can lead to a situation where models cannot be distinguished although they really have different performance. But their training (or internal cv) accuracies are too close to distinguish them because of their optimistic bias. E.g. iterative feature selection methods can be subject to such problems that may even persist for the internal cross validation accuracies (depending on how that cross validation is implemented).
So if such an issue could arise, I think it is a good idea to check whether a sensible choice can possibly result from the accuracies the program uses for the decision. This would mean checking that the internal cv accuracy (which is supposedly used for selection of the best model) is not or not too much optimistically biased with respect to an externally done cv with statistically independent splitting. Again, synthetic and/or random data can help finding out what the program actually does.
A second step is to have a look whether the observed differences for statistically independent splits are meaningful, as @mbq pointed out already.
I suggest you calculate what difference in accuracy you need to observe with your given sample size in order to have a statistically meaningful difference.
If your observed variation is less, you cannot decide which algorithm is better with your given data set: further optimization does not make sense.
|
Test accuracy higher than training. How to interpret?
I think a first step is to check whether the reported training and test performance are in fact correct.
Is the splitting during the 5-fold cross validation done in a way that yields statistically in
|
7,156
|
Test accuracy higher than training. How to interpret?
|
How to interpret a test accuracy higher than training set accuracy.
Most likely culprit is your train/test split percentage. Imagine if you're using 99% of the data to train, and 1% for test, then obviously testing set accuracy will be better than the testing set, 99 times out of 100. The solution here is to use 50% of the data to train on, and 50% to evaluate the model.
Accuracy on the training set might be noise, depending on which ML algorithm you are using. The training set accuracy doesn't evaluate the correctness of your model on unseen rows. One strategy is to ignore the training set accuracy.
To get a clearer picture of which hyper-parameter choices to your model such (train/test split, iterations, convergence criteria, learning rate alpha, etc) are most responsible for your model having superior accuracy on test set, then run your model 100 times for every hyper parameter choice, then average the differences between training accuracy and testing accuracy.
Another strategy is to bag up your models into a list of N-models all of which were trained on a 50/50 train test split. Then all of the models have access to all of the data, and yet also none of the models have the ability to observe more than 50% of the training data. The average result is the correct one, then your training accuracy and testing accuracy will be much closer to equal.
|
Test accuracy higher than training. How to interpret?
|
How to interpret a test accuracy higher than training set accuracy.
Most likely culprit is your train/test split percentage. Imagine if you're using 99% of the data to train, and 1% for test, then ob
|
Test accuracy higher than training. How to interpret?
How to interpret a test accuracy higher than training set accuracy.
Most likely culprit is your train/test split percentage. Imagine if you're using 99% of the data to train, and 1% for test, then obviously testing set accuracy will be better than the testing set, 99 times out of 100. The solution here is to use 50% of the data to train on, and 50% to evaluate the model.
Accuracy on the training set might be noise, depending on which ML algorithm you are using. The training set accuracy doesn't evaluate the correctness of your model on unseen rows. One strategy is to ignore the training set accuracy.
To get a clearer picture of which hyper-parameter choices to your model such (train/test split, iterations, convergence criteria, learning rate alpha, etc) are most responsible for your model having superior accuracy on test set, then run your model 100 times for every hyper parameter choice, then average the differences between training accuracy and testing accuracy.
Another strategy is to bag up your models into a list of N-models all of which were trained on a 50/50 train test split. Then all of the models have access to all of the data, and yet also none of the models have the ability to observe more than 50% of the training data. The average result is the correct one, then your training accuracy and testing accuracy will be much closer to equal.
|
Test accuracy higher than training. How to interpret?
How to interpret a test accuracy higher than training set accuracy.
Most likely culprit is your train/test split percentage. Imagine if you're using 99% of the data to train, and 1% for test, then ob
|
7,157
|
Test accuracy higher than training. How to interpret?
|
There are a few serious problems with the way you have gone about this. First of all, data splitting is unreliable unless the total sample size is huge. You would get different results if you split again. Among other things you are not considering confidence intervals on accuracy estimates. Second, 5-fold cross-validation is not sufficiently precise. It may be necessary to repeat it 100 times to achieve adequate precision. Third, you have chosen as an accuracy score a discontinuous improper scoring rule (proportion classified correctly). Such an improper scoring rule will lead to selection of the wrong model.
|
Test accuracy higher than training. How to interpret?
|
There are a few serious problems with the way you have gone about this. First of all, data splitting is unreliable unless the total sample size is huge. You would get different results if you split
|
Test accuracy higher than training. How to interpret?
There are a few serious problems with the way you have gone about this. First of all, data splitting is unreliable unless the total sample size is huge. You would get different results if you split again. Among other things you are not considering confidence intervals on accuracy estimates. Second, 5-fold cross-validation is not sufficiently precise. It may be necessary to repeat it 100 times to achieve adequate precision. Third, you have chosen as an accuracy score a discontinuous improper scoring rule (proportion classified correctly). Such an improper scoring rule will lead to selection of the wrong model.
|
Test accuracy higher than training. How to interpret?
There are a few serious problems with the way you have gone about this. First of all, data splitting is unreliable unless the total sample size is huge. You would get different results if you split
|
7,158
|
Test accuracy higher than training. How to interpret?
|
Assuming that there is no glitch in the implementation of the algorithms, let us look at the problem.
Imagine taking a small subset from your training data and running your learning algorithm on it. It'll obviously do very well. It's always possible to extract a subset that achieves close to 98% accuracy.
Now is your test data very similar to this subset? If yes, then you need to go and collect more data, hopefully a bit more varied. From a Bias-Variance point of view, I would say that your variance is high.
|
Test accuracy higher than training. How to interpret?
|
Assuming that there is no glitch in the implementation of the algorithms, let us look at the problem.
Imagine taking a small subset from your training data and running your learning algorithm on it. I
|
Test accuracy higher than training. How to interpret?
Assuming that there is no glitch in the implementation of the algorithms, let us look at the problem.
Imagine taking a small subset from your training data and running your learning algorithm on it. It'll obviously do very well. It's always possible to extract a subset that achieves close to 98% accuracy.
Now is your test data very similar to this subset? If yes, then you need to go and collect more data, hopefully a bit more varied. From a Bias-Variance point of view, I would say that your variance is high.
|
Test accuracy higher than training. How to interpret?
Assuming that there is no glitch in the implementation of the algorithms, let us look at the problem.
Imagine taking a small subset from your training data and running your learning algorithm on it. I
|
7,159
|
Test accuracy higher than training. How to interpret?
|
You have too many features (1000) for the number of samples that you have (150). You need to increase your samples or decrease your number of features.
They say usually number of features ^2 = number of samples needed. So you need at least million samples.
|
Test accuracy higher than training. How to interpret?
|
You have too many features (1000) for the number of samples that you have (150). You need to increase your samples or decrease your number of features.
They say usually number of features ^2 = number
|
Test accuracy higher than training. How to interpret?
You have too many features (1000) for the number of samples that you have (150). You need to increase your samples or decrease your number of features.
They say usually number of features ^2 = number of samples needed. So you need at least million samples.
|
Test accuracy higher than training. How to interpret?
You have too many features (1000) for the number of samples that you have (150). You need to increase your samples or decrease your number of features.
They say usually number of features ^2 = number
|
7,160
|
Test accuracy higher than training. How to interpret?
|
I had the same problem with Caret package R, however, note that what we obtain by the end of training is usually the range of performance of the models trained on the cross-validated dataset. So you need to predict the training data set again with the best model (Model$bestTune) and obtain metrics (e.g. RMSE, AUC and etc) again then by predicting again you can obtain test data, when you compare these two you'll see the training stage has better performance metrics
|
Test accuracy higher than training. How to interpret?
|
I had the same problem with Caret package R, however, note that what we obtain by the end of training is usually the range of performance of the models trained on the cross-validated dataset. So you n
|
Test accuracy higher than training. How to interpret?
I had the same problem with Caret package R, however, note that what we obtain by the end of training is usually the range of performance of the models trained on the cross-validated dataset. So you need to predict the training data set again with the best model (Model$bestTune) and obtain metrics (e.g. RMSE, AUC and etc) again then by predicting again you can obtain test data, when you compare these two you'll see the training stage has better performance metrics
|
Test accuracy higher than training. How to interpret?
I had the same problem with Caret package R, however, note that what we obtain by the end of training is usually the range of performance of the models trained on the cross-validated dataset. So you n
|
7,161
|
Test accuracy higher than training. How to interpret?
|
That can be happen using any ML algorithm and even custom classifiers. Try different k-fold cross validation schemes i.e. 2 or 10 fold as well. With higher k, it is expected that test error reduced.
|
Test accuracy higher than training. How to interpret?
|
That can be happen using any ML algorithm and even custom classifiers. Try different k-fold cross validation schemes i.e. 2 or 10 fold as well. With higher k, it is expected that test error reduced.
|
Test accuracy higher than training. How to interpret?
That can be happen using any ML algorithm and even custom classifiers. Try different k-fold cross validation schemes i.e. 2 or 10 fold as well. With higher k, it is expected that test error reduced.
|
Test accuracy higher than training. How to interpret?
That can be happen using any ML algorithm and even custom classifiers. Try different k-fold cross validation schemes i.e. 2 or 10 fold as well. With higher k, it is expected that test error reduced.
|
7,162
|
Timing functions in R [closed]
|
For effective timing of programs, especially when you are interested in comparing alternative solutions, you need a control! A good way is to put the procedure you're timing into a function. Call the function within a timing loop. Write a stub procedure, essentially by stripping out all the code from your function and just returning from it (but leave all the arguments in). Put the stub into your timing loop and re-time. This measures all the overhead associated with the timing. Subtract the stub time from the procedure time to get the net: this should be an accurate measure of the actual time needed.
Because most systems nowadays can be peremptorily interrupted, it is important to do several timing runs to check for variability. Instead of doing one long run of $N$ seconds, do $m$ runs of about $N/m$ seconds each. It helps to do this in a double loop all in one go. Not only is that easier to handle, it introduces a little bit of negative correlation in each time series, which actually improves the estimates.
By using these basic principles of experimental design, you essentially control for any differences due to how you deploy the code (e.g., the difference between a for loop and replicate()). That makes your problem go away.
|
Timing functions in R [closed]
|
For effective timing of programs, especially when you are interested in comparing alternative solutions, you need a control! A good way is to put the procedure you're timing into a function. Call th
|
Timing functions in R [closed]
For effective timing of programs, especially when you are interested in comparing alternative solutions, you need a control! A good way is to put the procedure you're timing into a function. Call the function within a timing loop. Write a stub procedure, essentially by stripping out all the code from your function and just returning from it (but leave all the arguments in). Put the stub into your timing loop and re-time. This measures all the overhead associated with the timing. Subtract the stub time from the procedure time to get the net: this should be an accurate measure of the actual time needed.
Because most systems nowadays can be peremptorily interrupted, it is important to do several timing runs to check for variability. Instead of doing one long run of $N$ seconds, do $m$ runs of about $N/m$ seconds each. It helps to do this in a double loop all in one go. Not only is that easier to handle, it introduces a little bit of negative correlation in each time series, which actually improves the estimates.
By using these basic principles of experimental design, you essentially control for any differences due to how you deploy the code (e.g., the difference between a for loop and replicate()). That makes your problem go away.
|
Timing functions in R [closed]
For effective timing of programs, especially when you are interested in comparing alternative solutions, you need a control! A good way is to put the procedure you're timing into a function. Call th
|
7,163
|
Timing functions in R [closed]
|
Regarding your two points:
It's stylistic. I like replicate() as it is functional.
I tend to focus on elapsed, i.e. the third number.
What I often do is
N <- someNumber
mean(replicate( N, system.time( f(...) )[3], trimmed=0.05) )
to get a trimmed mean of 90% of N repetitions of calling f().
(Edited, with thanks to Hadley for catching a thinko.)
|
Timing functions in R [closed]
|
Regarding your two points:
It's stylistic. I like replicate() as it is functional.
I tend to focus on elapsed, i.e. the third number.
What I often do is
N <- someNumber
mean(replicate( N, system.ti
|
Timing functions in R [closed]
Regarding your two points:
It's stylistic. I like replicate() as it is functional.
I tend to focus on elapsed, i.e. the third number.
What I often do is
N <- someNumber
mean(replicate( N, system.time( f(...) )[3], trimmed=0.05) )
to get a trimmed mean of 90% of N repetitions of calling f().
(Edited, with thanks to Hadley for catching a thinko.)
|
Timing functions in R [closed]
Regarding your two points:
It's stylistic. I like replicate() as it is functional.
I tend to focus on elapsed, i.e. the third number.
What I often do is
N <- someNumber
mean(replicate( N, system.ti
|
7,164
|
Timing functions in R [closed]
|
You can also time with timesteps returned by Sys.time; this of course measures walltime, so real time computation time. Example code:
Sys.time()->start;
replicate(N,doMeasuredComputation());
print(Sys.time()-start);
|
Timing functions in R [closed]
|
You can also time with timesteps returned by Sys.time; this of course measures walltime, so real time computation time. Example code:
Sys.time()->start;
replicate(N,doMeasuredComputation());
print(Sys
|
Timing functions in R [closed]
You can also time with timesteps returned by Sys.time; this of course measures walltime, so real time computation time. Example code:
Sys.time()->start;
replicate(N,doMeasuredComputation());
print(Sys.time()-start);
|
Timing functions in R [closed]
You can also time with timesteps returned by Sys.time; this of course measures walltime, so real time computation time. Example code:
Sys.time()->start;
replicate(N,doMeasuredComputation());
print(Sys
|
7,165
|
Timing functions in R [closed]
|
Regarding which timing metric to use, I can not add to the other responders.
Regarding the function to use, I like using the ?benchmark from the rbenchmark package.
|
Timing functions in R [closed]
|
Regarding which timing metric to use, I can not add to the other responders.
Regarding the function to use, I like using the ?benchmark from the rbenchmark package.
|
Timing functions in R [closed]
Regarding which timing metric to use, I can not add to the other responders.
Regarding the function to use, I like using the ?benchmark from the rbenchmark package.
|
Timing functions in R [closed]
Regarding which timing metric to use, I can not add to the other responders.
Regarding the function to use, I like using the ?benchmark from the rbenchmark package.
|
7,166
|
Timing functions in R [closed]
|
They do different things. Time what you wish done. replicate() returns a vector of results of each execution of the function. The for loop does not. Therefore, they're not equivalent statements.
In addition, time a number of ways you want something done. Then you can find the most efficient method.
|
Timing functions in R [closed]
|
They do different things. Time what you wish done. replicate() returns a vector of results of each execution of the function. The for loop does not. Therefore, they're not equivalent statements.
I
|
Timing functions in R [closed]
They do different things. Time what you wish done. replicate() returns a vector of results of each execution of the function. The for loop does not. Therefore, they're not equivalent statements.
In addition, time a number of ways you want something done. Then you can find the most efficient method.
|
Timing functions in R [closed]
They do different things. Time what you wish done. replicate() returns a vector of results of each execution of the function. The for loop does not. Therefore, they're not equivalent statements.
I
|
7,167
|
Measuring the "distance" between two multivariate distributions
|
There is also the Kullback-Leibler divergence, which is related to the Hellinger Distance you mention above.
|
Measuring the "distance" between two multivariate distributions
|
There is also the Kullback-Leibler divergence, which is related to the Hellinger Distance you mention above.
|
Measuring the "distance" between two multivariate distributions
There is also the Kullback-Leibler divergence, which is related to the Hellinger Distance you mention above.
|
Measuring the "distance" between two multivariate distributions
There is also the Kullback-Leibler divergence, which is related to the Hellinger Distance you mention above.
|
7,168
|
Measuring the "distance" between two multivariate distributions
|
Hmm, the Bhattacharyya distance seems to be what I'm looking for, though the Hellinger distance works too.
|
Measuring the "distance" between two multivariate distributions
|
Hmm, the Bhattacharyya distance seems to be what I'm looking for, though the Hellinger distance works too.
|
Measuring the "distance" between two multivariate distributions
Hmm, the Bhattacharyya distance seems to be what I'm looking for, though the Hellinger distance works too.
|
Measuring the "distance" between two multivariate distributions
Hmm, the Bhattacharyya distance seems to be what I'm looking for, though the Hellinger distance works too.
|
7,169
|
Measuring the "distance" between two multivariate distributions
|
Heuristic
Minkowski-form
Weighted-Mean-Variance (WMV)
Nonparametric test statistics
2 (Chi Square)
Kolmogorov-Smirnov (KS)
Cramer/von Mises (CvM)
Information-theory divergences
Kullback-Liebler (KL)
Jensen–Shannon divergence (metric)
Jeffrey-divergence (numerically stable and symmetric)
Ground distance measures
Histogram intersection
Quadratic form (QF)
Earth Movers Distance (EMD)
|
Measuring the "distance" between two multivariate distributions
|
Heuristic
Minkowski-form
Weighted-Mean-Variance (WMV)
Nonparametric test statistics
2 (Chi Square)
Kolmogorov-Smirnov (KS)
Cramer/von Mises (CvM)
Information-theory divergences
Kullback-Liebler (
|
Measuring the "distance" between two multivariate distributions
Heuristic
Minkowski-form
Weighted-Mean-Variance (WMV)
Nonparametric test statistics
2 (Chi Square)
Kolmogorov-Smirnov (KS)
Cramer/von Mises (CvM)
Information-theory divergences
Kullback-Liebler (KL)
Jensen–Shannon divergence (metric)
Jeffrey-divergence (numerically stable and symmetric)
Ground distance measures
Histogram intersection
Quadratic form (QF)
Earth Movers Distance (EMD)
|
Measuring the "distance" between two multivariate distributions
Heuristic
Minkowski-form
Weighted-Mean-Variance (WMV)
Nonparametric test statistics
2 (Chi Square)
Kolmogorov-Smirnov (KS)
Cramer/von Mises (CvM)
Information-theory divergences
Kullback-Liebler (
|
7,170
|
Measuring the "distance" between two multivariate distributions
|
The most complete survey is provided in Statistical Inference Based on Divergence Measures by Leandro Pardo, Complutense University, Chapman Hall 2006.
|
Measuring the "distance" between two multivariate distributions
|
The most complete survey is provided in Statistical Inference Based on Divergence Measures by Leandro Pardo, Complutense University, Chapman Hall 2006.
|
Measuring the "distance" between two multivariate distributions
The most complete survey is provided in Statistical Inference Based on Divergence Measures by Leandro Pardo, Complutense University, Chapman Hall 2006.
|
Measuring the "distance" between two multivariate distributions
The most complete survey is provided in Statistical Inference Based on Divergence Measures by Leandro Pardo, Complutense University, Chapman Hall 2006.
|
7,171
|
Measuring the "distance" between two multivariate distributions
|
Few more measures of "Statistical Difference"
Permutation test (by Fisher)
Central Limit Theorem & Slutsky’s theorem
Mann-Whitney-Wilcoxin test
Anderson–Darling test
Shapiro–Wilk test
Hosmer–Lemeshow test
Kuiper's test
kernelized Stein discrepancy
Jaccard similarity
Also, hierarchical clustering deals with similarity measures between groups. The most popular measures of group similarity are perhaps the single linkage, complete linkage, and average linkage.
|
Measuring the "distance" between two multivariate distributions
|
Few more measures of "Statistical Difference"
Permutation test (by Fisher)
Central Limit Theorem & Slutsky’s theorem
Mann-Whitney-Wilcoxin test
Anderson–Darling test
Shapiro–Wilk test
Hosmer–Lemesho
|
Measuring the "distance" between two multivariate distributions
Few more measures of "Statistical Difference"
Permutation test (by Fisher)
Central Limit Theorem & Slutsky’s theorem
Mann-Whitney-Wilcoxin test
Anderson–Darling test
Shapiro–Wilk test
Hosmer–Lemeshow test
Kuiper's test
kernelized Stein discrepancy
Jaccard similarity
Also, hierarchical clustering deals with similarity measures between groups. The most popular measures of group similarity are perhaps the single linkage, complete linkage, and average linkage.
|
Measuring the "distance" between two multivariate distributions
Few more measures of "Statistical Difference"
Permutation test (by Fisher)
Central Limit Theorem & Slutsky’s theorem
Mann-Whitney-Wilcoxin test
Anderson–Darling test
Shapiro–Wilk test
Hosmer–Lemesho
|
7,172
|
What is the difference between an estimator and a statistic?
|
Definition
From Wikipedia:
A statistic [...] is a single measure of some attribute of a
sample (e.g., its arithmetic mean value).
And
[A]n estimator is a rule for calculating an estimate of a given
quantity [of the underlying distribution] based on observed data.
The important difference is:
A statistic is a function of a sample.
An estimator is a function of a sample related to some quantity of the distribution.
For what "Quantity" means, see section below. It's simply a function of the distribution.
A statistic is not an estimator
An estimator is a statistic with something added. To turn a statistic into an estimator, you simply spell out which target quantity you want to estimate.
This is confusing, because you do not add anything "real" to the statistic, but only some intend.
To see that the difference is important, you have to realize that you cannot calculate the properties of an estimator (e.g. bias, variance, etc.) for a mere statistic. To calculate bias, you have to find the difference between the value your statistic gives you and the true value. Only an estimator comes with a "true value" which allows to compute a bias. A statistic is merely a function of the data, and it is neither right nor wrong.
Different estimators based on the same statistic
You can spell out different target quantities for the same statistic, resulting in different estimators.
Each such estimator has its own bias, although they all are (based on) the same value, the same statistic.
You can use sample mean as an estimator for distribution mean. This estimator has zero bias.
You can also use sample mean as an estimator for distribution variance. This estimator is biased for most distributions.
So saying "sample mean is unbiased" does not make sense. Sample mean is unbiased when you use it to estimate distribution mean. But at the same time it is biased when using it to estimate distribution variance.
Quantities of distributions and quantities of samples
A quantity is a function of the distribution. If you only have a single distribution, and no class, then the quantity is a single value (the domain of the function has one element).
Here quantity refers to some property of the distribution, which is usually unknown and thus has to be estimated. This is in contrast to a statistic, which is a property of a sample, e.g. the distribution mean is a quantity of your distribution, while the sample mean is a statistic (a quantity of your sample).
|
What is the difference between an estimator and a statistic?
|
Definition
From Wikipedia:
A statistic [...] is a single measure of some attribute of a
sample (e.g., its arithmetic mean value).
And
[A]n estimator is a rule for calculating an estimate of a given
|
What is the difference between an estimator and a statistic?
Definition
From Wikipedia:
A statistic [...] is a single measure of some attribute of a
sample (e.g., its arithmetic mean value).
And
[A]n estimator is a rule for calculating an estimate of a given
quantity [of the underlying distribution] based on observed data.
The important difference is:
A statistic is a function of a sample.
An estimator is a function of a sample related to some quantity of the distribution.
For what "Quantity" means, see section below. It's simply a function of the distribution.
A statistic is not an estimator
An estimator is a statistic with something added. To turn a statistic into an estimator, you simply spell out which target quantity you want to estimate.
This is confusing, because you do not add anything "real" to the statistic, but only some intend.
To see that the difference is important, you have to realize that you cannot calculate the properties of an estimator (e.g. bias, variance, etc.) for a mere statistic. To calculate bias, you have to find the difference between the value your statistic gives you and the true value. Only an estimator comes with a "true value" which allows to compute a bias. A statistic is merely a function of the data, and it is neither right nor wrong.
Different estimators based on the same statistic
You can spell out different target quantities for the same statistic, resulting in different estimators.
Each such estimator has its own bias, although they all are (based on) the same value, the same statistic.
You can use sample mean as an estimator for distribution mean. This estimator has zero bias.
You can also use sample mean as an estimator for distribution variance. This estimator is biased for most distributions.
So saying "sample mean is unbiased" does not make sense. Sample mean is unbiased when you use it to estimate distribution mean. But at the same time it is biased when using it to estimate distribution variance.
Quantities of distributions and quantities of samples
A quantity is a function of the distribution. If you only have a single distribution, and no class, then the quantity is a single value (the domain of the function has one element).
Here quantity refers to some property of the distribution, which is usually unknown and thus has to be estimated. This is in contrast to a statistic, which is a property of a sample, e.g. the distribution mean is a quantity of your distribution, while the sample mean is a statistic (a quantity of your sample).
|
What is the difference between an estimator and a statistic?
Definition
From Wikipedia:
A statistic [...] is a single measure of some attribute of a
sample (e.g., its arithmetic mean value).
And
[A]n estimator is a rule for calculating an estimate of a given
|
7,173
|
What is the difference between an estimator and a statistic?
|
This thread is a little old, but it appears that Wikipedia may have changed its definition and if it's accurate, it explains it more clearly for me:
An "estimator" or "point estimate" is a statistic (that is, a function
of the data) that is used to infer the value of an unknown parameter
in a statistical model.
So a statistic refers to the data itself and a calculation with that data. While an estimator refers to a parameter in a model.
If I understand it correctly, then, the mean is a statistic and may also be an estimator. The mean of a sample is a statistic (sum of the sample divided by the sample size). The mean of a sample is also an estimator of the mean of the population, assuming it's normally distributed.
I'd ask @whuber and others who really know this stuff if the (new?) Wikipedia quote is accurate.
|
What is the difference between an estimator and a statistic?
|
This thread is a little old, but it appears that Wikipedia may have changed its definition and if it's accurate, it explains it more clearly for me:
An "estimator" or "point estimate" is a statistic
|
What is the difference between an estimator and a statistic?
This thread is a little old, but it appears that Wikipedia may have changed its definition and if it's accurate, it explains it more clearly for me:
An "estimator" or "point estimate" is a statistic (that is, a function
of the data) that is used to infer the value of an unknown parameter
in a statistical model.
So a statistic refers to the data itself and a calculation with that data. While an estimator refers to a parameter in a model.
If I understand it correctly, then, the mean is a statistic and may also be an estimator. The mean of a sample is a statistic (sum of the sample divided by the sample size). The mean of a sample is also an estimator of the mean of the population, assuming it's normally distributed.
I'd ask @whuber and others who really know this stuff if the (new?) Wikipedia quote is accurate.
|
What is the difference between an estimator and a statistic?
This thread is a little old, but it appears that Wikipedia may have changed its definition and if it's accurate, it explains it more clearly for me:
An "estimator" or "point estimate" is a statistic
|
7,174
|
What is the difference between an estimator and a statistic?
|
"6" is an example of an estimator. Say your question was, "what is the slope of the best linear function mapping x to y?" Your answer could be "6". Or it could be $(X'X)^{-1}X'Y$. Both are estimators. Which one is better is left to you to decide.
A really good TA once explained the concept of an estimator to me that way.
Basically, an estimator is a thing that you apply to data to get a quantity that you don't know the value of. You know the value of a statistic -- it is a function of the data with no "best" or "optimal" about it. There is no "best" mean. There is just a mean.
Say you have a dataset on number of goats owned per person, and each person's happiness. You're interested in how people's happiness changes with the number of goats they own. An estimator can help you to estimate that relationship from your data. Statistics are just functions of the data that you have. For example, the variance of goat ownership may equal 7. Te forula for calculating variance would be identical between goats and toasters, or whether you're interested in happiness or propensity to get cancer. In that sense, all sensible estimators are statistics.
|
What is the difference between an estimator and a statistic?
|
"6" is an example of an estimator. Say your question was, "what is the slope of the best linear function mapping x to y?" Your answer could be "6". Or it could be $(X'X)^{-1}X'Y$. Both are estimat
|
What is the difference between an estimator and a statistic?
"6" is an example of an estimator. Say your question was, "what is the slope of the best linear function mapping x to y?" Your answer could be "6". Or it could be $(X'X)^{-1}X'Y$. Both are estimators. Which one is better is left to you to decide.
A really good TA once explained the concept of an estimator to me that way.
Basically, an estimator is a thing that you apply to data to get a quantity that you don't know the value of. You know the value of a statistic -- it is a function of the data with no "best" or "optimal" about it. There is no "best" mean. There is just a mean.
Say you have a dataset on number of goats owned per person, and each person's happiness. You're interested in how people's happiness changes with the number of goats they own. An estimator can help you to estimate that relationship from your data. Statistics are just functions of the data that you have. For example, the variance of goat ownership may equal 7. Te forula for calculating variance would be identical between goats and toasters, or whether you're interested in happiness or propensity to get cancer. In that sense, all sensible estimators are statistics.
|
What is the difference between an estimator and a statistic?
"6" is an example of an estimator. Say your question was, "what is the slope of the best linear function mapping x to y?" Your answer could be "6". Or it could be $(X'X)^{-1}X'Y$. Both are estimat
|
7,175
|
What is the difference between an estimator and a statistic?
|
Since other answers saying that they are the same give no authoritative reference, let me give you two quotes from Statistical inference handbook by Casella and Berger:
Definition 5.2.1 Let $X_1,\dots,X_n$ be a random sample of size $n$ from a population and let $T(x_1,\dots,x_n)$ be a real-valued or
vector-valued function whose domain includes the sample space of
$(X_1,\dots,X_n)$. Then the random variable or random vector $Y =
T(X_1,\dots,X_n)$ is called statistic. The probability distribution
of statistic $Y$ is called sampling distribution of $Y$.
and
Definition 7.1.1 A point estimator is any function $W(X_1,\dots,X_n)$ of a sample; that is, any statistic is a point
estimator.
I am not saying in here that this is the definite answer to the question, since I seem to agree with the two most upvoted answers that suggest that there is a difference, just giving a reference that says the opposite to highlight that this is not a clear-cut case.
|
What is the difference between an estimator and a statistic?
|
Since other answers saying that they are the same give no authoritative reference, let me give you two quotes from Statistical inference handbook by Casella and Berger:
Definition 5.2.1 Let $X_1,\dot
|
What is the difference between an estimator and a statistic?
Since other answers saying that they are the same give no authoritative reference, let me give you two quotes from Statistical inference handbook by Casella and Berger:
Definition 5.2.1 Let $X_1,\dots,X_n$ be a random sample of size $n$ from a population and let $T(x_1,\dots,x_n)$ be a real-valued or
vector-valued function whose domain includes the sample space of
$(X_1,\dots,X_n)$. Then the random variable or random vector $Y =
T(X_1,\dots,X_n)$ is called statistic. The probability distribution
of statistic $Y$ is called sampling distribution of $Y$.
and
Definition 7.1.1 A point estimator is any function $W(X_1,\dots,X_n)$ of a sample; that is, any statistic is a point
estimator.
I am not saying in here that this is the definite answer to the question, since I seem to agree with the two most upvoted answers that suggest that there is a difference, just giving a reference that says the opposite to highlight that this is not a clear-cut case.
|
What is the difference between an estimator and a statistic?
Since other answers saying that they are the same give no authoritative reference, let me give you two quotes from Statistical inference handbook by Casella and Berger:
Definition 5.2.1 Let $X_1,\dot
|
7,176
|
What is the difference between an estimator and a statistic?
|
Interesting question. Estimators and statistics do not need to be different things, though. They are different concepts.
A statistic is a function (in broad terms) in which the input is (statistical) data. The effect is that you gain a result, usually a number, from this statistic. In a more abstract term, a statistic may yield more than one number.
The statistic depends on the data, but the procedure is deterministic. So the statistic may be: "Sum all numbers and divide by the count" or, in the broader sense "take the gdp data and prepare a report on it".
In the statistical sense we are of course talking about a mathematical function as a statistic.
The significance of this is that if you know properties of the data you input (for example it beeing a random variable), then you can calculate the properties of your statistic, without actually putting in empirical data.
Estimators are estimators because of you intent: to estimate a property.
As it turns out, some statistics are good estimators.
For example if you pull data points out of a pool of i.i.d. variables, then the arithmetic mean - a statistic based on the data you pull, will probably be a good estimator for the expected value of that distribution. But then again any thing that produces an estimate is an estimator.
In practice, estimators that you use will be statistics, but there are statistics that aren't estimators. For example test-statistics - though one can argue about the semantics of this statement and to make matters worse, a test statistic may not only be but also include estimators. Though conceptually this doesn't have to be the case.
And of course you can have estimators that aren't statistics, though they are probably not very good at estimating.
|
What is the difference between an estimator and a statistic?
|
Interesting question. Estimators and statistics do not need to be different things, though. They are different concepts.
A statistic is a function (in broad terms) in which the input is (statistical)
|
What is the difference between an estimator and a statistic?
Interesting question. Estimators and statistics do not need to be different things, though. They are different concepts.
A statistic is a function (in broad terms) in which the input is (statistical) data. The effect is that you gain a result, usually a number, from this statistic. In a more abstract term, a statistic may yield more than one number.
The statistic depends on the data, but the procedure is deterministic. So the statistic may be: "Sum all numbers and divide by the count" or, in the broader sense "take the gdp data and prepare a report on it".
In the statistical sense we are of course talking about a mathematical function as a statistic.
The significance of this is that if you know properties of the data you input (for example it beeing a random variable), then you can calculate the properties of your statistic, without actually putting in empirical data.
Estimators are estimators because of you intent: to estimate a property.
As it turns out, some statistics are good estimators.
For example if you pull data points out of a pool of i.i.d. variables, then the arithmetic mean - a statistic based on the data you pull, will probably be a good estimator for the expected value of that distribution. But then again any thing that produces an estimate is an estimator.
In practice, estimators that you use will be statistics, but there are statistics that aren't estimators. For example test-statistics - though one can argue about the semantics of this statement and to make matters worse, a test statistic may not only be but also include estimators. Though conceptually this doesn't have to be the case.
And of course you can have estimators that aren't statistics, though they are probably not very good at estimating.
|
What is the difference between an estimator and a statistic?
Interesting question. Estimators and statistics do not need to be different things, though. They are different concepts.
A statistic is a function (in broad terms) in which the input is (statistical)
|
7,177
|
What is the difference between an estimator and a statistic?
|
I think a better understanding about what is a sample helps.
[Updated: Sample is a very broad concept, I was talking about "the random sample" . I don't know whether an estimator makes sense or not when the sample is not random.]
from wikipedia:
A random sample is defined as a sample where each individual member
of the population has a known, non-zero chance of being selected as
part of the sample.
An estimator is a function of a sample. A sample is actually a set of (say, $n$) i.i.d. random variables. That means an estimator is also a function of random variables. An estimator defines a measurement, but not the values of an actual measurement. But we can call it, "the rule for estimating a given quantity based on observed data." Because based on $n$ specific experiments, we can have $n$ specific values for the $n$ i.i.d. random variables. And we get a specific value of the size-$n$ sample.
We replace the sample in the estimator by the value of the sample. We get a value of the estimator, this is a specific measure. And this specific measure is a statistic.
(Check this link for the definition of an estimator, the last sentence reveals why we are always confused.)
|
What is the difference between an estimator and a statistic?
|
I think a better understanding about what is a sample helps.
[Updated: Sample is a very broad concept, I was talking about "the random sample" . I don't know whether an estimator makes sense or not wh
|
What is the difference between an estimator and a statistic?
I think a better understanding about what is a sample helps.
[Updated: Sample is a very broad concept, I was talking about "the random sample" . I don't know whether an estimator makes sense or not when the sample is not random.]
from wikipedia:
A random sample is defined as a sample where each individual member
of the population has a known, non-zero chance of being selected as
part of the sample.
An estimator is a function of a sample. A sample is actually a set of (say, $n$) i.i.d. random variables. That means an estimator is also a function of random variables. An estimator defines a measurement, but not the values of an actual measurement. But we can call it, "the rule for estimating a given quantity based on observed data." Because based on $n$ specific experiments, we can have $n$ specific values for the $n$ i.i.d. random variables. And we get a specific value of the size-$n$ sample.
We replace the sample in the estimator by the value of the sample. We get a value of the estimator, this is a specific measure. And this specific measure is a statistic.
(Check this link for the definition of an estimator, the last sentence reveals why we are always confused.)
|
What is the difference between an estimator and a statistic?
I think a better understanding about what is a sample helps.
[Updated: Sample is a very broad concept, I was talking about "the random sample" . I don't know whether an estimator makes sense or not wh
|
7,178
|
What is the difference between an estimator and a statistic?
|
The Goal of This Piece of Writing:
What I want to do here is to provide you with the similarities and differences between the two intimately related concepts called "statistic" and "estimator". However, I do not want to go through the differences between a parameter and a statistic, which I assume is clear enough to everyone who is struggling with the differences between a statistic and an estimator. If it is not the case for you, you need to study earlier posts first, and then start studying this post.
Relationship:
Basically, any real-valued function of observable random variables in a sample is called a statistic. There are some statistics that if they are well designed, and have some good properties (e.g. consistency, ... ), they can be used to estimate the parameters of the underlying distribution of the population. Therefore, statistics are a large set, and estimators are a subset inside the set of statistics. Hence, every estimator is a statistic, but not every statistic is an estimator.
Similarities:
Speaking of the similarities, as mentioned earlier, both are functions of random variables. In addition, both have distributions called "sampling distributions."
Differences:
Speaking of the differences, they are different in terms of their goals and tasks. The goals and tasks of a statistic could be summarizing the information in a sample (by using sufficient statistics), and sometimes doing hypothesis test, etc. In contrast, the primary goal and task of an estimator, as its name implies, is to estimate the parameters of the population being studied. It is important to mention that there are a wide variety of estimators, each of which has its own computational logic behind, such as MOMEs, MLEs, OLS estimators and so on. Another difference between these two concepts has to do with their desired properties. While one of the most desired properties of a statistic is "sufficiency", the desired properties of an estimator are things like "consistency", "unbiasedness", "precision", etc.
Caution:
Therefore, you need to be careful about using terminology correctly when dealing with statistics and estimators. For instance, it does not make much sense to talk about the biasedness of a mere statistic, which is by no means an estimator, because there is no parameter involved in such a context in order for us to be able to calculate the bias, and talk about it. Thus, you need to be careful about the terminology!
The Bottom Line:
To sum up, any function of observable random variables in a sample is a statistic. If a statistic has capability to estimate a parameter of a population, then we call it an estimator (of the parameter of interest). However, there are some statistics that are not designed to estimate parameters, so these statistics are not estimators, and here we call them "mere statistics".
What I offered above is the way I look at and think of these two concepts, and I tried my best to put it in simple words. I hope it helps!
|
What is the difference between an estimator and a statistic?
|
The Goal of This Piece of Writing:
What I want to do here is to provide you with the similarities and differences between the two intimately related concepts called "statistic" and "estimator". Howeve
|
What is the difference between an estimator and a statistic?
The Goal of This Piece of Writing:
What I want to do here is to provide you with the similarities and differences between the two intimately related concepts called "statistic" and "estimator". However, I do not want to go through the differences between a parameter and a statistic, which I assume is clear enough to everyone who is struggling with the differences between a statistic and an estimator. If it is not the case for you, you need to study earlier posts first, and then start studying this post.
Relationship:
Basically, any real-valued function of observable random variables in a sample is called a statistic. There are some statistics that if they are well designed, and have some good properties (e.g. consistency, ... ), they can be used to estimate the parameters of the underlying distribution of the population. Therefore, statistics are a large set, and estimators are a subset inside the set of statistics. Hence, every estimator is a statistic, but not every statistic is an estimator.
Similarities:
Speaking of the similarities, as mentioned earlier, both are functions of random variables. In addition, both have distributions called "sampling distributions."
Differences:
Speaking of the differences, they are different in terms of their goals and tasks. The goals and tasks of a statistic could be summarizing the information in a sample (by using sufficient statistics), and sometimes doing hypothesis test, etc. In contrast, the primary goal and task of an estimator, as its name implies, is to estimate the parameters of the population being studied. It is important to mention that there are a wide variety of estimators, each of which has its own computational logic behind, such as MOMEs, MLEs, OLS estimators and so on. Another difference between these two concepts has to do with their desired properties. While one of the most desired properties of a statistic is "sufficiency", the desired properties of an estimator are things like "consistency", "unbiasedness", "precision", etc.
Caution:
Therefore, you need to be careful about using terminology correctly when dealing with statistics and estimators. For instance, it does not make much sense to talk about the biasedness of a mere statistic, which is by no means an estimator, because there is no parameter involved in such a context in order for us to be able to calculate the bias, and talk about it. Thus, you need to be careful about the terminology!
The Bottom Line:
To sum up, any function of observable random variables in a sample is a statistic. If a statistic has capability to estimate a parameter of a population, then we call it an estimator (of the parameter of interest). However, there are some statistics that are not designed to estimate parameters, so these statistics are not estimators, and here we call them "mere statistics".
What I offered above is the way I look at and think of these two concepts, and I tried my best to put it in simple words. I hope it helps!
|
What is the difference between an estimator and a statistic?
The Goal of This Piece of Writing:
What I want to do here is to provide you with the similarities and differences between the two intimately related concepts called "statistic" and "estimator". Howeve
|
7,179
|
What is the difference between an estimator and a statistic?
|
New answer to an old Q:
Definition 1. A statistic is a function that maps each sample to a real number.
Every estimator is a statistic.
But we tend to call only those statistics that are used to generate estimates ("guesses") some parameter an estimator.
So for example, the t-statistic and the sample mean are BOTH statistics. The sample mean is also an estimator (because we often use it to estimate the true population mean).
In contrast, we rarely/never call the t-statistic an estimator, because we rarely/never use it to estimate any parameter.
In the example below, $P$ is a statistic, but not an estimator. While $Q$ is both a statistic and an estimator.
$$$$
$$\underline{\text{Example}}$$
Suppose our parameter-of-interest is the average outcome $\theta$ of a
die-roll.
$\theta$ is some fixed real number that is perhaps known only to
God. Nonetheless, we can try to estimate it.
Here's one possible method. We roll a die 3 times.
A sample is any $\textbf{s}=\left(x_1,x_2,x_3\right)$, where $x_1$ is
the outcome of the first roll, $x_2$ that of the second, and $x_3$
that of the third.
Here are three examples of samples:
$\textbf{s}_1=\left(5,4,1\right)$, $\textbf{s}_2=\left(4,1,6\right)$,
and $\textbf{s}_3=\left(6,3,2\right)$.
Here are two examples of statistics $P$ and $Q$ (remember that a
statistic is simply a function). Define $P$ and $Q$ by: For any
$\textbf{s}=\left(x_1,x_2,x_3\right)$,
$$P(\textbf{s})=\frac{x_1}{\ln(x_2+x_3)},$$
$$Q(\textbf{s})=\frac{x_1+x_2+x_3}{3}.$$
The statistic $P$ is a rather-bizarre statistic and is probably not
very useful for anything. Nonetheless, it is a statistic all the same,
simply because it satisfies the definition of a statistic (it is a
function that maps each sample to a real number).
$Q$ is also a statistic. But in addition, it is also an estimator for
the parameter $\theta$.
(We could, of course, claim that $P$ is also an estimator for $\theta$. But it would be a very poor estimator that no one would want to use.)
|
What is the difference between an estimator and a statistic?
|
New answer to an old Q:
Definition 1. A statistic is a function that maps each sample to a real number.
Every estimator is a statistic.
But we tend to call only those statistics that are used to gener
|
What is the difference between an estimator and a statistic?
New answer to an old Q:
Definition 1. A statistic is a function that maps each sample to a real number.
Every estimator is a statistic.
But we tend to call only those statistics that are used to generate estimates ("guesses") some parameter an estimator.
So for example, the t-statistic and the sample mean are BOTH statistics. The sample mean is also an estimator (because we often use it to estimate the true population mean).
In contrast, we rarely/never call the t-statistic an estimator, because we rarely/never use it to estimate any parameter.
In the example below, $P$ is a statistic, but not an estimator. While $Q$ is both a statistic and an estimator.
$$$$
$$\underline{\text{Example}}$$
Suppose our parameter-of-interest is the average outcome $\theta$ of a
die-roll.
$\theta$ is some fixed real number that is perhaps known only to
God. Nonetheless, we can try to estimate it.
Here's one possible method. We roll a die 3 times.
A sample is any $\textbf{s}=\left(x_1,x_2,x_3\right)$, where $x_1$ is
the outcome of the first roll, $x_2$ that of the second, and $x_3$
that of the third.
Here are three examples of samples:
$\textbf{s}_1=\left(5,4,1\right)$, $\textbf{s}_2=\left(4,1,6\right)$,
and $\textbf{s}_3=\left(6,3,2\right)$.
Here are two examples of statistics $P$ and $Q$ (remember that a
statistic is simply a function). Define $P$ and $Q$ by: For any
$\textbf{s}=\left(x_1,x_2,x_3\right)$,
$$P(\textbf{s})=\frac{x_1}{\ln(x_2+x_3)},$$
$$Q(\textbf{s})=\frac{x_1+x_2+x_3}{3}.$$
The statistic $P$ is a rather-bizarre statistic and is probably not
very useful for anything. Nonetheless, it is a statistic all the same,
simply because it satisfies the definition of a statistic (it is a
function that maps each sample to a real number).
$Q$ is also a statistic. But in addition, it is also an estimator for
the parameter $\theta$.
(We could, of course, claim that $P$ is also an estimator for $\theta$. But it would be a very poor estimator that no one would want to use.)
|
What is the difference between an estimator and a statistic?
New answer to an old Q:
Definition 1. A statistic is a function that maps each sample to a real number.
Every estimator is a statistic.
But we tend to call only those statistics that are used to gener
|
7,180
|
What is the difference between an estimator and a statistic?
|
In hypothesis testing :
A test-statistic is about hypothesis testing. A test-statistic is a random variable given/under the null hypothesis. Now, some may call a statistic the value/measure of the test-statistic given the sample.
With these two you can get the p-value which is a measure that helps to reject or not reject the null hypothesis. All in all, a statistic is an estimation of how far/close to your hypothesis.
This link may be useful.
|
What is the difference between an estimator and a statistic?
|
In hypothesis testing :
A test-statistic is about hypothesis testing. A test-statistic is a random variable given/under the null hypothesis. Now, some may call a statistic the value/measure of the te
|
What is the difference between an estimator and a statistic?
In hypothesis testing :
A test-statistic is about hypothesis testing. A test-statistic is a random variable given/under the null hypothesis. Now, some may call a statistic the value/measure of the test-statistic given the sample.
With these two you can get the p-value which is a measure that helps to reject or not reject the null hypothesis. All in all, a statistic is an estimation of how far/close to your hypothesis.
This link may be useful.
|
What is the difference between an estimator and a statistic?
In hypothesis testing :
A test-statistic is about hypothesis testing. A test-statistic is a random variable given/under the null hypothesis. Now, some may call a statistic the value/measure of the te
|
7,181
|
Kernel logistic regression vs SVM
|
KLRs and SVMs
Classification performance is almost identical in both cases.
KLR can provide class probabilities whereas SVM is a
deterministic classifier.
KLR has a natural extension to multi-class classification whereas in SVM, there are multiple ways to extend it to multi-class classification (and it is still an area of research whether there is a version which has provably superior qualities over the others).
Surprisingly or unsurprisingly, KLR also has optimal margin properties that the SVMs enjoy (well in the limit at least)!
Looking at the above it almost feels like kernel logistic regression is what you should be using. However, there are certain advantages that SVMs enjoy
KLR is computationally more expensive than SVM - $O(N^3)$ vs $O(N^2k)$ where $k$ is the number of support vectors.
The classifier in SVM is designed such that it is defined only in terms of the support vectors, whereas in KLR, the classifier is defined over all the points and not just the support vectors. This allows SVMs to enjoy some natural speed-ups (in terms of efficient code-writing) that is hard to achieve for KLR.
|
Kernel logistic regression vs SVM
|
KLRs and SVMs
Classification performance is almost identical in both cases.
KLR can provide class probabilities whereas SVM is a
deterministic classifier.
KLR has a natural extension to multi-class
|
Kernel logistic regression vs SVM
KLRs and SVMs
Classification performance is almost identical in both cases.
KLR can provide class probabilities whereas SVM is a
deterministic classifier.
KLR has a natural extension to multi-class classification whereas in SVM, there are multiple ways to extend it to multi-class classification (and it is still an area of research whether there is a version which has provably superior qualities over the others).
Surprisingly or unsurprisingly, KLR also has optimal margin properties that the SVMs enjoy (well in the limit at least)!
Looking at the above it almost feels like kernel logistic regression is what you should be using. However, there are certain advantages that SVMs enjoy
KLR is computationally more expensive than SVM - $O(N^3)$ vs $O(N^2k)$ where $k$ is the number of support vectors.
The classifier in SVM is designed such that it is defined only in terms of the support vectors, whereas in KLR, the classifier is defined over all the points and not just the support vectors. This allows SVMs to enjoy some natural speed-ups (in terms of efficient code-writing) that is hard to achieve for KLR.
|
Kernel logistic regression vs SVM
KLRs and SVMs
Classification performance is almost identical in both cases.
KLR can provide class probabilities whereas SVM is a
deterministic classifier.
KLR has a natural extension to multi-class
|
7,182
|
Kernel logistic regression vs SVM
|
Here's my take on the issue:
SVMs are a very elegant way to do classification. There's some nice theory, some beautiful math, they generalize well, and they're not too slow either. Try to use them for regression though, and it gets messy.
Here's a resource on SVM regression. Notice the extra parameters to twiddle and the in depth discussion about optimization algorithms.
Gaussian Process Regression has a lot of the same kernelly math, and it works great for regression. Again, the very elegant, and it's not too slow. Try to use them for classification, and it starts feeling pretty kludgy.
Here's a chapter from the GP book on regression.
Here's a chapter on classification, for comparison. Notice that you end up with some complicated approximations or an iterative method.
One nice thing about using GPs for classification, though, is that it gives you a predictive distribution, rather than a simple yes/no classification.
|
Kernel logistic regression vs SVM
|
Here's my take on the issue:
SVMs are a very elegant way to do classification. There's some nice theory, some beautiful math, they generalize well, and they're not too slow either. Try to use them for
|
Kernel logistic regression vs SVM
Here's my take on the issue:
SVMs are a very elegant way to do classification. There's some nice theory, some beautiful math, they generalize well, and they're not too slow either. Try to use them for regression though, and it gets messy.
Here's a resource on SVM regression. Notice the extra parameters to twiddle and the in depth discussion about optimization algorithms.
Gaussian Process Regression has a lot of the same kernelly math, and it works great for regression. Again, the very elegant, and it's not too slow. Try to use them for classification, and it starts feeling pretty kludgy.
Here's a chapter from the GP book on regression.
Here's a chapter on classification, for comparison. Notice that you end up with some complicated approximations or an iterative method.
One nice thing about using GPs for classification, though, is that it gives you a predictive distribution, rather than a simple yes/no classification.
|
Kernel logistic regression vs SVM
Here's my take on the issue:
SVMs are a very elegant way to do classification. There's some nice theory, some beautiful math, they generalize well, and they're not too slow either. Try to use them for
|
7,183
|
Kernel logistic regression vs SVM
|
please visit http://www.stanford.edu/~hastie/Papers/svmtalk.pdf
Some conclusions:
The classification performance is very similar.
Has limiting optimal margin properties.
Provides estimates of the class probabilities. Often these are
more useful than the classifications.
Generalizes naturally to M-class classification through kernel
multi-logit regression.
|
Kernel logistic regression vs SVM
|
please visit http://www.stanford.edu/~hastie/Papers/svmtalk.pdf
Some conclusions:
The classification performance is very similar.
Has limiting optimal margin properties.
Provides estimates of the class
|
Kernel logistic regression vs SVM
please visit http://www.stanford.edu/~hastie/Papers/svmtalk.pdf
Some conclusions:
The classification performance is very similar.
Has limiting optimal margin properties.
Provides estimates of the class probabilities. Often these are
more useful than the classifications.
Generalizes naturally to M-class classification through kernel
multi-logit regression.
|
Kernel logistic regression vs SVM
please visit http://www.stanford.edu/~hastie/Papers/svmtalk.pdf
Some conclusions:
The classification performance is very similar.
Has limiting optimal margin properties.
Provides estimates of the class
|
7,184
|
Intuition for Conditional Expectation of $\sigma$-algebra
|
One way to think about conditional expectation is as a projection onto the $\sigma$-algebra $\mathscr{G}$.
(from Wikimedia commons)
This is actually rigorously true when talking about square-integrable random variables; in this case $\mathbb{E}[\xi|\mathscr{G}]$ is actually the orthogonal projection of the random variable $\xi$ onto the subspace of $L^2(\Omega)$ consisting of random variables measurable with respect to $\mathscr{G}$. And in fact this even turns out to be true in some sense for $L^1$ random variables via approximation by $L^2$ random variables.
(See the comments for references.)
If one considers $\sigma-$algebras as representing how much information we have available (an interpretation which is de rigueur in the theory of stochastic processes), then larger $\sigma-$algebras mean more possible events and thus more information about possible outcomes, while smaller $\sigma-$algebras mean fewer possible events and thus less information about possible outcomes.
Therefore, projecting the $\mathscr{F}$-measurable random variable $\xi$ onto the smaller $\sigma-$algebra $\mathscr{G}$ means taking our best guess for the value of $\xi$ given the more limited information available from $\mathscr{G}$.
In other words, given only the information from $\mathscr{G}$, and not the whole of information from $\mathscr{F}$, $\mathbb{E}[\xi|\mathscr{G}]$ is in a rigorous sense our best possible guess for what the random variable $\xi$ is.
With regards to your example, I think you might be confusing random variables and their values. A random variable $X$ is a function whose domain is the event space; it is not a number. In other words, $X: \Omega \to \mathbb{R}$, $X \in \{f\ |\ f: \Omega \to \mathbb{R} \}$ whereas for an $\omega \in \Omega$, $X(\omega)\in\mathbb{R}$.
The notation for conditional expectation, in my opinion, is really bad, because it is a random variable itself, i.e. also a function. In contrast, the (regular) expectation of a random variable is a number. The conditional expectation of a random variable is an entirely different quantity from the expectation of the same random variable, i.e., $\mathbb{E}[\xi|\mathscr{G}]$ doesn't even "type-check" with $\mathbb{E}[\xi]$.
In other words, using the symbol $\mathbb{E}$ to denote both regular and conditional expectation is a very big abuse of notation, which leads to much unnecessary confusion.
All of that being said, note that $\mathbb{E}[\xi|\mathscr{G}](\omega)$ is a number (the value of the random variable $\mathbb{E}[\xi|\mathscr{G}]$ evaluated at the value $\omega$), but $\mathbb{E}[\xi|\Omega]$ is a random variable, but it turns out to be a constant random variable (i.e. trivial degenerate), because the $\sigma$-algebra generated by $\Omega$, $\{ \emptyset, \Omega\}$ is trivial/degenerate, and then technically speaking the constant value of this constant random variable, is $\mathbb{E}[\xi]$, where here $\mathbb{E}$ denotes regular expectation and thus a number, not conditional expectation and thus not a random variable.
Also you seem to be confused about what the notation $\mathbb{E}[\xi|A]$ means; technically speaking it is only possible to condition on $\sigma-$algebras, not on individual events, since probability measures are only defined on complete $\sigma-$algebras, not on individual events. Thus, $\mathbb{E}[\xi|A]$ is just (lazy) shorthand for $\mathbb{E}[\xi|\sigma(A)]$, where $\sigma(A)$ stands for the $\sigma-$algebra generated by the event $A$, which is $\{ \emptyset, A, A^c, \Omega\}$. Note that $\sigma(A) = \mathscr{G} = \sigma(A^c)$; in other words, $\mathbb{E}[\xi|A]$, $\mathbb{E}[\xi|\mathscr{G}]$, and $\mathbb{E}[\xi|A^c]$ are all different ways to denote the exact same object.
Finally I just want to add that the intuitive explanation I gave above explains why the constant value of the random variable $\mathbb{E}[\xi|\Omega]=\mathbb{E}[\xi|\sigma(\Omega)]= \mathbb{E}[\xi| \{ \emptyset, \Omega\}]$ is just the number $\mathbb{E}[\xi]$ -- the $\sigma-$algebra $\{ \emptyset, \Omega\}$ represents the least possible amount of information we could have, in fact essentially no information, so under this extreme circumstance the best possible guess we could have for which random variable $\xi$ is is the constant random variable whose constant value is $\mathbb{E}[\xi]$.
Note that all constant random variables are $L^2$ random variables, and they are all measurable with respect to the trivial $\sigma$-algebra $\{\emptyset, \Omega\}$, so indeed we do have that the constant random $\mathbb{E}[\xi]$ is the orthogonal projection of $\xi$ onto the subspace of $L^2(\Omega)$ consisting of random variables measurable with respect to $\{\emptyset, \Omega\}$, as was claimed.
|
Intuition for Conditional Expectation of $\sigma$-algebra
|
One way to think about conditional expectation is as a projection onto the $\sigma$-algebra $\mathscr{G}$.
(from Wikimedia commons)
This is actually rigorously true when talking about square-integrab
|
Intuition for Conditional Expectation of $\sigma$-algebra
One way to think about conditional expectation is as a projection onto the $\sigma$-algebra $\mathscr{G}$.
(from Wikimedia commons)
This is actually rigorously true when talking about square-integrable random variables; in this case $\mathbb{E}[\xi|\mathscr{G}]$ is actually the orthogonal projection of the random variable $\xi$ onto the subspace of $L^2(\Omega)$ consisting of random variables measurable with respect to $\mathscr{G}$. And in fact this even turns out to be true in some sense for $L^1$ random variables via approximation by $L^2$ random variables.
(See the comments for references.)
If one considers $\sigma-$algebras as representing how much information we have available (an interpretation which is de rigueur in the theory of stochastic processes), then larger $\sigma-$algebras mean more possible events and thus more information about possible outcomes, while smaller $\sigma-$algebras mean fewer possible events and thus less information about possible outcomes.
Therefore, projecting the $\mathscr{F}$-measurable random variable $\xi$ onto the smaller $\sigma-$algebra $\mathscr{G}$ means taking our best guess for the value of $\xi$ given the more limited information available from $\mathscr{G}$.
In other words, given only the information from $\mathscr{G}$, and not the whole of information from $\mathscr{F}$, $\mathbb{E}[\xi|\mathscr{G}]$ is in a rigorous sense our best possible guess for what the random variable $\xi$ is.
With regards to your example, I think you might be confusing random variables and their values. A random variable $X$ is a function whose domain is the event space; it is not a number. In other words, $X: \Omega \to \mathbb{R}$, $X \in \{f\ |\ f: \Omega \to \mathbb{R} \}$ whereas for an $\omega \in \Omega$, $X(\omega)\in\mathbb{R}$.
The notation for conditional expectation, in my opinion, is really bad, because it is a random variable itself, i.e. also a function. In contrast, the (regular) expectation of a random variable is a number. The conditional expectation of a random variable is an entirely different quantity from the expectation of the same random variable, i.e., $\mathbb{E}[\xi|\mathscr{G}]$ doesn't even "type-check" with $\mathbb{E}[\xi]$.
In other words, using the symbol $\mathbb{E}$ to denote both regular and conditional expectation is a very big abuse of notation, which leads to much unnecessary confusion.
All of that being said, note that $\mathbb{E}[\xi|\mathscr{G}](\omega)$ is a number (the value of the random variable $\mathbb{E}[\xi|\mathscr{G}]$ evaluated at the value $\omega$), but $\mathbb{E}[\xi|\Omega]$ is a random variable, but it turns out to be a constant random variable (i.e. trivial degenerate), because the $\sigma$-algebra generated by $\Omega$, $\{ \emptyset, \Omega\}$ is trivial/degenerate, and then technically speaking the constant value of this constant random variable, is $\mathbb{E}[\xi]$, where here $\mathbb{E}$ denotes regular expectation and thus a number, not conditional expectation and thus not a random variable.
Also you seem to be confused about what the notation $\mathbb{E}[\xi|A]$ means; technically speaking it is only possible to condition on $\sigma-$algebras, not on individual events, since probability measures are only defined on complete $\sigma-$algebras, not on individual events. Thus, $\mathbb{E}[\xi|A]$ is just (lazy) shorthand for $\mathbb{E}[\xi|\sigma(A)]$, where $\sigma(A)$ stands for the $\sigma-$algebra generated by the event $A$, which is $\{ \emptyset, A, A^c, \Omega\}$. Note that $\sigma(A) = \mathscr{G} = \sigma(A^c)$; in other words, $\mathbb{E}[\xi|A]$, $\mathbb{E}[\xi|\mathscr{G}]$, and $\mathbb{E}[\xi|A^c]$ are all different ways to denote the exact same object.
Finally I just want to add that the intuitive explanation I gave above explains why the constant value of the random variable $\mathbb{E}[\xi|\Omega]=\mathbb{E}[\xi|\sigma(\Omega)]= \mathbb{E}[\xi| \{ \emptyset, \Omega\}]$ is just the number $\mathbb{E}[\xi]$ -- the $\sigma-$algebra $\{ \emptyset, \Omega\}$ represents the least possible amount of information we could have, in fact essentially no information, so under this extreme circumstance the best possible guess we could have for which random variable $\xi$ is is the constant random variable whose constant value is $\mathbb{E}[\xi]$.
Note that all constant random variables are $L^2$ random variables, and they are all measurable with respect to the trivial $\sigma$-algebra $\{\emptyset, \Omega\}$, so indeed we do have that the constant random $\mathbb{E}[\xi]$ is the orthogonal projection of $\xi$ onto the subspace of $L^2(\Omega)$ consisting of random variables measurable with respect to $\{\emptyset, \Omega\}$, as was claimed.
|
Intuition for Conditional Expectation of $\sigma$-algebra
One way to think about conditional expectation is as a projection onto the $\sigma$-algebra $\mathscr{G}$.
(from Wikimedia commons)
This is actually rigorously true when talking about square-integrab
|
7,185
|
Intuition for Conditional Expectation of $\sigma$-algebra
|
I am going to try to elaborate what William suggested.
Let $\Omega$ be the sample space of tossing a coin twice. Define the ran. var. $\xi$ to be the num. of heads that occur in the experiment. Clearly, $E[\xi] = 1$. One way of thinking of what $1$, as an expec. value, represents is as the best possible estimate for $\xi$. If we had to take a guess for what value $\xi$ would take, we would guess $1$. This is because $E[(\xi - 1)^2] \leq E[(\xi - a)^2]$ for any real number $a$.
Denote by $A = \{ HT, HH \}$ to be the event that the first outcome is a head. Let $\mathscr{G} = \{ \emptyset, A, A^c, \Omega\}$ be the $\sigma$-alg. gen. by $A$. We think of $\mathscr{G}$ as representing what we know after the first toss. After the first toss, either heads occured, or heads did not occur. Hence, we are either in the event $A$ or $A^c$ after the first toss.
If we are in the event $A$, then the best possible estimate for $\xi$ would be $E[\xi|A] = 1.5$, and if we are in the event $A^c$, then the best possible estimate for $\xi$ would be $E[\xi|A^c] = 0.5$.
Now define the ran. var. $\eta(\omega)$ to be either $1.5$ or $0.5$ depending on whether or not $\omega\in A$. This ran. var. $\eta$, is a better approximation than $1 = E[\xi]$ since $E[(\xi - \eta)^2] \leq E[(\xi -1)^2]$.
What $\eta$ is doing is providing the answer to the question: what is the best estimate of $\xi$ after the first toss? Since we do not know the information after the first toss, $\eta$ will depend on $A$. Once the event $\mathscr{G}$ is revealed to us, after the first toss, the value of $\eta$ is determined and provides the best possible estimate for $\xi$.
The problem with using $\xi$ as its own estimate, i.e. $0=E[(\xi - \xi)^2] \leq E[(\xi - \eta)^2]$ is as follows. $\xi$ is not well-defined after the first toss. Say the outcome of the experiment is $\omega$ with first outcome being heads, we are in the event $A$, but what is $\xi(\omega)=?$ We do not know from just the first toss, that value is ambiguous to us, and so $\xi$ is not well-defined. More formally, we say that $\xi$ is not $\mathscr{G}$-measurable i.e. its value is not well-defined after the first toss. Thus, $\eta$ is the best possible estimate of $\xi$ after the first toss.
Perhaps, somebody here can come up with a more sophisticated example using the sample space $[0,1]$, with $\xi (\omega) = \omega$, and $\mathscr{G}$ some non-trivial $\sigma$-algebra.
|
Intuition for Conditional Expectation of $\sigma$-algebra
|
I am going to try to elaborate what William suggested.
Let $\Omega$ be the sample space of tossing a coin twice. Define the ran. var. $\xi$ to be the num. of heads that occur in the experiment. Clear
|
Intuition for Conditional Expectation of $\sigma$-algebra
I am going to try to elaborate what William suggested.
Let $\Omega$ be the sample space of tossing a coin twice. Define the ran. var. $\xi$ to be the num. of heads that occur in the experiment. Clearly, $E[\xi] = 1$. One way of thinking of what $1$, as an expec. value, represents is as the best possible estimate for $\xi$. If we had to take a guess for what value $\xi$ would take, we would guess $1$. This is because $E[(\xi - 1)^2] \leq E[(\xi - a)^2]$ for any real number $a$.
Denote by $A = \{ HT, HH \}$ to be the event that the first outcome is a head. Let $\mathscr{G} = \{ \emptyset, A, A^c, \Omega\}$ be the $\sigma$-alg. gen. by $A$. We think of $\mathscr{G}$ as representing what we know after the first toss. After the first toss, either heads occured, or heads did not occur. Hence, we are either in the event $A$ or $A^c$ after the first toss.
If we are in the event $A$, then the best possible estimate for $\xi$ would be $E[\xi|A] = 1.5$, and if we are in the event $A^c$, then the best possible estimate for $\xi$ would be $E[\xi|A^c] = 0.5$.
Now define the ran. var. $\eta(\omega)$ to be either $1.5$ or $0.5$ depending on whether or not $\omega\in A$. This ran. var. $\eta$, is a better approximation than $1 = E[\xi]$ since $E[(\xi - \eta)^2] \leq E[(\xi -1)^2]$.
What $\eta$ is doing is providing the answer to the question: what is the best estimate of $\xi$ after the first toss? Since we do not know the information after the first toss, $\eta$ will depend on $A$. Once the event $\mathscr{G}$ is revealed to us, after the first toss, the value of $\eta$ is determined and provides the best possible estimate for $\xi$.
The problem with using $\xi$ as its own estimate, i.e. $0=E[(\xi - \xi)^2] \leq E[(\xi - \eta)^2]$ is as follows. $\xi$ is not well-defined after the first toss. Say the outcome of the experiment is $\omega$ with first outcome being heads, we are in the event $A$, but what is $\xi(\omega)=?$ We do not know from just the first toss, that value is ambiguous to us, and so $\xi$ is not well-defined. More formally, we say that $\xi$ is not $\mathscr{G}$-measurable i.e. its value is not well-defined after the first toss. Thus, $\eta$ is the best possible estimate of $\xi$ after the first toss.
Perhaps, somebody here can come up with a more sophisticated example using the sample space $[0,1]$, with $\xi (\omega) = \omega$, and $\mathscr{G}$ some non-trivial $\sigma$-algebra.
|
Intuition for Conditional Expectation of $\sigma$-algebra
I am going to try to elaborate what William suggested.
Let $\Omega$ be the sample space of tossing a coin twice. Define the ran. var. $\xi$ to be the num. of heads that occur in the experiment. Clear
|
7,186
|
Intuition for Conditional Expectation of $\sigma$-algebra
|
Although you request not to use the formal definition, I think that the formal definition is probably the best way of explaining it.
Wikipedia - conditional expectation:
Then a conditional expectation of X given $\displaystyle \scriptstyle
{\mathcal {H}}$, denoted as $\displaystyle \scriptstyle \operatorname
{E} (X\mid {\mathcal {H}})$, is any $\displaystyle \scriptstyle
{\mathcal {H}}$-measurable function ( $\displaystyle \scriptstyle
\Omega \to \mathbb {R} ^{n}$) which satisfies:
$\displaystyle \int _{H}\operatorname {E} (X\mid {\mathcal
{H}})\;dP=\int _{H}X\;dP\qquad {\text{for each}}\quad H\in {\mathcal
{H}}$
Firstly, it is a $\displaystyle \scriptstyle {\mathcal {H}}$-measurable function. Secondly it has to match the expectation over every measurable (sub)set in $\displaystyle \scriptstyle {\mathcal {H}}$. So for an event,A, the sigma algebra is $ \{A,A^C,\emptyset, \Omega\}$, so clearly it is set as you specified in your question for $\omega \in A/A^c$. Similarly for any discrete random variable ( and combinations of them), we list out all primitive events and assign the expectation given that primitive event.
Now consider tossing a coin an infinite number of times, where at each toss i, you get $1/2^i$, if your coin is tails then your total winnings are $X=\sum _{i=1}^\infty \frac{1}{2^i}c_i$ where $c_i$ = 1 for tails and 0 for heads. Then X is a real random variable on $[0,1]$. After n coin tosses, you know the value of X to precision $1/2^n$, eg after 2 coin tosses it is in [0,1/4], [1/4,1/2], [1/2,3/4] or [3/4,1] - after every coin toss, your associated sigma algebra is getting finer and finer, and similarly the conditional expectation of X is getting more and more precise.
Hopefully this example of a real valued random variable with a sequence of sigma algebras getting finer and finer (Filtration) gets you away from the purely event based intuition you are used to, and clarifies its purpose.
|
Intuition for Conditional Expectation of $\sigma$-algebra
|
Although you request not to use the formal definition, I think that the formal definition is probably the best way of explaining it.
Wikipedia - conditional expectation:
Then a conditional expectatio
|
Intuition for Conditional Expectation of $\sigma$-algebra
Although you request not to use the formal definition, I think that the formal definition is probably the best way of explaining it.
Wikipedia - conditional expectation:
Then a conditional expectation of X given $\displaystyle \scriptstyle
{\mathcal {H}}$, denoted as $\displaystyle \scriptstyle \operatorname
{E} (X\mid {\mathcal {H}})$, is any $\displaystyle \scriptstyle
{\mathcal {H}}$-measurable function ( $\displaystyle \scriptstyle
\Omega \to \mathbb {R} ^{n}$) which satisfies:
$\displaystyle \int _{H}\operatorname {E} (X\mid {\mathcal
{H}})\;dP=\int _{H}X\;dP\qquad {\text{for each}}\quad H\in {\mathcal
{H}}$
Firstly, it is a $\displaystyle \scriptstyle {\mathcal {H}}$-measurable function. Secondly it has to match the expectation over every measurable (sub)set in $\displaystyle \scriptstyle {\mathcal {H}}$. So for an event,A, the sigma algebra is $ \{A,A^C,\emptyset, \Omega\}$, so clearly it is set as you specified in your question for $\omega \in A/A^c$. Similarly for any discrete random variable ( and combinations of them), we list out all primitive events and assign the expectation given that primitive event.
Now consider tossing a coin an infinite number of times, where at each toss i, you get $1/2^i$, if your coin is tails then your total winnings are $X=\sum _{i=1}^\infty \frac{1}{2^i}c_i$ where $c_i$ = 1 for tails and 0 for heads. Then X is a real random variable on $[0,1]$. After n coin tosses, you know the value of X to precision $1/2^n$, eg after 2 coin tosses it is in [0,1/4], [1/4,1/2], [1/2,3/4] or [3/4,1] - after every coin toss, your associated sigma algebra is getting finer and finer, and similarly the conditional expectation of X is getting more and more precise.
Hopefully this example of a real valued random variable with a sequence of sigma algebras getting finer and finer (Filtration) gets you away from the purely event based intuition you are used to, and clarifies its purpose.
|
Intuition for Conditional Expectation of $\sigma$-algebra
Although you request not to use the formal definition, I think that the formal definition is probably the best way of explaining it.
Wikipedia - conditional expectation:
Then a conditional expectatio
|
7,187
|
Intuition for Conditional Expectation of $\sigma$-algebra
|
To help a little bit more, case ii in your question is a special case that a sigma-algebra being conditioned on is generated by a partition. I am sure you will find that case intuitive as well.
|
Intuition for Conditional Expectation of $\sigma$-algebra
|
To help a little bit more, case ii in your question is a special case that a sigma-algebra being conditioned on is generated by a partition. I am sure you will find that case intuitive as well.
|
Intuition for Conditional Expectation of $\sigma$-algebra
To help a little bit more, case ii in your question is a special case that a sigma-algebra being conditioned on is generated by a partition. I am sure you will find that case intuitive as well.
|
Intuition for Conditional Expectation of $\sigma$-algebra
To help a little bit more, case ii in your question is a special case that a sigma-algebra being conditioned on is generated by a partition. I am sure you will find that case intuitive as well.
|
7,188
|
How to calculate pooled variance of two or more groups given known group variances, means, and sample sizes?
|
The idea is to express quantities as sums rather than fractions.
Given any $n$ data values $x_i,$ use the definitions of the mean
$$\mu_{1:n} = \frac{1}{\Omega_{1;n}}\sum_{i=1}^n \omega_{i} x_i$$
and sample variance
$$\sigma_{1:n}^2 = \frac{1}{\Omega_{1;n}}\sum_{i=1}^n \omega_{i}\left(x_i - \mu_{1:n}\right)^2 = \frac{1}{\Omega_{1;n}}\sum_{i=1}^n \omega_{i}x_i^2 - \mu_{1:n}^2$$
to find the (weighted) sum of squares of the data as
$$\Omega_{1;n}\mu_{1:n} = \sum_{i=1}^n \omega_{i} x_i$$
and
$$\Omega_{1;n} \sigma_{1:n}^2 = \sum_{i=1}^n \omega_{i}\left(x_i - \mu_{1:n}\right)^2 = \sum_{i=1}^n \omega_{i}x_i^2 - \Omega_{1;n}\mu_{1:n}^2.$$
For notational convenience I have written $$\Omega_{j;k}=\sum_{i=j}^k \omega_i$$ for sums of weights. (In applications with equal weights, which are the usual ones, we may take $\omega_i=1$ for all $i,$ whence $\Omega_{1;n}=n.$)
Let's do the (simple) algebra. Order the indexes $i$ so that $i=1,\ldots,n$ designates elements of the first group and $i=n+1,\ldots,n+m$ designates elements of the second group. Break the overall combination of squares by group and re-express the two pieces in terms of the variances and means of the subsets of the data:
$$\eqalign{
\Omega_{1;n+m}(\sigma^2_{1:m+n} + \mu_{1:m+n}^2)&= \sum_{i=1}^{1:n+m} \omega_{i}x_i^2 \\
&= \sum_{i=1}^n \omega_{i} x_i^2 + \sum_{i=n+1}^{n+m} \omega_{i} x_i^2 \\
&= \Omega_{1;n}(\sigma^2_{1:n} + \mu_{1:n}^2) + \Omega_{n+1;n+m}(\sigma^2_{1+n:m+n} + \mu_{1+n:m+n}^2).
}$$
Algebraically solving this for $\sigma^2_{m+n}$ in terms of the other (known) quantities yields
$$\sigma^2_{1:m+n} = \frac{\Omega_{1;n}(\sigma^2_{1:n} + \mu_{1:n}^2) + \Omega_{n+1;n+m}(\sigma^2_{1+n:m+n} + \mu_{1+n:m+n}^2)}{\Omega_{1;n+m}} - \mu^2_{1:m+n}.$$
Of course, using the same approach, $\mu_{1:m+n} = (\Omega_{1;n}\mu_{1:n} + \Omega_{n+1;n+m}\mu_{1+n:m+n})/\Omega_{1;n+m}$ can be expressed in terms of the group means, too.
Edit 1
An anonymous contributor points out that when the sample means are equal (so that $\mu_{1:n}=\mu_{1+n:m+n}=\mu_{1:m+n}$), the solution for $\sigma^2_{m+n}$ is a weighted mean of the group sample variances.
Edit 2
I have generalized the formulas to weighted statistics. The motivation for this is a recent federal court case in the US involving a dispute over how to pool weighted variances: a government agency contends the proper method is to weight the two group variances equally. In working on this case I found it difficult to find authoritative references on combining weighted statistics: most textbooks do not deal with this or they assume the generalization is obvious (which it is, but not necessarily to government employees or lawyers!).
BTW, I used entirely different notation in my work on that case. If in the editing process any error has crept into the formulas in this post I apologize in advance and will fix them--but that would not reflect any error in my testimony, which was very carefully checked.
|
How to calculate pooled variance of two or more groups given known group variances, means, and sampl
|
The idea is to express quantities as sums rather than fractions.
Given any $n$ data values $x_i,$ use the definitions of the mean
$$\mu_{1:n} = \frac{1}{\Omega_{1;n}}\sum_{i=1}^n \omega_{i} x_i$$
and
|
How to calculate pooled variance of two or more groups given known group variances, means, and sample sizes?
The idea is to express quantities as sums rather than fractions.
Given any $n$ data values $x_i,$ use the definitions of the mean
$$\mu_{1:n} = \frac{1}{\Omega_{1;n}}\sum_{i=1}^n \omega_{i} x_i$$
and sample variance
$$\sigma_{1:n}^2 = \frac{1}{\Omega_{1;n}}\sum_{i=1}^n \omega_{i}\left(x_i - \mu_{1:n}\right)^2 = \frac{1}{\Omega_{1;n}}\sum_{i=1}^n \omega_{i}x_i^2 - \mu_{1:n}^2$$
to find the (weighted) sum of squares of the data as
$$\Omega_{1;n}\mu_{1:n} = \sum_{i=1}^n \omega_{i} x_i$$
and
$$\Omega_{1;n} \sigma_{1:n}^2 = \sum_{i=1}^n \omega_{i}\left(x_i - \mu_{1:n}\right)^2 = \sum_{i=1}^n \omega_{i}x_i^2 - \Omega_{1;n}\mu_{1:n}^2.$$
For notational convenience I have written $$\Omega_{j;k}=\sum_{i=j}^k \omega_i$$ for sums of weights. (In applications with equal weights, which are the usual ones, we may take $\omega_i=1$ for all $i,$ whence $\Omega_{1;n}=n.$)
Let's do the (simple) algebra. Order the indexes $i$ so that $i=1,\ldots,n$ designates elements of the first group and $i=n+1,\ldots,n+m$ designates elements of the second group. Break the overall combination of squares by group and re-express the two pieces in terms of the variances and means of the subsets of the data:
$$\eqalign{
\Omega_{1;n+m}(\sigma^2_{1:m+n} + \mu_{1:m+n}^2)&= \sum_{i=1}^{1:n+m} \omega_{i}x_i^2 \\
&= \sum_{i=1}^n \omega_{i} x_i^2 + \sum_{i=n+1}^{n+m} \omega_{i} x_i^2 \\
&= \Omega_{1;n}(\sigma^2_{1:n} + \mu_{1:n}^2) + \Omega_{n+1;n+m}(\sigma^2_{1+n:m+n} + \mu_{1+n:m+n}^2).
}$$
Algebraically solving this for $\sigma^2_{m+n}$ in terms of the other (known) quantities yields
$$\sigma^2_{1:m+n} = \frac{\Omega_{1;n}(\sigma^2_{1:n} + \mu_{1:n}^2) + \Omega_{n+1;n+m}(\sigma^2_{1+n:m+n} + \mu_{1+n:m+n}^2)}{\Omega_{1;n+m}} - \mu^2_{1:m+n}.$$
Of course, using the same approach, $\mu_{1:m+n} = (\Omega_{1;n}\mu_{1:n} + \Omega_{n+1;n+m}\mu_{1+n:m+n})/\Omega_{1;n+m}$ can be expressed in terms of the group means, too.
Edit 1
An anonymous contributor points out that when the sample means are equal (so that $\mu_{1:n}=\mu_{1+n:m+n}=\mu_{1:m+n}$), the solution for $\sigma^2_{m+n}$ is a weighted mean of the group sample variances.
Edit 2
I have generalized the formulas to weighted statistics. The motivation for this is a recent federal court case in the US involving a dispute over how to pool weighted variances: a government agency contends the proper method is to weight the two group variances equally. In working on this case I found it difficult to find authoritative references on combining weighted statistics: most textbooks do not deal with this or they assume the generalization is obvious (which it is, but not necessarily to government employees or lawyers!).
BTW, I used entirely different notation in my work on that case. If in the editing process any error has crept into the formulas in this post I apologize in advance and will fix them--but that would not reflect any error in my testimony, which was very carefully checked.
|
How to calculate pooled variance of two or more groups given known group variances, means, and sampl
The idea is to express quantities as sums rather than fractions.
Given any $n$ data values $x_i,$ use the definitions of the mean
$$\mu_{1:n} = \frac{1}{\Omega_{1;n}}\sum_{i=1}^n \omega_{i} x_i$$
and
|
7,189
|
How to calculate pooled variance of two or more groups given known group variances, means, and sample sizes?
|
I'm going to use standard notation for sample means and sample variances in this answer, rather than the notation used in the question. Using standard notation, another formula for the pooled sample variance of two groups can be found in O'Neill (2014) (Result 1):
$$\begin{equation} \begin{aligned}
s_\text{pooled}^2 &= \frac{1}{n_1+n_2-1} \Bigg[ (n_1-1) s_1^2 + (n_2-1) s_2^2 + \frac{n_1 n_2}{n_1+n_2} (\bar{x}_1 - \bar{x}_2)^2 \Bigg]. \\[10pt]
\end{aligned} \end{equation}$$
This formula works directly with the underlying sample means and sample variances of the two subgroups, and does not require intermediate calculation of the pooled sample mean. (Proof of result in linked paper.)
|
How to calculate pooled variance of two or more groups given known group variances, means, and sampl
|
I'm going to use standard notation for sample means and sample variances in this answer, rather than the notation used in the question. Using standard notation, another formula for the pooled sample
|
How to calculate pooled variance of two or more groups given known group variances, means, and sample sizes?
I'm going to use standard notation for sample means and sample variances in this answer, rather than the notation used in the question. Using standard notation, another formula for the pooled sample variance of two groups can be found in O'Neill (2014) (Result 1):
$$\begin{equation} \begin{aligned}
s_\text{pooled}^2 &= \frac{1}{n_1+n_2-1} \Bigg[ (n_1-1) s_1^2 + (n_2-1) s_2^2 + \frac{n_1 n_2}{n_1+n_2} (\bar{x}_1 - \bar{x}_2)^2 \Bigg]. \\[10pt]
\end{aligned} \end{equation}$$
This formula works directly with the underlying sample means and sample variances of the two subgroups, and does not require intermediate calculation of the pooled sample mean. (Proof of result in linked paper.)
|
How to calculate pooled variance of two or more groups given known group variances, means, and sampl
I'm going to use standard notation for sample means and sample variances in this answer, rather than the notation used in the question. Using standard notation, another formula for the pooled sample
|
7,190
|
How to calculate pooled variance of two or more groups given known group variances, means, and sample sizes?
|
Use the sample.decomp function in the utilities package
Statistical problems of this kind have now been automated in the sample.decomp function in the utilities package. This function can compute pooled sample moments from subgroup moments, or compute missing subgroup moments from the other subgroup moments and pooled moments. It works for decompositions up to fourth order ---i.e., decompositions of sample size, sample mean, sample variance/standard deviation, sample skewness, and sample kurtosis.
How to use the function: Here we give an example where we use the function to compute the sample moments of a pooled sample composed of three subgroups. To do this, we first generate a mock dataset DATA containing three subgroups with unequal sizes, and we pool these as the single dataset POOL. The moments of the subgroups and the pooled sample can be obtained using the moments function in the same package.
#Create some subgroups of mock data and a pooled dataset
set.seed(1)
N <- c(28, 44, 51)
SUB1 <- rnorm(N[1])
SUB2 <- rnorm(N[2])
SUB3 <- rnorm(N[3])
DATA <- list(SUB1 = SUB1, SUB2 = SUB2, SUB3 = SUB3)
POOL <- c(SUB1, SUB2, SUB3)
#Show sample statistics for the subgroups
library(utilities)
moments(DATA)
n sample.mean sample.var sample.skew sample.kurt NAs
SUB1 28 0.09049834 0.9013829 -0.7648008 3.174128 0
SUB2 44 0.18637936 0.8246700 0.3653918 3.112901 0
SUB3 51 0.05986594 0.6856030 0.3076281 2.306243 0
#Show sample statistics for the pooled sample
moments(POOL)
n sample.mean sample.var sample.skew sample.kurt NAs
POOL 123 0.112096 0.7743711 0.04697463 2.95196 0
Now that we have set of moments for subgroups, we can use the sample.decomp function to obtain the pooled sample moments from the subgroup sample moments. As an input to this function you can either use the moments output for the subgroups or you can input the sample sizes and sample moments separately as vectors (here we will do the latter). As you can see, this gives the same sample moments for the pooled sample as direct computation from the underlying data.
#Compute sample statistics for subgroups
library(utilities)
MEAN <- c( mean(SUB1), mean(SUB2), mean(SUB3))
VAR <- c( var(SUB1), var(SUB2), var(SUB3))
SKEW <- c(skewness(SUB1), skewness(SUB2), skewness(SUB3))
KURT <- c(kurtosis(SUB1), kurtosis(SUB2), kurtosis(SUB3))
#Compute sample decomposition
sample.decomp(n = N,
sample.mean = MEAN,
sample.var = VAR,
sample.skew = SKEW,
sample.kurt = KURT,
names = names(DATA))
n sample.mean sample.var sample.skew sample.kurt
SUB1 28 0.09049834 0.9013829 -0.76480085 3.174128
SUB2 44 0.18637936 0.8246700 0.36539179 3.112901
SUB3 51 0.05986594 0.6856030 0.30762810 2.306243
--pooled-- 123 0.11209600 0.7743711 0.04697463 2.951960
As you can see, the sample.decomp function allows computation of the pooled sample variance and also other pooled sample central moments, up to fourth order. You can read about this function in the package documentation. However, it is worth noting that for the higher-order moments (the skewness and kurtosis) there are several different statistics that can be used. The above functions accommodate these variations through the arguments skew.type, kurt.type and kurt.excess, which have default values that we have used in the above computations.
|
How to calculate pooled variance of two or more groups given known group variances, means, and sampl
|
Use the sample.decomp function in the utilities package
Statistical problems of this kind have now been automated in the sample.decomp function in the utilities package. This function can compute poo
|
How to calculate pooled variance of two or more groups given known group variances, means, and sample sizes?
Use the sample.decomp function in the utilities package
Statistical problems of this kind have now been automated in the sample.decomp function in the utilities package. This function can compute pooled sample moments from subgroup moments, or compute missing subgroup moments from the other subgroup moments and pooled moments. It works for decompositions up to fourth order ---i.e., decompositions of sample size, sample mean, sample variance/standard deviation, sample skewness, and sample kurtosis.
How to use the function: Here we give an example where we use the function to compute the sample moments of a pooled sample composed of three subgroups. To do this, we first generate a mock dataset DATA containing three subgroups with unequal sizes, and we pool these as the single dataset POOL. The moments of the subgroups and the pooled sample can be obtained using the moments function in the same package.
#Create some subgroups of mock data and a pooled dataset
set.seed(1)
N <- c(28, 44, 51)
SUB1 <- rnorm(N[1])
SUB2 <- rnorm(N[2])
SUB3 <- rnorm(N[3])
DATA <- list(SUB1 = SUB1, SUB2 = SUB2, SUB3 = SUB3)
POOL <- c(SUB1, SUB2, SUB3)
#Show sample statistics for the subgroups
library(utilities)
moments(DATA)
n sample.mean sample.var sample.skew sample.kurt NAs
SUB1 28 0.09049834 0.9013829 -0.7648008 3.174128 0
SUB2 44 0.18637936 0.8246700 0.3653918 3.112901 0
SUB3 51 0.05986594 0.6856030 0.3076281 2.306243 0
#Show sample statistics for the pooled sample
moments(POOL)
n sample.mean sample.var sample.skew sample.kurt NAs
POOL 123 0.112096 0.7743711 0.04697463 2.95196 0
Now that we have set of moments for subgroups, we can use the sample.decomp function to obtain the pooled sample moments from the subgroup sample moments. As an input to this function you can either use the moments output for the subgroups or you can input the sample sizes and sample moments separately as vectors (here we will do the latter). As you can see, this gives the same sample moments for the pooled sample as direct computation from the underlying data.
#Compute sample statistics for subgroups
library(utilities)
MEAN <- c( mean(SUB1), mean(SUB2), mean(SUB3))
VAR <- c( var(SUB1), var(SUB2), var(SUB3))
SKEW <- c(skewness(SUB1), skewness(SUB2), skewness(SUB3))
KURT <- c(kurtosis(SUB1), kurtosis(SUB2), kurtosis(SUB3))
#Compute sample decomposition
sample.decomp(n = N,
sample.mean = MEAN,
sample.var = VAR,
sample.skew = SKEW,
sample.kurt = KURT,
names = names(DATA))
n sample.mean sample.var sample.skew sample.kurt
SUB1 28 0.09049834 0.9013829 -0.76480085 3.174128
SUB2 44 0.18637936 0.8246700 0.36539179 3.112901
SUB3 51 0.05986594 0.6856030 0.30762810 2.306243
--pooled-- 123 0.11209600 0.7743711 0.04697463 2.951960
As you can see, the sample.decomp function allows computation of the pooled sample variance and also other pooled sample central moments, up to fourth order. You can read about this function in the package documentation. However, it is worth noting that for the higher-order moments (the skewness and kurtosis) there are several different statistics that can be used. The above functions accommodate these variations through the arguments skew.type, kurt.type and kurt.excess, which have default values that we have used in the above computations.
|
How to calculate pooled variance of two or more groups given known group variances, means, and sampl
Use the sample.decomp function in the utilities package
Statistical problems of this kind have now been automated in the sample.decomp function in the utilities package. This function can compute poo
|
7,191
|
How to fit an ARIMAX-model with R?
|
You're going to have a little bit of trouble modeling a series with 2 levels of seasonality using an ARIMA model. Getting this right is going highly dependent on setting things up correctly. Have you considered a simple linear model yet? They're a lot faster and easier to fit than ARIMA models, and if you use dummy variables for your different seasonality levels they are often quite accurate.
I'm assuming you have hourly data, so make sure your TS object is setup with a frequency of 24.
You can model other levels of seasonality using dummy variables. For example, you might want a set of 0/1 dummies representing the month of the year.
Include the dummy variables in the xreg argument, along with any covariates (like temperature).
Fit the model with the arima function in base R. This function can handle ARMAX models through the use of the xreg argument.
Try the Arima and auto.arima functions in the forecast package. auto.arima is nice because it will automatically find good parameters for your arima model. However, it will take FOREVER to fit on your dataset.
Try the tslm function in the arima package, using dummy variables for each level of seasonality. This will fit a lot faster than the Arima model, and may even work better in your situation.
If 4/5/6 don't work, THEN start worrying about transfer functions. You have to crawl before you can walk.
If you are planning to forecast into the future, you will first need to forecast your xreg variables. This is easy for seasonal dummies, but you'll have to think about how to make a good weather forecasts. Maybe use the median of historical data?
Here is an example of how I would approach this:
#Setup a fake time series
set.seed(1)
library(lubridate)
index <- ISOdatetime(2010,1,1,0,0,0)+1:8759*60*60
month <- month(index)
hour <- hour(index)
usage <- 1000+10*rnorm(length(index))-25*(month-6)^2-(hour-12)^2
usage <- ts(usage,frequency=24)
#Create monthly dummies. Add other xvars to this matrix
xreg <- model.matrix(~as.factor(month))[,2:12]
colnames(xreg) <- c('Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
#Fit a model
library(forecast)
model <- Arima(usage, order=c(0,0,0), seasonal=list(order=c(1,0,0), period=24), xreg=xreg)
plot(usage)
lines(fitted(model),col=2)
#Benchmark against other models
model2 <- tslm(usage~as.factor(month)+as.factor(hour))
model3 <- tslm(usage~as.factor(month))
model4 <- rep(mean(usage),length(usage))
#Compare the 4 models
library(plyr) #for rbind.fill
ACC <- rbind.fill( data.frame(t(accuracy(model))),
data.frame(t(accuracy(model2))),
data.frame(t(accuracy(model3))),
data.frame(t(accuracy(model4,usage)))
)
ACC <- round(ACC,2)
ACC <- cbind(Type=c('Arima','LM1','Monthly Mean','Mean'),ACC)
ACC[order(ACC$MAE),]
|
How to fit an ARIMAX-model with R?
|
You're going to have a little bit of trouble modeling a series with 2 levels of seasonality using an ARIMA model. Getting this right is going highly dependent on setting things up correctly. Have yo
|
How to fit an ARIMAX-model with R?
You're going to have a little bit of trouble modeling a series with 2 levels of seasonality using an ARIMA model. Getting this right is going highly dependent on setting things up correctly. Have you considered a simple linear model yet? They're a lot faster and easier to fit than ARIMA models, and if you use dummy variables for your different seasonality levels they are often quite accurate.
I'm assuming you have hourly data, so make sure your TS object is setup with a frequency of 24.
You can model other levels of seasonality using dummy variables. For example, you might want a set of 0/1 dummies representing the month of the year.
Include the dummy variables in the xreg argument, along with any covariates (like temperature).
Fit the model with the arima function in base R. This function can handle ARMAX models through the use of the xreg argument.
Try the Arima and auto.arima functions in the forecast package. auto.arima is nice because it will automatically find good parameters for your arima model. However, it will take FOREVER to fit on your dataset.
Try the tslm function in the arima package, using dummy variables for each level of seasonality. This will fit a lot faster than the Arima model, and may even work better in your situation.
If 4/5/6 don't work, THEN start worrying about transfer functions. You have to crawl before you can walk.
If you are planning to forecast into the future, you will first need to forecast your xreg variables. This is easy for seasonal dummies, but you'll have to think about how to make a good weather forecasts. Maybe use the median of historical data?
Here is an example of how I would approach this:
#Setup a fake time series
set.seed(1)
library(lubridate)
index <- ISOdatetime(2010,1,1,0,0,0)+1:8759*60*60
month <- month(index)
hour <- hour(index)
usage <- 1000+10*rnorm(length(index))-25*(month-6)^2-(hour-12)^2
usage <- ts(usage,frequency=24)
#Create monthly dummies. Add other xvars to this matrix
xreg <- model.matrix(~as.factor(month))[,2:12]
colnames(xreg) <- c('Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
#Fit a model
library(forecast)
model <- Arima(usage, order=c(0,0,0), seasonal=list(order=c(1,0,0), period=24), xreg=xreg)
plot(usage)
lines(fitted(model),col=2)
#Benchmark against other models
model2 <- tslm(usage~as.factor(month)+as.factor(hour))
model3 <- tslm(usage~as.factor(month))
model4 <- rep(mean(usage),length(usage))
#Compare the 4 models
library(plyr) #for rbind.fill
ACC <- rbind.fill( data.frame(t(accuracy(model))),
data.frame(t(accuracy(model2))),
data.frame(t(accuracy(model3))),
data.frame(t(accuracy(model4,usage)))
)
ACC <- round(ACC,2)
ACC <- cbind(Type=c('Arima','LM1','Monthly Mean','Mean'),ACC)
ACC[order(ACC$MAE),]
|
How to fit an ARIMAX-model with R?
You're going to have a little bit of trouble modeling a series with 2 levels of seasonality using an ARIMA model. Getting this right is going highly dependent on setting things up correctly. Have yo
|
7,192
|
How to fit an ARIMAX-model with R?
|
I've been using R to do load forecasting for a while and I can suggest you to use forecast package and its invaluable functions (like auto.arima).
You can build an ARIMA model with the following command:
model = arima(y, order, xreg = exogenous_data)
with y your predictand (I suppose dayy), order the order of your model (considering seasonality) and exogenous_data your temperature, solar radiation, etc. The function auto.arima helps you to find the optimal model order. You can find a brief tutorial about `forecast' package here.
|
How to fit an ARIMAX-model with R?
|
I've been using R to do load forecasting for a while and I can suggest you to use forecast package and its invaluable functions (like auto.arima).
You can build an ARIMA model with the following comm
|
How to fit an ARIMAX-model with R?
I've been using R to do load forecasting for a while and I can suggest you to use forecast package and its invaluable functions (like auto.arima).
You can build an ARIMA model with the following command:
model = arima(y, order, xreg = exogenous_data)
with y your predictand (I suppose dayy), order the order of your model (considering seasonality) and exogenous_data your temperature, solar radiation, etc. The function auto.arima helps you to find the optimal model order. You can find a brief tutorial about `forecast' package here.
|
How to fit an ARIMAX-model with R?
I've been using R to do load forecasting for a while and I can suggest you to use forecast package and its invaluable functions (like auto.arima).
You can build an ARIMA model with the following comm
|
7,193
|
How to fit an ARIMAX-model with R?
|
I personally don't understand transfer functions, but I think you got the xtransf and xreg reversed. At least in R's base arima it is xreg that contains your exogenous variables. It's my impression that a transfer function describes how (lagged data affects future values) rather than what.
I'd try using xreg for your exogenous variables, perhaps using arima if arimax demands a transfer function. The problem is that your model is daily, but your data has both daily and yearly seasonality, and I'm not sure right now if a first difference (the order=(*, 1, *)) will take care of that or not. (You certainly won't get magical year-round forecasts out of a model that only considers daily seasonality.)
P.S. What is the time that you use in your lm? Literal clock time or a 1-up observation number? I think you could get something by using a mixed-effect model (lmer in the lme4 package), though I haven't figured out whether doing that correctly accounts for the autocorrelation that will occur in a time series. If not accounted for, which anlm does not, you might get an interesting fit, but your concept of how precise your prediction is will be way too optimistic.
|
How to fit an ARIMAX-model with R?
|
I personally don't understand transfer functions, but I think you got the xtransf and xreg reversed. At least in R's base arima it is xreg that contains your exogenous variables. It's my impression th
|
How to fit an ARIMAX-model with R?
I personally don't understand transfer functions, but I think you got the xtransf and xreg reversed. At least in R's base arima it is xreg that contains your exogenous variables. It's my impression that a transfer function describes how (lagged data affects future values) rather than what.
I'd try using xreg for your exogenous variables, perhaps using arima if arimax demands a transfer function. The problem is that your model is daily, but your data has both daily and yearly seasonality, and I'm not sure right now if a first difference (the order=(*, 1, *)) will take care of that or not. (You certainly won't get magical year-round forecasts out of a model that only considers daily seasonality.)
P.S. What is the time that you use in your lm? Literal clock time or a 1-up observation number? I think you could get something by using a mixed-effect model (lmer in the lme4 package), though I haven't figured out whether doing that correctly accounts for the autocorrelation that will occur in a time series. If not accounted for, which anlm does not, you might get an interesting fit, but your concept of how precise your prediction is will be way too optimistic.
|
How to fit an ARIMAX-model with R?
I personally don't understand transfer functions, but I think you got the xtransf and xreg reversed. At least in R's base arima it is xreg that contains your exogenous variables. It's my impression th
|
7,194
|
When is logistic regression solved in closed form?
|
As kjetil b halvorsen pointed out, it is, in its own way, a miracle that linear regression admits an analytical solution. And this is so only by virtue of the linearity of the problem (with respect to the parameters). In OLS, you have
$$
\sum_i (y_i - x_i \beta)^2 \to \min_\beta,
$$
which has the first order conditions
$$
-2 \sum_i (y_i - x_i\beta) x_i = 0
$$
For a problem with $p$ variables (including constant, if needed— there are some regression through the origin problems, too), this is a system with $p$ equations and $p$ unknowns. Most importantly, it is a linear system, so you can find a solution using the standard linear algebra theory and practice. This system will have a solution with probability 1 unless you have perfectly collinear variables.
Now, with logistic regression, things aren't that easy anymore. Writing down the log-likelihood function,
$$
l(y;x,\beta) = \sum_i y_i \ln p_i + (1-y_i) \ln(1-p_i), \quad p_i = (1+\exp(-\theta_i))^{-1}, \quad \theta_i = x_i \beta,
$$
and taking its derivative to find the MLE, we get
$$
\frac{\partial l}{\partial \beta'}
= \sum_i \frac{{\rm d}p_i}{{\rm d}\theta}\Bigl( \frac{y_i}{p_i} - \frac{1-y_i}{1-p_i} \Bigr)x_i
= \sum_i \Bigl[y_i-\frac1{1+\exp(x_i\beta)}\Bigr]x_i
$$
The parameters $\beta$ enter this in a very nonlinear way: for each $i$, there's a nonlinear function, and they are added together. There is no analytical solution (except probably in a trivial situation with two observations, or something like that), and you have to use nonlinear optimization methods to find the estimates $\hat\beta$.
A somewhat deeper look into the problem (taking the second derivative) reveals that this is a convex optimization problem of finding a maximum of a concave function (a glorified multivariate parabola), so either one exists, and any reasonable algorithm should be finding it rather quickly, or things blow off to infinity. The latter does happen to logistic regression when ${\rm Prob}[Y_i=1|x_i\beta > c] = 1$ for some $c$, i.e., you have a perfect prediction. This is a rather unpleasant artifact: you would think that when you have a perfect prediction, the model works perfectly, but curiously enough, it is the other way round.
|
When is logistic regression solved in closed form?
|
As kjetil b halvorsen pointed out, it is, in its own way, a miracle that linear regression admits an analytical solution. And this is so only by virtue of the linearity of the problem (with respect to
|
When is logistic regression solved in closed form?
As kjetil b halvorsen pointed out, it is, in its own way, a miracle that linear regression admits an analytical solution. And this is so only by virtue of the linearity of the problem (with respect to the parameters). In OLS, you have
$$
\sum_i (y_i - x_i \beta)^2 \to \min_\beta,
$$
which has the first order conditions
$$
-2 \sum_i (y_i - x_i\beta) x_i = 0
$$
For a problem with $p$ variables (including constant, if needed— there are some regression through the origin problems, too), this is a system with $p$ equations and $p$ unknowns. Most importantly, it is a linear system, so you can find a solution using the standard linear algebra theory and practice. This system will have a solution with probability 1 unless you have perfectly collinear variables.
Now, with logistic regression, things aren't that easy anymore. Writing down the log-likelihood function,
$$
l(y;x,\beta) = \sum_i y_i \ln p_i + (1-y_i) \ln(1-p_i), \quad p_i = (1+\exp(-\theta_i))^{-1}, \quad \theta_i = x_i \beta,
$$
and taking its derivative to find the MLE, we get
$$
\frac{\partial l}{\partial \beta'}
= \sum_i \frac{{\rm d}p_i}{{\rm d}\theta}\Bigl( \frac{y_i}{p_i} - \frac{1-y_i}{1-p_i} \Bigr)x_i
= \sum_i \Bigl[y_i-\frac1{1+\exp(x_i\beta)}\Bigr]x_i
$$
The parameters $\beta$ enter this in a very nonlinear way: for each $i$, there's a nonlinear function, and they are added together. There is no analytical solution (except probably in a trivial situation with two observations, or something like that), and you have to use nonlinear optimization methods to find the estimates $\hat\beta$.
A somewhat deeper look into the problem (taking the second derivative) reveals that this is a convex optimization problem of finding a maximum of a concave function (a glorified multivariate parabola), so either one exists, and any reasonable algorithm should be finding it rather quickly, or things blow off to infinity. The latter does happen to logistic regression when ${\rm Prob}[Y_i=1|x_i\beta > c] = 1$ for some $c$, i.e., you have a perfect prediction. This is a rather unpleasant artifact: you would think that when you have a perfect prediction, the model works perfectly, but curiously enough, it is the other way round.
|
When is logistic regression solved in closed form?
As kjetil b halvorsen pointed out, it is, in its own way, a miracle that linear regression admits an analytical solution. And this is so only by virtue of the linearity of the problem (with respect to
|
7,195
|
When is logistic regression solved in closed form?
|
This post was originally intended as a long comment rather than a complete answer to the question at hand.
From the question, it's a little unclear if the interest lies only in the binary case or, perhaps, in more general cases where they may be continuous or take on other discrete values.
One example that doesn't quite answer the question, but is related, and which I like, deals with item-preference rankings obtained via paired comparisons. The Bradley–Terry model can be expressed as a logistic regression where
$$
\mathrm{logit}( \Pr(Y_{ij} = 1) ) = \alpha_i - \alpha_j ,
$$
and $\alpha_i$ is an "affinity", "popularity", or "strength" parameter of item $i$ with $Y_{ij} = 1$ indicating item $i$ was preferred over item $j$ in a paired comparison.
If a full round-robin of comparisons is performed (i.e., a pairwise preference is recorded for each unordered $(i,j)$ pair), then it turns out that the rank order of the MLEs $\hat{\alpha}_i$ correspond to the rank order of $S_i = \sum_{j \neq i} Y_{ij}$, the sum total of times each object was preferred over another.
To interpret this, imagine a full round-robin tournament in your favorite competitive sport. Then, this result says that the Bradley–Terry model ranks the players/teams according to their winning percentage. Whether this is an encouraging or disappointing result depends on your point of view, I suppose.
NB This rank-ordering result does not hold, in general, when a full round-robin is not played.
|
When is logistic regression solved in closed form?
|
This post was originally intended as a long comment rather than a complete answer to the question at hand.
From the question, it's a little unclear if the interest lies only in the binary case or, per
|
When is logistic regression solved in closed form?
This post was originally intended as a long comment rather than a complete answer to the question at hand.
From the question, it's a little unclear if the interest lies only in the binary case or, perhaps, in more general cases where they may be continuous or take on other discrete values.
One example that doesn't quite answer the question, but is related, and which I like, deals with item-preference rankings obtained via paired comparisons. The Bradley–Terry model can be expressed as a logistic regression where
$$
\mathrm{logit}( \Pr(Y_{ij} = 1) ) = \alpha_i - \alpha_j ,
$$
and $\alpha_i$ is an "affinity", "popularity", or "strength" parameter of item $i$ with $Y_{ij} = 1$ indicating item $i$ was preferred over item $j$ in a paired comparison.
If a full round-robin of comparisons is performed (i.e., a pairwise preference is recorded for each unordered $(i,j)$ pair), then it turns out that the rank order of the MLEs $\hat{\alpha}_i$ correspond to the rank order of $S_i = \sum_{j \neq i} Y_{ij}$, the sum total of times each object was preferred over another.
To interpret this, imagine a full round-robin tournament in your favorite competitive sport. Then, this result says that the Bradley–Terry model ranks the players/teams according to their winning percentage. Whether this is an encouraging or disappointing result depends on your point of view, I suppose.
NB This rank-ordering result does not hold, in general, when a full round-robin is not played.
|
When is logistic regression solved in closed form?
This post was originally intended as a long comment rather than a complete answer to the question at hand.
From the question, it's a little unclear if the interest lies only in the binary case or, per
|
7,196
|
Why is using squared error the standard when absolute error is more relevant to most problems? [duplicate]
|
The first 5 answers fail to distinguish between estimation loss1 and prediction loss2, something that is crucial in answering the question. A priori, there is no reason that the two should coincide. I will discuss both types of loss in the context of point prediction using linear regression. The discussion can be extended to models other than linear regression and tasks other than point prediction, but the essence remains the same.
Setup
Suppose you are facing a prediction problem where the model is
$$
y=X\beta+\varepsilon
$$
with $\varepsilon\sim D(0,\sigma)$, $D$ being some probability distribution with location $0$ and scale $\sigma$. You aim to predict $y_0$ given $x_0$, and your point prediction will be $\hat y_0$, a function of $x_0$, the data sample, the model and the penalty (the negative of reward) function defined on the prediction error. The penalty function you are facing is $L_P(y-\hat y)$. It has a minimum at zero (the value $L_P(0)$ can be set to zero without loss of generality) and is nondecreasing to both sides of zero; this is a typical characterization of a sensible prediction loss function. You can freely choose an estimation loss function $L_E(\cdot)$ and a point prediction function $y_hat_0$. What are your optimal choices for each? This will depend on the error distribution $D$ and the prediction loss function $L_P(\cdot)$.
Estimation loss
Estimation loss specifies how parameter estimates of a model are obtained from sample data. In our example of linear regression, it concern the estimation of $\beta$ and $\sigma$. You can estimate them by minimizing the sum of squared residuals (OLS) between the actual $y$ and the corresponding fitted values, sum of absolute residuals (quantile regression at the median) or another function. The choice of the estimation loss can be determined by the distribution of model errors. The most accurate estimator in some technical sense* will be achieved by the estimation loss that makes the parameter estimator the maximum likelihood (ML) estimator. If the model errors are distributed normally ($D$ is normal), this will be OLS; if they are distributed according to a Laplace distribution ($D$ is Laplace), this will be quantile regression at the mean; etc.
*To simplify, given a ML estimator, you may expect more accurate parameter estimates from your model than provided by alternative estimators.
Prediction loss
Prediction loss specifies how prediction errors are penalized. You do not choose it, it is given. (Usually, it is the client that specifies it. If the client is not capable of doing that mathematically, the analyst should strive to do that by listening carefully to the client's arguments.) If the prediction error causes the client's loss (e.g. financial loss) to grow quadratically and symmetrically about zero, you are facing square prediction loss. If the client's loss grows linearly and symmetrically about zero, you are facing absolute prediction loss. There are plenty of other possibilities for types of prediction loss you may be facing, too.
Prediction
Given the parameter estimates of the model and the values of the regressors of the point of interest, $x_0$, you should choose the point prediction $\hat y_0$ based on the prediction loss. For square loss, you will choose the estimated mean of $y_0$, as the true mean minimizes square loss on average (where the average is taken across random samples of $y_0$ subject to $x=x_0$). For absolute loss, you will choose the estimated median. For other loss function, you will choose other features of the distribution of $y_0$ that you have modelled.
Back to your question
Why do people frequently choose square error rather than absolute error, or correspondingly square loss rather than absolute loss, as estimation loss? Because normal errors ($D$ being normal) are common in applications, arguably more so than Laplace errors ($D$ being Laplace). They also make the regression estimators analytically tractable. They are not much easier to compute, however. Computational complexity of OLS (corresponding to ML estimation under normal errors) vs. quantile regression at the median (corresponding to ML estimation under Laplace errors) are not vastly different. Thus there are some sound arguments for the choice of OLS over quantile regression at the median, or square error over absolute error.
Why do people choose square error, or correspondingly square loss, as prediction loss? Perhaps for simplicity. As some of the previous answers might have mentioned, you have to choose some baseline for a textbook exposition; you cannot discuss all possible cases in detail. However, the case for preferring square loss over absolute loss as prediction loss is less convincing than in the case of estimation loss. Actual prediction loss is likely to be asymmetric (as discussed in some previous answers) and not more likely to grow quadratically than linearly with prediction error. Of course, in practice you should follow the client's specification of prediction loss. Meanwhile, in casual examples and discussions where there is no concrete client around, I do not see a strong argument for preferring square error over absolute error.
1 Also known as estimation cost, fitting loss, fitting cost, training loss, training cost.
2 Also known as prediction cost, evaluation loss, evaluation cost.
|
Why is using squared error the standard when absolute error is more relevant to most problems? [dupl
|
The first 5 answers fail to distinguish between estimation loss1 and prediction loss2, something that is crucial in answering the question. A priori, there is no reason that the two should coincide. I
|
Why is using squared error the standard when absolute error is more relevant to most problems? [duplicate]
The first 5 answers fail to distinguish between estimation loss1 and prediction loss2, something that is crucial in answering the question. A priori, there is no reason that the two should coincide. I will discuss both types of loss in the context of point prediction using linear regression. The discussion can be extended to models other than linear regression and tasks other than point prediction, but the essence remains the same.
Setup
Suppose you are facing a prediction problem where the model is
$$
y=X\beta+\varepsilon
$$
with $\varepsilon\sim D(0,\sigma)$, $D$ being some probability distribution with location $0$ and scale $\sigma$. You aim to predict $y_0$ given $x_0$, and your point prediction will be $\hat y_0$, a function of $x_0$, the data sample, the model and the penalty (the negative of reward) function defined on the prediction error. The penalty function you are facing is $L_P(y-\hat y)$. It has a minimum at zero (the value $L_P(0)$ can be set to zero without loss of generality) and is nondecreasing to both sides of zero; this is a typical characterization of a sensible prediction loss function. You can freely choose an estimation loss function $L_E(\cdot)$ and a point prediction function $y_hat_0$. What are your optimal choices for each? This will depend on the error distribution $D$ and the prediction loss function $L_P(\cdot)$.
Estimation loss
Estimation loss specifies how parameter estimates of a model are obtained from sample data. In our example of linear regression, it concern the estimation of $\beta$ and $\sigma$. You can estimate them by minimizing the sum of squared residuals (OLS) between the actual $y$ and the corresponding fitted values, sum of absolute residuals (quantile regression at the median) or another function. The choice of the estimation loss can be determined by the distribution of model errors. The most accurate estimator in some technical sense* will be achieved by the estimation loss that makes the parameter estimator the maximum likelihood (ML) estimator. If the model errors are distributed normally ($D$ is normal), this will be OLS; if they are distributed according to a Laplace distribution ($D$ is Laplace), this will be quantile regression at the mean; etc.
*To simplify, given a ML estimator, you may expect more accurate parameter estimates from your model than provided by alternative estimators.
Prediction loss
Prediction loss specifies how prediction errors are penalized. You do not choose it, it is given. (Usually, it is the client that specifies it. If the client is not capable of doing that mathematically, the analyst should strive to do that by listening carefully to the client's arguments.) If the prediction error causes the client's loss (e.g. financial loss) to grow quadratically and symmetrically about zero, you are facing square prediction loss. If the client's loss grows linearly and symmetrically about zero, you are facing absolute prediction loss. There are plenty of other possibilities for types of prediction loss you may be facing, too.
Prediction
Given the parameter estimates of the model and the values of the regressors of the point of interest, $x_0$, you should choose the point prediction $\hat y_0$ based on the prediction loss. For square loss, you will choose the estimated mean of $y_0$, as the true mean minimizes square loss on average (where the average is taken across random samples of $y_0$ subject to $x=x_0$). For absolute loss, you will choose the estimated median. For other loss function, you will choose other features of the distribution of $y_0$ that you have modelled.
Back to your question
Why do people frequently choose square error rather than absolute error, or correspondingly square loss rather than absolute loss, as estimation loss? Because normal errors ($D$ being normal) are common in applications, arguably more so than Laplace errors ($D$ being Laplace). They also make the regression estimators analytically tractable. They are not much easier to compute, however. Computational complexity of OLS (corresponding to ML estimation under normal errors) vs. quantile regression at the median (corresponding to ML estimation under Laplace errors) are not vastly different. Thus there are some sound arguments for the choice of OLS over quantile regression at the median, or square error over absolute error.
Why do people choose square error, or correspondingly square loss, as prediction loss? Perhaps for simplicity. As some of the previous answers might have mentioned, you have to choose some baseline for a textbook exposition; you cannot discuss all possible cases in detail. However, the case for preferring square loss over absolute loss as prediction loss is less convincing than in the case of estimation loss. Actual prediction loss is likely to be asymmetric (as discussed in some previous answers) and not more likely to grow quadratically than linearly with prediction error. Of course, in practice you should follow the client's specification of prediction loss. Meanwhile, in casual examples and discussions where there is no concrete client around, I do not see a strong argument for preferring square error over absolute error.
1 Also known as estimation cost, fitting loss, fitting cost, training loss, training cost.
2 Also known as prediction cost, evaluation loss, evaluation cost.
|
Why is using squared error the standard when absolute error is more relevant to most problems? [dupl
The first 5 answers fail to distinguish between estimation loss1 and prediction loss2, something that is crucial in answering the question. A priori, there is no reason that the two should coincide. I
|
7,197
|
Why is using squared error the standard when absolute error is more relevant to most problems? [duplicate]
|
TLDR; when nothing is known about actual cost of error to the user of the model, MSE is a better default option compared to MAE because, in my opinion, it is easier to manipulate analytically and is more likely to match the actual cost of error.
It's a great question. I like that you start with desire to make your loss function match actual costs. This is how it's supposed to be done ideally in my opinion. However, it is impractical to derive the cost function from actual costs every time you build a model, so we tend to gravitate to using one of the loss functions available in software. Least squares is one of the most popular functions mainly due to mathematical convenience. It is easier to deal with it analytically. Also, in some cases least squares produces unbiased point forecast, that is $E[y]-\hat y=0$, which is often considered desirable for sentimental reasons.
Having said this, I must argue that it is not obvious to me that absolute value loss is more realistic. Consider, drug overdoses - they are much costlier than underdoses in some situations: not getting high enough vs dying.
Within your parts example, consider this: what if you underestimated the cost of parts to be \$1, and entered into a forward agreement to deliver one million parts one month later at \$1.1 knowing that you will have $1M one month from today. You are going to make 10% profit!
Then comes the day and parts are actually $1.2 a piece. So, you are not only going to incur loss of \$100K, but will also lack funds to deliver 1M parts. So, you are forced to default and go into bankruptcy which is very expensive. On the other hand if you overestimated the cost of parts, then you wold forego some profit but wouldn't end up in dire situation of insolvency or liquidity crisis.
This is a very common situation in business where the losses are asymmetric and highly nonlinear with rapidly escalating costs in one direction of forecast error but not the other.
Hence, I'd argue that absolute loss, which is symmetric and has linear losses on forecasting error, is not realistic in most business situations. Also, although symmetric, the squared loss is at least non linear.
Yet the differences between absolute and squared loss functions don't end here. For instance, it can be shown that the optimal point forecast in absolute loss is the median while for the squared loss it is mean.
I think that the following loss function is more suitable to business forecasting in many cases where over forecasting error $e=y-\hat y$ can become very costly very quickly: $$\mathcal L(e,\hat y)=|\ln\left(1+\frac e {\hat y}\right)|$$
Here, if you are forecasting a non negative quantity $y$, then over forecasting is potentially devastating. Imagine you are bank forecasting the deposit volume, and the actual deposit volume turned out to be much lower than you hoped for. This can have severe consequences. This type of asymmetric loss function will lead to a biased optimal point forecast, i.e. $E[y]-\hat y\ne 0$, but that's exactly what you want: you want to err on the side of under forecasting in this kind of business problem.
|
Why is using squared error the standard when absolute error is more relevant to most problems? [dupl
|
TLDR; when nothing is known about actual cost of error to the user of the model, MSE is a better default option compared to MAE because, in my opinion, it is easier to manipulate analytically and is m
|
Why is using squared error the standard when absolute error is more relevant to most problems? [duplicate]
TLDR; when nothing is known about actual cost of error to the user of the model, MSE is a better default option compared to MAE because, in my opinion, it is easier to manipulate analytically and is more likely to match the actual cost of error.
It's a great question. I like that you start with desire to make your loss function match actual costs. This is how it's supposed to be done ideally in my opinion. However, it is impractical to derive the cost function from actual costs every time you build a model, so we tend to gravitate to using one of the loss functions available in software. Least squares is one of the most popular functions mainly due to mathematical convenience. It is easier to deal with it analytically. Also, in some cases least squares produces unbiased point forecast, that is $E[y]-\hat y=0$, which is often considered desirable for sentimental reasons.
Having said this, I must argue that it is not obvious to me that absolute value loss is more realistic. Consider, drug overdoses - they are much costlier than underdoses in some situations: not getting high enough vs dying.
Within your parts example, consider this: what if you underestimated the cost of parts to be \$1, and entered into a forward agreement to deliver one million parts one month later at \$1.1 knowing that you will have $1M one month from today. You are going to make 10% profit!
Then comes the day and parts are actually $1.2 a piece. So, you are not only going to incur loss of \$100K, but will also lack funds to deliver 1M parts. So, you are forced to default and go into bankruptcy which is very expensive. On the other hand if you overestimated the cost of parts, then you wold forego some profit but wouldn't end up in dire situation of insolvency or liquidity crisis.
This is a very common situation in business where the losses are asymmetric and highly nonlinear with rapidly escalating costs in one direction of forecast error but not the other.
Hence, I'd argue that absolute loss, which is symmetric and has linear losses on forecasting error, is not realistic in most business situations. Also, although symmetric, the squared loss is at least non linear.
Yet the differences between absolute and squared loss functions don't end here. For instance, it can be shown that the optimal point forecast in absolute loss is the median while for the squared loss it is mean.
I think that the following loss function is more suitable to business forecasting in many cases where over forecasting error $e=y-\hat y$ can become very costly very quickly: $$\mathcal L(e,\hat y)=|\ln\left(1+\frac e {\hat y}\right)|$$
Here, if you are forecasting a non negative quantity $y$, then over forecasting is potentially devastating. Imagine you are bank forecasting the deposit volume, and the actual deposit volume turned out to be much lower than you hoped for. This can have severe consequences. This type of asymmetric loss function will lead to a biased optimal point forecast, i.e. $E[y]-\hat y\ne 0$, but that's exactly what you want: you want to err on the side of under forecasting in this kind of business problem.
|
Why is using squared error the standard when absolute error is more relevant to most problems? [dupl
TLDR; when nothing is known about actual cost of error to the user of the model, MSE is a better default option compared to MAE because, in my opinion, it is easier to manipulate analytically and is m
|
7,198
|
Why is using squared error the standard when absolute error is more relevant to most problems? [duplicate]
|
I think the reason is more sociological that statistical.
Short version: We do it this way because we always have.
Longer version:
Historically, we could not do many of the things we now take for granted. Many things are computer intensive and Ronald Fisher was born before Alan Turing.
So, people did OLS regression - a lot. And people read those regressions in all sorts of substantive fields and statistics courses in those fields taught ANOVA/regression and not more modern methods.
Additionally, editors of journals learned those methods and not others, and many will reject articles with modern methods because e.g. "they won't be understood".
Many practitioners reject modern methods too; I used to be a sort of data analysis geek at a hospital. Doctors would come to ask my advice and, if it wasn't "do OLS regression" or "do logistic regression" they would reject my advice.
I got my PhD in psychometrics and many of my professors in other branches of psychology did not know any modern methods (one said: "just report the p value, that's what matters").
|
Why is using squared error the standard when absolute error is more relevant to most problems? [dupl
|
I think the reason is more sociological that statistical.
Short version: We do it this way because we always have.
Longer version:
Historically, we could not do many of the things we now take for gran
|
Why is using squared error the standard when absolute error is more relevant to most problems? [duplicate]
I think the reason is more sociological that statistical.
Short version: We do it this way because we always have.
Longer version:
Historically, we could not do many of the things we now take for granted. Many things are computer intensive and Ronald Fisher was born before Alan Turing.
So, people did OLS regression - a lot. And people read those regressions in all sorts of substantive fields and statistics courses in those fields taught ANOVA/regression and not more modern methods.
Additionally, editors of journals learned those methods and not others, and many will reject articles with modern methods because e.g. "they won't be understood".
Many practitioners reject modern methods too; I used to be a sort of data analysis geek at a hospital. Doctors would come to ask my advice and, if it wasn't "do OLS regression" or "do logistic regression" they would reject my advice.
I got my PhD in psychometrics and many of my professors in other branches of psychology did not know any modern methods (one said: "just report the p value, that's what matters").
|
Why is using squared error the standard when absolute error is more relevant to most problems? [dupl
I think the reason is more sociological that statistical.
Short version: We do it this way because we always have.
Longer version:
Historically, we could not do many of the things we now take for gran
|
7,199
|
Why is using squared error the standard when absolute error is more relevant to most problems? [duplicate]
|
I think it's worth taking a step back and considering what the two losses imply.
Looking at it from a probabilistic point of view, the loss function is equivalent to the assumed log-likelihood function and thus should correspond to how we think our measurements are distributed around their unknown 'true' values.
As you say, in the case of OLS this is equivalent to assuming a Gaussian likelihood, where as an absolute error loss function is equivalent to a Laplacian likelihood. Gaussian likelihoods are far far more often a good match to real life as a consequence of the central limit theorem.
Our predictions are in general improved by making our assumed (and implicitly generative) model as close a match to reality as possible. In many (most?) cases this will improve the predictive accuracy by any sensible metric (including e.g. mean absolute error). It is far more often the case assuming a Gaussian likelihood will achieve this.
|
Why is using squared error the standard when absolute error is more relevant to most problems? [dupl
|
I think it's worth taking a step back and considering what the two losses imply.
Looking at it from a probabilistic point of view, the loss function is equivalent to the assumed log-likelihood functio
|
Why is using squared error the standard when absolute error is more relevant to most problems? [duplicate]
I think it's worth taking a step back and considering what the two losses imply.
Looking at it from a probabilistic point of view, the loss function is equivalent to the assumed log-likelihood function and thus should correspond to how we think our measurements are distributed around their unknown 'true' values.
As you say, in the case of OLS this is equivalent to assuming a Gaussian likelihood, where as an absolute error loss function is equivalent to a Laplacian likelihood. Gaussian likelihoods are far far more often a good match to real life as a consequence of the central limit theorem.
Our predictions are in general improved by making our assumed (and implicitly generative) model as close a match to reality as possible. In many (most?) cases this will improve the predictive accuracy by any sensible metric (including e.g. mean absolute error). It is far more often the case assuming a Gaussian likelihood will achieve this.
|
Why is using squared error the standard when absolute error is more relevant to most problems? [dupl
I think it's worth taking a step back and considering what the two losses imply.
Looking at it from a probabilistic point of view, the loss function is equivalent to the assumed log-likelihood functio
|
7,200
|
Why is using squared error the standard when absolute error is more relevant to most problems? [duplicate]
|
If errors are independent and follow the normal distribution (of any variance but consistent), then the sum of squared errors corresponds to their joint probability/likelihood.
$\Pi e^{-x_i^2}=e^{-\Sigma x_i^2}$
So under those conditions minimizing the sum of square errors is the same as maximizing the likelihood.
If a cost-minimizing prediction is needed (where the cost metric is different from MSE) the general/accurate approach would be to explicitly minimize the expected cost over the entire distribution of models weighted by their likelihoods (or probabilies if you have prior knowledge). This completely decouples the problem of minimizing expected cost from the problem of estimation in the presence of noise.
Suppose you are measuring a constant quantity in the presence of Gaussian noise. Even if your cost metric for future outcomes is MAE, you would rather predict with the mean (minimizing past MSE) than the median (minimizing past MAE), if indeed you know the quantity is constant and the measurement noise is Gaussian.
Example
Consider the following spread of hits produced by a gun that was mechanically fixed in place. You place a circle of a given size somewhere on the target. If the next shot lands entirely inside your circle, you win, else you lose. The cost function is of the form $f_C(x,y)=sign((x-x_C)^2+(y-y_C)^2-R^2)$.
If you minimize $\sum_i f_C(x_i,y_i)$, you would place the circle in the blue position, containing entirely the maximum number of past shots.
But if you knew that the gun is fixed in place and the error is Gaussian, you would place the circle in the green position, centered on the data's mean/centroid (minimizing MSE), as you are optimizing future expected payoff, not average past payoff.
|
Why is using squared error the standard when absolute error is more relevant to most problems? [dupl
|
If errors are independent and follow the normal distribution (of any variance but consistent), then the sum of squared errors corresponds to their joint probability/likelihood.
$\Pi e^{-x_i^2}=e^{-\Si
|
Why is using squared error the standard when absolute error is more relevant to most problems? [duplicate]
If errors are independent and follow the normal distribution (of any variance but consistent), then the sum of squared errors corresponds to their joint probability/likelihood.
$\Pi e^{-x_i^2}=e^{-\Sigma x_i^2}$
So under those conditions minimizing the sum of square errors is the same as maximizing the likelihood.
If a cost-minimizing prediction is needed (where the cost metric is different from MSE) the general/accurate approach would be to explicitly minimize the expected cost over the entire distribution of models weighted by their likelihoods (or probabilies if you have prior knowledge). This completely decouples the problem of minimizing expected cost from the problem of estimation in the presence of noise.
Suppose you are measuring a constant quantity in the presence of Gaussian noise. Even if your cost metric for future outcomes is MAE, you would rather predict with the mean (minimizing past MSE) than the median (minimizing past MAE), if indeed you know the quantity is constant and the measurement noise is Gaussian.
Example
Consider the following spread of hits produced by a gun that was mechanically fixed in place. You place a circle of a given size somewhere on the target. If the next shot lands entirely inside your circle, you win, else you lose. The cost function is of the form $f_C(x,y)=sign((x-x_C)^2+(y-y_C)^2-R^2)$.
If you minimize $\sum_i f_C(x_i,y_i)$, you would place the circle in the blue position, containing entirely the maximum number of past shots.
But if you knew that the gun is fixed in place and the error is Gaussian, you would place the circle in the green position, centered on the data's mean/centroid (minimizing MSE), as you are optimizing future expected payoff, not average past payoff.
|
Why is using squared error the standard when absolute error is more relevant to most problems? [dupl
If errors are independent and follow the normal distribution (of any variance but consistent), then the sum of squared errors corresponds to their joint probability/likelihood.
$\Pi e^{-x_i^2}=e^{-\Si
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.