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 |
|---|---|---|---|---|---|---|
20,901 | How can I find the standard deviation of the sample standard deviation from a normal distribution? | It sounds like you're asking for a calculation of the standard deviation of the sample standard deviation. That is, you're asking for ${\rm SD}(s) = \sqrt{ {\rm var}(s) }$, where
$$ s = \sqrt{ \frac{1}{n-1} \sum_{i=1}^{n} (X_i - \overline{X}) }, $$
$X_1, ..., X_n \sim N(\mu, \sigma^2)$ and $\overline{X}$ is the sample mean.
First, we know from the basic properties of variance that
$$ {\rm var}(s) = E(s^2) - E(s)^2 $$
Since the sample variance is unbiased, we know $E(s^2) = \sigma^2$. In Why is sample standard deviation a biased estimator of $\sigma$?, $E(s)$ is calculated, from which we can infer
$$ E(s)^2
= \frac{2 \sigma^2 }{n-1} \cdot \left( \frac{ \Gamma(n/2) }{ \Gamma( \frac{n-1}{2} ) } \right)^2 $$
therefore
$$ {\rm SD}(s) = \sqrt{ E(s^2) - E(s)^2 } = \sigma \sqrt{ 1 - \frac{2}{n-1} \cdot \left( \frac{ \Gamma(n/2) }{ \Gamma( \frac{n-1}{2} ) } \right)^2 } $$ | How can I find the standard deviation of the sample standard deviation from a normal distribution? | It sounds like you're asking for a calculation of the standard deviation of the sample standard deviation. That is, you're asking for ${\rm SD}(s) = \sqrt{ {\rm var}(s) }$, where
$$ s = \sqrt{ \frac{ | How can I find the standard deviation of the sample standard deviation from a normal distribution?
It sounds like you're asking for a calculation of the standard deviation of the sample standard deviation. That is, you're asking for ${\rm SD}(s) = \sqrt{ {\rm var}(s) }$, where
$$ s = \sqrt{ \frac{1}{n-1} \sum_{i=1}^{n} (X_i - \overline{X}) }, $$
$X_1, ..., X_n \sim N(\mu, \sigma^2)$ and $\overline{X}$ is the sample mean.
First, we know from the basic properties of variance that
$$ {\rm var}(s) = E(s^2) - E(s)^2 $$
Since the sample variance is unbiased, we know $E(s^2) = \sigma^2$. In Why is sample standard deviation a biased estimator of $\sigma$?, $E(s)$ is calculated, from which we can infer
$$ E(s)^2
= \frac{2 \sigma^2 }{n-1} \cdot \left( \frac{ \Gamma(n/2) }{ \Gamma( \frac{n-1}{2} ) } \right)^2 $$
therefore
$$ {\rm SD}(s) = \sqrt{ E(s^2) - E(s)^2 } = \sigma \sqrt{ 1 - \frac{2}{n-1} \cdot \left( \frac{ \Gamma(n/2) }{ \Gamma( \frac{n-1}{2} ) } \right)^2 } $$ | How can I find the standard deviation of the sample standard deviation from a normal distribution?
It sounds like you're asking for a calculation of the standard deviation of the sample standard deviation. That is, you're asking for ${\rm SD}(s) = \sqrt{ {\rm var}(s) }$, where
$$ s = \sqrt{ \frac{ |
20,902 | How can I find the standard deviation of the sample standard deviation from a normal distribution? | The quantity $X=(n-1) s^2/\sigma^2$ has a chi-squared distribution with $n-1$ degrees of freedom when the samples are independent and distributed with the same normal distribution This quantity can be used to get confidence intervals for the variance of the normal and its standard deviation. If you have the raw values and not just the central value of the bins you can calculate $s^2$.
It is known that if $X$ has a chi-squared distribution with $n-1$ degrees of freedom its variance is $2(n-1)$. Knowing this and the fact the $\mathrm{Var}(cX) = c^2 \mathrm{Var}(X)$ we get that $s^2$ has a variance equal to $$\frac{2(n-1)\sigma^4}{(n-1)^2} =\frac{2\sigma^4}{n-1} \>.$$ Although $\sigma^4$ is unknown you can approximate it by $s^4$ and you have a rough idea of what the variance of $s^2$ is. | How can I find the standard deviation of the sample standard deviation from a normal distribution? | The quantity $X=(n-1) s^2/\sigma^2$ has a chi-squared distribution with $n-1$ degrees of freedom when the samples are independent and distributed with the same normal distribution This quantity can be | How can I find the standard deviation of the sample standard deviation from a normal distribution?
The quantity $X=(n-1) s^2/\sigma^2$ has a chi-squared distribution with $n-1$ degrees of freedom when the samples are independent and distributed with the same normal distribution This quantity can be used to get confidence intervals for the variance of the normal and its standard deviation. If you have the raw values and not just the central value of the bins you can calculate $s^2$.
It is known that if $X$ has a chi-squared distribution with $n-1$ degrees of freedom its variance is $2(n-1)$. Knowing this and the fact the $\mathrm{Var}(cX) = c^2 \mathrm{Var}(X)$ we get that $s^2$ has a variance equal to $$\frac{2(n-1)\sigma^4}{(n-1)^2} =\frac{2\sigma^4}{n-1} \>.$$ Although $\sigma^4$ is unknown you can approximate it by $s^4$ and you have a rough idea of what the variance of $s^2$ is. | How can I find the standard deviation of the sample standard deviation from a normal distribution?
The quantity $X=(n-1) s^2/\sigma^2$ has a chi-squared distribution with $n-1$ degrees of freedom when the samples are independent and distributed with the same normal distribution This quantity can be |
20,903 | How can I find the standard deviation of the sample standard deviation from a normal distribution? | There are several ways of quantifying the error of the standard deviation in the normal case. I am going to present the profile likelihood of $\sigma$ which can be used for approximating confidence intervals.
Let $x=(x_1,...,x_n)$ be a sample from a Normal$(\mu,\sigma)$. The corresponding likelihood function is given by
$${\mathcal L}(\mu,\sigma) \propto \dfrac{1}{\sigma^n}\exp\left(-\dfrac{1}{2\sigma^2}\sum_{j=1}^n(x_j-\mu)^2\right)$$
Then, the Maximum Likelihood Estimators are given by $(\hat\mu,\hat\sigma)=(\bar x,s)$, where $s=\sqrt{\dfrac{1}{n}\sum_{j=1}^n(x_j-\bar x)^2}$. Given that you are interested on quantifying the error on $\sigma$, you can then calculate the normalised profile likelihood of this parameter as follows.
$$R_p(\sigma)=\dfrac{\sup_{\mu}{\mathcal L}(\mu,\sigma)}{{\mathcal L}(\hat\mu,\hat\sigma)} = \left(\dfrac{\hat\sigma}{\sigma}\right)^n\exp\left[\dfrac{n}{2}\left(1-\left(\dfrac{\hat\sigma}{\sigma}\right)^2\right)\right]$$
Note that $R_p:{\mathbb R}_+\rightarrow (0,1]$. An interval of level $0.147$ has an approximate confidence of $0.95$. Next I attach an $R$ code that can be used for calculating these intervals. You can modify it accordingly in your context (or if you post the data I can include these changes).
data = rnorm(30)
n = length(data)
sg = sqrt(mean((data-mean(data))^2))
# Profile likelihood
rp = function(sigma) return( (sg/sigma)^n*exp(0.5*n*(1-(sg/sigma)^2)) )
vec = rvec = seq(0.5,1.5,0.01)
for(i in 1:length(rvec)) rvec[i] = rp(vec[i])
plot(vec,rvec,type="l")
rpc = function(sigma) return(rp(sigma)-0.147)
# Approximate 95% confidence interval
c(uniroot(rpc,c(0.7,0.8))$root,uniroot(rpc,c(1.1,1.3))$root)
An advantage of this sort of intervals is that they are invariant under transformations. In this case if you calculate an interval for $\sigma$, $I=(L,U)$, then the corresponding interval for $\sigma^2$ is simply $I^{\prime}=(L^2,U^2)$. | How can I find the standard deviation of the sample standard deviation from a normal distribution? | There are several ways of quantifying the error of the standard deviation in the normal case. I am going to present the profile likelihood of $\sigma$ which can be used for approximating confidence in | How can I find the standard deviation of the sample standard deviation from a normal distribution?
There are several ways of quantifying the error of the standard deviation in the normal case. I am going to present the profile likelihood of $\sigma$ which can be used for approximating confidence intervals.
Let $x=(x_1,...,x_n)$ be a sample from a Normal$(\mu,\sigma)$. The corresponding likelihood function is given by
$${\mathcal L}(\mu,\sigma) \propto \dfrac{1}{\sigma^n}\exp\left(-\dfrac{1}{2\sigma^2}\sum_{j=1}^n(x_j-\mu)^2\right)$$
Then, the Maximum Likelihood Estimators are given by $(\hat\mu,\hat\sigma)=(\bar x,s)$, where $s=\sqrt{\dfrac{1}{n}\sum_{j=1}^n(x_j-\bar x)^2}$. Given that you are interested on quantifying the error on $\sigma$, you can then calculate the normalised profile likelihood of this parameter as follows.
$$R_p(\sigma)=\dfrac{\sup_{\mu}{\mathcal L}(\mu,\sigma)}{{\mathcal L}(\hat\mu,\hat\sigma)} = \left(\dfrac{\hat\sigma}{\sigma}\right)^n\exp\left[\dfrac{n}{2}\left(1-\left(\dfrac{\hat\sigma}{\sigma}\right)^2\right)\right]$$
Note that $R_p:{\mathbb R}_+\rightarrow (0,1]$. An interval of level $0.147$ has an approximate confidence of $0.95$. Next I attach an $R$ code that can be used for calculating these intervals. You can modify it accordingly in your context (or if you post the data I can include these changes).
data = rnorm(30)
n = length(data)
sg = sqrt(mean((data-mean(data))^2))
# Profile likelihood
rp = function(sigma) return( (sg/sigma)^n*exp(0.5*n*(1-(sg/sigma)^2)) )
vec = rvec = seq(0.5,1.5,0.01)
for(i in 1:length(rvec)) rvec[i] = rp(vec[i])
plot(vec,rvec,type="l")
rpc = function(sigma) return(rp(sigma)-0.147)
# Approximate 95% confidence interval
c(uniroot(rpc,c(0.7,0.8))$root,uniroot(rpc,c(1.1,1.3))$root)
An advantage of this sort of intervals is that they are invariant under transformations. In this case if you calculate an interval for $\sigma$, $I=(L,U)$, then the corresponding interval for $\sigma^2$ is simply $I^{\prime}=(L^2,U^2)$. | How can I find the standard deviation of the sample standard deviation from a normal distribution?
There are several ways of quantifying the error of the standard deviation in the normal case. I am going to present the profile likelihood of $\sigma$ which can be used for approximating confidence in |
20,904 | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables? | A few thoughts:
The old canard about correlation not being causation is only half the story. Correlation may not be causation, but some form of association between the two variables is a necessary step along the path to showing causation, and correlation can help show that.
It helps point out trends. Show it to a business owner, and they may say "Yeah, that makes sense, you see Widget X and Widget Y both end up being used by a particular group of people, even though they're not really related. Or they might say "that's...odd", at which point you prompted further investigation.
Look at it this way. Correlation is a tool. A hammer, by itself, isn't all that useful. It certainly won't build a house all by itself. But have you ever tried to build a house without a hammer? | If correlation doesn't imply causality then what's the value of knowing the correlation between two | A few thoughts:
The old canard about correlation not being causation is only half the story. Correlation may not be causation, but some form of association between the two variables is a necessary st | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables?
A few thoughts:
The old canard about correlation not being causation is only half the story. Correlation may not be causation, but some form of association between the two variables is a necessary step along the path to showing causation, and correlation can help show that.
It helps point out trends. Show it to a business owner, and they may say "Yeah, that makes sense, you see Widget X and Widget Y both end up being used by a particular group of people, even though they're not really related. Or they might say "that's...odd", at which point you prompted further investigation.
Look at it this way. Correlation is a tool. A hammer, by itself, isn't all that useful. It certainly won't build a house all by itself. But have you ever tried to build a house without a hammer? | If correlation doesn't imply causality then what's the value of knowing the correlation between two
A few thoughts:
The old canard about correlation not being causation is only half the story. Correlation may not be causation, but some form of association between the two variables is a necessary st |
20,905 | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables? | Look at it from a gambling perspective. Let's say we know that on average people who wear workboots to work will have 1.5 injuries on the job, and people wear loafers will have .05 injuries on average. Or, maybe the chances of an injury for a person wearing workboots is .85, and the chances of injury to a person wearing loafers is .1.
If I randomly select a person from the population, and tell you the person is wearing workboots, and offer you an even money bet on whether or not they had a workplace injury last year, would you take the bet? Well, you'd take the bet if you were to be able to bet on the side that they had an injury.. 85% of the time you'll win, and you're getting even money.
The point is, knowing that piece of information gives us information about whether or not they are likely to experience an injury at work.. The shoes have nothing to do with it, in fact, the workboots prevent injury.. But the confounding variable here is the type of job that goes along with the workboots.. And maybe other things like the person possibly being more reckless. | If correlation doesn't imply causality then what's the value of knowing the correlation between two | Look at it from a gambling perspective. Let's say we know that on average people who wear workboots to work will have 1.5 injuries on the job, and people wear loafers will have .05 injuries on averag | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables?
Look at it from a gambling perspective. Let's say we know that on average people who wear workboots to work will have 1.5 injuries on the job, and people wear loafers will have .05 injuries on average. Or, maybe the chances of an injury for a person wearing workboots is .85, and the chances of injury to a person wearing loafers is .1.
If I randomly select a person from the population, and tell you the person is wearing workboots, and offer you an even money bet on whether or not they had a workplace injury last year, would you take the bet? Well, you'd take the bet if you were to be able to bet on the side that they had an injury.. 85% of the time you'll win, and you're getting even money.
The point is, knowing that piece of information gives us information about whether or not they are likely to experience an injury at work.. The shoes have nothing to do with it, in fact, the workboots prevent injury.. But the confounding variable here is the type of job that goes along with the workboots.. And maybe other things like the person possibly being more reckless. | If correlation doesn't imply causality then what's the value of knowing the correlation between two
Look at it from a gambling perspective. Let's say we know that on average people who wear workboots to work will have 1.5 injuries on the job, and people wear loafers will have .05 injuries on averag |
20,906 | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables? | The phrase "correlation doesn't imply causation" gets overplayed. (As Cohen wrote, "it's an awfully big hint".) We beat this phrase into students because of a bias intrinsic to the human mind. When you hear 'the crime rate is correlated with the poverty rate', or something like that, you cannot help but think this means that poverty causes the crime. It is natural for people to assume this, because that's the way the mind works. We use the phrase over and over in the hopes of counteracting that. However, once you've absorbed the idea, the phrase loses most of it's value, and it's time to move on to a more sophisticated understanding.
When there is a correlation between two variables, there are two possibilities: it's all a coincidence, or there's some causal pattern at work. Calling a pattern in the world a coincidence is a terrible explanatory framework and should probably be your last resort. That leaves causality. The problem is that we don't know the nature of that causal pattern. It could well be that poverty causes crime, but it could also be that crime causes poverty (e.g., people don't want to live in a high-crime area, so they move out and property values fall, etc.). It could also be that there is some third variable or group of variables that cause both crime and poverty, but that there is, in fact, no direct causal link between crime and poverty (known as the 'common cause' model). This is especially pernicious, because, in a statistical model, all other sources of variation are collapsed into the dependent variable's error term. As a result, the independent variable is correlated with (caused by) the error term, leading to the problem of endogeneity. These problems are very difficult, and should not be taken lightly. Nonetheless, even in this scenario, it is important to recognize that there is real causality at work.
In short, when you see a correlation, you should think that there probably is some sort of causality at play somewhere, but that you don't know the nature of that causal pattern. | If correlation doesn't imply causality then what's the value of knowing the correlation between two | The phrase "correlation doesn't imply causation" gets overplayed. (As Cohen wrote, "it's an awfully big hint".) We beat this phrase into students because of a bias intrinsic to the human mind. When | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables?
The phrase "correlation doesn't imply causation" gets overplayed. (As Cohen wrote, "it's an awfully big hint".) We beat this phrase into students because of a bias intrinsic to the human mind. When you hear 'the crime rate is correlated with the poverty rate', or something like that, you cannot help but think this means that poverty causes the crime. It is natural for people to assume this, because that's the way the mind works. We use the phrase over and over in the hopes of counteracting that. However, once you've absorbed the idea, the phrase loses most of it's value, and it's time to move on to a more sophisticated understanding.
When there is a correlation between two variables, there are two possibilities: it's all a coincidence, or there's some causal pattern at work. Calling a pattern in the world a coincidence is a terrible explanatory framework and should probably be your last resort. That leaves causality. The problem is that we don't know the nature of that causal pattern. It could well be that poverty causes crime, but it could also be that crime causes poverty (e.g., people don't want to live in a high-crime area, so they move out and property values fall, etc.). It could also be that there is some third variable or group of variables that cause both crime and poverty, but that there is, in fact, no direct causal link between crime and poverty (known as the 'common cause' model). This is especially pernicious, because, in a statistical model, all other sources of variation are collapsed into the dependent variable's error term. As a result, the independent variable is correlated with (caused by) the error term, leading to the problem of endogeneity. These problems are very difficult, and should not be taken lightly. Nonetheless, even in this scenario, it is important to recognize that there is real causality at work.
In short, when you see a correlation, you should think that there probably is some sort of causality at play somewhere, but that you don't know the nature of that causal pattern. | If correlation doesn't imply causality then what's the value of knowing the correlation between two
The phrase "correlation doesn't imply causation" gets overplayed. (As Cohen wrote, "it's an awfully big hint".) We beat this phrase into students because of a bias intrinsic to the human mind. When |
20,907 | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables? | I thought I was knowledgeable about these things, but it was only last month that I looked up "imply" in the dictionary and found it had two strikingly different meanings. 1. Suggest and 2. Necessitate. (!) Correlation seldom necessitates causation, but it certainly can suggest it. As @EpiGrad points out, it is a necessary though not sufficient condition for establishing causation.
As time goes on one hopefully finds a middle ground between seeing correlation as the end-all and as completely useless. And one takes into account subject-/domain-/content-specific knowledge in interpreting correlational results. Few people would question there being at least some causal link when seeing the advertising-sales results you describe. But it's always good to stay open to other possibilities, other variables that could at least partly explain the relationship observed. Readings about confounding variables, validity, and the like pay off with big dividends. For example, Cook and Campbell's old classic Quasi-Experimentation has a good section on validity and threats to validity. | If correlation doesn't imply causality then what's the value of knowing the correlation between two | I thought I was knowledgeable about these things, but it was only last month that I looked up "imply" in the dictionary and found it had two strikingly different meanings. 1. Suggest and 2. Necessita | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables?
I thought I was knowledgeable about these things, but it was only last month that I looked up "imply" in the dictionary and found it had two strikingly different meanings. 1. Suggest and 2. Necessitate. (!) Correlation seldom necessitates causation, but it certainly can suggest it. As @EpiGrad points out, it is a necessary though not sufficient condition for establishing causation.
As time goes on one hopefully finds a middle ground between seeing correlation as the end-all and as completely useless. And one takes into account subject-/domain-/content-specific knowledge in interpreting correlational results. Few people would question there being at least some causal link when seeing the advertising-sales results you describe. But it's always good to stay open to other possibilities, other variables that could at least partly explain the relationship observed. Readings about confounding variables, validity, and the like pay off with big dividends. For example, Cook and Campbell's old classic Quasi-Experimentation has a good section on validity and threats to validity. | If correlation doesn't imply causality then what's the value of knowing the correlation between two
I thought I was knowledgeable about these things, but it was only last month that I looked up "imply" in the dictionary and found it had two strikingly different meanings. 1. Suggest and 2. Necessita |
20,908 | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables? | A correlation coefficient, as other measures of association, is useful if you want to know how much knowing the value of X is informative about the value of Y. This is different from knowing whether if you were to set X to a particular value, what value of Y you would get (which is the essence of a counterfactual interpretation of causation).
Nevertheless, in many contexts (e.g. prediction) inferences based on correlation would be valuable in their own right. Yellow teeth are correlated with lung cancer (as they are both probabilistically caused by cancer). There is no causation between the two: whitening teeth would not cure lung cancer. But if you need a quick screening test for who is likely to have lung cancer, checking for yellow teeth might be a good first step.
It is a different question whether the correlation coefficient is the best available measure of association, but I think the question is more about what is the value of knowing non-causal association.
Btw, not only is correlation not sufficient demonstration of causation, but it is not necessary neither. Two variables can be causally related yet exhibit no correlation in any particular dataset (e.g. due to selection bias or confounders). | If correlation doesn't imply causality then what's the value of knowing the correlation between two | A correlation coefficient, as other measures of association, is useful if you want to know how much knowing the value of X is informative about the value of Y. This is different from knowing whether i | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables?
A correlation coefficient, as other measures of association, is useful if you want to know how much knowing the value of X is informative about the value of Y. This is different from knowing whether if you were to set X to a particular value, what value of Y you would get (which is the essence of a counterfactual interpretation of causation).
Nevertheless, in many contexts (e.g. prediction) inferences based on correlation would be valuable in their own right. Yellow teeth are correlated with lung cancer (as they are both probabilistically caused by cancer). There is no causation between the two: whitening teeth would not cure lung cancer. But if you need a quick screening test for who is likely to have lung cancer, checking for yellow teeth might be a good first step.
It is a different question whether the correlation coefficient is the best available measure of association, but I think the question is more about what is the value of knowing non-causal association.
Btw, not only is correlation not sufficient demonstration of causation, but it is not necessary neither. Two variables can be causally related yet exhibit no correlation in any particular dataset (e.g. due to selection bias or confounders). | If correlation doesn't imply causality then what's the value of knowing the correlation between two
A correlation coefficient, as other measures of association, is useful if you want to know how much knowing the value of X is informative about the value of Y. This is different from knowing whether i |
20,909 | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables? | correlation by itself is not of much use - so what "IS" the use?
Let me disagree with this phrase, correlation let to know the level of association between 2 variables. Then, it is useful when trying to explain relation between such variables.
On the other hand, (as Macro wrote) correlation is not a necessary condition for causation, however, is enough to explain the level of association. Furthermore, you can test the independence of the variables, but correlation can give you another useful information, the coefficient of determination.
Nevertheless, analyst must know the domain to be able to explain the kind of relation. | If correlation doesn't imply causality then what's the value of knowing the correlation between two | correlation by itself is not of much use - so what "IS" the use?
Let me disagree with this phrase, correlation let to know the level of association between 2 variables. Then, it is useful when trying | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables?
correlation by itself is not of much use - so what "IS" the use?
Let me disagree with this phrase, correlation let to know the level of association between 2 variables. Then, it is useful when trying to explain relation between such variables.
On the other hand, (as Macro wrote) correlation is not a necessary condition for causation, however, is enough to explain the level of association. Furthermore, you can test the independence of the variables, but correlation can give you another useful information, the coefficient of determination.
Nevertheless, analyst must know the domain to be able to explain the kind of relation. | If correlation doesn't imply causality then what's the value of knowing the correlation between two
correlation by itself is not of much use - so what "IS" the use?
Let me disagree with this phrase, correlation let to know the level of association between 2 variables. Then, it is useful when trying |
20,910 | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables? | I think data collection and study design may also play a role in answer this question. You won't design a study and collect a set of data completely irrelevant to each other, even in the observational studies.Therefore "the correlation does not imply causation" may be justified. Even though it is not causal relationship, there might be an association related.
However if you are talking about two dataset completely irrelevant, but you still wanna use correlation to explain the association and causation, then it might be inappropriate. For example, if two dataset all have downward trends, say ice cream sales and number of marriages, the correlation coefficient might be very high. But is it necessary to mean an association? | If correlation doesn't imply causality then what's the value of knowing the correlation between two | I think data collection and study design may also play a role in answer this question. You won't design a study and collect a set of data completely irrelevant to each other, even in the observational | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables?
I think data collection and study design may also play a role in answer this question. You won't design a study and collect a set of data completely irrelevant to each other, even in the observational studies.Therefore "the correlation does not imply causation" may be justified. Even though it is not causal relationship, there might be an association related.
However if you are talking about two dataset completely irrelevant, but you still wanna use correlation to explain the association and causation, then it might be inappropriate. For example, if two dataset all have downward trends, say ice cream sales and number of marriages, the correlation coefficient might be very high. But is it necessary to mean an association? | If correlation doesn't imply causality then what's the value of knowing the correlation between two
I think data collection and study design may also play a role in answer this question. You won't design a study and collect a set of data completely irrelevant to each other, even in the observational |
20,911 | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables? | In addition to Fomite's answer, I include an option that has not been considered in the rest of the answers: correlation is a measure of strength of a relationship when you already know there is causation.
For example, we know that there is a causal relationship between specific humidity in the atmosphere and probability of precipitation at close locations. However, we do not know (or cannot measure) all factors involved, so this relationship is not deterministic. Correlation helps measuring the strength of this association*, e.g. obtaining a spearman correlation of 0.8 says that most of the time an increase in one variable when the other one increases.
*Correlation is probably not the best measure of association, but this is out of the scope of this question. | If correlation doesn't imply causality then what's the value of knowing the correlation between two | In addition to Fomite's answer, I include an option that has not been considered in the rest of the answers: correlation is a measure of strength of a relationship when you already know there is causa | If correlation doesn't imply causality then what's the value of knowing the correlation between two variables?
In addition to Fomite's answer, I include an option that has not been considered in the rest of the answers: correlation is a measure of strength of a relationship when you already know there is causation.
For example, we know that there is a causal relationship between specific humidity in the atmosphere and probability of precipitation at close locations. However, we do not know (or cannot measure) all factors involved, so this relationship is not deterministic. Correlation helps measuring the strength of this association*, e.g. obtaining a spearman correlation of 0.8 says that most of the time an increase in one variable when the other one increases.
*Correlation is probably not the best measure of association, but this is out of the scope of this question. | If correlation doesn't imply causality then what's the value of knowing the correlation between two
In addition to Fomite's answer, I include an option that has not been considered in the rest of the answers: correlation is a measure of strength of a relationship when you already know there is causa |
20,912 | How do I reduce the number of data points in a series? | You have two problems: too many points and how to smooth over the remaining points.
Thinning your sample
If you have too many observations arriving in real time, you could always use simple random sampling to thin your sample. Note, for this too be true, the number of points would have to be very large.
Suppose you have N points and you only want n of them. Then generate n random numbers from a discrete uniform U(0, N-1) distribution. These would be the points you use.
If you want to do this sequentially, i.e. at each point you decide to use it or not, then just accept a point with probability p. So if you set p=0.01 you would accept (on average) 1 point in a hundred.
If your data is unevenly spread and you only want to thin dense regions of points, then just make your thinning function a bit more sophisticated. For example, instead of p, what about:
$$1-p \exp(-\lambda t)$$
where $\lambda$ is a positive number and $t$ is the time since the last observation. If the time between two points is large, i.e. large $t$, the probability of accepting a point will be one. Conversely, if two points are close together, the probability of accepting a point will be $1-p$.
You will need to experiment with values of $\lambda$ and $p$.
Smoothing
Possibly something like a simple moving average type scheme. Or you could go for something more advanced like a kernel smoother (as others suggested). You will need to be careful that you don't smooth too much, since I assume that a sudden drop should be picked up very quickly in your scenario.
There should be C# libraries available for this sort of stuff.
Conclusion
Thin if necessary, then smooth. | How do I reduce the number of data points in a series? | You have two problems: too many points and how to smooth over the remaining points.
Thinning your sample
If you have too many observations arriving in real time, you could always use simple random sam | How do I reduce the number of data points in a series?
You have two problems: too many points and how to smooth over the remaining points.
Thinning your sample
If you have too many observations arriving in real time, you could always use simple random sampling to thin your sample. Note, for this too be true, the number of points would have to be very large.
Suppose you have N points and you only want n of them. Then generate n random numbers from a discrete uniform U(0, N-1) distribution. These would be the points you use.
If you want to do this sequentially, i.e. at each point you decide to use it or not, then just accept a point with probability p. So if you set p=0.01 you would accept (on average) 1 point in a hundred.
If your data is unevenly spread and you only want to thin dense regions of points, then just make your thinning function a bit more sophisticated. For example, instead of p, what about:
$$1-p \exp(-\lambda t)$$
where $\lambda$ is a positive number and $t$ is the time since the last observation. If the time between two points is large, i.e. large $t$, the probability of accepting a point will be one. Conversely, if two points are close together, the probability of accepting a point will be $1-p$.
You will need to experiment with values of $\lambda$ and $p$.
Smoothing
Possibly something like a simple moving average type scheme. Or you could go for something more advanced like a kernel smoother (as others suggested). You will need to be careful that you don't smooth too much, since I assume that a sudden drop should be picked up very quickly in your scenario.
There should be C# libraries available for this sort of stuff.
Conclusion
Thin if necessary, then smooth. | How do I reduce the number of data points in a series?
You have two problems: too many points and how to smooth over the remaining points.
Thinning your sample
If you have too many observations arriving in real time, you could always use simple random sam |
20,913 | How do I reduce the number of data points in a series? | Well, I think the word you're looking for is "sampling," but I'm not sure why you want to do it. Thousands of data points isn't very many. Or are you looking just to plot a smaller number of equally-spaced points? That's usually called "binning."
Is your goal to generate a visualization? In that case, you might want to keep the raw data, plot it as a scattergraph, then overlay some sort of central tendency (regression line, spline, whatever) to communicate whatever the takehome message ought to be.
Or is your goal to numerically summarize the results in some way? In that case, you might want to explain your problem in more detail! | How do I reduce the number of data points in a series? | Well, I think the word you're looking for is "sampling," but I'm not sure why you want to do it. Thousands of data points isn't very many. Or are you looking just to plot a smaller number of equally-s | How do I reduce the number of data points in a series?
Well, I think the word you're looking for is "sampling," but I'm not sure why you want to do it. Thousands of data points isn't very many. Or are you looking just to plot a smaller number of equally-spaced points? That's usually called "binning."
Is your goal to generate a visualization? In that case, you might want to keep the raw data, plot it as a scattergraph, then overlay some sort of central tendency (regression line, spline, whatever) to communicate whatever the takehome message ought to be.
Or is your goal to numerically summarize the results in some way? In that case, you might want to explain your problem in more detail! | How do I reduce the number of data points in a series?
Well, I think the word you're looking for is "sampling," but I'm not sure why you want to do it. Thousands of data points isn't very many. Or are you looking just to plot a smaller number of equally-s |
20,914 | How do I reduce the number of data points in a series? | Calculating averages leads to a different dataset than simply reducing the number of data points.
If one heartbeat per minute is much faster than the other heart beats you will lose the signal through your smoothing process.
If you summary 125-125-0-125-125 as 100 than the story that the data tells is different through your smoothing.
Sometimes the heart even skips beats and I believe that's an event that interesting for however wants to look at plotted heart rate data.
I would therefore propose that you calculate the distance between two points with a formula like d=sqrt((time1-time2)^2 + (bpm1-bpm2)).
You set a minimum distance in your program.
Then you iterate through your data and after every point you delete all following points for which d is smaller than your minimum distance.
As the unit of time and bpm isn't the same you might want to think about how you can find a way to scale the units meaningfully. To do this task right you should speak to the doctors who in the end have to interpret your graphs and ask them what information they consider to be essential. | How do I reduce the number of data points in a series? | Calculating averages leads to a different dataset than simply reducing the number of data points.
If one heartbeat per minute is much faster than the other heart beats you will lose the signal through | How do I reduce the number of data points in a series?
Calculating averages leads to a different dataset than simply reducing the number of data points.
If one heartbeat per minute is much faster than the other heart beats you will lose the signal through your smoothing process.
If you summary 125-125-0-125-125 as 100 than the story that the data tells is different through your smoothing.
Sometimes the heart even skips beats and I believe that's an event that interesting for however wants to look at plotted heart rate data.
I would therefore propose that you calculate the distance between two points with a formula like d=sqrt((time1-time2)^2 + (bpm1-bpm2)).
You set a minimum distance in your program.
Then you iterate through your data and after every point you delete all following points for which d is smaller than your minimum distance.
As the unit of time and bpm isn't the same you might want to think about how you can find a way to scale the units meaningfully. To do this task right you should speak to the doctors who in the end have to interpret your graphs and ask them what information they consider to be essential. | How do I reduce the number of data points in a series?
Calculating averages leads to a different dataset than simply reducing the number of data points.
If one heartbeat per minute is much faster than the other heart beats you will lose the signal through |
20,915 | How do I reduce the number of data points in a series? | If BPM is staying the same over many samples (or changing infinitesimally in a way you aren't concerned about) you can truncate your data to a significant digit that you actually care about and then do Run Length Encoding.
For example, in R this data:
0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
has this output
rle(data)
Run Length Encoding
lengths: int [1:3] 10 15 15
values : num [1:3] 0 1 2 | How do I reduce the number of data points in a series? | If BPM is staying the same over many samples (or changing infinitesimally in a way you aren't concerned about) you can truncate your data to a significant digit that you actually care about and then d | How do I reduce the number of data points in a series?
If BPM is staying the same over many samples (or changing infinitesimally in a way you aren't concerned about) you can truncate your data to a significant digit that you actually care about and then do Run Length Encoding.
For example, in R this data:
0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
has this output
rle(data)
Run Length Encoding
lengths: int [1:3] 10 15 15
values : num [1:3] 0 1 2 | How do I reduce the number of data points in a series?
If BPM is staying the same over many samples (or changing infinitesimally in a way you aren't concerned about) you can truncate your data to a significant digit that you actually care about and then d |
20,916 | How do I reduce the number of data points in a series? | For reducing your data points, you can use the Ramer–Douglas–Peucker algorithm which is very easy to understand and implement. The sampled signal will be very similar to the original one. | How do I reduce the number of data points in a series? | For reducing your data points, you can use the Ramer–Douglas–Peucker algorithm which is very easy to understand and implement. The sampled signal will be very similar to the original one. | How do I reduce the number of data points in a series?
For reducing your data points, you can use the Ramer–Douglas–Peucker algorithm which is very easy to understand and implement. The sampled signal will be very similar to the original one. | How do I reduce the number of data points in a series?
For reducing your data points, you can use the Ramer–Douglas–Peucker algorithm which is very easy to understand and implement. The sampled signal will be very similar to the original one. |
20,917 | How do I reduce the number of data points in a series? | You're not providing enough information. Why do you want to reduce the data points. A few thousand is nothing these days.
Given that you want the same result each time you view the same data perhaps you want to simply bin averages. You have variable spacing on your x-axis. Maybe you're trying to make that consistent? In that case you would set a bin width of perhaps 50 msec, or 100, and then average all the points in there. Make the bin width as large as you need to reduce the data points to the size of the set you want.
It's really a hard question to answer without a reason for why you're getting rid of data. | How do I reduce the number of data points in a series? | You're not providing enough information. Why do you want to reduce the data points. A few thousand is nothing these days.
Given that you want the same result each time you view the same data perhaps | How do I reduce the number of data points in a series?
You're not providing enough information. Why do you want to reduce the data points. A few thousand is nothing these days.
Given that you want the same result each time you view the same data perhaps you want to simply bin averages. You have variable spacing on your x-axis. Maybe you're trying to make that consistent? In that case you would set a bin width of perhaps 50 msec, or 100, and then average all the points in there. Make the bin width as large as you need to reduce the data points to the size of the set you want.
It's really a hard question to answer without a reason for why you're getting rid of data. | How do I reduce the number of data points in a series?
You're not providing enough information. Why do you want to reduce the data points. A few thousand is nothing these days.
Given that you want the same result each time you view the same data perhaps |
20,918 | Quantifying diversity of bird species | Just about any general book on ecological methods has a section on diversity measures and there are indeed several dedicated monographs on diversity in ecology alone, to say nothing about related literatures. Ecologists can get quite agitated and even angry about which measures are good and especially about if any is best. Much of the literature is naive mathematically or scientifically, although as an outsider I won't give precise references, beyond hinting that some popular accounts are shockingly muddled.
You are too pessimistic about Simpson's measure which shows in your case for both sites a high probability of random pairs of individuals being different species. However, small differences can be important. I suggest that the Simpson measure is usually better thought of on a different scale.
You are evidently using Simpson's measure as the complement of $R := \sum_{i=1}^S p_i^2$, namely $1 - R$ or $1 - \sum_{i=1}^S p_i^2$. Here the notation is that there are $S$ species and the typical species occurs with probability $p_i$. The $R$ notation is suggested by the term repeat rate, one of many terms in the jungle.
A reference case is $S$ species occurring equally frequently, for which $R =
\sum_{i=1}^S p_i^2 = \sum_{i=1}^S (1/S)^2 = S/S^2 = 1/S$. This motivates $1/R$ as a numbers equivalent, namely an equivalent number of equally common species. I get that measure to be about 16.1 and 24.0 for your two sites, which is a fair contrast.
Similarly, consider Shannon entropy $H := \sum_{i=1}^S p_i \ln(1/p_i)$ which for $S$ equally common species is $S (1/S) \ln S = \ln S$. Hence $\exp(H)$ is a numbers equivalent. For your sites that gives 21.6 and 30.8.
Simplest of all is just the number of species present, $S$ itself, which for your sites are 32 and 53.
In general, $(1/R) \le \exp(H) \le S$. The measure of those three that responds best to the occurrence of rare or unusual species is number of species!
These measures are all part of a family $\sum p_i^a (\ln 1/p_i)^b$. For Simpson's measure as a sum of squared probabilities or repeat rate $a = 2, b = 0$; for entropy $a = 1, b=1$; and for the number of species $a=0, b=0$. This easy unification was published by I.J. Good in 1953. There are fancier families associated with the names of C.R. Rao and M.O. Hill, but that Good family is simpler.
There are many other measures in the literature.
If you prefer $\log_2$ or $\log_{10}$ for calculating entropy, the corresponding numbers equivalent is then $2^H$ or $10^H$.
Note: This answer treats the data literally, as being say results from comparable sampling effort. The problem that the more you observe, the more you will find, and other more biological points, are well covered in other answers.
All that said, any idea that a single measure can capture all the information here is likely to prove disappointing. But that is true of any summary statistic. | Quantifying diversity of bird species | Just about any general book on ecological methods has a section on diversity measures and there are indeed several dedicated monographs on diversity in ecology alone, to say nothing about related lite | Quantifying diversity of bird species
Just about any general book on ecological methods has a section on diversity measures and there are indeed several dedicated monographs on diversity in ecology alone, to say nothing about related literatures. Ecologists can get quite agitated and even angry about which measures are good and especially about if any is best. Much of the literature is naive mathematically or scientifically, although as an outsider I won't give precise references, beyond hinting that some popular accounts are shockingly muddled.
You are too pessimistic about Simpson's measure which shows in your case for both sites a high probability of random pairs of individuals being different species. However, small differences can be important. I suggest that the Simpson measure is usually better thought of on a different scale.
You are evidently using Simpson's measure as the complement of $R := \sum_{i=1}^S p_i^2$, namely $1 - R$ or $1 - \sum_{i=1}^S p_i^2$. Here the notation is that there are $S$ species and the typical species occurs with probability $p_i$. The $R$ notation is suggested by the term repeat rate, one of many terms in the jungle.
A reference case is $S$ species occurring equally frequently, for which $R =
\sum_{i=1}^S p_i^2 = \sum_{i=1}^S (1/S)^2 = S/S^2 = 1/S$. This motivates $1/R$ as a numbers equivalent, namely an equivalent number of equally common species. I get that measure to be about 16.1 and 24.0 for your two sites, which is a fair contrast.
Similarly, consider Shannon entropy $H := \sum_{i=1}^S p_i \ln(1/p_i)$ which for $S$ equally common species is $S (1/S) \ln S = \ln S$. Hence $\exp(H)$ is a numbers equivalent. For your sites that gives 21.6 and 30.8.
Simplest of all is just the number of species present, $S$ itself, which for your sites are 32 and 53.
In general, $(1/R) \le \exp(H) \le S$. The measure of those three that responds best to the occurrence of rare or unusual species is number of species!
These measures are all part of a family $\sum p_i^a (\ln 1/p_i)^b$. For Simpson's measure as a sum of squared probabilities or repeat rate $a = 2, b = 0$; for entropy $a = 1, b=1$; and for the number of species $a=0, b=0$. This easy unification was published by I.J. Good in 1953. There are fancier families associated with the names of C.R. Rao and M.O. Hill, but that Good family is simpler.
There are many other measures in the literature.
If you prefer $\log_2$ or $\log_{10}$ for calculating entropy, the corresponding numbers equivalent is then $2^H$ or $10^H$.
Note: This answer treats the data literally, as being say results from comparable sampling effort. The problem that the more you observe, the more you will find, and other more biological points, are well covered in other answers.
All that said, any idea that a single measure can capture all the information here is likely to prove disappointing. But that is true of any summary statistic. | Quantifying diversity of bird species
Just about any general book on ecological methods has a section on diversity measures and there are indeed several dedicated monographs on diversity in ecology alone, to say nothing about related lite |
20,919 | Quantifying diversity of bird species | Firstly, I assume that you are talking about alpha-diversity (although the existence of multiple sites where the data were taken suggests that beta-diversity could be also relevant).
The simplest diversity indices (but see also here - Wikipedia has two complementary articles on the subject) are:
Species richness : the number of species present, $R$.
Shannon entropy : $H=-\sum_{i=1}^R p_i\log_2 p_i$
Simpson index : $\lambda=\sum_{i=1}^R p_i^2$
where $p_i$ is the proportional abundance of species of type $i$ (i.e., the fraction of these species in respect to the size of the sample).
Shannon entropy and Simpson index differ from simple richness in that they give less weight to rare species, and thus less subject to fluctuations from site to site and less dependent on the sampling depth (total number of individuals sampled).
More general measures are Hill numbers
$$
^qD=\left(\sum_{i=1}^Rp_i^q\right)^{\frac{1}{q-1}},
$$
which for $q=0,1,2$ are related to the diversity indices mentioned above. Hill numbers with $q>0$ can be interpreted as effective number of species.
As a crash course about quantifying alpha-diversity, I could recommend Measuring and Estimating Species Richness, Species Diversity, and Biotic Similarity from Sampling Data by Gotelli and Chao. This also contains information on estimating the true diversity, as well as such important tools as rarefaction curves.
Finally, relative species abundance, presented by Fisher plot or Whittaker plot can be also of interest here.
Remark: As I am more a python person than an R person, I could recommend using scikit-bio, which contains library skbio.diversity, with functions for calculating alpha- and beta-diversity. Note however that most alpha-diversity metrics are easily implemented by hand. | Quantifying diversity of bird species | Firstly, I assume that you are talking about alpha-diversity (although the existence of multiple sites where the data were taken suggests that beta-diversity could be also relevant).
The simplest dive | Quantifying diversity of bird species
Firstly, I assume that you are talking about alpha-diversity (although the existence of multiple sites where the data were taken suggests that beta-diversity could be also relevant).
The simplest diversity indices (but see also here - Wikipedia has two complementary articles on the subject) are:
Species richness : the number of species present, $R$.
Shannon entropy : $H=-\sum_{i=1}^R p_i\log_2 p_i$
Simpson index : $\lambda=\sum_{i=1}^R p_i^2$
where $p_i$ is the proportional abundance of species of type $i$ (i.e., the fraction of these species in respect to the size of the sample).
Shannon entropy and Simpson index differ from simple richness in that they give less weight to rare species, and thus less subject to fluctuations from site to site and less dependent on the sampling depth (total number of individuals sampled).
More general measures are Hill numbers
$$
^qD=\left(\sum_{i=1}^Rp_i^q\right)^{\frac{1}{q-1}},
$$
which for $q=0,1,2$ are related to the diversity indices mentioned above. Hill numbers with $q>0$ can be interpreted as effective number of species.
As a crash course about quantifying alpha-diversity, I could recommend Measuring and Estimating Species Richness, Species Diversity, and Biotic Similarity from Sampling Data by Gotelli and Chao. This also contains information on estimating the true diversity, as well as such important tools as rarefaction curves.
Finally, relative species abundance, presented by Fisher plot or Whittaker plot can be also of interest here.
Remark: As I am more a python person than an R person, I could recommend using scikit-bio, which contains library skbio.diversity, with functions for calculating alpha- and beta-diversity. Note however that most alpha-diversity metrics are easily implemented by hand. | Quantifying diversity of bird species
Firstly, I assume that you are talking about alpha-diversity (although the existence of multiple sites where the data were taken suggests that beta-diversity could be also relevant).
The simplest dive |
20,920 | Quantifying diversity of bird species | The other thing that's worth taking into account (although it involves similar deep rabbit holes as the other aspects of diversity metrics mentioned in other answers and comments) is that diversity measures with low $q$ (as in @RogerVadim's answer), i.e. richness and similar metrics, are sensitive to sample size. There are 126 total breeding pairs at site 1 vs. 468 at site 2.
Here are the rarefaction curves mentioned by @RogerVadim:
library(vegan)
## site1 and site2 from OP example above
r1 <- rarecurve(rbind(site1), tidy = TRUE)
r2 <- rarecurve(rbind(site2), tidy = TRUE)
## plot site 2 first because larger sample
plot(Species~Sample, data = r2, type = "l")
with(r1, lines(Sample, Species, col = 2))
There are 32 species at site 1; if there were only 126 breeding pairs at site 2, we would expect to see only 34 or 35 species rather than the 53 actually observed.
(You can do these computations and draw the plot slightly more elegantly if your data are organized as a species-by-site matrix with zeros filled in for species that are not observed in any samples at a particular site.)
subset(r2, Sample == max(r1$Sample))
There are various ways to deal with issue; here I'm just pointing out a possible source of confounding/confusion. | Quantifying diversity of bird species | The other thing that's worth taking into account (although it involves similar deep rabbit holes as the other aspects of diversity metrics mentioned in other answers and comments) is that diversity me | Quantifying diversity of bird species
The other thing that's worth taking into account (although it involves similar deep rabbit holes as the other aspects of diversity metrics mentioned in other answers and comments) is that diversity measures with low $q$ (as in @RogerVadim's answer), i.e. richness and similar metrics, are sensitive to sample size. There are 126 total breeding pairs at site 1 vs. 468 at site 2.
Here are the rarefaction curves mentioned by @RogerVadim:
library(vegan)
## site1 and site2 from OP example above
r1 <- rarecurve(rbind(site1), tidy = TRUE)
r2 <- rarecurve(rbind(site2), tidy = TRUE)
## plot site 2 first because larger sample
plot(Species~Sample, data = r2, type = "l")
with(r1, lines(Sample, Species, col = 2))
There are 32 species at site 1; if there were only 126 breeding pairs at site 2, we would expect to see only 34 or 35 species rather than the 53 actually observed.
(You can do these computations and draw the plot slightly more elegantly if your data are organized as a species-by-site matrix with zeros filled in for species that are not observed in any samples at a particular site.)
subset(r2, Sample == max(r1$Sample))
There are various ways to deal with issue; here I'm just pointing out a possible source of confounding/confusion. | Quantifying diversity of bird species
The other thing that's worth taking into account (although it involves similar deep rabbit holes as the other aspects of diversity metrics mentioned in other answers and comments) is that diversity me |
20,921 | How did the “Hat Matrix” get its name | The name "hat matrix" is a mnemonic: a shortcut to help us remember the role it plays in regression. As @RobertLong explains in Learning hat matrix,
The hat matrix is the projection matrix that maps the response vector $Y$ to the vector of fitted values $\hat{Y}$ (hence the name "hat" matrix).
As to history, according to
David, H. A. “First (?) Occurrence of Common Terms in Mathematical Statistics.” The American Statistician, vol. 49, no. 2, 1995, pp. 121–33. https://doi.org/10.2307/2684625.
the term "hat matrix" first appears in
Hoaglin, David C., and Roy E. Welsch. “The Hat Matrix in Regression and ANOVA.” The American Statistician, vol. 32, no. 1, 1978, pp. 17–22. https://doi.org/10.2307/2683469.
But the authors themselves attribute it to J. W. Tukey. | How did the “Hat Matrix” get its name | The name "hat matrix" is a mnemonic: a shortcut to help us remember the role it plays in regression. As @RobertLong explains in Learning hat matrix,
The hat matrix is the projection matrix that maps | How did the “Hat Matrix” get its name
The name "hat matrix" is a mnemonic: a shortcut to help us remember the role it plays in regression. As @RobertLong explains in Learning hat matrix,
The hat matrix is the projection matrix that maps the response vector $Y$ to the vector of fitted values $\hat{Y}$ (hence the name "hat" matrix).
As to history, according to
David, H. A. “First (?) Occurrence of Common Terms in Mathematical Statistics.” The American Statistician, vol. 49, no. 2, 1995, pp. 121–33. https://doi.org/10.2307/2684625.
the term "hat matrix" first appears in
Hoaglin, David C., and Roy E. Welsch. “The Hat Matrix in Regression and ANOVA.” The American Statistician, vol. 32, no. 1, 1978, pp. 17–22. https://doi.org/10.2307/2683469.
But the authors themselves attribute it to J. W. Tukey. | How did the “Hat Matrix” get its name
The name "hat matrix" is a mnemonic: a shortcut to help us remember the role it plays in regression. As @RobertLong explains in Learning hat matrix,
The hat matrix is the projection matrix that maps |
20,922 | How did the “Hat Matrix” get its name | In fact the formula should read $\mathbf{H} = \mathbf{X} \left( \mathbf{X}^\textsf{T} \mathbf{X} \right)^{-1} \mathbf{X}^\textsf{T}$, therefore $\hat{\mathbf{y}}=\mathbf{H}\mathbf{y}$. The hat matrix is called hat matrix because it puts a hat on the $\mathbf{y}$. (This is in fact mentioned on the Wikipedia page linked by @dipetkov, but I had heard it before from somebody who I think had heard Tukey mentioning it.) | How did the “Hat Matrix” get its name | In fact the formula should read $\mathbf{H} = \mathbf{X} \left( \mathbf{X}^\textsf{T} \mathbf{X} \right)^{-1} \mathbf{X}^\textsf{T}$, therefore $\hat{\mathbf{y}}=\mathbf{H}\mathbf{y}$. The hat matrix | How did the “Hat Matrix” get its name
In fact the formula should read $\mathbf{H} = \mathbf{X} \left( \mathbf{X}^\textsf{T} \mathbf{X} \right)^{-1} \mathbf{X}^\textsf{T}$, therefore $\hat{\mathbf{y}}=\mathbf{H}\mathbf{y}$. The hat matrix is called hat matrix because it puts a hat on the $\mathbf{y}$. (This is in fact mentioned on the Wikipedia page linked by @dipetkov, but I had heard it before from somebody who I think had heard Tukey mentioning it.) | How did the “Hat Matrix” get its name
In fact the formula should read $\mathbf{H} = \mathbf{X} \left( \mathbf{X}^\textsf{T} \mathbf{X} \right)^{-1} \mathbf{X}^\textsf{T}$, therefore $\hat{\mathbf{y}}=\mathbf{H}\mathbf{y}$. The hat matrix |
20,923 | Splines in GLM and GAM | You are mistaken. Splines have a linear representation using derived covariates. As an example, a quadratic trend is non-linear, but can be modeled in a linear model by taking: $E[Y|X] = \beta_0 + \beta_1 X + \beta_2 X^2$, thus $X$ and its square are input into a linear model.
The spline can simply be seen as a sophisticated parametrization of one or more continuously or pseudo-continuously valued covariates. | Splines in GLM and GAM | You are mistaken. Splines have a linear representation using derived covariates. As an example, a quadratic trend is non-linear, but can be modeled in a linear model by taking: $E[Y|X] = \beta_0 + \be | Splines in GLM and GAM
You are mistaken. Splines have a linear representation using derived covariates. As an example, a quadratic trend is non-linear, but can be modeled in a linear model by taking: $E[Y|X] = \beta_0 + \beta_1 X + \beta_2 X^2$, thus $X$ and its square are input into a linear model.
The spline can simply be seen as a sophisticated parametrization of one or more continuously or pseudo-continuously valued covariates. | Splines in GLM and GAM
You are mistaken. Splines have a linear representation using derived covariates. As an example, a quadratic trend is non-linear, but can be modeled in a linear model by taking: $E[Y|X] = \beta_0 + \be |
20,924 | Splines in GLM and GAM | @AdamO's answer is correct, in that spline-based fits can certainly be done in the standard GLM framework. That's not to say that GAM's are just a special case of GLM's though! While there are a series of models that exactly identical and can be framed as both a GAM or as a GLM with a spline expansion of the covariates, there are some GAM models that are not available in the standard GLM framework.
For example, one could fit a GAM model using a smoothing spline for each of the covariates. This basically results in a spline expansion of the variables, but with a penalty on the second derivatives. This results in a model that is a bit outside the standard GLM framework.
In addition, it's often considered standard procedure, and is built into most GAM libraries, to fit smoothing parameters (i.e. spline degrees of freedom, etc.) by optimizing various measures of out of sample errors, while the GLM formulation typically considers the covariate space fixed. | Splines in GLM and GAM | @AdamO's answer is correct, in that spline-based fits can certainly be done in the standard GLM framework. That's not to say that GAM's are just a special case of GLM's though! While there are a serie | Splines in GLM and GAM
@AdamO's answer is correct, in that spline-based fits can certainly be done in the standard GLM framework. That's not to say that GAM's are just a special case of GLM's though! While there are a series of models that exactly identical and can be framed as both a GAM or as a GLM with a spline expansion of the covariates, there are some GAM models that are not available in the standard GLM framework.
For example, one could fit a GAM model using a smoothing spline for each of the covariates. This basically results in a spline expansion of the variables, but with a penalty on the second derivatives. This results in a model that is a bit outside the standard GLM framework.
In addition, it's often considered standard procedure, and is built into most GAM libraries, to fit smoothing parameters (i.e. spline degrees of freedom, etc.) by optimizing various measures of out of sample errors, while the GLM formulation typically considers the covariate space fixed. | Splines in GLM and GAM
@AdamO's answer is correct, in that spline-based fits can certainly be done in the standard GLM framework. That's not to say that GAM's are just a special case of GLM's though! While there are a serie |
20,925 | Can Tree-based regression perform worse than plain linear regression? | You should not just throw the data at different algorithms and look at the quality of the predictions. You need to understand your data better, and the way of going about that is to first, visualize your data (the marginal distributions). Even if you are only interested finally in the predictions, you will be in a better position to make better models if you understand the data better. So, first, try to understand the data (and simple models fitted to the data) better, and then you are in a much better position to create more complex, and hopefully better, models.
Then, fit linear regression models, with your 15 variables as precictors (later you can look at possible interactions). Then, calculate the residuals from that fit, that is,
$$
r_i = Y_i - \hat{Y}_i, \qquad i=1, 2,\dots, n
$$
If the model is adecuate, that is, it was able to extract the signal (structure) from the data, then the residuals should show no patterns. Box, Hunter & Hunter: "Statistics for Experimenters" (which you should have a look at, its one of the best ever books on statistics) compares this with an analogy from chemistry: The model is a "filter" designed to catch impurities from water (the data). What is left, which passed through the filter, should then be "clean" and analysis of it (residuals analysis) can show that, when it does not contain impurities (structure). See Checking residuals for normality in generalised linear models
To know what to check for you need to understand the assumptions behind linear regression, see What is a complete list of the usual assumptions for linear regression?
One usual assumption is homoskedasticity, that is, constant variance. To check that, plot the residuals $r_i$ against the predicted values, $\hat{Y}_i$. To understand this procedure see: Why are residual plots constructed using the residuals vs the predicted values?.
Other assumptions is linearity. To check those, plot the residuals against each of the predictors in the model. If you see any curvity in those plots, that is evidence against linearity. If you find non-linearity, either you can try some transformations or (more modern approch) include that non-linear predictor in the model in a non-linear way, maybe using splines (you have 60 million examples so should be quite feasible!).
Then you need to check for possible interactions. The above ideas can be used also for variables not in the fitted model. Since you fit a model without interactions, that include interaction variables, like the product $x_i \cdot z_i$ for two variables $x$, $z$. So plot the residuals against all this interaction variables. A blog post with many example plots is http://docs.statwing.com/interpreting-residual-plots-to-improve-your-regression/
A book-length treatment is R Dennis Cook & Sanford Weisberg: "Residuals and influence in regression", Chapman & Hall. A more modern book-length treatment is Frank Harrell: "Regression modeling Strategies".
And, coming bact to the question in the title: "Can Tree-based regression perform worse than plain linear regression?" Yes, of course it can. Tree-based models has as regression function a very complex step function. If the data truly comes from (behave as simulated from) a linear model, then step functions can be a bad approximation. And, as shown by examples in the other answer, tree-based models might extrapolate badly outside the range of the observed predictors. You could also try randomforrest and see how much better that is than a single tree. | Can Tree-based regression perform worse than plain linear regression? | You should not just throw the data at different algorithms and look at the quality of the predictions. You need to understand your data better, and the way of going about that is to first, visualize | Can Tree-based regression perform worse than plain linear regression?
You should not just throw the data at different algorithms and look at the quality of the predictions. You need to understand your data better, and the way of going about that is to first, visualize your data (the marginal distributions). Even if you are only interested finally in the predictions, you will be in a better position to make better models if you understand the data better. So, first, try to understand the data (and simple models fitted to the data) better, and then you are in a much better position to create more complex, and hopefully better, models.
Then, fit linear regression models, with your 15 variables as precictors (later you can look at possible interactions). Then, calculate the residuals from that fit, that is,
$$
r_i = Y_i - \hat{Y}_i, \qquad i=1, 2,\dots, n
$$
If the model is adecuate, that is, it was able to extract the signal (structure) from the data, then the residuals should show no patterns. Box, Hunter & Hunter: "Statistics for Experimenters" (which you should have a look at, its one of the best ever books on statistics) compares this with an analogy from chemistry: The model is a "filter" designed to catch impurities from water (the data). What is left, which passed through the filter, should then be "clean" and analysis of it (residuals analysis) can show that, when it does not contain impurities (structure). See Checking residuals for normality in generalised linear models
To know what to check for you need to understand the assumptions behind linear regression, see What is a complete list of the usual assumptions for linear regression?
One usual assumption is homoskedasticity, that is, constant variance. To check that, plot the residuals $r_i$ against the predicted values, $\hat{Y}_i$. To understand this procedure see: Why are residual plots constructed using the residuals vs the predicted values?.
Other assumptions is linearity. To check those, plot the residuals against each of the predictors in the model. If you see any curvity in those plots, that is evidence against linearity. If you find non-linearity, either you can try some transformations or (more modern approch) include that non-linear predictor in the model in a non-linear way, maybe using splines (you have 60 million examples so should be quite feasible!).
Then you need to check for possible interactions. The above ideas can be used also for variables not in the fitted model. Since you fit a model without interactions, that include interaction variables, like the product $x_i \cdot z_i$ for two variables $x$, $z$. So plot the residuals against all this interaction variables. A blog post with many example plots is http://docs.statwing.com/interpreting-residual-plots-to-improve-your-regression/
A book-length treatment is R Dennis Cook & Sanford Weisberg: "Residuals and influence in regression", Chapman & Hall. A more modern book-length treatment is Frank Harrell: "Regression modeling Strategies".
And, coming bact to the question in the title: "Can Tree-based regression perform worse than plain linear regression?" Yes, of course it can. Tree-based models has as regression function a very complex step function. If the data truly comes from (behave as simulated from) a linear model, then step functions can be a bad approximation. And, as shown by examples in the other answer, tree-based models might extrapolate badly outside the range of the observed predictors. You could also try randomforrest and see how much better that is than a single tree. | Can Tree-based regression perform worse than plain linear regression?
You should not just throw the data at different algorithms and look at the quality of the predictions. You need to understand your data better, and the way of going about that is to first, visualize |
20,926 | Can Tree-based regression perform worse than plain linear regression? | Peter Ellis has a
very simple example
where linear regression performs better than regression trees, extrapolating beyond the observed values in the sample.
In this image the black points are the observed values, and the colored points are the predicted values. The actual data are generated according to a simple line with some noise, so linear regression and the neural network do a good job of extrapolating beyond the observed data. The tree based models do not.
Now, with 60 million data points you might not be worried about this. (The future always manages to surprise me though!) But it is an intuitive illustration as to one situation in which trees will fail. | Can Tree-based regression perform worse than plain linear regression? | Peter Ellis has a
very simple example
where linear regression performs better than regression trees, extrapolating beyond the observed values in the sample.
In this image the black points are the ob | Can Tree-based regression perform worse than plain linear regression?
Peter Ellis has a
very simple example
where linear regression performs better than regression trees, extrapolating beyond the observed values in the sample.
In this image the black points are the observed values, and the colored points are the predicted values. The actual data are generated according to a simple line with some noise, so linear regression and the neural network do a good job of extrapolating beyond the observed data. The tree based models do not.
Now, with 60 million data points you might not be worried about this. (The future always manages to surprise me though!) But it is an intuitive illustration as to one situation in which trees will fail. | Can Tree-based regression perform worse than plain linear regression?
Peter Ellis has a
very simple example
where linear regression performs better than regression trees, extrapolating beyond the observed values in the sample.
In this image the black points are the ob |
20,927 | Can Tree-based regression perform worse than plain linear regression? | It is a well known fact that trees are ill-suited to model truly linear relationships. Here is an illustration (Fig 8.7) from the ISLR book:
Top Row: A two-dimensional classification example in which
the true decision boundary is linear, and is indicated by the shaded regions.
A classical approach that assumes a linear boundary (left) will outperform a decision
tree that performs splits parallel to the axes (right).
So if your dependent variable depends on the regressors in a more or less linear fashion, you would expect that "linear regression performs great". | Can Tree-based regression perform worse than plain linear regression? | It is a well known fact that trees are ill-suited to model truly linear relationships. Here is an illustration (Fig 8.7) from the ISLR book:
Top Row: A two-dimensional classification example in which | Can Tree-based regression perform worse than plain linear regression?
It is a well known fact that trees are ill-suited to model truly linear relationships. Here is an illustration (Fig 8.7) from the ISLR book:
Top Row: A two-dimensional classification example in which
the true decision boundary is linear, and is indicated by the shaded regions.
A classical approach that assumes a linear boundary (left) will outperform a decision
tree that performs splits parallel to the axes (right).
So if your dependent variable depends on the regressors in a more or less linear fashion, you would expect that "linear regression performs great". | Can Tree-based regression perform worse than plain linear regression?
It is a well known fact that trees are ill-suited to model truly linear relationships. Here is an illustration (Fig 8.7) from the ISLR book:
Top Row: A two-dimensional classification example in which |
20,928 | Can Tree-based regression perform worse than plain linear regression? | Any decision-tree based approach (CART, C5.0, random forests, Boosted regression trees etc.) identify homogeneous areas in your data and assign the mean value of the data contained in that region to the corresponding 'leave'. So, they are granular and then, they must show a series of steps in the outputs. Those based on 'forests' do not show that phenomenon pronouncedly but it is still there. The aggregation of a large number of trees nuances it. When a given value is outside the original range the datum is assigned to the ‘leave’ that includes the extreme condition found in the training dataset and the output is consequently the mean value of the values contained in that leave. Thus, no extrapolation is possible.
By the way ANNs are poor extrapolators. You can check: Pichaid Varoonchotikul - Flood Forecasting using Artificial Neural and Hettiarachchi et al. The extrapolation of artificial neural networks for the modelling of rainfall—runoff relationships they are very illustrative and are easy to find in the net!
Good luck! | Can Tree-based regression perform worse than plain linear regression? | Any decision-tree based approach (CART, C5.0, random forests, Boosted regression trees etc.) identify homogeneous areas in your data and assign the mean value of the data contained in that region to t | Can Tree-based regression perform worse than plain linear regression?
Any decision-tree based approach (CART, C5.0, random forests, Boosted regression trees etc.) identify homogeneous areas in your data and assign the mean value of the data contained in that region to the corresponding 'leave'. So, they are granular and then, they must show a series of steps in the outputs. Those based on 'forests' do not show that phenomenon pronouncedly but it is still there. The aggregation of a large number of trees nuances it. When a given value is outside the original range the datum is assigned to the ‘leave’ that includes the extreme condition found in the training dataset and the output is consequently the mean value of the values contained in that leave. Thus, no extrapolation is possible.
By the way ANNs are poor extrapolators. You can check: Pichaid Varoonchotikul - Flood Forecasting using Artificial Neural and Hettiarachchi et al. The extrapolation of artificial neural networks for the modelling of rainfall—runoff relationships they are very illustrative and are easy to find in the net!
Good luck! | Can Tree-based regression perform worse than plain linear regression?
Any decision-tree based approach (CART, C5.0, random forests, Boosted regression trees etc.) identify homogeneous areas in your data and assign the mean value of the data contained in that region to t |
20,929 | Why doesn't runif generate the same result every time? | At heart this is not really just an R question; it relates to random number generation more generally.
"Random" numbers are very important in many parts of statistics. We need the random values we generate to have certain properties, and (usually) a lot of effort goes into constructing random number generators and checking their properties.
The idea is we want to get a sequence of values that are a good proxy for actually random numbers. The usual workhorse of random number generation is the uniform distribution (from that we construct others, like Gaussian random numbers).
So (most typically) a numerical algorithm is used to construct a sequence of integers, each one in terms of some function of previous ones. These integers are then scaled to lie between 0 and 1 (usually $[0,1)$ ).
For example, many just work on the previous one:
$$x_1=f(x_0)\hspace{1cm}z_1=x_1/m\\
x_2=f(x_1)\hspace{1cm}z_2=x_2/m\\
x_3=f(x_2)\hspace{1cm}z_3=x_3/m\\
\vdots$$
... where the $x$'s are integers, the $z$'s are then scaled to be in the unit interval, and $f$ is some often complicated but usually fast function that operates on the bits in its argument to produce a new set of bits that (hopefully) don't seem to be related to any previous values (if we look at them in all manner of ways, even quite carefully -- even though they really are related, since that's how they're made). These have to be constructed carefully to make sure the sequence has a very long cycle and that its values are really uniform and aren't sequentially dependent in any way we might really care about (along with a host of other requirements that are usually regarded as important).
They require a starting ("seed") integer ($x_0$), which you supply (some algorithms may need more than one seed). If you use the same seed again, you get the same sequence (which is handy for being able to reproduce results). But some of the time, you just want some random numbers, and you don't care what the seed is as long as the start point is different from the previous lot you used.
So if you don't supply a seed, many packages can just make one for you. Some packages look at the last few digits on the internal digital clock (usually manipulated in some way). Some (R included) store the last value (the integer $x_3$ above, more generally the term "the state" is used to cover cases where there's more than one number involved) that was generated by the random number generator to use as the next seed if you don't supply one.
See ?runif in R and you'll note that it explains about the existence of the random seed, with a link to the help on that ?.Random.seed which explains the large number of random number generators available in R (you can even supply your own). The same help page explains that if you haven't used random number generation before or set the seed, to begin with the seed is taken from the clock, and thereafter the previous value is stored (so that the next random number you get would be the same one you'd have obtained if you'd generated one more value last time -- it remembers "where you're up to").
The function runif in R (like quite a few other random number generation routines in other packages which can usually do something similar) knows about the place where the random number seed is kept. It keeps updating that value as it goes. So it can operate without having to explicitly be passed a seed, but it still uses one; if you didn't give it one, it just uses the one it saved last.
As for why it gives different outputs each time (if you don't tell it to give the same sequence): it does this because the same values every time would usually be very counter productive -- it wouldn't have the properties that repeated random sampling would have, making it not very useful for the putposes we use random number generators for. | Why doesn't runif generate the same result every time? | At heart this is not really just an R question; it relates to random number generation more generally.
"Random" numbers are very important in many parts of statistics. We need the random values we gen | Why doesn't runif generate the same result every time?
At heart this is not really just an R question; it relates to random number generation more generally.
"Random" numbers are very important in many parts of statistics. We need the random values we generate to have certain properties, and (usually) a lot of effort goes into constructing random number generators and checking their properties.
The idea is we want to get a sequence of values that are a good proxy for actually random numbers. The usual workhorse of random number generation is the uniform distribution (from that we construct others, like Gaussian random numbers).
So (most typically) a numerical algorithm is used to construct a sequence of integers, each one in terms of some function of previous ones. These integers are then scaled to lie between 0 and 1 (usually $[0,1)$ ).
For example, many just work on the previous one:
$$x_1=f(x_0)\hspace{1cm}z_1=x_1/m\\
x_2=f(x_1)\hspace{1cm}z_2=x_2/m\\
x_3=f(x_2)\hspace{1cm}z_3=x_3/m\\
\vdots$$
... where the $x$'s are integers, the $z$'s are then scaled to be in the unit interval, and $f$ is some often complicated but usually fast function that operates on the bits in its argument to produce a new set of bits that (hopefully) don't seem to be related to any previous values (if we look at them in all manner of ways, even quite carefully -- even though they really are related, since that's how they're made). These have to be constructed carefully to make sure the sequence has a very long cycle and that its values are really uniform and aren't sequentially dependent in any way we might really care about (along with a host of other requirements that are usually regarded as important).
They require a starting ("seed") integer ($x_0$), which you supply (some algorithms may need more than one seed). If you use the same seed again, you get the same sequence (which is handy for being able to reproduce results). But some of the time, you just want some random numbers, and you don't care what the seed is as long as the start point is different from the previous lot you used.
So if you don't supply a seed, many packages can just make one for you. Some packages look at the last few digits on the internal digital clock (usually manipulated in some way). Some (R included) store the last value (the integer $x_3$ above, more generally the term "the state" is used to cover cases where there's more than one number involved) that was generated by the random number generator to use as the next seed if you don't supply one.
See ?runif in R and you'll note that it explains about the existence of the random seed, with a link to the help on that ?.Random.seed which explains the large number of random number generators available in R (you can even supply your own). The same help page explains that if you haven't used random number generation before or set the seed, to begin with the seed is taken from the clock, and thereafter the previous value is stored (so that the next random number you get would be the same one you'd have obtained if you'd generated one more value last time -- it remembers "where you're up to").
The function runif in R (like quite a few other random number generation routines in other packages which can usually do something similar) knows about the place where the random number seed is kept. It keeps updating that value as it goes. So it can operate without having to explicitly be passed a seed, but it still uses one; if you didn't give it one, it just uses the one it saved last.
As for why it gives different outputs each time (if you don't tell it to give the same sequence): it does this because the same values every time would usually be very counter productive -- it wouldn't have the properties that repeated random sampling would have, making it not very useful for the putposes we use random number generators for. | Why doesn't runif generate the same result every time?
At heart this is not really just an R question; it relates to random number generation more generally.
"Random" numbers are very important in many parts of statistics. We need the random values we gen |
20,930 | Why doesn't runif generate the same result every time? | You have to set the random seed in order to get the same result each time. Use ?set.seed to do so. Consider:
> runif(1)
[1] 0.6467259
> runif(1)
[1] 0.2101857
> set.seed(1)
> runif(1)
[1] 0.2655087
> set.seed(1)
> runif(1)
[1] 0.2655087
You may be interested in reading this: Reasons for using the set.seed function. | Why doesn't runif generate the same result every time? | You have to set the random seed in order to get the same result each time. Use ?set.seed to do so. Consider:
> runif(1)
[1] 0.6467259
> runif(1)
[1] 0.2101857
> set.seed(1)
> runif(1)
[1] 0.265508 | Why doesn't runif generate the same result every time?
You have to set the random seed in order to get the same result each time. Use ?set.seed to do so. Consider:
> runif(1)
[1] 0.6467259
> runif(1)
[1] 0.2101857
> set.seed(1)
> runif(1)
[1] 0.2655087
> set.seed(1)
> runif(1)
[1] 0.2655087
You may be interested in reading this: Reasons for using the set.seed function. | Why doesn't runif generate the same result every time?
You have to set the random seed in order to get the same result each time. Use ?set.seed to do so. Consider:
> runif(1)
[1] 0.6467259
> runif(1)
[1] 0.2101857
> set.seed(1)
> runif(1)
[1] 0.265508 |
20,931 | Multiple imputation for missing values | One solution is to write your own custom imputation functions for the mice package. The package is prepared for this and the setup surprisingly pain-free.
First we setup the data as suggested:
dat=data.frame(x1=c(21, 50, 31, 15, 36, 82, 14, 14, 19, 18, 16, 36, 583, NA,NA,NA, 50, 52, 26, 24),
x2=c(0, NA, 18,0, 19, 0, NA, 0, 0, 0, 0, 0, 0,NA,NA, NA, 22, NA, 0, 0),
x3=c(0, 0, 0, 0, 0, 54, 0 ,0, 0, 0, 0, 0, 0, NA, NA, NA, NA, 0, 0, 0))
Next we load the micepackage and see what methods it choose by default:
library(mice)
# Do a non-imputation
imp_base <- mice(dat, m=0, maxit = 0)
# Find the methods that mice chooses
imp_base$method
# Returns: "pmm" "pmm" "pmm"
# Look at the imputation matrix
imp_base$predictorMatrix
# Returns:
# x1 x2 x3
#x1 0 1 1
#x2 1 0 1
#x3 1 1 0
The pmm stands for predictive mean matching - probably the most popular imputation algorithm for imputing continuous variables. It calculates the predicted value using a regression model and picks the 5 closest elements to the predicted value (by Euclidean distance). These chosen elements are called the donor pool and the final value is chosen at random from this donor pool.
From the prediction matrix we find that the methods get the variables passed that are of interest for the restrictions. Note that the row is the target variable and the column the predictors. If x1 did not have 1 in the x3 column we would have to add this in the matrix: imp_base$predictorMatrix["x1","x3"] <- 1
Now to the fun part, generating the imputation methods. I've chosen a rather crude method here where I discard all values if they don't meet the criteria. This may result in long loop time and it may potentially be more efficient to keep the valid imputations and only redo the remaining ones, it would require a little more tweaking though.
# Generate our custom methods
mice.impute.pmm_x1 <-
function (y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "",
...)
{
max_sum <- sum(max(x[,"x2"], na.rm=TRUE),
max(x[,"x3"], na.rm=TRUE))
repeat{
vals <- mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05,
version = "", ...)
if (all(vals < max_sum)){
break
}
}
return(vals)
}
mice.impute.pmm_x2 <-
function (y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "",
...)
{
repeat{
vals <- mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05,
version = "", ...)
if (all(vals == 0 | vals >= 14)){
break
}
}
return(vals)
}
mice.impute.pmm_x3 <-
function (y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "",
...)
{
repeat{
vals <- mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05,
version = "", ...)
if (all(vals == 0 | vals >= 16)){
break
}
}
return(vals)
}
Once we are done defining the methods we simple change the previous methods. If you only want to change a single variable then you can simply use imp_base$method["x2"] <- "pmm_x2" but for this example we will change all (the naming is not necessary):
imp_base$method <- c(x1 = "pmm_x1", x2 = "pmm_x2", x3 = "pmm_x3")
# The predictor matrix is not really necessary for this example
# but I use it just to illustrate in case you would like to
# modify it
imp_ds <-
mice(dat,
method = imp_base$method,
predictorMatrix = imp_base$predictorMatrix)
Now let's have a look at the third imputed dataset:
> complete(imp_ds, action = 3)
x1 x2 x3
1 21 0 0
2 50 19 0
3 31 18 0
4 15 0 0
5 36 19 0
6 82 0 54
7 14 0 0
8 14 0 0
9 19 0 0
10 18 0 0
11 16 0 0
12 36 0 0
13 583 0 0
14 50 22 0
15 52 19 0
16 14 0 0
17 50 22 0
18 52 0 0
19 26 0 0
20 24 0 0
Ok, that does the job. I like this solution as you can piggyback on top of mainstream functions and just add the restrictions that you find meaningful.
Update
In order to enforce the rigorous restraints @t0x1n mentioned in the comments, we may want to add the following abilities to the wrapper function:
Save valid values during the loops so that data from previous, partially successful runs is not discarded
An escape mechanism in order to avoid infinite loops
Inflate the donor pool after trying x times without finding a suitable match (this primarily applies to pmm)
This results in a slightly more complicated wrapper function:
mice.impute.pmm_x1_adv <- function (y, ry,
x, donors = 5,
type = 1, ridge = 1e-05,
version = "", ...) {
# The mice:::remove.lindep may remove the parts required for
# the test - in those cases we should escape the test
if (!all(c("x2", "x3") %in% colnames(x))){
warning("Could not enforce pmm_x1 due to missing column(s):",
c("x2", "x3")[!c("x2", "x3") %in% colnames(x)])
return(mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05,
version = "", ...))
}
# Select those missing
max_vals <- rowSums(x[!ry, c("x2", "x3")])
# We will keep saving the valid values in the valid_vals
valid_vals <- rep(NA, length.out = sum(!ry))
# We need a counter in order to avoid an eternal loop
# and for inflating the donor pool if no match is found
cntr <- 0
repeat{
# We should be prepared to increase the donor pool, otherwise
# the criteria may become imposs
donor_inflation <- floor(cntr/10)
vals <- mice.impute.pmm(y, ry, x,
donors = min(5 + donor_inflation, sum(ry)),
type = 1, ridge = 1e-05,
version = "", ...)
# Our criteria check
correct <- vals < max_vals
if (all(!is.na(valid_vals) |
correct)){
valid_vals[correct] <-
vals[correct]
break
}else if (any(is.na(valid_vals) &
correct)){
# Save the new valid values
valid_vals[correct] <-
vals[correct]
}
# An emergency exit to avoid endless loop
cntr <- cntr + 1
if (cntr > 200){
warning("Could not completely enforce constraints for ",
sum(is.na(valid_vals)),
" out of ",
length(valid_vals),
" missing elements")
if (all(is.na(valid_vals))){
valid_vals <- vals
}else{
valid_vals[is.na(valid_vals)] <-
vals[is.na(valid_vals)]
}
break
}
}
return(valid_vals)
}
Note that this does not perform that well, most likely due to that the suggested data set fails the constraints for all cases without missing. I need to increase the loop length to 400-500 before it even starts to behave. I assume that this is unintentional, your imputation should mimic how the actual data is generated.
Optimization
The argument ry contains the non-missing values and we could possibly speed up the loop by removing the elements that we have found eligible imputations, but as I'm unfamiliar with the inner functions I have refrained from this.
I think the most important thing when you have strong constraints that take time to full-fill is to parallelize your imputations (see my answer on CrossValidated). Most have today computers with 4-8 cores and R only uses one of them by default. The time can be (almost) sliced in half by doubling the number of cores.
Missing parameters at imputation
Regarding the problem of x2 being missing at the time of imputation - mice actually never feeds missing values into the x-data.frame. The mice method includes filling in some random value at start. The chain-part of the imputation limits the impact from this initial value. If you look at the mice-function you can find this prior to the imputation call (the mice:::sampler-function):
...
if (method[j] != "") {
for (i in 1:m) {
if (nmis[j] < nrow(data)) {
if (is.null(data.init)) {
imp[[j]][, i] <- mice.impute.sample(y,
ry, ...)
}
else {
imp[[j]][, i] <- data.init[!ry, j]
}
}
else imp[[j]][, i] <- rnorm(nrow(data))
}
}
...
The data.init can be supplied to the mice function and the mice.imput.sample is a basic sampling procedure.
Visiting sequence
If visiting sequence is important you can specify the order in which the mice-function runs the imputations. Default is from 1:ncol(data) but you can set the visitSequence to be anything you like. | Multiple imputation for missing values | One solution is to write your own custom imputation functions for the mice package. The package is prepared for this and the setup surprisingly pain-free.
First we setup the data as suggested:
dat=da | Multiple imputation for missing values
One solution is to write your own custom imputation functions for the mice package. The package is prepared for this and the setup surprisingly pain-free.
First we setup the data as suggested:
dat=data.frame(x1=c(21, 50, 31, 15, 36, 82, 14, 14, 19, 18, 16, 36, 583, NA,NA,NA, 50, 52, 26, 24),
x2=c(0, NA, 18,0, 19, 0, NA, 0, 0, 0, 0, 0, 0,NA,NA, NA, 22, NA, 0, 0),
x3=c(0, 0, 0, 0, 0, 54, 0 ,0, 0, 0, 0, 0, 0, NA, NA, NA, NA, 0, 0, 0))
Next we load the micepackage and see what methods it choose by default:
library(mice)
# Do a non-imputation
imp_base <- mice(dat, m=0, maxit = 0)
# Find the methods that mice chooses
imp_base$method
# Returns: "pmm" "pmm" "pmm"
# Look at the imputation matrix
imp_base$predictorMatrix
# Returns:
# x1 x2 x3
#x1 0 1 1
#x2 1 0 1
#x3 1 1 0
The pmm stands for predictive mean matching - probably the most popular imputation algorithm for imputing continuous variables. It calculates the predicted value using a regression model and picks the 5 closest elements to the predicted value (by Euclidean distance). These chosen elements are called the donor pool and the final value is chosen at random from this donor pool.
From the prediction matrix we find that the methods get the variables passed that are of interest for the restrictions. Note that the row is the target variable and the column the predictors. If x1 did not have 1 in the x3 column we would have to add this in the matrix: imp_base$predictorMatrix["x1","x3"] <- 1
Now to the fun part, generating the imputation methods. I've chosen a rather crude method here where I discard all values if they don't meet the criteria. This may result in long loop time and it may potentially be more efficient to keep the valid imputations and only redo the remaining ones, it would require a little more tweaking though.
# Generate our custom methods
mice.impute.pmm_x1 <-
function (y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "",
...)
{
max_sum <- sum(max(x[,"x2"], na.rm=TRUE),
max(x[,"x3"], na.rm=TRUE))
repeat{
vals <- mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05,
version = "", ...)
if (all(vals < max_sum)){
break
}
}
return(vals)
}
mice.impute.pmm_x2 <-
function (y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "",
...)
{
repeat{
vals <- mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05,
version = "", ...)
if (all(vals == 0 | vals >= 14)){
break
}
}
return(vals)
}
mice.impute.pmm_x3 <-
function (y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "",
...)
{
repeat{
vals <- mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05,
version = "", ...)
if (all(vals == 0 | vals >= 16)){
break
}
}
return(vals)
}
Once we are done defining the methods we simple change the previous methods. If you only want to change a single variable then you can simply use imp_base$method["x2"] <- "pmm_x2" but for this example we will change all (the naming is not necessary):
imp_base$method <- c(x1 = "pmm_x1", x2 = "pmm_x2", x3 = "pmm_x3")
# The predictor matrix is not really necessary for this example
# but I use it just to illustrate in case you would like to
# modify it
imp_ds <-
mice(dat,
method = imp_base$method,
predictorMatrix = imp_base$predictorMatrix)
Now let's have a look at the third imputed dataset:
> complete(imp_ds, action = 3)
x1 x2 x3
1 21 0 0
2 50 19 0
3 31 18 0
4 15 0 0
5 36 19 0
6 82 0 54
7 14 0 0
8 14 0 0
9 19 0 0
10 18 0 0
11 16 0 0
12 36 0 0
13 583 0 0
14 50 22 0
15 52 19 0
16 14 0 0
17 50 22 0
18 52 0 0
19 26 0 0
20 24 0 0
Ok, that does the job. I like this solution as you can piggyback on top of mainstream functions and just add the restrictions that you find meaningful.
Update
In order to enforce the rigorous restraints @t0x1n mentioned in the comments, we may want to add the following abilities to the wrapper function:
Save valid values during the loops so that data from previous, partially successful runs is not discarded
An escape mechanism in order to avoid infinite loops
Inflate the donor pool after trying x times without finding a suitable match (this primarily applies to pmm)
This results in a slightly more complicated wrapper function:
mice.impute.pmm_x1_adv <- function (y, ry,
x, donors = 5,
type = 1, ridge = 1e-05,
version = "", ...) {
# The mice:::remove.lindep may remove the parts required for
# the test - in those cases we should escape the test
if (!all(c("x2", "x3") %in% colnames(x))){
warning("Could not enforce pmm_x1 due to missing column(s):",
c("x2", "x3")[!c("x2", "x3") %in% colnames(x)])
return(mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05,
version = "", ...))
}
# Select those missing
max_vals <- rowSums(x[!ry, c("x2", "x3")])
# We will keep saving the valid values in the valid_vals
valid_vals <- rep(NA, length.out = sum(!ry))
# We need a counter in order to avoid an eternal loop
# and for inflating the donor pool if no match is found
cntr <- 0
repeat{
# We should be prepared to increase the donor pool, otherwise
# the criteria may become imposs
donor_inflation <- floor(cntr/10)
vals <- mice.impute.pmm(y, ry, x,
donors = min(5 + donor_inflation, sum(ry)),
type = 1, ridge = 1e-05,
version = "", ...)
# Our criteria check
correct <- vals < max_vals
if (all(!is.na(valid_vals) |
correct)){
valid_vals[correct] <-
vals[correct]
break
}else if (any(is.na(valid_vals) &
correct)){
# Save the new valid values
valid_vals[correct] <-
vals[correct]
}
# An emergency exit to avoid endless loop
cntr <- cntr + 1
if (cntr > 200){
warning("Could not completely enforce constraints for ",
sum(is.na(valid_vals)),
" out of ",
length(valid_vals),
" missing elements")
if (all(is.na(valid_vals))){
valid_vals <- vals
}else{
valid_vals[is.na(valid_vals)] <-
vals[is.na(valid_vals)]
}
break
}
}
return(valid_vals)
}
Note that this does not perform that well, most likely due to that the suggested data set fails the constraints for all cases without missing. I need to increase the loop length to 400-500 before it even starts to behave. I assume that this is unintentional, your imputation should mimic how the actual data is generated.
Optimization
The argument ry contains the non-missing values and we could possibly speed up the loop by removing the elements that we have found eligible imputations, but as I'm unfamiliar with the inner functions I have refrained from this.
I think the most important thing when you have strong constraints that take time to full-fill is to parallelize your imputations (see my answer on CrossValidated). Most have today computers with 4-8 cores and R only uses one of them by default. The time can be (almost) sliced in half by doubling the number of cores.
Missing parameters at imputation
Regarding the problem of x2 being missing at the time of imputation - mice actually never feeds missing values into the x-data.frame. The mice method includes filling in some random value at start. The chain-part of the imputation limits the impact from this initial value. If you look at the mice-function you can find this prior to the imputation call (the mice:::sampler-function):
...
if (method[j] != "") {
for (i in 1:m) {
if (nmis[j] < nrow(data)) {
if (is.null(data.init)) {
imp[[j]][, i] <- mice.impute.sample(y,
ry, ...)
}
else {
imp[[j]][, i] <- data.init[!ry, j]
}
}
else imp[[j]][, i] <- rnorm(nrow(data))
}
}
...
The data.init can be supplied to the mice function and the mice.imput.sample is a basic sampling procedure.
Visiting sequence
If visiting sequence is important you can specify the order in which the mice-function runs the imputations. Default is from 1:ncol(data) but you can set the visitSequence to be anything you like. | Multiple imputation for missing values
One solution is to write your own custom imputation functions for the mice package. The package is prepared for this and the setup surprisingly pain-free.
First we setup the data as suggested:
dat=da |
20,932 | Multiple imputation for missing values | The closest thing I could find is Amelia's prior information inclusion. See chapter 4.7 in the vignette, specifically 4.7.2:
Observation-level priors
Researchers often have additional prior
information about missing data values based on previous research,
academic consensus, or personal experience. Amelia can incorporate
this information to produce vastly improved imputations. The Amelia
algorithm allows users to include informative Bayesian priors about
individual missing data cells instead of the more general model
parameters, many of which have little direct meaning.
The
incorporation of priors follows basic Bayesian analysis where the
imputation turns out to be a weighted average of the model-based
imputation and the prior mean, where the weights are functions of the
relative strength of the data and prior: when the model predicts very
well, the imputation will down-weight the prior, and vice versa
(Honaker and King, 2010).
The priors about individual observations
should describe the analyst's belief about the distribution of the
missing data cell. This can either take the form of a mean and a
standard deviation or a condence interval. For instance, we might
know that 1986 tari rates in Thailand around 40%, but we have some
uncertainty as to the exact value. Our prior belief about the
distribution of the missing data cell, then, centers on 40 with a
standard deviation that re ects the amount of uncertainty we have
about our prior belief.
To input priors you must build a priors matrix
with either four or five columns. Each row of the matrix represents a
prior on either one observation or one variable. In any row, the entry
in the rst column is the row of the observation and the entry is the
second column is the column of the observation. In the four column
priors matrix the third and fourth columns are the mean and standard
deviation of the prior distribution of the missing value.
So while you won't be able to generally say something like x1<x2+x3, you could loop over your data set and add an observation-level prior for each relevant case. Constant bounds can also be applied (such as setting x1, x2, and x3 to be non-negative). For example:
priors = matrix(NA, nrow=0, ncol=5);
for (i in seq(1, length(data)))
{
x1 = data$x1[i];
x2 = data$x2[i];
x3 = data$x3[i];
if (is.na(x1) && !is.na(x2) && !is.na(x3))
{
priors = rbind(priors, c(i, 1, 0, x2+x3, 0.999999))
}
}
amelia(data, m=1, bound = rbind(c(1, 0, Inf), c(2, 0, Inf), c(3, 0, Inf)), pr = priors); | Multiple imputation for missing values | The closest thing I could find is Amelia's prior information inclusion. See chapter 4.7 in the vignette, specifically 4.7.2:
Observation-level priors
Researchers often have additional prior
inform | Multiple imputation for missing values
The closest thing I could find is Amelia's prior information inclusion. See chapter 4.7 in the vignette, specifically 4.7.2:
Observation-level priors
Researchers often have additional prior
information about missing data values based on previous research,
academic consensus, or personal experience. Amelia can incorporate
this information to produce vastly improved imputations. The Amelia
algorithm allows users to include informative Bayesian priors about
individual missing data cells instead of the more general model
parameters, many of which have little direct meaning.
The
incorporation of priors follows basic Bayesian analysis where the
imputation turns out to be a weighted average of the model-based
imputation and the prior mean, where the weights are functions of the
relative strength of the data and prior: when the model predicts very
well, the imputation will down-weight the prior, and vice versa
(Honaker and King, 2010).
The priors about individual observations
should describe the analyst's belief about the distribution of the
missing data cell. This can either take the form of a mean and a
standard deviation or a condence interval. For instance, we might
know that 1986 tari rates in Thailand around 40%, but we have some
uncertainty as to the exact value. Our prior belief about the
distribution of the missing data cell, then, centers on 40 with a
standard deviation that re ects the amount of uncertainty we have
about our prior belief.
To input priors you must build a priors matrix
with either four or five columns. Each row of the matrix represents a
prior on either one observation or one variable. In any row, the entry
in the rst column is the row of the observation and the entry is the
second column is the column of the observation. In the four column
priors matrix the third and fourth columns are the mean and standard
deviation of the prior distribution of the missing value.
So while you won't be able to generally say something like x1<x2+x3, you could loop over your data set and add an observation-level prior for each relevant case. Constant bounds can also be applied (such as setting x1, x2, and x3 to be non-negative). For example:
priors = matrix(NA, nrow=0, ncol=5);
for (i in seq(1, length(data)))
{
x1 = data$x1[i];
x2 = data$x2[i];
x3 = data$x3[i];
if (is.na(x1) && !is.na(x2) && !is.na(x3))
{
priors = rbind(priors, c(i, 1, 0, x2+x3, 0.999999))
}
}
amelia(data, m=1, bound = rbind(c(1, 0, Inf), c(2, 0, Inf), c(3, 0, Inf)), pr = priors); | Multiple imputation for missing values
The closest thing I could find is Amelia's prior information inclusion. See chapter 4.7 in the vignette, specifically 4.7.2:
Observation-level priors
Researchers often have additional prior
inform |
20,933 | Multiple imputation for missing values | Constraints are probably easier to implement in predictive mean matching multiple imputation. This assumes that there is a significant number of observations with non-missing constraining variables that meet the constraints. I'm thinking about implementing this in the R Hmisc package aregImpute function. You may want to check back in a month or so. It will be important to specify the maximum distance from the target that a donor observation can be, because the constraints will push donors further from the ideal unconstrained donor. | Multiple imputation for missing values | Constraints are probably easier to implement in predictive mean matching multiple imputation. This assumes that there is a significant number of observations with non-missing constraining variables t | Multiple imputation for missing values
Constraints are probably easier to implement in predictive mean matching multiple imputation. This assumes that there is a significant number of observations with non-missing constraining variables that meet the constraints. I'm thinking about implementing this in the R Hmisc package aregImpute function. You may want to check back in a month or so. It will be important to specify the maximum distance from the target that a donor observation can be, because the constraints will push donors further from the ideal unconstrained donor. | Multiple imputation for missing values
Constraints are probably easier to implement in predictive mean matching multiple imputation. This assumes that there is a significant number of observations with non-missing constraining variables t |
20,934 | Multiple imputation for missing values | I believe that the Amelia (Amelia II) package currently has the most comprehensive support for specifying data values range constraints. However, the problem is that Amelia assumes that data is multivariate normal.
If in your case the assumption of multivariate normality doesn't apply, you might want to check mice package, which implements multiple imputation (MI) via chained equations. This package doesn't have the assumption of multivariate normality. It also has a function that might be enough for specifying constraints, but I'm not sure to what degree. The function is called squeeze(). You can read about it in the documentation: http://cran.r-project.org/web/packages/mice/mice.pdf. An additional benefit of mice is its flexibility in terms of allowing specification of user-defined imputation functions and wider selection of algorithms. Here's a tutorial on performing MI, using mice: http://www.ats.ucla.edu/stat/r/faq/R_pmm_mi.htm.
As far as I understand, Dr. Harrell's Hmisc package, using the same chained equations (predictive mean matching) approach, probably supports non-normal data (with the exception of normpmm method). Maybe he has already implemented the constraints specification functionality per his answer above. I haven't used aregImpute(), so can't say much more about it (I've used Amelia and mice, but I'm definitely not an expert in statistics, just trying to learn as much as I can).
Finally, you may find interesting the following, a little dated, but still nice, overview of approaches, methods and software for multiple imputation of data with missing values: http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1839993. I'm sure that there are newer overview papers on MI, but that's all I'm aware of at the present time. I hope that this is somewhat helpful. | Multiple imputation for missing values | I believe that the Amelia (Amelia II) package currently has the most comprehensive support for specifying data values range constraints. However, the problem is that Amelia assumes that data is multiv | Multiple imputation for missing values
I believe that the Amelia (Amelia II) package currently has the most comprehensive support for specifying data values range constraints. However, the problem is that Amelia assumes that data is multivariate normal.
If in your case the assumption of multivariate normality doesn't apply, you might want to check mice package, which implements multiple imputation (MI) via chained equations. This package doesn't have the assumption of multivariate normality. It also has a function that might be enough for specifying constraints, but I'm not sure to what degree. The function is called squeeze(). You can read about it in the documentation: http://cran.r-project.org/web/packages/mice/mice.pdf. An additional benefit of mice is its flexibility in terms of allowing specification of user-defined imputation functions and wider selection of algorithms. Here's a tutorial on performing MI, using mice: http://www.ats.ucla.edu/stat/r/faq/R_pmm_mi.htm.
As far as I understand, Dr. Harrell's Hmisc package, using the same chained equations (predictive mean matching) approach, probably supports non-normal data (with the exception of normpmm method). Maybe he has already implemented the constraints specification functionality per his answer above. I haven't used aregImpute(), so can't say much more about it (I've used Amelia and mice, but I'm definitely not an expert in statistics, just trying to learn as much as I can).
Finally, you may find interesting the following, a little dated, but still nice, overview of approaches, methods and software for multiple imputation of data with missing values: http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1839993. I'm sure that there are newer overview papers on MI, but that's all I'm aware of at the present time. I hope that this is somewhat helpful. | Multiple imputation for missing values
I believe that the Amelia (Amelia II) package currently has the most comprehensive support for specifying data values range constraints. However, the problem is that Amelia assumes that data is multiv |
20,935 | Multiple imputation for missing values | If I understand your question correctly, it seems to me that you already know what values the missing variables should take subject to some constraints. I am not very conversant in SPSS but in R I think you can write a function to do that (which shouldn't be too difficult depending on your experience I should say). I don't know of any package that works with such constraints. | Multiple imputation for missing values | If I understand your question correctly, it seems to me that you already know what values the missing variables should take subject to some constraints. I am not very conversant in SPSS but in R I th | Multiple imputation for missing values
If I understand your question correctly, it seems to me that you already know what values the missing variables should take subject to some constraints. I am not very conversant in SPSS but in R I think you can write a function to do that (which shouldn't be too difficult depending on your experience I should say). I don't know of any package that works with such constraints. | Multiple imputation for missing values
If I understand your question correctly, it seems to me that you already know what values the missing variables should take subject to some constraints. I am not very conversant in SPSS but in R I th |
20,936 | How to draw an interaction plot with confidence intervals? | If you're willing to use ggplot, you can try the following code.
With a continuous predictor
library(ggplot2)
gp <- ggplot(data=br, aes(x=tangle, y=gtangles))
gp + geom_point() + stat_smooth(method="lm", fullrange=T) + facet_grid(. ~ up)
for a facetted interaction plot
For a standard interaction plot (like the one produced by interaction.plot()), you just have to remove the facetting.
gp <- ggplot(data=br, aes(x=tangle, y=gtangles, colour=factor(up)))
gp + geom_point() + stat_smooth(method="lm")
With a discrete predictor
Using the ToothGrowth dataset (see help(ToothGrowth)),
ToothGrowth$dose.cat <- factor(ToothGrowth$dose, labels=paste("d", 1:3, sep=""))
df <- with(ToothGrowth , aggregate(len, list(supp=supp, dose=dose.cat), mean))
df$se <- with(ToothGrowth , aggregate(len, list(supp=supp, dose=dose.cat),
function(x) sd(x)/sqrt(10)))[,3]
opar <- theme_update(panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.background = theme_rect(colour = "black"))
gp <- ggplot(df, aes(x=dose, y=x, colour=supp, group=supp))
gp + geom_line(aes(linetype=supp), size=.6) +
geom_point(aes(shape=supp), size=3) +
geom_errorbar(aes(ymax=x+se, ymin=x-se), width=.1)
theme_set(opar) | How to draw an interaction plot with confidence intervals? | If you're willing to use ggplot, you can try the following code.
With a continuous predictor
library(ggplot2)
gp <- ggplot(data=br, aes(x=tangle, y=gtangles))
gp + geom_point() + stat_smooth(method=" | How to draw an interaction plot with confidence intervals?
If you're willing to use ggplot, you can try the following code.
With a continuous predictor
library(ggplot2)
gp <- ggplot(data=br, aes(x=tangle, y=gtangles))
gp + geom_point() + stat_smooth(method="lm", fullrange=T) + facet_grid(. ~ up)
for a facetted interaction plot
For a standard interaction plot (like the one produced by interaction.plot()), you just have to remove the facetting.
gp <- ggplot(data=br, aes(x=tangle, y=gtangles, colour=factor(up)))
gp + geom_point() + stat_smooth(method="lm")
With a discrete predictor
Using the ToothGrowth dataset (see help(ToothGrowth)),
ToothGrowth$dose.cat <- factor(ToothGrowth$dose, labels=paste("d", 1:3, sep=""))
df <- with(ToothGrowth , aggregate(len, list(supp=supp, dose=dose.cat), mean))
df$se <- with(ToothGrowth , aggregate(len, list(supp=supp, dose=dose.cat),
function(x) sd(x)/sqrt(10)))[,3]
opar <- theme_update(panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.background = theme_rect(colour = "black"))
gp <- ggplot(df, aes(x=dose, y=x, colour=supp, group=supp))
gp + geom_line(aes(linetype=supp), size=.6) +
geom_point(aes(shape=supp), size=3) +
geom_errorbar(aes(ymax=x+se, ymin=x-se), width=.1)
theme_set(opar) | How to draw an interaction plot with confidence intervals?
If you're willing to use ggplot, you can try the following code.
With a continuous predictor
library(ggplot2)
gp <- ggplot(data=br, aes(x=tangle, y=gtangles))
gp + geom_point() + stat_smooth(method=" |
20,937 | How to draw an interaction plot with confidence intervals? | There's also Fox and Hong's effects package in R. See the J. Stat. Soft. papers here and here for examples with confidence intervals and generating R code.
It's not quite as pretty as a ggplot solution, but quite a bit more general, and a lifesaver for moderately complex GLMs. | How to draw an interaction plot with confidence intervals? | There's also Fox and Hong's effects package in R. See the J. Stat. Soft. papers here and here for examples with confidence intervals and generating R code.
It's not quite as pretty as a ggplot solu | How to draw an interaction plot with confidence intervals?
There's also Fox and Hong's effects package in R. See the J. Stat. Soft. papers here and here for examples with confidence intervals and generating R code.
It's not quite as pretty as a ggplot solution, but quite a bit more general, and a lifesaver for moderately complex GLMs. | How to draw an interaction plot with confidence intervals?
There's also Fox and Hong's effects package in R. See the J. Stat. Soft. papers here and here for examples with confidence intervals and generating R code.
It's not quite as pretty as a ggplot solu |
20,938 | Validating questionnaires | I will assume that your questionnaire is to be considered as one unidimensional scale (otherwise, Cronbach's alpha doesn't make very much sense). It is worth running an exploratory factor analysis to check for that. It will also allow you to see how items relate to the scale (i.e., through their loadings).
Basic steps for validating your items and your scale should include:
a complete report on the items' basic statistics (range, quartiles, central tendency, ceiling and floor effects if any);
checking the internal consistency as you've done with your alpha (best, give 95% confidence intervals, because it is sample-dependent);
describe you summary measure (e.g., total or mean score, aka scale score) with usual statistics (histogram + density, quantiles etc.);
check your summary responses against specific covariates which are supposed to be related to the construct your are assessing -- this is referred to as known-group validity;
if possible, check your summary responses against known instruments that purport to measure the same construct (concurrent or convergent validity).
If your scale is not unidimensional, these steps have to be done for each subscale, and you could also factor out the correlation matrix of your factors to assess the second-order factor structure (or use structural equation modeling, or confirmatory factor analysis, or whatever you want). You can also assess convergent and discriminant validity by using Multi-trait scaling or Multi-trait multi-method modeling (based on interitem correlations within and between scales), or, again, SEMs.
Then, I would say that Item Response Theory would not help that much unless you are interested in shortening your questionnaire, filtering out some items that show differential item functioning, or use your test in some kind of a computer adaptive test.
In any case, the Rasch model is for binary items. For polytomous ordered items, the most commonly used models are :
the graded response model
the partial credit model
the rating scale model.
Only the latter two are from the Rasch family, and they basically use an adjacent odds formulation, with the idea that subject has to "pass" several thresholds to endorse a given response category. The difference between these two models is that the PCM does not impose that thresholds are equally spaced on the theta (ability, or subject location on the latent trait) scale. The graded response model relies on a cumulative odds formulation. Be aware that these models all suppose that the scale is unidimensional; i.e., there's only one latent trait. There are additional assumptions like, e.g., local independence (i.e., the correlations between responses are explained by variation on the ability scale).
Anyway, you will find a very complete documentation and useful clues to apply psychometric methods in R in volume 20 of the Journal of Statistical Software: Special Volume: Psychometrics in R. Basically, the most interesting R packages that I use in my daily work are: ltm, eRm, psych, psy. Others are referenced on the CRAN task view Psychometrics. Other resources of interest are:
Notes on the use of R for psychology experiments and questionnaires
Using R for psychological research (W. Revelle is actually writing a book on psychometrics in R)
the PsychoR project (it does not focus on IRT and scale development, though).
A good review on the use of FA vs. IRT in scale development can be found in Scale construction and evaluation in practice: A review of factor analysis versus item response theory applications, by ten Holt et al (Psychological Test and Assessment Modeling (2010) 52(3): 272-297). | Validating questionnaires | I will assume that your questionnaire is to be considered as one unidimensional scale (otherwise, Cronbach's alpha doesn't make very much sense). It is worth running an exploratory factor analysis to | Validating questionnaires
I will assume that your questionnaire is to be considered as one unidimensional scale (otherwise, Cronbach's alpha doesn't make very much sense). It is worth running an exploratory factor analysis to check for that. It will also allow you to see how items relate to the scale (i.e., through their loadings).
Basic steps for validating your items and your scale should include:
a complete report on the items' basic statistics (range, quartiles, central tendency, ceiling and floor effects if any);
checking the internal consistency as you've done with your alpha (best, give 95% confidence intervals, because it is sample-dependent);
describe you summary measure (e.g., total or mean score, aka scale score) with usual statistics (histogram + density, quantiles etc.);
check your summary responses against specific covariates which are supposed to be related to the construct your are assessing -- this is referred to as known-group validity;
if possible, check your summary responses against known instruments that purport to measure the same construct (concurrent or convergent validity).
If your scale is not unidimensional, these steps have to be done for each subscale, and you could also factor out the correlation matrix of your factors to assess the second-order factor structure (or use structural equation modeling, or confirmatory factor analysis, or whatever you want). You can also assess convergent and discriminant validity by using Multi-trait scaling or Multi-trait multi-method modeling (based on interitem correlations within and between scales), or, again, SEMs.
Then, I would say that Item Response Theory would not help that much unless you are interested in shortening your questionnaire, filtering out some items that show differential item functioning, or use your test in some kind of a computer adaptive test.
In any case, the Rasch model is for binary items. For polytomous ordered items, the most commonly used models are :
the graded response model
the partial credit model
the rating scale model.
Only the latter two are from the Rasch family, and they basically use an adjacent odds formulation, with the idea that subject has to "pass" several thresholds to endorse a given response category. The difference between these two models is that the PCM does not impose that thresholds are equally spaced on the theta (ability, or subject location on the latent trait) scale. The graded response model relies on a cumulative odds formulation. Be aware that these models all suppose that the scale is unidimensional; i.e., there's only one latent trait. There are additional assumptions like, e.g., local independence (i.e., the correlations between responses are explained by variation on the ability scale).
Anyway, you will find a very complete documentation and useful clues to apply psychometric methods in R in volume 20 of the Journal of Statistical Software: Special Volume: Psychometrics in R. Basically, the most interesting R packages that I use in my daily work are: ltm, eRm, psych, psy. Others are referenced on the CRAN task view Psychometrics. Other resources of interest are:
Notes on the use of R for psychology experiments and questionnaires
Using R for psychological research (W. Revelle is actually writing a book on psychometrics in R)
the PsychoR project (it does not focus on IRT and scale development, though).
A good review on the use of FA vs. IRT in scale development can be found in Scale construction and evaluation in practice: A review of factor analysis versus item response theory applications, by ten Holt et al (Psychological Test and Assessment Modeling (2010) 52(3): 272-297). | Validating questionnaires
I will assume that your questionnaire is to be considered as one unidimensional scale (otherwise, Cronbach's alpha doesn't make very much sense). It is worth running an exploratory factor analysis to |
20,939 | Validating questionnaires | While supporting everything said above, i would suggest that you do the following (in similiar enough order)
Firstly, you should be using R, if not you should start. The following advice is predicated on the use of R.
I'll assume that you have, at this point, calculated the descriptive statistics et al. If not, the psych package has a describe() function which should give you the stats you need.
Install the psych package from CRAN.
Load the psych package.
Use the fa.parallel routine on your data. This should give you a number of factors to retain.
Then, use the VSS(routine). This calculates the MAP criterion which gives you a different (normally) number of factors to retain.
Use a form of factor analysis (not principal components) and an oblique rotation for each number of factors. If your factors do not appear to be correlated after an oblique rotation, switch to orhogonal rotation. This is as an orthogonal structure can be determined from an oblique rotation, but not vice versa.
Extract all the factor solutions between the MAP criterion and the parallel analysis criterion. Determine which of these has the best fit indices and makes the most sense. This is the one you should retain.
On IRT, having used both ltm and eRm, I would suggest starting with eRm. It has better graphics functions for your models, and support for polytomous models is greater. That being said, it only fits Rasch models, and often data from psychological questionnaires do not meet the requirements for them.
Good luck! Psychometrics is a lot of fun, as you will no doubt discover. | Validating questionnaires | While supporting everything said above, i would suggest that you do the following (in similiar enough order)
Firstly, you should be using R, if not you should start. The following advice is predicated | Validating questionnaires
While supporting everything said above, i would suggest that you do the following (in similiar enough order)
Firstly, you should be using R, if not you should start. The following advice is predicated on the use of R.
I'll assume that you have, at this point, calculated the descriptive statistics et al. If not, the psych package has a describe() function which should give you the stats you need.
Install the psych package from CRAN.
Load the psych package.
Use the fa.parallel routine on your data. This should give you a number of factors to retain.
Then, use the VSS(routine). This calculates the MAP criterion which gives you a different (normally) number of factors to retain.
Use a form of factor analysis (not principal components) and an oblique rotation for each number of factors. If your factors do not appear to be correlated after an oblique rotation, switch to orhogonal rotation. This is as an orthogonal structure can be determined from an oblique rotation, but not vice versa.
Extract all the factor solutions between the MAP criterion and the parallel analysis criterion. Determine which of these has the best fit indices and makes the most sense. This is the one you should retain.
On IRT, having used both ltm and eRm, I would suggest starting with eRm. It has better graphics functions for your models, and support for polytomous models is greater. That being said, it only fits Rasch models, and often data from psychological questionnaires do not meet the requirements for them.
Good luck! Psychometrics is a lot of fun, as you will no doubt discover. | Validating questionnaires
While supporting everything said above, i would suggest that you do the following (in similiar enough order)
Firstly, you should be using R, if not you should start. The following advice is predicated |
20,940 | Validating questionnaires | Validating a questionnaire means proving it measures what it's supposed to measure. So I'd say, this is mostly not a statistical question and it cannot be answered without knowing your questionnaire's specific content. Cronbach alpha is not about validity, but about internal consistency, which is somewhat related to reliability (or one can say it is reliability presuming your questions are interchangeable -- but they're not).
So what could you do to validate your questionnaire? You could study which psychological processes give rise to specific pattern of results (e.g. by trying to induce such patterns with experimental manipulations, or using a think-aloud procedure ["protocol analysis", Ericsson & Simon, 1992]). Or compare some contrasting groups (e.g. patients with controls) that should have differing scores. Or correlate it with an external criterion that should be correlated with the trait you're measuring. Or measure the trait by the Psychoscope (TM) and use that as a criterion.
The other answers are more useful in pointing out what you probably can realistically do -- even though most of it is, strictly speaking, not about validity (exc. Chi's references to "known group validity" and external validity).
See also Markus & Borsboom (2013) for a modern approach to validity (this and some other useful refs @Borsboom's homepage). | Validating questionnaires | Validating a questionnaire means proving it measures what it's supposed to measure. So I'd say, this is mostly not a statistical question and it cannot be answered without knowing your questionnaire's | Validating questionnaires
Validating a questionnaire means proving it measures what it's supposed to measure. So I'd say, this is mostly not a statistical question and it cannot be answered without knowing your questionnaire's specific content. Cronbach alpha is not about validity, but about internal consistency, which is somewhat related to reliability (or one can say it is reliability presuming your questions are interchangeable -- but they're not).
So what could you do to validate your questionnaire? You could study which psychological processes give rise to specific pattern of results (e.g. by trying to induce such patterns with experimental manipulations, or using a think-aloud procedure ["protocol analysis", Ericsson & Simon, 1992]). Or compare some contrasting groups (e.g. patients with controls) that should have differing scores. Or correlate it with an external criterion that should be correlated with the trait you're measuring. Or measure the trait by the Psychoscope (TM) and use that as a criterion.
The other answers are more useful in pointing out what you probably can realistically do -- even though most of it is, strictly speaking, not about validity (exc. Chi's references to "known group validity" and external validity).
See also Markus & Borsboom (2013) for a modern approach to validity (this and some other useful refs @Borsboom's homepage). | Validating questionnaires
Validating a questionnaire means proving it measures what it's supposed to measure. So I'd say, this is mostly not a statistical question and it cannot be answered without knowing your questionnaire's |
20,941 | How should one approch Project Euler problem 213 ("Flea Circus")? | You're right; Monte Carlo is impracticable. (In a naive simulation--that is, one that exactly reproduces the problem situation without any simplifications--each iteration would involve 900 flea moves. A crude estimate of the proportion of empty cells is $1/e$, implying the variance of the Monte-Carlo estimate after $N$ such iterations is approximately $1/N 1/e (1 - 1/e) = 0.2325\ldots /N$. To pin down the answer to six decimal places, you would need to estimate it to within 5.E-7 and, to achieve a confidence of 95+% (say), you would have to approximately halve that precision to 2.5E-7. Solving $\sqrt(0.2325/N) \lt 2.5E-7$ gives $N > 4E12$, approximately. That would be around 3.6E15 flea moves, each taking several ticks of a CPU. With one modern CPU available you will need a full year of (highly efficient) computing. And I have somewhat incorrectly and overoptimistically assumed the answer is given as a proportion instead of a count: as a count, it will need three more significant figures, entailing a million fold increase in computation... Can you wait a long time?)
As far as an analytical solution goes, some simplifications are available. (These can be used to shorten a Monte Carlo computation, too.) The expected number of empty cells is the sum of the probabilities of emptiness over all the cells. To find this, you could compute the probability distribution of occupancy numbers of each cell. Those distributions are obtained by summing over the (independent!) contributions from each flea. This reduces your problem to finding the number of paths of length 50 along a 30 by 30 grid between any given pair of cells on that grid (one is the flea's origin and the other is a cell for which you want to calculate the probability of the flea's occupancy). | How should one approch Project Euler problem 213 ("Flea Circus")? | You're right; Monte Carlo is impracticable. (In a naive simulation--that is, one that exactly reproduces the problem situation without any simplifications--each iteration would involve 900 flea moves | How should one approch Project Euler problem 213 ("Flea Circus")?
You're right; Monte Carlo is impracticable. (In a naive simulation--that is, one that exactly reproduces the problem situation without any simplifications--each iteration would involve 900 flea moves. A crude estimate of the proportion of empty cells is $1/e$, implying the variance of the Monte-Carlo estimate after $N$ such iterations is approximately $1/N 1/e (1 - 1/e) = 0.2325\ldots /N$. To pin down the answer to six decimal places, you would need to estimate it to within 5.E-7 and, to achieve a confidence of 95+% (say), you would have to approximately halve that precision to 2.5E-7. Solving $\sqrt(0.2325/N) \lt 2.5E-7$ gives $N > 4E12$, approximately. That would be around 3.6E15 flea moves, each taking several ticks of a CPU. With one modern CPU available you will need a full year of (highly efficient) computing. And I have somewhat incorrectly and overoptimistically assumed the answer is given as a proportion instead of a count: as a count, it will need three more significant figures, entailing a million fold increase in computation... Can you wait a long time?)
As far as an analytical solution goes, some simplifications are available. (These can be used to shorten a Monte Carlo computation, too.) The expected number of empty cells is the sum of the probabilities of emptiness over all the cells. To find this, you could compute the probability distribution of occupancy numbers of each cell. Those distributions are obtained by summing over the (independent!) contributions from each flea. This reduces your problem to finding the number of paths of length 50 along a 30 by 30 grid between any given pair of cells on that grid (one is the flea's origin and the other is a cell for which you want to calculate the probability of the flea's occupancy). | How should one approch Project Euler problem 213 ("Flea Circus")?
You're right; Monte Carlo is impracticable. (In a naive simulation--that is, one that exactly reproduces the problem situation without any simplifications--each iteration would involve 900 flea moves |
20,942 | How should one approch Project Euler problem 213 ("Flea Circus")? | Could you not iterate through the probabilities of occupation of the cells for each flea. That is, flea k is initially in cell (i(k),j(k)) with probability 1. After 1 iteration, he has probability 1/4 in each of the 4 adjacent cells (assuming he's not on an edge or in a corner). Then the next iteration, each of those quarters gets "smeared" in turn. After 50 iterations you have a matrix of occupation probabilities for flea k. Repeat over all 900 fleas (if you take advantage of symmetries this reduces by nearly a factor of 8) and add the probabilities (you don't need to store all of them at once, just the current flea's matrix (hmm, unless you are very clever, you may want an additional working matrix) and the current sum of matrices). It looks to me like there are lots of ways to speed this up here and there.
This involves no simulation at all. However, it does involve quite a lot of computation; it should not be very hard to work out the simulation size required to give the answers to somewhat better than 6 dp accuracy with high probability and figure out which approach will be faster. I expect this approach would beat simulation by some margin. | How should one approch Project Euler problem 213 ("Flea Circus")? | Could you not iterate through the probabilities of occupation of the cells for each flea. That is, flea k is initially in cell (i(k),j(k)) with probability 1. After 1 iteration, he has probability 1/4 | How should one approch Project Euler problem 213 ("Flea Circus")?
Could you not iterate through the probabilities of occupation of the cells for each flea. That is, flea k is initially in cell (i(k),j(k)) with probability 1. After 1 iteration, he has probability 1/4 in each of the 4 adjacent cells (assuming he's not on an edge or in a corner). Then the next iteration, each of those quarters gets "smeared" in turn. After 50 iterations you have a matrix of occupation probabilities for flea k. Repeat over all 900 fleas (if you take advantage of symmetries this reduces by nearly a factor of 8) and add the probabilities (you don't need to store all of them at once, just the current flea's matrix (hmm, unless you are very clever, you may want an additional working matrix) and the current sum of matrices). It looks to me like there are lots of ways to speed this up here and there.
This involves no simulation at all. However, it does involve quite a lot of computation; it should not be very hard to work out the simulation size required to give the answers to somewhat better than 6 dp accuracy with high probability and figure out which approach will be faster. I expect this approach would beat simulation by some margin. | How should one approch Project Euler problem 213 ("Flea Circus")?
Could you not iterate through the probabilities of occupation of the cells for each flea. That is, flea k is initially in cell (i(k),j(k)) with probability 1. After 1 iteration, he has probability 1/4 |
20,943 | How should one approch Project Euler problem 213 ("Flea Circus")? | While I do not object to the practical impossibility (or impracticality) of a Monte Carlo resolution of this problem with a precision of 6 decimal places pointed out by whuber, I would think a resolution with six digits of accuracy can be achieved.
First, following Glen_b, the particles are exchangeable in a stationary regime, hence it is sufficient (as in sufficiency) to monitor the occupancy of the different cells, as this constitutes a Markov process as well. The distribution of the occupancies at the next time step $t+1$ is completed determined by the occupancies at the current time $t$. Writing the transition matrix $K$ is definitely impractical but simulating the transition is straightforward.
Second, as noted by shabbychef, one can follow the occupancy process on the 450 odd (or even) squares, which remains on the odd squares when only considering even times, i.e. the squared Markov matrix $K^2$.
Third, the original problem only considers the frequency of zero occupancies, $\hat{p}_0$, after $50$ Markov transitions. Given that the starting point has a very high value for the stationary probability distribution of the Markov chain $(\mathbf{X}^{(t)})$, and given that focus on a single average across all cells,$$\hat{p}_0=\frac{1}{450}\sum_{i=1}^{450}\mathbb{I}_0(X_i^ {(50)})$$we can consider that the realisation of the chain $(\mathbf{X}^{(t)})$ at time $t=50$ is a realisation from the stationary probability distribution. This brings a major reduction to the computing cost, as we can simulate directly from this stationary distribution $\mathbf{\pi}$, which is a multinomial distribution with probabilities proportional to 2, 3, and 4 on the even corner, other cells on the edge, and inner cells, respectively.
Obviously, the stationary distribution provides directly the expected number of empty cells as
$$\sum_{i=1}^{450} (1-\pi_i)^{450}$$
equal to $166.1069$,
pot=rep(c(rep(c(0,1),15),rep(c(1,0),15)),15)*c(2,
rep(3,28),2,rep(c(3,rep(4,28),3),28),2,rep(3,28),2)
pot=pot/sum(pot)
sum((1-pot)^450)-450
[1] 166.1069
which is quite close to a Monte Carlo approximation of $166.11$ [based on 10⁸ simulations, which took 14 hours on my machine]. But not close enough for 6 decimals.
As commented by whuber, the estimates need to be multiplied by 2 to correctly answer the question, hence a final value of 332.2137, | How should one approch Project Euler problem 213 ("Flea Circus")? | While I do not object to the practical impossibility (or impracticality) of a Monte Carlo resolution of this problem with a precision of 6 decimal places pointed out by whuber, I would think a resolut | How should one approch Project Euler problem 213 ("Flea Circus")?
While I do not object to the practical impossibility (or impracticality) of a Monte Carlo resolution of this problem with a precision of 6 decimal places pointed out by whuber, I would think a resolution with six digits of accuracy can be achieved.
First, following Glen_b, the particles are exchangeable in a stationary regime, hence it is sufficient (as in sufficiency) to monitor the occupancy of the different cells, as this constitutes a Markov process as well. The distribution of the occupancies at the next time step $t+1$ is completed determined by the occupancies at the current time $t$. Writing the transition matrix $K$ is definitely impractical but simulating the transition is straightforward.
Second, as noted by shabbychef, one can follow the occupancy process on the 450 odd (or even) squares, which remains on the odd squares when only considering even times, i.e. the squared Markov matrix $K^2$.
Third, the original problem only considers the frequency of zero occupancies, $\hat{p}_0$, after $50$ Markov transitions. Given that the starting point has a very high value for the stationary probability distribution of the Markov chain $(\mathbf{X}^{(t)})$, and given that focus on a single average across all cells,$$\hat{p}_0=\frac{1}{450}\sum_{i=1}^{450}\mathbb{I}_0(X_i^ {(50)})$$we can consider that the realisation of the chain $(\mathbf{X}^{(t)})$ at time $t=50$ is a realisation from the stationary probability distribution. This brings a major reduction to the computing cost, as we can simulate directly from this stationary distribution $\mathbf{\pi}$, which is a multinomial distribution with probabilities proportional to 2, 3, and 4 on the even corner, other cells on the edge, and inner cells, respectively.
Obviously, the stationary distribution provides directly the expected number of empty cells as
$$\sum_{i=1}^{450} (1-\pi_i)^{450}$$
equal to $166.1069$,
pot=rep(c(rep(c(0,1),15),rep(c(1,0),15)),15)*c(2,
rep(3,28),2,rep(c(3,rep(4,28),3),28),2,rep(3,28),2)
pot=pot/sum(pot)
sum((1-pot)^450)-450
[1] 166.1069
which is quite close to a Monte Carlo approximation of $166.11$ [based on 10⁸ simulations, which took 14 hours on my machine]. But not close enough for 6 decimals.
As commented by whuber, the estimates need to be multiplied by 2 to correctly answer the question, hence a final value of 332.2137, | How should one approch Project Euler problem 213 ("Flea Circus")?
While I do not object to the practical impossibility (or impracticality) of a Monte Carlo resolution of this problem with a precision of 6 decimal places pointed out by whuber, I would think a resolut |
20,944 | How should one approch Project Euler problem 213 ("Flea Circus")? | An analytical approach may be tedious and I have not thought through the intricacies but here is an approach that you may want to consider. Since you are interested in the expected number of cells that are empty after 50 rings you need to define a markov chain over the "No of the fleas in a cell" rather than the position of a flea (See Glen_b's answer which models the position of a flea as a markov chain. As pointed out by Andy in the comments to that answer that approach may not get what you want.)
Specifically, let:
$n_{ij}(t)$ be the number of fleas in a cell in row $i$ and column $j$.
Then the markov chain starts with the following state:
$n_{ij}(0) =1$ for all $i$ and $j$.
Since, fleas move to one of four adjacent cells, the state of a cell changes depending on how many fleas are in the target cell and how many fleas are there in the four adjacent cells and the probability that they will move to that cell. Using this observation, you can write the state transition probabilities for each cell as a function of the state of that cell and the state of the adjacent cells.
If you wish I can expand the answer further but this along with a basic introduction to markov chains should get you started. | How should one approch Project Euler problem 213 ("Flea Circus")? | An analytical approach may be tedious and I have not thought through the intricacies but here is an approach that you may want to consider. Since you are interested in the expected number of cells tha | How should one approch Project Euler problem 213 ("Flea Circus")?
An analytical approach may be tedious and I have not thought through the intricacies but here is an approach that you may want to consider. Since you are interested in the expected number of cells that are empty after 50 rings you need to define a markov chain over the "No of the fleas in a cell" rather than the position of a flea (See Glen_b's answer which models the position of a flea as a markov chain. As pointed out by Andy in the comments to that answer that approach may not get what you want.)
Specifically, let:
$n_{ij}(t)$ be the number of fleas in a cell in row $i$ and column $j$.
Then the markov chain starts with the following state:
$n_{ij}(0) =1$ for all $i$ and $j$.
Since, fleas move to one of four adjacent cells, the state of a cell changes depending on how many fleas are in the target cell and how many fleas are there in the four adjacent cells and the probability that they will move to that cell. Using this observation, you can write the state transition probabilities for each cell as a function of the state of that cell and the state of the adjacent cells.
If you wish I can expand the answer further but this along with a basic introduction to markov chains should get you started. | How should one approch Project Euler problem 213 ("Flea Circus")?
An analytical approach may be tedious and I have not thought through the intricacies but here is an approach that you may want to consider. Since you are interested in the expected number of cells tha |
20,945 | How should one approch Project Euler problem 213 ("Flea Circus")? | if you are going to go the numerical route, a simple observation: the problem appears to be subject to red-black parity (a flea on a red square always moves to a black square, and vice-versa). This can help reduce your problem size by a half (just consider two moves at a time, and only look at fleas on the red squares, say.) | How should one approch Project Euler problem 213 ("Flea Circus")? | if you are going to go the numerical route, a simple observation: the problem appears to be subject to red-black parity (a flea on a red square always moves to a black square, and vice-versa). This ca | How should one approch Project Euler problem 213 ("Flea Circus")?
if you are going to go the numerical route, a simple observation: the problem appears to be subject to red-black parity (a flea on a red square always moves to a black square, and vice-versa). This can help reduce your problem size by a half (just consider two moves at a time, and only look at fleas on the red squares, say.) | How should one approch Project Euler problem 213 ("Flea Circus")?
if you are going to go the numerical route, a simple observation: the problem appears to be subject to red-black parity (a flea on a red square always moves to a black square, and vice-versa). This ca |
20,946 | How should one approch Project Euler problem 213 ("Flea Circus")? | I suspect that some knowledge of discrete-time Markov chains could prove useful. | How should one approch Project Euler problem 213 ("Flea Circus")? | I suspect that some knowledge of discrete-time Markov chains could prove useful. | How should one approch Project Euler problem 213 ("Flea Circus")?
I suspect that some knowledge of discrete-time Markov chains could prove useful. | How should one approch Project Euler problem 213 ("Flea Circus")?
I suspect that some knowledge of discrete-time Markov chains could prove useful. |
20,947 | Not getting 95% coverage for 95% t-distribution CI | Per @whuber's comment, np.std() provides a biased estimate of the sample standard deviation. Fortunately, the function allows you to correct for that by specifying a number of degrees of freedom with the ddof parameter:
s = samples.std(axis=1, ddof=1)
Fixing this gives coverage probabilities that are consistent with the expected 95% CI: (0.9485, 0.9508) | Not getting 95% coverage for 95% t-distribution CI | Per @whuber's comment, np.std() provides a biased estimate of the sample standard deviation. Fortunately, the function allows you to correct for that by specifying a number of degrees of freedom with | Not getting 95% coverage for 95% t-distribution CI
Per @whuber's comment, np.std() provides a biased estimate of the sample standard deviation. Fortunately, the function allows you to correct for that by specifying a number of degrees of freedom with the ddof parameter:
s = samples.std(axis=1, ddof=1)
Fixing this gives coverage probabilities that are consistent with the expected 95% CI: (0.9485, 0.9508) | Not getting 95% coverage for 95% t-distribution CI
Per @whuber's comment, np.std() provides a biased estimate of the sample standard deviation. Fortunately, the function allows you to correct for that by specifying a number of degrees of freedom with |
20,948 | Not getting 95% coverage for 95% t-distribution CI | In R, using $-notation to pick the 95% CI out of t.test output,
I get $0.949 \pm 0.001,$ from 100,000 iterations.
set.seed(2021)
CI = replicate( 10^5, t.test(rnorm(10))$conf.int)
mean(CI[1,] <= 0 & CI[2,] >= 0)
[1] 0.94907
sd(CI[1,]<=0 & CI[2,]>=0)/sqrt(10^5)
[1] 0.0006952454 # aprx 95% margin of simulation error | Not getting 95% coverage for 95% t-distribution CI | In R, using $-notation to pick the 95% CI out of t.test output,
I get $0.949 \pm 0.001,$ from 100,000 iterations.
set.seed(2021)
CI = replicate( 10^5, t.test(rnorm(10))$conf.int)
mean(CI[1,] <= 0 & CI | Not getting 95% coverage for 95% t-distribution CI
In R, using $-notation to pick the 95% CI out of t.test output,
I get $0.949 \pm 0.001,$ from 100,000 iterations.
set.seed(2021)
CI = replicate( 10^5, t.test(rnorm(10))$conf.int)
mean(CI[1,] <= 0 & CI[2,] >= 0)
[1] 0.94907
sd(CI[1,]<=0 & CI[2,]>=0)/sqrt(10^5)
[1] 0.0006952454 # aprx 95% margin of simulation error | Not getting 95% coverage for 95% t-distribution CI
In R, using $-notation to pick the 95% CI out of t.test output,
I get $0.949 \pm 0.001,$ from 100,000 iterations.
set.seed(2021)
CI = replicate( 10^5, t.test(rnorm(10))$conf.int)
mean(CI[1,] <= 0 & CI |
20,949 | Why log-transform to normal distribution for decision trees? | In this case, the salary is the target (dependent variable/outcome) of the decision tree, not one of the features (independent variables/predictors). You are correct that decision trees are insensitive to the scale of the predictors, but since I suspect there are a small number of extremely large salaries, transforming the salaries might improve predictions because loss functions which minimize square error will not be so strongly influenced by these large values. | Why log-transform to normal distribution for decision trees? | In this case, the salary is the target (dependent variable/outcome) of the decision tree, not one of the features (independent variables/predictors). You are correct that decision trees are insensitiv | Why log-transform to normal distribution for decision trees?
In this case, the salary is the target (dependent variable/outcome) of the decision tree, not one of the features (independent variables/predictors). You are correct that decision trees are insensitive to the scale of the predictors, but since I suspect there are a small number of extremely large salaries, transforming the salaries might improve predictions because loss functions which minimize square error will not be so strongly influenced by these large values. | Why log-transform to normal distribution for decision trees?
In this case, the salary is the target (dependent variable/outcome) of the decision tree, not one of the features (independent variables/predictors). You are correct that decision trees are insensitiv |
20,950 | Why log-transform to normal distribution for decision trees? | I downloaded last year's salaries. It is very likely they follow a Pareto distribution. The histogram is shown below.
The pdf of the Pareto distribution is $$\frac{\alpha{x_m}^\alpha}{x^{\alpha+1}}.$$
The scale parameter $x_m$ is \$545,000, the lowest salary last year. I estimated the shape parameter, $\alpha$, as 0.7848238 using MLE. This matters because when $\alpha<2,$ then the distribution has no variance. More properly, its variance is undefined. If any of your variables lacks a mean or a variance, then you cannot use anything that minimizes squared loss.
The distribution of the log of the variables does have a variance and so you can use least squares style methodologies on them. This is actually a serious omission from your textbook. Some things, like the stock market returns which have neither a mean nor a variance, or baseball salaries, which lack a variance will make OLS models meaningless. The log is not, inherently, the best treatment, but it does work.
Taking the log does not give you a bell shape.
This is entirely about being certain that all of your data has a variance. If all of the assumptions for OLS are met, then the underlying distributions do not matter. They can be insane looking, but variance has to be defined everywhere.
EDIT As Therkel pointed out in the comments when $\alpha<1$ then no mean exists either. There is a comment by Cliff AB that I should take up as well. He argues that the distribution is doubly bounded and so a finite variance and mean exist. I would disagree with that as an economist. It is true that there is only so much wealth in the world, but it is also true that we have no idea what it is. Furthermore, that wealth is changing every second of every day as people make individual choices.
The worker who does not pick that one apple reduces wealth if that apple is never picked and reduces available wealth regardless. An apple on a tree has no income value until it picked and processed. This makes the right-hand side constraint stochastic. For the purposes of baseball, the stochastic effect should be considered to be zero.
Baseball, as a percentage of world output, is so miniscule that you could ignore it. The same is true for American football, North American hockey, or for that matter, live stage theater for the whole United States.
The fact that you can model this data with a Pareto distribution means you have no mean or variance if the estimates are valid. If you take the log, you end up with finite variance. If you divide the data by its minimum value and take the logs, you end up with the exponential distribution, which is well enough behaved, but then you get interpretation problems. | Why log-transform to normal distribution for decision trees? | I downloaded last year's salaries. It is very likely they follow a Pareto distribution. The histogram is shown below.
The pdf of the Pareto distribution is $$\frac{\alpha{x_m}^\alpha}{x^{\alpha+1}} | Why log-transform to normal distribution for decision trees?
I downloaded last year's salaries. It is very likely they follow a Pareto distribution. The histogram is shown below.
The pdf of the Pareto distribution is $$\frac{\alpha{x_m}^\alpha}{x^{\alpha+1}}.$$
The scale parameter $x_m$ is \$545,000, the lowest salary last year. I estimated the shape parameter, $\alpha$, as 0.7848238 using MLE. This matters because when $\alpha<2,$ then the distribution has no variance. More properly, its variance is undefined. If any of your variables lacks a mean or a variance, then you cannot use anything that minimizes squared loss.
The distribution of the log of the variables does have a variance and so you can use least squares style methodologies on them. This is actually a serious omission from your textbook. Some things, like the stock market returns which have neither a mean nor a variance, or baseball salaries, which lack a variance will make OLS models meaningless. The log is not, inherently, the best treatment, but it does work.
Taking the log does not give you a bell shape.
This is entirely about being certain that all of your data has a variance. If all of the assumptions for OLS are met, then the underlying distributions do not matter. They can be insane looking, but variance has to be defined everywhere.
EDIT As Therkel pointed out in the comments when $\alpha<1$ then no mean exists either. There is a comment by Cliff AB that I should take up as well. He argues that the distribution is doubly bounded and so a finite variance and mean exist. I would disagree with that as an economist. It is true that there is only so much wealth in the world, but it is also true that we have no idea what it is. Furthermore, that wealth is changing every second of every day as people make individual choices.
The worker who does not pick that one apple reduces wealth if that apple is never picked and reduces available wealth regardless. An apple on a tree has no income value until it picked and processed. This makes the right-hand side constraint stochastic. For the purposes of baseball, the stochastic effect should be considered to be zero.
Baseball, as a percentage of world output, is so miniscule that you could ignore it. The same is true for American football, North American hockey, or for that matter, live stage theater for the whole United States.
The fact that you can model this data with a Pareto distribution means you have no mean or variance if the estimates are valid. If you take the log, you end up with finite variance. If you divide the data by its minimum value and take the logs, you end up with the exponential distribution, which is well enough behaved, but then you get interpretation problems. | Why log-transform to normal distribution for decision trees?
I downloaded last year's salaries. It is very likely they follow a Pareto distribution. The histogram is shown below.
The pdf of the Pareto distribution is $$\frac{\alpha{x_m}^\alpha}{x^{\alpha+1}} |
20,951 | Gradient Ascent vs Gradient Descent in Logistic Regression | https://en.wikipedia.org/wiki/Gradient_descent:
To find a local minimum of a function using gradient descent,
one takes steps proportional to the negative of the gradient (or of
the approximate gradient) of the function at the current point.
If instead one takes steps proportional to the positive of the
gradient, one approaches a local maximum of that function; the
procedure is then known as gradient ascent.
In other words:
gradient descent aims at minimizing some objective function: $\theta_j \leftarrow \theta_j-\alpha \frac{\partial}{\partial \theta_{j}} J(\theta)$
gradient ascent aims at maximizing some objective function: $\theta_j \leftarrow \theta_j+\alpha \frac{\partial}{\partial \theta_{j}} J(\theta)$ | Gradient Ascent vs Gradient Descent in Logistic Regression | https://en.wikipedia.org/wiki/Gradient_descent:
To find a local minimum of a function using gradient descent,
one takes steps proportional to the negative of the gradient (or of
the approximate | Gradient Ascent vs Gradient Descent in Logistic Regression
https://en.wikipedia.org/wiki/Gradient_descent:
To find a local minimum of a function using gradient descent,
one takes steps proportional to the negative of the gradient (or of
the approximate gradient) of the function at the current point.
If instead one takes steps proportional to the positive of the
gradient, one approaches a local maximum of that function; the
procedure is then known as gradient ascent.
In other words:
gradient descent aims at minimizing some objective function: $\theta_j \leftarrow \theta_j-\alpha \frac{\partial}{\partial \theta_{j}} J(\theta)$
gradient ascent aims at maximizing some objective function: $\theta_j \leftarrow \theta_j+\alpha \frac{\partial}{\partial \theta_{j}} J(\theta)$ | Gradient Ascent vs Gradient Descent in Logistic Regression
https://en.wikipedia.org/wiki/Gradient_descent:
To find a local minimum of a function using gradient descent,
one takes steps proportional to the negative of the gradient (or of
the approximate |
20,952 | Gradient Ascent vs Gradient Descent in Logistic Regression | What is a gradient?
It is a derivative of a function at a certain point. Basically, gives the slope of the line at that point. How to calculate this slope geometrically(just consider a 2 D graph and any continuous function)? You draw a tangent at that point crossing x-axis and a perpendicular to the x-axis from that point. It will form a triangle and now calculating slope is easy. Also if this tangent is parallel to x-axis the gradient is 0 and if it is parallel to y-axis the gradient is infinity.
Why use ascent or descent?
If I have a function which is convex then at the bottom the gradient or derivative is 0. Similarly, if we have a concave function at the top gradient or derivative is 0. Why are we interested in 0? This is because it helps us find either the lowest(convex) or highest(concave) value of the function
Now our machine learning has a cost function and they can either be concave or convex. If it is convex we use Gradient Descent and if it is concave we use we use Gradient Ascent. Now there are two cost functions for logistic regression. When we use the convex one we use gradient descent and when we use the concave one we use gradient ascent. Also, note that if I add a minus before a convex function it becomes concave and vice versa. | Gradient Ascent vs Gradient Descent in Logistic Regression | What is a gradient?
It is a derivative of a function at a certain point. Basically, gives the slope of the line at that point. How to calculate this slope geometrically(just consider a 2 D graph and a | Gradient Ascent vs Gradient Descent in Logistic Regression
What is a gradient?
It is a derivative of a function at a certain point. Basically, gives the slope of the line at that point. How to calculate this slope geometrically(just consider a 2 D graph and any continuous function)? You draw a tangent at that point crossing x-axis and a perpendicular to the x-axis from that point. It will form a triangle and now calculating slope is easy. Also if this tangent is parallel to x-axis the gradient is 0 and if it is parallel to y-axis the gradient is infinity.
Why use ascent or descent?
If I have a function which is convex then at the bottom the gradient or derivative is 0. Similarly, if we have a concave function at the top gradient or derivative is 0. Why are we interested in 0? This is because it helps us find either the lowest(convex) or highest(concave) value of the function
Now our machine learning has a cost function and they can either be concave or convex. If it is convex we use Gradient Descent and if it is concave we use we use Gradient Ascent. Now there are two cost functions for logistic regression. When we use the convex one we use gradient descent and when we use the concave one we use gradient ascent. Also, note that if I add a minus before a convex function it becomes concave and vice versa. | Gradient Ascent vs Gradient Descent in Logistic Regression
What is a gradient?
It is a derivative of a function at a certain point. Basically, gives the slope of the line at that point. How to calculate this slope geometrically(just consider a 2 D graph and a |
20,953 | Gradient Ascent vs Gradient Descent in Logistic Regression | @Franck is correct, they are the same thing other than the sign is positive or negative. There is good explanation in the book: | Gradient Ascent vs Gradient Descent in Logistic Regression | @Franck is correct, they are the same thing other than the sign is positive or negative. There is good explanation in the book: | Gradient Ascent vs Gradient Descent in Logistic Regression
@Franck is correct, they are the same thing other than the sign is positive or negative. There is good explanation in the book: | Gradient Ascent vs Gradient Descent in Logistic Regression
@Franck is correct, they are the same thing other than the sign is positive or negative. There is good explanation in the book: |
20,954 | Gradient Ascent vs Gradient Descent in Logistic Regression | If you want to minimize a function, we use Gradient Descent. For eg. in Deep learning we want to minimize the loss hence we use Gradient Descent.
If you want to maximize a function, we use Gradient Ascent. For eg. in Reinforcement Learning - Policy Gradient methods our goal is to maximize the reward function hence we use Gradient Ascent. | Gradient Ascent vs Gradient Descent in Logistic Regression | If you want to minimize a function, we use Gradient Descent. For eg. in Deep learning we want to minimize the loss hence we use Gradient Descent.
If you want to maximize a function, we use Gradient As | Gradient Ascent vs Gradient Descent in Logistic Regression
If you want to minimize a function, we use Gradient Descent. For eg. in Deep learning we want to minimize the loss hence we use Gradient Descent.
If you want to maximize a function, we use Gradient Ascent. For eg. in Reinforcement Learning - Policy Gradient methods our goal is to maximize the reward function hence we use Gradient Ascent. | Gradient Ascent vs Gradient Descent in Logistic Regression
If you want to minimize a function, we use Gradient Descent. For eg. in Deep learning we want to minimize the loss hence we use Gradient Descent.
If you want to maximize a function, we use Gradient As |
20,955 | Is R's glm function useless in a big data / machine learning setting? [duplicate] | The unregularized model is suffering from complete separation because you are trying to predict the dichotomized variable price_c from the continuous variable price from which it is derived.
The regularized model avoids the problem of complete separation by imposing a penalty that keeps the coefficient for the price predictor from going off to $\infty$ or $-\infty$. So it manages to converge fine and work well.
You should remove the continuous price predictor from the design matrix in this toy example.
Edit: As @Erik points out, the continuous price predictor is already removed from the design matrix, which I somehow missed. So the complete separation arises from some other predictor or combination of predictors.
It's also worth adding that, of course, none of these issues have anything to do with the particular implementation of logistic regression in R's glm() function. It is simply about regularized vs. unregularized logistic regression. | Is R's glm function useless in a big data / machine learning setting? [duplicate] | The unregularized model is suffering from complete separation because you are trying to predict the dichotomized variable price_c from the continuous variable price from which it is derived.
The regul | Is R's glm function useless in a big data / machine learning setting? [duplicate]
The unregularized model is suffering from complete separation because you are trying to predict the dichotomized variable price_c from the continuous variable price from which it is derived.
The regularized model avoids the problem of complete separation by imposing a penalty that keeps the coefficient for the price predictor from going off to $\infty$ or $-\infty$. So it manages to converge fine and work well.
You should remove the continuous price predictor from the design matrix in this toy example.
Edit: As @Erik points out, the continuous price predictor is already removed from the design matrix, which I somehow missed. So the complete separation arises from some other predictor or combination of predictors.
It's also worth adding that, of course, none of these issues have anything to do with the particular implementation of logistic regression in R's glm() function. It is simply about regularized vs. unregularized logistic regression. | Is R's glm function useless in a big data / machine learning setting? [duplicate]
The unregularized model is suffering from complete separation because you are trying to predict the dichotomized variable price_c from the continuous variable price from which it is derived.
The regul |
20,956 | Is R's glm function useless in a big data / machine learning setting? [duplicate] | This has nothing to do with glm, you simply created a problem with an artificial perfect separation:
df <- data.frame(x = rnorm(100), y = rnorm(100))
df$y_c = df$y > 0
glm(y_c~., data=df, family=binomial())
Warning messages:
1: glm.fit: algorithm did not converge
2: glm.fit: fitted probabilities numerically 0 or 1 occurred
y is a perfect predictor of y_c. | Is R's glm function useless in a big data / machine learning setting? [duplicate] | This has nothing to do with glm, you simply created a problem with an artificial perfect separation:
df <- data.frame(x = rnorm(100), y = rnorm(100))
df$y_c = df$y > 0
glm(y_c~., data=df, family=bino | Is R's glm function useless in a big data / machine learning setting? [duplicate]
This has nothing to do with glm, you simply created a problem with an artificial perfect separation:
df <- data.frame(x = rnorm(100), y = rnorm(100))
df$y_c = df$y > 0
glm(y_c~., data=df, family=binomial())
Warning messages:
1: glm.fit: algorithm did not converge
2: glm.fit: fitted probabilities numerically 0 or 1 occurred
y is a perfect predictor of y_c. | Is R's glm function useless in a big data / machine learning setting? [duplicate]
This has nothing to do with glm, you simply created a problem with an artificial perfect separation:
df <- data.frame(x = rnorm(100), y = rnorm(100))
df$y_c = df$y > 0
glm(y_c~., data=df, family=bino |
20,957 | How to create ROC curve to assess the performance of regression models? | You can't, really.
A (binary) classification task has a small set of possible outcomes: you either correctly detect/reject something or you don't. The ROC curve measures the trade-off between these (specifically, between the false positive rate and the true positive rate). In this setting, there's no notion of "close-but-not-quite-right", but there is often a "knob" you can turn to increase your true positive rate (at the expense of more false positives too), or vice versa.
Regression typically(*) makes continuous predictions. With so many possible outcomes, it's vanishingly unlikely that the model will make an exact prediction (imagine predicting Amazon's annual sales down to the penny--it's not going to happen). There also isn't a TP/FP trade-off.
Instead, people measure a regression model's performance using a loss function, which describes how good/bad a certain amount of error is. For example, a common loss function is the mean-squared error: $\frac{1}{N}\sum_{i=1}^{i=N} (\textrm{obs}_i - \textrm{pred}_i)^2$. This penalizes large errors a lot, but tolerates smaller errors more.
* In some cases, regression can be converted into a classification problem by adding a decision rule. For example, logistic regression, despite the name, is often used as classifier. The "bare" logistic regression output is the probability that an example (i.e., a feature vector) belongs to the positive class: $P(\textrm{class=+} | \textrm{ data})$.
However, you could use a decision rule to assign that example to a class. The obvious decision rule is to assign it to the more likely class: the positive one if the probability is at least a half, and the negative one otherwise. By varying this decision rule (e.g., an example is in the positive class if $P(\textrm{class}=+) > \{0.25, 0.5, 0.75, \textrm{etc}\}$, you can turn the TP/FP knob and generate an ROC curve.
All that said, for most regression tasks, where you're predicting something continuous, ROC analysis is an odd choice. | How to create ROC curve to assess the performance of regression models? | You can't, really.
A (binary) classification task has a small set of possible outcomes: you either correctly detect/reject something or you don't. The ROC curve measures the trade-off between these ( | How to create ROC curve to assess the performance of regression models?
You can't, really.
A (binary) classification task has a small set of possible outcomes: you either correctly detect/reject something or you don't. The ROC curve measures the trade-off between these (specifically, between the false positive rate and the true positive rate). In this setting, there's no notion of "close-but-not-quite-right", but there is often a "knob" you can turn to increase your true positive rate (at the expense of more false positives too), or vice versa.
Regression typically(*) makes continuous predictions. With so many possible outcomes, it's vanishingly unlikely that the model will make an exact prediction (imagine predicting Amazon's annual sales down to the penny--it's not going to happen). There also isn't a TP/FP trade-off.
Instead, people measure a regression model's performance using a loss function, which describes how good/bad a certain amount of error is. For example, a common loss function is the mean-squared error: $\frac{1}{N}\sum_{i=1}^{i=N} (\textrm{obs}_i - \textrm{pred}_i)^2$. This penalizes large errors a lot, but tolerates smaller errors more.
* In some cases, regression can be converted into a classification problem by adding a decision rule. For example, logistic regression, despite the name, is often used as classifier. The "bare" logistic regression output is the probability that an example (i.e., a feature vector) belongs to the positive class: $P(\textrm{class=+} | \textrm{ data})$.
However, you could use a decision rule to assign that example to a class. The obvious decision rule is to assign it to the more likely class: the positive one if the probability is at least a half, and the negative one otherwise. By varying this decision rule (e.g., an example is in the positive class if $P(\textrm{class}=+) > \{0.25, 0.5, 0.75, \textrm{etc}\}$, you can turn the TP/FP knob and generate an ROC curve.
All that said, for most regression tasks, where you're predicting something continuous, ROC analysis is an odd choice. | How to create ROC curve to assess the performance of regression models?
You can't, really.
A (binary) classification task has a small set of possible outcomes: you either correctly detect/reject something or you don't. The ROC curve measures the trade-off between these ( |
20,958 | How to create ROC curve to assess the performance of regression models? | I haven't enough reputation to make a comment to Matt's comment, that's why I add something via an "answer". Maybe I am wrong, but you can use regression as a classifier, like a logit/probit model, if you have a binary outcome (y variable). Than your "knob", as Matt called it, would be the threshold at which value you choose to see your y* (your continuous prediction of e.g. a linear regression) to be y = 1. Than you can use this threshold for a ROC.
Edit: I agree to the (*) edit of Matt's answer.
Example: There is a continuous variable x and a binary variable y. What you can do is a normal regression of y on x. Then you calculate the predictions of your model dependent on x for each individual, calling these predictions y*. Than you look for a threshold c which does something like
$y_{prediction} = \left\{\begin{matrix} 1\text{ if y*} > c
\\
0\text{ else}
\end{matrix}\right.$
Than you can use this c for a ROC analysis. (Sorry for my bad formatting, it is my first post here) | How to create ROC curve to assess the performance of regression models? | I haven't enough reputation to make a comment to Matt's comment, that's why I add something via an "answer". Maybe I am wrong, but you can use regression as a classifier, like a logit/probit model, if | How to create ROC curve to assess the performance of regression models?
I haven't enough reputation to make a comment to Matt's comment, that's why I add something via an "answer". Maybe I am wrong, but you can use regression as a classifier, like a logit/probit model, if you have a binary outcome (y variable). Than your "knob", as Matt called it, would be the threshold at which value you choose to see your y* (your continuous prediction of e.g. a linear regression) to be y = 1. Than you can use this threshold for a ROC.
Edit: I agree to the (*) edit of Matt's answer.
Example: There is a continuous variable x and a binary variable y. What you can do is a normal regression of y on x. Then you calculate the predictions of your model dependent on x for each individual, calling these predictions y*. Than you look for a threshold c which does something like
$y_{prediction} = \left\{\begin{matrix} 1\text{ if y*} > c
\\
0\text{ else}
\end{matrix}\right.$
Than you can use this c for a ROC analysis. (Sorry for my bad formatting, it is my first post here) | How to create ROC curve to assess the performance of regression models?
I haven't enough reputation to make a comment to Matt's comment, that's why I add something via an "answer". Maybe I am wrong, but you can use regression as a classifier, like a logit/probit model, if |
20,959 | How to create ROC curve to assess the performance of regression models? | As mentioned by others, you cannot compute the AUC for a linear regression model because there are no true or false positives.
However, AUC is concerned with ranking, more specifically the probability that a randomly-chosen positive sample is ranked higher than a randomly-chosen negative sample. Our predictions are of course numerical and can therefore be ranked, the idea of a positive or negative observation doesn't exist but for a randomly selected pair of predictions there will be a clear positive and negative in that one value will be higher than the other, this is also true in our ground truth values (excluding pairs of identical values). Hence each pair of predictions can be evaluated as being ranked correctly/incorrectly by whether or not they are in the same order as observed in the ground truth.
Repeating this for a sufficient number of predictions and taking the mean number of correct evaluations will provide you a "ranking accuracy" analogous to ROC AUC. A ranking accuracy of 1 means that if you were to order your data points by their predicted value they would be in exactly the same order as if you were to order them by their ground truth value. A ranking accuracy of 0 would mean that the two sequences would be exactly opposite. Important to note is that the actual error on the predicted values could be huge and this metric would not necessarily capture that, for example if all of your predictions were exactly 100x their ground truth values you would observe the maximum ranking accuracy of 1.
This ranking approach to evaluating continuous predictions is used by Rendle et al. in BPR: Bayesian Personalized Ranking from Implicit Feedback (2009) [Arxiv] in deriving their optimization criteria. Section 4.1.1 of that paper demonstrates mathematically the analogies between AUC and this approach.
An interesting metric, useful if the final value is not as important as their relative values (such as in recommendation where the intended output is usually an ordered list). | How to create ROC curve to assess the performance of regression models? | As mentioned by others, you cannot compute the AUC for a linear regression model because there are no true or false positives.
However, AUC is concerned with ranking, more specifically the probabilit | How to create ROC curve to assess the performance of regression models?
As mentioned by others, you cannot compute the AUC for a linear regression model because there are no true or false positives.
However, AUC is concerned with ranking, more specifically the probability that a randomly-chosen positive sample is ranked higher than a randomly-chosen negative sample. Our predictions are of course numerical and can therefore be ranked, the idea of a positive or negative observation doesn't exist but for a randomly selected pair of predictions there will be a clear positive and negative in that one value will be higher than the other, this is also true in our ground truth values (excluding pairs of identical values). Hence each pair of predictions can be evaluated as being ranked correctly/incorrectly by whether or not they are in the same order as observed in the ground truth.
Repeating this for a sufficient number of predictions and taking the mean number of correct evaluations will provide you a "ranking accuracy" analogous to ROC AUC. A ranking accuracy of 1 means that if you were to order your data points by their predicted value they would be in exactly the same order as if you were to order them by their ground truth value. A ranking accuracy of 0 would mean that the two sequences would be exactly opposite. Important to note is that the actual error on the predicted values could be huge and this metric would not necessarily capture that, for example if all of your predictions were exactly 100x their ground truth values you would observe the maximum ranking accuracy of 1.
This ranking approach to evaluating continuous predictions is used by Rendle et al. in BPR: Bayesian Personalized Ranking from Implicit Feedback (2009) [Arxiv] in deriving their optimization criteria. Section 4.1.1 of that paper demonstrates mathematically the analogies between AUC and this approach.
An interesting metric, useful if the final value is not as important as their relative values (such as in recommendation where the intended output is usually an ordered list). | How to create ROC curve to assess the performance of regression models?
As mentioned by others, you cannot compute the AUC for a linear regression model because there are no true or false positives.
However, AUC is concerned with ranking, more specifically the probabilit |
20,960 | Is there any statistical reason for diagonal lines in scatterplot on a log scale? [duplicate] | I see that the lines are always at $\log( y ) = a - <log( x )$, e.g. in the lower left panel, proportion of $10^{-4}$ corresponds to population of $10^4$. I think that the population was used when calculating the value.
For example, maybe the census did not record "what is the proportion of Chinese in the neighborhood", but rather "how many Chinese are living in the neighborhood". The answers were $1, 2, 3,\ldots$ etc. And automatically, given population size of $N$, the corresponding values will be $\frac{1}{N}$, $\frac{2}{N},\ldots$ etc. These will correspond to the first lower-left diagonal line, second lower left diagonal line and so forth. | Is there any statistical reason for diagonal lines in scatterplot on a log scale? [duplicate] | I see that the lines are always at $\log( y ) = a - <log( x )$, e.g. in the lower left panel, proportion of $10^{-4}$ corresponds to population of $10^4$. I think that the population was used when ca | Is there any statistical reason for diagonal lines in scatterplot on a log scale? [duplicate]
I see that the lines are always at $\log( y ) = a - <log( x )$, e.g. in the lower left panel, proportion of $10^{-4}$ corresponds to population of $10^4$. I think that the population was used when calculating the value.
For example, maybe the census did not record "what is the proportion of Chinese in the neighborhood", but rather "how many Chinese are living in the neighborhood". The answers were $1, 2, 3,\ldots$ etc. And automatically, given population size of $N$, the corresponding values will be $\frac{1}{N}$, $\frac{2}{N},\ldots$ etc. These will correspond to the first lower-left diagonal line, second lower left diagonal line and so forth. | Is there any statistical reason for diagonal lines in scatterplot on a log scale? [duplicate]
I see that the lines are always at $\log( y ) = a - <log( x )$, e.g. in the lower left panel, proportion of $10^{-4}$ corresponds to population of $10^4$. I think that the population was used when ca |
20,961 | Is there any statistical reason for diagonal lines in scatterplot on a log scale? [duplicate] | It's due to integer effects with low counts for the class membership.
Consider the "Not Filipino" graph at the lower left. Note how the lower left line goes through the point (-3,3). That point would correspond to 1 observation of a Not Filipino out of $10^3$ people in the neighborhood. Note also that for the Chinese graph, the line goes through the same (-3,3), and likewise for the Disabled graph. The lines also go through the (-4,4) point - one observation out of $10^4$ people. If you consider where one observation out of 3,500 people would lie (at (-3.54,3.54)), you can see how the line gets generated.
The next line to the right goes through points that appear to be about 0.3 x-units larger than the first line; this is the line corresponding to two observations of Not Filipinos, or Chinese, or Disabled (log10(2) = 0.3). Since you can't observe between 1 and 2 Not Filipinos, you have a gap between the two lines.
These things happen, I've seen similar myself. | Is there any statistical reason for diagonal lines in scatterplot on a log scale? [duplicate] | It's due to integer effects with low counts for the class membership.
Consider the "Not Filipino" graph at the lower left. Note how the lower left line goes through the point (-3,3). That point wo | Is there any statistical reason for diagonal lines in scatterplot on a log scale? [duplicate]
It's due to integer effects with low counts for the class membership.
Consider the "Not Filipino" graph at the lower left. Note how the lower left line goes through the point (-3,3). That point would correspond to 1 observation of a Not Filipino out of $10^3$ people in the neighborhood. Note also that for the Chinese graph, the line goes through the same (-3,3), and likewise for the Disabled graph. The lines also go through the (-4,4) point - one observation out of $10^4$ people. If you consider where one observation out of 3,500 people would lie (at (-3.54,3.54)), you can see how the line gets generated.
The next line to the right goes through points that appear to be about 0.3 x-units larger than the first line; this is the line corresponding to two observations of Not Filipinos, or Chinese, or Disabled (log10(2) = 0.3). Since you can't observe between 1 and 2 Not Filipinos, you have a gap between the two lines.
These things happen, I've seen similar myself. | Is there any statistical reason for diagonal lines in scatterplot on a log scale? [duplicate]
It's due to integer effects with low counts for the class membership.
Consider the "Not Filipino" graph at the lower left. Note how the lower left line goes through the point (-3,3). That point wo |
20,962 | Lagging over a grouped time series | There are several ways how you can get a lagged variable within a group. First of all you should sort the data, so that in each group the time is sorted accordingly.
First let us create a sample data.frame:
> set.seed(13)
> dt <- data.frame(location = rep(letters[1:2], each = 4), time = rep(1:4, 2), var = rnorm(8))
> dt
location time var
1 a 1 0.5543269
2 a 2 -0.2802719
3 a 3 1.7751634
4 a 4 0.1873201
5 b 1 1.1425261
6 b 2 0.4155261
7 b 3 1.2295066
8 b 4 0.2366797
Define our lag function:
lg <- function(x)c(NA, x[1:(length(x)-1)])
Then the lag of variable within group can be calculated using tapply:
> unlist(tapply(dt$var, dt$location, lg))
a1 a2 a3 a4 b1 b2 b3 b4
NA 0.5543269 -0.2802719 1.7751634 NA 1.1425261 0.4155261 1.2295066
Using ddply from package plyr:
> ddply(dt, ~location, transform, lvar = lg(var))
location time var lvar
1 a 1 -0.1307015 NA
2 a 2 -0.6365957 -0.1307015
3 a 3 -0.6417577 -0.6365957
4 a 4 -1.5191950 -0.6417577
5 b 1 -1.6281638 NA
6 b 2 0.8748671 -1.6281638
7 b 3 -1.3343222 0.8748671
8 b 4 1.5431753 -1.3343222
Speedier version using data.table from package data.table
> ddt <- data.table(dt)
> ddt[,lvar := lg(var), by = c("location")]
location time var lvar
[1,] a 1 -0.1307015 NA
[2,] a 2 -0.6365957 -0.1307015
[3,] a 3 -0.6417577 -0.6365957
[4,] a 4 -1.5191950 -0.6417577
[5,] b 1 -1.6281638 NA
[6,] b 2 0.8748671 -1.6281638
[7,] b 3 -1.3343222 0.8748671
[8,] b 4 1.5431753 -1.3343222
Using lag function from package plm
> pdt <- pdata.frame(dt)
> lag(pdt$var)
a-1 a-2 a-3 a-4 b-1 b-2 b-3 b-4
NA 0.5543269 -0.2802719 1.7751634 NA 1.1425261 0.4155261 1.2295066
Using lag function from package dplyr
> dt %>% group_by(location) %>% mutate(lvar = lag(var))
Source: local data frame [8 x 4]
Groups: location
location time var lvar
1 a 1 0.5543269 NA
2 a 2 -0.2802719 0.5543269
3 a 3 1.7751634 -0.2802719
4 a 4 0.1873201 1.7751634
5 b 1 1.1425261 NA
6 b 2 0.4155261 1.1425261
7 b 3 1.2295066 0.4155261
8 b 4 0.2366797 1.2295066
Last two approaches require conversion from data.frame to another object, although then you do not need to worry about sorting. My personal preference is the last one, which was not available when writing the answer initially.
Update: Changed the data.table code to reflect the developments of the data.table package, pointed out by @Hibernating.
Update 2: Added dplyr example. | Lagging over a grouped time series | There are several ways how you can get a lagged variable within a group. First of all you should sort the data, so that in each group the time is sorted accordingly.
First let us create a sample data | Lagging over a grouped time series
There are several ways how you can get a lagged variable within a group. First of all you should sort the data, so that in each group the time is sorted accordingly.
First let us create a sample data.frame:
> set.seed(13)
> dt <- data.frame(location = rep(letters[1:2], each = 4), time = rep(1:4, 2), var = rnorm(8))
> dt
location time var
1 a 1 0.5543269
2 a 2 -0.2802719
3 a 3 1.7751634
4 a 4 0.1873201
5 b 1 1.1425261
6 b 2 0.4155261
7 b 3 1.2295066
8 b 4 0.2366797
Define our lag function:
lg <- function(x)c(NA, x[1:(length(x)-1)])
Then the lag of variable within group can be calculated using tapply:
> unlist(tapply(dt$var, dt$location, lg))
a1 a2 a3 a4 b1 b2 b3 b4
NA 0.5543269 -0.2802719 1.7751634 NA 1.1425261 0.4155261 1.2295066
Using ddply from package plyr:
> ddply(dt, ~location, transform, lvar = lg(var))
location time var lvar
1 a 1 -0.1307015 NA
2 a 2 -0.6365957 -0.1307015
3 a 3 -0.6417577 -0.6365957
4 a 4 -1.5191950 -0.6417577
5 b 1 -1.6281638 NA
6 b 2 0.8748671 -1.6281638
7 b 3 -1.3343222 0.8748671
8 b 4 1.5431753 -1.3343222
Speedier version using data.table from package data.table
> ddt <- data.table(dt)
> ddt[,lvar := lg(var), by = c("location")]
location time var lvar
[1,] a 1 -0.1307015 NA
[2,] a 2 -0.6365957 -0.1307015
[3,] a 3 -0.6417577 -0.6365957
[4,] a 4 -1.5191950 -0.6417577
[5,] b 1 -1.6281638 NA
[6,] b 2 0.8748671 -1.6281638
[7,] b 3 -1.3343222 0.8748671
[8,] b 4 1.5431753 -1.3343222
Using lag function from package plm
> pdt <- pdata.frame(dt)
> lag(pdt$var)
a-1 a-2 a-3 a-4 b-1 b-2 b-3 b-4
NA 0.5543269 -0.2802719 1.7751634 NA 1.1425261 0.4155261 1.2295066
Using lag function from package dplyr
> dt %>% group_by(location) %>% mutate(lvar = lag(var))
Source: local data frame [8 x 4]
Groups: location
location time var lvar
1 a 1 0.5543269 NA
2 a 2 -0.2802719 0.5543269
3 a 3 1.7751634 -0.2802719
4 a 4 0.1873201 1.7751634
5 b 1 1.1425261 NA
6 b 2 0.4155261 1.1425261
7 b 3 1.2295066 0.4155261
8 b 4 0.2366797 1.2295066
Last two approaches require conversion from data.frame to another object, although then you do not need to worry about sorting. My personal preference is the last one, which was not available when writing the answer initially.
Update: Changed the data.table code to reflect the developments of the data.table package, pointed out by @Hibernating.
Update 2: Added dplyr example. | Lagging over a grouped time series
There are several ways how you can get a lagged variable within a group. First of all you should sort the data, so that in each group the time is sorted accordingly.
First let us create a sample data |
20,963 | Lagging over a grouped time series | @ mpiktas Just to briefly mention two small oversights in version 3 of your answer. Firstly, the phrase "speedier version" has clearly been left in by error. Secondly, the word ":=" has been missed out in the code. Fixing the latter fixes the former :=)
library(data.table);ddt <- data.table(dt)
f0<-function() plyr::ddply(dt,~location,transform,lvar=lg(var))
f1<-function() ddt[,transform(.SD,lvar=lg(var)),by=c("location")]
f2<-function() ddt[,lvar:=lg(var),by=location]
r0<-f0();r1<-f1();r2<-f2();all.equal(r0,r1,r2,check.attributes = FALSE)
boxplot(microbenchmark::microbenchmark(f0(),f1(),f2(),times=1000L)) | Lagging over a grouped time series | @ mpiktas Just to briefly mention two small oversights in version 3 of your answer. Firstly, the phrase "speedier version" has clearly been left in by error. Secondly, the word ":=" has been missed | Lagging over a grouped time series
@ mpiktas Just to briefly mention two small oversights in version 3 of your answer. Firstly, the phrase "speedier version" has clearly been left in by error. Secondly, the word ":=" has been missed out in the code. Fixing the latter fixes the former :=)
library(data.table);ddt <- data.table(dt)
f0<-function() plyr::ddply(dt,~location,transform,lvar=lg(var))
f1<-function() ddt[,transform(.SD,lvar=lg(var)),by=c("location")]
f2<-function() ddt[,lvar:=lg(var),by=location]
r0<-f0();r1<-f1();r2<-f2();all.equal(r0,r1,r2,check.attributes = FALSE)
boxplot(microbenchmark::microbenchmark(f0(),f1(),f2(),times=1000L)) | Lagging over a grouped time series
@ mpiktas Just to briefly mention two small oversights in version 3 of your answer. Firstly, the phrase "speedier version" has clearly been left in by error. Secondly, the word ":=" has been missed |
20,964 | Lagging over a grouped time series | Rather than going through all the tapply and additional steps, here's a faster way:
dt<-data.frame(location=rep(letters[1:2],each=4),time=rep(1:4,2),var=rnorm(8))
lg<-function(x)c(NA,x[1:(length(x)-1)])
dt$lg <- ave(dt$var, dt$location, FUN=lg) | Lagging over a grouped time series | Rather than going through all the tapply and additional steps, here's a faster way:
dt<-data.frame(location=rep(letters[1:2],each=4),time=rep(1:4,2),var=rnorm(8))
lg<-function(x)c(NA,x[1:(length(x)-1) | Lagging over a grouped time series
Rather than going through all the tapply and additional steps, here's a faster way:
dt<-data.frame(location=rep(letters[1:2],each=4),time=rep(1:4,2),var=rnorm(8))
lg<-function(x)c(NA,x[1:(length(x)-1)])
dt$lg <- ave(dt$var, dt$location, FUN=lg) | Lagging over a grouped time series
Rather than going through all the tapply and additional steps, here's a faster way:
dt<-data.frame(location=rep(letters[1:2],each=4),time=rep(1:4,2),var=rnorm(8))
lg<-function(x)c(NA,x[1:(length(x)-1) |
20,965 | Lagging over a grouped time series | With dplyr
dt %>% group_by(location) %>% mutate(lvar=lag(var)) | Lagging over a grouped time series | With dplyr
dt %>% group_by(location) %>% mutate(lvar=lag(var)) | Lagging over a grouped time series
With dplyr
dt %>% group_by(location) %>% mutate(lvar=lag(var)) | Lagging over a grouped time series
With dplyr
dt %>% group_by(location) %>% mutate(lvar=lag(var)) |
20,966 | Lagging over a grouped time series | Just to provide a brief update: The new fastest way to do this in R is with the function flag/L in the collapse package. collapse also supports sequences of lags/leads on vectors, matrices and data frames.
library(collapse)
dt <- data.frame(location = rep(letters[1:2], each = 4), time = rep(1:4, 2), var = rnorm(8))
# Fastest way to append data.frame with lagged variable
settransform(dt, lvar = flag(var, 1, location, time))
dt
location time var lvar
1 a 1 -0.5808824 NA
2 a 2 -0.1606213 -0.5808824
3 a 3 0.6499493 -0.1606213
4 a 4 -0.2126608 0.6499493
5 b 1 -0.5082747 NA
6 b 2 -0.7450488 -0.5082747
7 b 3 -1.5895110 -0.7450488
8 b 4 0.2482062 -1.5895110
# Using plm classes - supported by collapse
pdt <- plm::pdata.frame(dt)
flag(pdt$var)
a-1 a-2 a-3 a-4 b-1 b-2 b-3 b-4
NA -0.5808824 -0.1606213 0.6499493 NA -0.5082747 -0.7450488 -1.5895110
# Using lag operator directly
L(dt, 1, var ~ location, ~ time)
location time L1.var
1 a 1 NA
2 a 2 -0.5808824
3 a 3 -0.1606213
4 a 4 0.6499493
5 b 1 NA
6 b 2 -0.5082747
7 b 3 -0.7450488
8 b 4 -1.5895110
# Benchmark
library(data.table); ddt <- data.table(dt)
f2 <- function() ddt[, lvar:=shift(var), by=location]
f3 <- function() settransform(dt, lvar = flag(var, 1, location, time))
microbenchmark::microbenchmark(data.table = f2(), collapse = f3(), times=1000L)
Unit: microseconds
expr min lq mean median uq max neval cld
data.table 518.539 568.519 788.7076 638.579 779.5935 23060.711 1000 b
collapse 44.179 60.913 100.3122 78.094 104.1990 2941.214 1000 a | Lagging over a grouped time series | Just to provide a brief update: The new fastest way to do this in R is with the function flag/L in the collapse package. collapse also supports sequences of lags/leads on vectors, matrices and data fr | Lagging over a grouped time series
Just to provide a brief update: The new fastest way to do this in R is with the function flag/L in the collapse package. collapse also supports sequences of lags/leads on vectors, matrices and data frames.
library(collapse)
dt <- data.frame(location = rep(letters[1:2], each = 4), time = rep(1:4, 2), var = rnorm(8))
# Fastest way to append data.frame with lagged variable
settransform(dt, lvar = flag(var, 1, location, time))
dt
location time var lvar
1 a 1 -0.5808824 NA
2 a 2 -0.1606213 -0.5808824
3 a 3 0.6499493 -0.1606213
4 a 4 -0.2126608 0.6499493
5 b 1 -0.5082747 NA
6 b 2 -0.7450488 -0.5082747
7 b 3 -1.5895110 -0.7450488
8 b 4 0.2482062 -1.5895110
# Using plm classes - supported by collapse
pdt <- plm::pdata.frame(dt)
flag(pdt$var)
a-1 a-2 a-3 a-4 b-1 b-2 b-3 b-4
NA -0.5808824 -0.1606213 0.6499493 NA -0.5082747 -0.7450488 -1.5895110
# Using lag operator directly
L(dt, 1, var ~ location, ~ time)
location time L1.var
1 a 1 NA
2 a 2 -0.5808824
3 a 3 -0.1606213
4 a 4 0.6499493
5 b 1 NA
6 b 2 -0.5082747
7 b 3 -0.7450488
8 b 4 -1.5895110
# Benchmark
library(data.table); ddt <- data.table(dt)
f2 <- function() ddt[, lvar:=shift(var), by=location]
f3 <- function() settransform(dt, lvar = flag(var, 1, location, time))
microbenchmark::microbenchmark(data.table = f2(), collapse = f3(), times=1000L)
Unit: microseconds
expr min lq mean median uq max neval cld
data.table 518.539 568.519 788.7076 638.579 779.5935 23060.711 1000 b
collapse 44.179 60.913 100.3122 78.094 104.1990 2941.214 1000 a | Lagging over a grouped time series
Just to provide a brief update: The new fastest way to do this in R is with the function flag/L in the collapse package. collapse also supports sequences of lags/leads on vectors, matrices and data fr |
20,967 | Lagging over a grouped time series | You might want to look at the vars package. Sounds like a Vector Autoregression (VAR) is what you may be trying to do. | Lagging over a grouped time series | You might want to look at the vars package. Sounds like a Vector Autoregression (VAR) is what you may be trying to do. | Lagging over a grouped time series
You might want to look at the vars package. Sounds like a Vector Autoregression (VAR) is what you may be trying to do. | Lagging over a grouped time series
You might want to look at the vars package. Sounds like a Vector Autoregression (VAR) is what you may be trying to do. |
20,968 | Lagging over a grouped time series | With DataCombine:
library(DataCombine)
slide(df, Var="observationB", TimeVar="date", GroupVar="location", NewVar="lead.observationB",
slideBy = 1, keepInvalid = FALSE, reminder = FALSE)
Data needs to be sorted as well. Use slideBy=-1 instead for lags. | Lagging over a grouped time series | With DataCombine:
library(DataCombine)
slide(df, Var="observationB", TimeVar="date", GroupVar="location", NewVar="lead.observationB",
slideBy = 1, keepInvalid = FALSE, reminder = FALSE)
Data needs | Lagging over a grouped time series
With DataCombine:
library(DataCombine)
slide(df, Var="observationB", TimeVar="date", GroupVar="location", NewVar="lead.observationB",
slideBy = 1, keepInvalid = FALSE, reminder = FALSE)
Data needs to be sorted as well. Use slideBy=-1 instead for lags. | Lagging over a grouped time series
With DataCombine:
library(DataCombine)
slide(df, Var="observationB", TimeVar="date", GroupVar="location", NewVar="lead.observationB",
slideBy = 1, keepInvalid = FALSE, reminder = FALSE)
Data needs |
20,969 | Is it true that the type of ML model used is irrelevant? | There's a lot of truth in what you say and that's certainly the argument in what some people have branded data centric AI. For a start, a lot of academic research looks at optimizing some measure (e.g. accuracy) on a fixed given dataset (e.g. ImageNet), which kind of makes sense to measure progress in algorithms. However, in practice, instead of tinkering with minute improvements in algorithms it is often better to just get more data (or label in different ways). Similarly, in Kaggle competitions there will often be pretty small differences between well-tuned XGBoost, LightGBM, Random Forrest and certain Neural Network architectures on tabular data (plus you can often squeeze out a bit more by ensembling them), but in practice you might be pretty happy with just using of these (never mind that you could be better by a few decimal points that for many applications might be irrelevant, or at least less important than the model running fast and cheaply).
On the other hand, it is clear that some algorithms are just much better at certain tasks than others. E.g. look at the spread in performance on ImageNet, results got better year by year and e.g. the error rate got halved from 2011 to 2012 when a convolutional neural network got used. You even see a big spread in neural network performance when assessed on a newly created similar test set ranging from below 70% to over 95%. That certainly is a huge difference in performance. Or, if you get a new image classification task and have just 50 to 100 images of some reasonable size (i.e. 100 or more pixels or so in each dimension) from each class, your first thought should really be transfer learning with some kind of neural network (e.g. convolutional NN or some vision transformer) picked based on trading off good performance on ImageNet with feasible size. In contrast, it's pretty unlikely that training a RF, XGBoost, or a neural network from scratch would come anywhere near that approach in performance.
Additionally, let's not forget that often a lot is to be gained by creating the right features (especially in tabular data) or by representing the data in a good way (e.g. it turns out that you can turn audio data into spectrograms and then use neural networks for images on that, and that works pretty well). While, if one misses creating the right features or represents the data in a poor way, even a theoretically good model will struggle. | Is it true that the type of ML model used is irrelevant? | There's a lot of truth in what you say and that's certainly the argument in what some people have branded data centric AI. For a start, a lot of academic research looks at optimizing some measure (e.g | Is it true that the type of ML model used is irrelevant?
There's a lot of truth in what you say and that's certainly the argument in what some people have branded data centric AI. For a start, a lot of academic research looks at optimizing some measure (e.g. accuracy) on a fixed given dataset (e.g. ImageNet), which kind of makes sense to measure progress in algorithms. However, in practice, instead of tinkering with minute improvements in algorithms it is often better to just get more data (or label in different ways). Similarly, in Kaggle competitions there will often be pretty small differences between well-tuned XGBoost, LightGBM, Random Forrest and certain Neural Network architectures on tabular data (plus you can often squeeze out a bit more by ensembling them), but in practice you might be pretty happy with just using of these (never mind that you could be better by a few decimal points that for many applications might be irrelevant, or at least less important than the model running fast and cheaply).
On the other hand, it is clear that some algorithms are just much better at certain tasks than others. E.g. look at the spread in performance on ImageNet, results got better year by year and e.g. the error rate got halved from 2011 to 2012 when a convolutional neural network got used. You even see a big spread in neural network performance when assessed on a newly created similar test set ranging from below 70% to over 95%. That certainly is a huge difference in performance. Or, if you get a new image classification task and have just 50 to 100 images of some reasonable size (i.e. 100 or more pixels or so in each dimension) from each class, your first thought should really be transfer learning with some kind of neural network (e.g. convolutional NN or some vision transformer) picked based on trading off good performance on ImageNet with feasible size. In contrast, it's pretty unlikely that training a RF, XGBoost, or a neural network from scratch would come anywhere near that approach in performance.
Additionally, let's not forget that often a lot is to be gained by creating the right features (especially in tabular data) or by representing the data in a good way (e.g. it turns out that you can turn audio data into spectrograms and then use neural networks for images on that, and that works pretty well). While, if one misses creating the right features or represents the data in a poor way, even a theoretically good model will struggle. | Is it true that the type of ML model used is irrelevant?
There's a lot of truth in what you say and that's certainly the argument in what some people have branded data centric AI. For a start, a lot of academic research looks at optimizing some measure (e.g |
20,970 | Is it true that the type of ML model used is irrelevant? | The idea that "ml model doesn't matter" is brushing a few concepts under the rug.
First and most to the point, there's a fundamental question of how well can you predict your outcome given your features. If your income is "income" and the only feature you have is "subject's height", it doesn't matter what model you use, you just can't predict the outcome well. If you have a high resolution picture and the variable you want to predict is "is the main subject of this picture a cat?", this can be known with very high accuracy, however the relation between inputs and outputs is extremely complex. In the second case, ML model definitely matters.
The idea that "ML model doesn't matter" is an observation that in many (but definitely not all) real world applications of ML, the best way to improve predictions is to get more relevant data, and there's only a minimal amount of improvement you can get from switching the model you are using. So if you have an application in which your ML model is not performing up to requirements, your time is often better spent trying to find more relevant features rather than comparing outcomes of 30 different model choices.
EDIT: It's also worth noting that in your example with MNIST, 98% is actually not very good. Convolutional NN have an error rate of ~0.25%, meaning 1/8 as many errors the Random Forrests you tried. While 98% may seem "good enough", note that for certain applications, such as recognizing whether an object is moving or not for autonomous driving, using a model with a 98% accuracy could lead to hundreds of thousands of deaths if uses by millions of drivers. So the difference between 98% accurate, 99%, 99.9%, etc are all very meaningful differences. | Is it true that the type of ML model used is irrelevant? | The idea that "ml model doesn't matter" is brushing a few concepts under the rug.
First and most to the point, there's a fundamental question of how well can you predict your outcome given your featur | Is it true that the type of ML model used is irrelevant?
The idea that "ml model doesn't matter" is brushing a few concepts under the rug.
First and most to the point, there's a fundamental question of how well can you predict your outcome given your features. If your income is "income" and the only feature you have is "subject's height", it doesn't matter what model you use, you just can't predict the outcome well. If you have a high resolution picture and the variable you want to predict is "is the main subject of this picture a cat?", this can be known with very high accuracy, however the relation between inputs and outputs is extremely complex. In the second case, ML model definitely matters.
The idea that "ML model doesn't matter" is an observation that in many (but definitely not all) real world applications of ML, the best way to improve predictions is to get more relevant data, and there's only a minimal amount of improvement you can get from switching the model you are using. So if you have an application in which your ML model is not performing up to requirements, your time is often better spent trying to find more relevant features rather than comparing outcomes of 30 different model choices.
EDIT: It's also worth noting that in your example with MNIST, 98% is actually not very good. Convolutional NN have an error rate of ~0.25%, meaning 1/8 as many errors the Random Forrests you tried. While 98% may seem "good enough", note that for certain applications, such as recognizing whether an object is moving or not for autonomous driving, using a model with a 98% accuracy could lead to hundreds of thousands of deaths if uses by millions of drivers. So the difference between 98% accurate, 99%, 99.9%, etc are all very meaningful differences. | Is it true that the type of ML model used is irrelevant?
The idea that "ml model doesn't matter" is brushing a few concepts under the rug.
First and most to the point, there's a fundamental question of how well can you predict your outcome given your featur |
20,971 | Is it true that the type of ML model used is irrelevant? | The answer to "Is it true that the type of ML model used is irrelevant?" is most definitely "No". While other answers make a reasonable points e.g. about value of collecting new data vs. selecting between models, I feel there is one point missing. Namely, your observation that "model is irrelevant" is suffering from observation bias: you are training models on MNIST that are known to perform well on this type of data. This may give false impression that the type of model doesn't matter. There will be a large number of algorithms/models that do very poorly on MNIST, try for instance a very simple linear regression and compare that to random forest and neural nets. My intuition (no rigorous evidence) is that certain algorithms also do similarly on certain datasets; I have often observed simple neural nets (MLPs) and Random forests / xgboost to be a case in point. But of course if we had more complex image data then all these methods would do much worse than convolutional NN's, and so on.
Edit: I would advise against adopting the general notion that most problems can just be solved/made progress on by collecting more data. There is a plethora of applied ML problems where improvements in model architecture, optimization etc. can yield large benefits. | Is it true that the type of ML model used is irrelevant? | The answer to "Is it true that the type of ML model used is irrelevant?" is most definitely "No". While other answers make a reasonable points e.g. about value of collecting new data vs. selecting bet | Is it true that the type of ML model used is irrelevant?
The answer to "Is it true that the type of ML model used is irrelevant?" is most definitely "No". While other answers make a reasonable points e.g. about value of collecting new data vs. selecting between models, I feel there is one point missing. Namely, your observation that "model is irrelevant" is suffering from observation bias: you are training models on MNIST that are known to perform well on this type of data. This may give false impression that the type of model doesn't matter. There will be a large number of algorithms/models that do very poorly on MNIST, try for instance a very simple linear regression and compare that to random forest and neural nets. My intuition (no rigorous evidence) is that certain algorithms also do similarly on certain datasets; I have often observed simple neural nets (MLPs) and Random forests / xgboost to be a case in point. But of course if we had more complex image data then all these methods would do much worse than convolutional NN's, and so on.
Edit: I would advise against adopting the general notion that most problems can just be solved/made progress on by collecting more data. There is a plethora of applied ML problems where improvements in model architecture, optimization etc. can yield large benefits. | Is it true that the type of ML model used is irrelevant?
The answer to "Is it true that the type of ML model used is irrelevant?" is most definitely "No". While other answers make a reasonable points e.g. about value of collecting new data vs. selecting bet |
20,972 | Is it true that the type of ML model used is irrelevant? | You should try to improve both your Data and your Model. Each is a critical piece in a real-world ML application, and spending too much time on one vs the other is unwise.
If you like to use open-source Python packages to work efficiently, you can try improving your model with packages like: sklearn, huggingface, timm. Try improving your data with packages like: cleanlab, featuretools, refinery.
Don't forget to utilize your knowledge as well! Improve your model by experimenting with appropriate training techniques you learned in ML class, and improve your data by relying on your domain expertise. | Is it true that the type of ML model used is irrelevant? | You should try to improve both your Data and your Model. Each is a critical piece in a real-world ML application, and spending too much time on one vs the other is unwise.
If you like to use open-sour | Is it true that the type of ML model used is irrelevant?
You should try to improve both your Data and your Model. Each is a critical piece in a real-world ML application, and spending too much time on one vs the other is unwise.
If you like to use open-source Python packages to work efficiently, you can try improving your model with packages like: sklearn, huggingface, timm. Try improving your data with packages like: cleanlab, featuretools, refinery.
Don't forget to utilize your knowledge as well! Improve your model by experimenting with appropriate training techniques you learned in ML class, and improve your data by relying on your domain expertise. | Is it true that the type of ML model used is irrelevant?
You should try to improve both your Data and your Model. Each is a critical piece in a real-world ML application, and spending too much time on one vs the other is unwise.
If you like to use open-sour |
20,973 | Report power if result is statistically significant | Context: I wrote this answer before the OP clarified that they are working with a large dataset, so the study (probably) has sufficient power. In my post I consider the more common case of a small study with a "significant finding". Imagine, for example, that the article under review presents an estimate of 1.25 in a domain where previous studies about related phonemena have reported estimates in the range [0.9, 1.1]. How does the article's author respond to the reviewer's request for a post-hoc estimate of power to detect an effect of size 1.25?
It's hard to argue that it doesn't matter if a study with significant p-value is underpowered. If a study has low power and the null hypothesis is rejected, then the sample statistic is likely to be a biased estimate of the population parameter. Yes, you are lucky to get evidence against the null hypothesis but also likely to be over-optimistic. The reviewer knows this so he asks how much power your study had to detect the effect you detected.
It's not recommended to do post-hoc power estimation. This is a much discussed topic on CV; see references below. In short – if your study was indeed underpowered to detect the true effect size – by doing post-hoc power analysis you compound the issue of overestimating the effect by also overestimating the power. Mathematically, the power at the observed effect is a function of the p-value: if the p-value is small, the post-hoc power is large. It's as if the result is more convincing because the same fact — the null is rejected — gets reported twice.
Okay, so enough bad news. How can you respond to the reviewer? Computing the power retroactively is not meaningful because your study is already done. Instead compute confidence interval(s) for the effect(s) of interest and emphasize estimation, not hypothesis testing. If the power of your study is low, the intervals are wide (as low power means that we can't make precise estimates). If the power of your study is high, the intervals are tight, demonstrating convincingly how much you have learned from your data.
If the reviewer insists on a power calculation, don't compute the power by plugging in the estimated effect for the true effect, aka post-hoc power. Instead do sensitivity power analysis: For example, fix the sample size, the power and the significance level, and determine the range of effect sizes that can be detected. Or fix the sample size and the significance, and plot power as a function of effect size. It will be especially informative to know what the power is for a range of realistic effect sizes.
Daniël Lakens discusses power at great length in Improving Your Statistical Inferences. There is even a section on "What to do if Your Editor Asks for Post-hoc Power?" He has great advice.
References
J. M. Hoenig and D. M. Heisey. The abuse of power. The American Statistician, 55(1):19–24, 2001.
A. Gelman. Don't calculate post-hoc power using observed estimate of effect size. Annals of Surgery, 269(1), 2019.
Do underpowered studies have increased likelihood of false positives?
What is the post-hoc power in my experiment? How to calculate this?
Why is the power of studies that only report significant effects not always 100%?
Post hoc power analysis for a non significant result?
This simulation shows that "significant" estimates from underpowered studies are inflated. A study with little power to detect a small effect has more power to detect a large effect. So if the true effect is small and the null hypothesis of no effect is rejected, the estimated effect tends to be larger than the true one.
I simulate 1000 studies with 50%, so about half of the studies have p-value < 0.05. The sample means from those "significant" studies are mostly to the right of the true mean 0.1, ie. they overestimate the true mean, often by a lot.
library("pwr")
library("tidyverse")
# Choose settings for an underpowered study
mu0 <- 0
mu <- 0.1
sigma <- 1
alpha <- 0.05
power <- 0.5
pwr.t.test(d = (mu - mu0) / sigma, power = power, sig.level = alpha, type = "one.sample")
#>
#> One-sample t test power calculation
#>
#> n = 386.0261
#> d = 0.1
#> sig.level = 0.05
#> power = 0.5
#> alternative = two.sided
# Sample size to achieve 50% power to detect mean 0.1 with a one-sided t-test
n <- 387
# Simulate 1,000 studies with low power
set.seed(123)
reps <- 1000
studies <-
tibble(
study = rep(seq(reps), each = n),
x = rnorm(reps * n, mean = mu, sd = sigma)
)
results <- studies %>%
group_by(
study
) %>%
group_modify(
~ broom::tidy(t.test(.))
)
results %>%
# We are only interested in studies where the null is rejected
filter(
p.value < alpha
) %>%
ggplot(
aes(estimate)
) +
geom_histogram(
bins = 33
) +
geom_vline(
xintercept = mu,
color = "red"
) +
labs(
x = glue::glue("estimate of true effect {mu} in studies with {100*power}% power"),
y = "",
title = "\"Significant\" effect estimates from underpowered studies are inflated"
)
Created on 2022-04-30 by the reprex package (v2.0.1) | Report power if result is statistically significant | Context: I wrote this answer before the OP clarified that they are working with a large dataset, so the study (probably) has sufficient power. In my post I consider the more common case of a small stu | Report power if result is statistically significant
Context: I wrote this answer before the OP clarified that they are working with a large dataset, so the study (probably) has sufficient power. In my post I consider the more common case of a small study with a "significant finding". Imagine, for example, that the article under review presents an estimate of 1.25 in a domain where previous studies about related phonemena have reported estimates in the range [0.9, 1.1]. How does the article's author respond to the reviewer's request for a post-hoc estimate of power to detect an effect of size 1.25?
It's hard to argue that it doesn't matter if a study with significant p-value is underpowered. If a study has low power and the null hypothesis is rejected, then the sample statistic is likely to be a biased estimate of the population parameter. Yes, you are lucky to get evidence against the null hypothesis but also likely to be over-optimistic. The reviewer knows this so he asks how much power your study had to detect the effect you detected.
It's not recommended to do post-hoc power estimation. This is a much discussed topic on CV; see references below. In short – if your study was indeed underpowered to detect the true effect size – by doing post-hoc power analysis you compound the issue of overestimating the effect by also overestimating the power. Mathematically, the power at the observed effect is a function of the p-value: if the p-value is small, the post-hoc power is large. It's as if the result is more convincing because the same fact — the null is rejected — gets reported twice.
Okay, so enough bad news. How can you respond to the reviewer? Computing the power retroactively is not meaningful because your study is already done. Instead compute confidence interval(s) for the effect(s) of interest and emphasize estimation, not hypothesis testing. If the power of your study is low, the intervals are wide (as low power means that we can't make precise estimates). If the power of your study is high, the intervals are tight, demonstrating convincingly how much you have learned from your data.
If the reviewer insists on a power calculation, don't compute the power by plugging in the estimated effect for the true effect, aka post-hoc power. Instead do sensitivity power analysis: For example, fix the sample size, the power and the significance level, and determine the range of effect sizes that can be detected. Or fix the sample size and the significance, and plot power as a function of effect size. It will be especially informative to know what the power is for a range of realistic effect sizes.
Daniël Lakens discusses power at great length in Improving Your Statistical Inferences. There is even a section on "What to do if Your Editor Asks for Post-hoc Power?" He has great advice.
References
J. M. Hoenig and D. M. Heisey. The abuse of power. The American Statistician, 55(1):19–24, 2001.
A. Gelman. Don't calculate post-hoc power using observed estimate of effect size. Annals of Surgery, 269(1), 2019.
Do underpowered studies have increased likelihood of false positives?
What is the post-hoc power in my experiment? How to calculate this?
Why is the power of studies that only report significant effects not always 100%?
Post hoc power analysis for a non significant result?
This simulation shows that "significant" estimates from underpowered studies are inflated. A study with little power to detect a small effect has more power to detect a large effect. So if the true effect is small and the null hypothesis of no effect is rejected, the estimated effect tends to be larger than the true one.
I simulate 1000 studies with 50%, so about half of the studies have p-value < 0.05. The sample means from those "significant" studies are mostly to the right of the true mean 0.1, ie. they overestimate the true mean, often by a lot.
library("pwr")
library("tidyverse")
# Choose settings for an underpowered study
mu0 <- 0
mu <- 0.1
sigma <- 1
alpha <- 0.05
power <- 0.5
pwr.t.test(d = (mu - mu0) / sigma, power = power, sig.level = alpha, type = "one.sample")
#>
#> One-sample t test power calculation
#>
#> n = 386.0261
#> d = 0.1
#> sig.level = 0.05
#> power = 0.5
#> alternative = two.sided
# Sample size to achieve 50% power to detect mean 0.1 with a one-sided t-test
n <- 387
# Simulate 1,000 studies with low power
set.seed(123)
reps <- 1000
studies <-
tibble(
study = rep(seq(reps), each = n),
x = rnorm(reps * n, mean = mu, sd = sigma)
)
results <- studies %>%
group_by(
study
) %>%
group_modify(
~ broom::tidy(t.test(.))
)
results %>%
# We are only interested in studies where the null is rejected
filter(
p.value < alpha
) %>%
ggplot(
aes(estimate)
) +
geom_histogram(
bins = 33
) +
geom_vline(
xintercept = mu,
color = "red"
) +
labs(
x = glue::glue("estimate of true effect {mu} in studies with {100*power}% power"),
y = "",
title = "\"Significant\" effect estimates from underpowered studies are inflated"
)
Created on 2022-04-30 by the reprex package (v2.0.1) | Report power if result is statistically significant
Context: I wrote this answer before the OP clarified that they are working with a large dataset, so the study (probably) has sufficient power. In my post I consider the more common case of a small stu |
20,974 | Report power if result is statistically significant | Roughly speaking, observing a significant result in a test with low power means that the observed result is unlikely both under the null hypothesis and under the alternative. So interpreting such a result as evidence in favor of the alternative hypothesis can be problematic.
Now you can say that this is just a wrong interpretation (rejecting the null hypothesis does not mean accepting the alternative), but if there is no evidence in favor of some alternative it's not clear how to interpret the result.
As an extreme example, suppose that someone tries to reject some arbitrary null hypothesis (for example, that there is global warming) by flipping a coin 5 times. If they are lucky enough and observe 5 heads in a row, they can claim that the result is significant ($p < 0.05$) and therefore they reject the null hypothesis. But clearly claiming that global warming doesn't exist based on coin flips is completely meaningless.
The issue here is that such a test has no power (more precisely , the power of the test is equal it's size) - the distribution of the test statistic is exactly the same under both hypotheses.
Notice that in a Bayesian analysis those issues don't exist - in the above case, for example, the posterior probabilities will just be euqal to the prior probabilities of both hypotheses because the test carries no relevant information whatsoever. This is one example of the sometimes problematic aspects of frequentist quantities. | Report power if result is statistically significant | Roughly speaking, observing a significant result in a test with low power means that the observed result is unlikely both under the null hypothesis and under the alternative. So interpreting such a re | Report power if result is statistically significant
Roughly speaking, observing a significant result in a test with low power means that the observed result is unlikely both under the null hypothesis and under the alternative. So interpreting such a result as evidence in favor of the alternative hypothesis can be problematic.
Now you can say that this is just a wrong interpretation (rejecting the null hypothesis does not mean accepting the alternative), but if there is no evidence in favor of some alternative it's not clear how to interpret the result.
As an extreme example, suppose that someone tries to reject some arbitrary null hypothesis (for example, that there is global warming) by flipping a coin 5 times. If they are lucky enough and observe 5 heads in a row, they can claim that the result is significant ($p < 0.05$) and therefore they reject the null hypothesis. But clearly claiming that global warming doesn't exist based on coin flips is completely meaningless.
The issue here is that such a test has no power (more precisely , the power of the test is equal it's size) - the distribution of the test statistic is exactly the same under both hypotheses.
Notice that in a Bayesian analysis those issues don't exist - in the above case, for example, the posterior probabilities will just be euqal to the prior probabilities of both hypotheses because the test carries no relevant information whatsoever. This is one example of the sometimes problematic aspects of frequentist quantities. | Report power if result is statistically significant
Roughly speaking, observing a significant result in a test with low power means that the observed result is unlikely both under the null hypothesis and under the alternative. So interpreting such a re |
20,975 | Report power if result is statistically significant | The existing answers provide useful information and arguments, but I disagree with them on what I see as the core question: is it useful to do a post hoc power analysis? I would argue that it IS useful - if you are set on using a Null Hypothesis Statistical Testing framework.
It is absolutely crucial that this analysis is not done with the effect size estimated from the study itself. Instead, I would use either (a) the best estimate based on previous studies that have examined this question, or if this isn't possible, (b) the smallest effect size that would be interesting.
What would such an analysis achieve? It would indicate whether the study was appropriately powered to detect a meaningful effect size. If your study was unlikely to detect the expected effect size, it doesn't mean your finding was wrong - but it is reasonable to be sceptical of the robustness of the analysis and inferences.
Why is it important to not use the effect size estimated in the same study? Because as @dipetkov's answer shows, significant effect sizes are inflated in underpowered studies (and are quite likely to be in the opposite direction of the true effect!). Plugging an inflated estimate into a power calculation would be circular and overestimate the study's power.
That said, I agree with the answers pointing you towards thinking of this in a Bayesian framework. This avoids some of the messiness arising as a result of NHST, which can sometimes struggle for coherence as a result of the "p < 0.05 = truth" fallacy with which it is so tightly enmeshed.
In support of these claims, I'll point you to the same Andrew Gelman letter that @dipetkov's answer does, and also to his blog post about it that makes the same point less formally:
https://statmodeling.stat.columbia.edu/2018/09/24/dont-calculate-post-hoc-power-using-observed-estimate-effect-size/
Gelman, A. (2019). Don’t calculate post-hoc power using observed estimate of effect size. Annals of Surgery, 269(1), e9-e10. | Report power if result is statistically significant | The existing answers provide useful information and arguments, but I disagree with them on what I see as the core question: is it useful to do a post hoc power analysis? I would argue that it IS usefu | Report power if result is statistically significant
The existing answers provide useful information and arguments, but I disagree with them on what I see as the core question: is it useful to do a post hoc power analysis? I would argue that it IS useful - if you are set on using a Null Hypothesis Statistical Testing framework.
It is absolutely crucial that this analysis is not done with the effect size estimated from the study itself. Instead, I would use either (a) the best estimate based on previous studies that have examined this question, or if this isn't possible, (b) the smallest effect size that would be interesting.
What would such an analysis achieve? It would indicate whether the study was appropriately powered to detect a meaningful effect size. If your study was unlikely to detect the expected effect size, it doesn't mean your finding was wrong - but it is reasonable to be sceptical of the robustness of the analysis and inferences.
Why is it important to not use the effect size estimated in the same study? Because as @dipetkov's answer shows, significant effect sizes are inflated in underpowered studies (and are quite likely to be in the opposite direction of the true effect!). Plugging an inflated estimate into a power calculation would be circular and overestimate the study's power.
That said, I agree with the answers pointing you towards thinking of this in a Bayesian framework. This avoids some of the messiness arising as a result of NHST, which can sometimes struggle for coherence as a result of the "p < 0.05 = truth" fallacy with which it is so tightly enmeshed.
In support of these claims, I'll point you to the same Andrew Gelman letter that @dipetkov's answer does, and also to his blog post about it that makes the same point less formally:
https://statmodeling.stat.columbia.edu/2018/09/24/dont-calculate-post-hoc-power-using-observed-estimate-effect-size/
Gelman, A. (2019). Don’t calculate post-hoc power using observed estimate of effect size. Annals of Surgery, 269(1), e9-e10. | Report power if result is statistically significant
The existing answers provide useful information and arguments, but I disagree with them on what I see as the core question: is it useful to do a post hoc power analysis? I would argue that it IS usefu |
20,976 | Report power if result is statistically significant | The power of the observed effect is very often equal to a simple relationship with the p-value (and the significance level) since both the p-value and the power are dependent on how many standard deviations the effect size is away from zero effect.
Let's consider this simplistic model in which you have an observation whose likelihood function can be approximated with a normal distribution. Say that the significance level is 5% (or roughly 2 deviations away from zero effect) and we observe an effect with a p-value of 1.24% (or roughly 2.5 deviations away from zero effect) then the power for that observed effect is equal to roughly 69.1% (the probability that the observed effect is more than 2 deviations away from the zero effect given that the true effect is 3 deviations away).
You have a more complex model but often the estimates are approximately equal to a normal distributed variable. | Report power if result is statistically significant | The power of the observed effect is very often equal to a simple relationship with the p-value (and the significance level) since both the p-value and the power are dependent on how many standard devi | Report power if result is statistically significant
The power of the observed effect is very often equal to a simple relationship with the p-value (and the significance level) since both the p-value and the power are dependent on how many standard deviations the effect size is away from zero effect.
Let's consider this simplistic model in which you have an observation whose likelihood function can be approximated with a normal distribution. Say that the significance level is 5% (or roughly 2 deviations away from zero effect) and we observe an effect with a p-value of 1.24% (or roughly 2.5 deviations away from zero effect) then the power for that observed effect is equal to roughly 69.1% (the probability that the observed effect is more than 2 deviations away from the zero effect given that the true effect is 3 deviations away).
You have a more complex model but often the estimates are approximately equal to a normal distributed variable. | Report power if result is statistically significant
The power of the observed effect is very often equal to a simple relationship with the p-value (and the significance level) since both the p-value and the power are dependent on how many standard devi |
20,977 | How simple should a Baseline model be? | Mainly, how to do this is a question of experience. This will also tell you what kind of model is a good candidate for such a baseline. For instance, in time series forecasting, the simplest models, which are actually surprisingly hard to beat, are the historical average of a time series, and the last observation. Note that both models need precisely zero tuning!
An alternative approach would be to pick the simplest model that can at least output some "reasonable" figure. For time series forecasting, the simplest model would be one that always output a flat zero, but that is not "reasonable". So the next most simple would be one of the two above, and either one would be a good start.
Finally, you could also start by time-boxing your entire development effort, then allot the first 5-10% (or whatever is a reasonable number - I would use something closer to 5%, or even 2%, than to 10%) to building this simple benchmark. This allows for a little tuning, but keeps you from over-engineering something that is intended to only be a simple benchmark. | How simple should a Baseline model be? | Mainly, how to do this is a question of experience. This will also tell you what kind of model is a good candidate for such a baseline. For instance, in time series forecasting, the simplest models, w | How simple should a Baseline model be?
Mainly, how to do this is a question of experience. This will also tell you what kind of model is a good candidate for such a baseline. For instance, in time series forecasting, the simplest models, which are actually surprisingly hard to beat, are the historical average of a time series, and the last observation. Note that both models need precisely zero tuning!
An alternative approach would be to pick the simplest model that can at least output some "reasonable" figure. For time series forecasting, the simplest model would be one that always output a flat zero, but that is not "reasonable". So the next most simple would be one of the two above, and either one would be a good start.
Finally, you could also start by time-boxing your entire development effort, then allot the first 5-10% (or whatever is a reasonable number - I would use something closer to 5%, or even 2%, than to 10%) to building this simple benchmark. This allows for a little tuning, but keeps you from over-engineering something that is intended to only be a simple benchmark. | How simple should a Baseline model be?
Mainly, how to do this is a question of experience. This will also tell you what kind of model is a good candidate for such a baseline. For instance, in time series forecasting, the simplest models, w |
20,978 | How simple should a Baseline model be? | You should tune the model if best practice application of that technique demands it. The baseline needs to be competently implemented to be meaningful.
Hyper-parameter tuning can make a very significant difference, sometimes the difference between a state-of-the-art method and an un-competitive one, see e.g.
Anthony Bagnall, Gavin C Cawley "On the use of default parameter settings in the empirical evaluation of classification algorithms" arxiv
Just pick an algorithm you think would not be regarded as a straw man by an experienced practitioner (or reviewer 3 ;o) and apply it competently. Do bear in mind that the better your baseline system, the more eye-catching the results if your proposed method is significantly better.
Caveat lector, Gavin Cawley is my alter-ego. | How simple should a Baseline model be? | You should tune the model if best practice application of that technique demands it. The baseline needs to be competently implemented to be meaningful.
Hyper-parameter tuning can make a very signific | How simple should a Baseline model be?
You should tune the model if best practice application of that technique demands it. The baseline needs to be competently implemented to be meaningful.
Hyper-parameter tuning can make a very significant difference, sometimes the difference between a state-of-the-art method and an un-competitive one, see e.g.
Anthony Bagnall, Gavin C Cawley "On the use of default parameter settings in the empirical evaluation of classification algorithms" arxiv
Just pick an algorithm you think would not be regarded as a straw man by an experienced practitioner (or reviewer 3 ;o) and apply it competently. Do bear in mind that the better your baseline system, the more eye-catching the results if your proposed method is significantly better.
Caveat lector, Gavin Cawley is my alter-ego. | How simple should a Baseline model be?
You should tune the model if best practice application of that technique demands it. The baseline needs to be competently implemented to be meaningful.
Hyper-parameter tuning can make a very signific |
20,979 | How simple should a Baseline model be? | There's multiple type of baseline models:
A first try that you can compare yourself to, to see whether you are even doing anything meaningful, at all. E.g. a super-simple logistic regression linear model, or even just something as simple as predicting the average sale of the last month as the sale for the next day. If you do not beat or even do worse than such a baseline, there is a problem (either you have messed something up, or perhaps there is no useful information for making a prediction). This is mostly a sanity check to protect yourself from wasting a lot of effort without achieving anything even marginally useful.
Very similar to 1, but using an option that many would regard as a basic default choice (e.g. LightGBM with parameters tuned using cross-validation for tabular data, modern convolutional neural network competently trained with suitable image augmentation for image classification etc.) without extra fancy add-ons (e.g. no model stacking of models from different model classes). An experienced person can put something like this together in as little as 1 day or perhaps up to a week (assuming it's a relatively standard use case, depending on the exact details and depending on how much the data/data loading still needs to be optimized etc.).
A comparison baseline that you wish to beat (or at least be close to) to demonstrate that a new method is useful. This would typically be the currently best option (e.g. the system that is currently used in an industry example) / state of the art (for academic publishing purposes). | How simple should a Baseline model be? | There's multiple type of baseline models:
A first try that you can compare yourself to, to see whether you are even doing anything meaningful, at all. E.g. a super-simple logistic regression linear m | How simple should a Baseline model be?
There's multiple type of baseline models:
A first try that you can compare yourself to, to see whether you are even doing anything meaningful, at all. E.g. a super-simple logistic regression linear model, or even just something as simple as predicting the average sale of the last month as the sale for the next day. If you do not beat or even do worse than such a baseline, there is a problem (either you have messed something up, or perhaps there is no useful information for making a prediction). This is mostly a sanity check to protect yourself from wasting a lot of effort without achieving anything even marginally useful.
Very similar to 1, but using an option that many would regard as a basic default choice (e.g. LightGBM with parameters tuned using cross-validation for tabular data, modern convolutional neural network competently trained with suitable image augmentation for image classification etc.) without extra fancy add-ons (e.g. no model stacking of models from different model classes). An experienced person can put something like this together in as little as 1 day or perhaps up to a week (assuming it's a relatively standard use case, depending on the exact details and depending on how much the data/data loading still needs to be optimized etc.).
A comparison baseline that you wish to beat (or at least be close to) to demonstrate that a new method is useful. This would typically be the currently best option (e.g. the system that is currently used in an industry example) / state of the art (for academic publishing purposes). | How simple should a Baseline model be?
There's multiple type of baseline models:
A first try that you can compare yourself to, to see whether you are even doing anything meaningful, at all. E.g. a super-simple logistic regression linear m |
20,980 | How simple should a Baseline model be? | I agree (+1) with the answers by Stephan Kolassa and Dikran Marsupial, but let me add my two cents.
What you need to consider as well is what is your target model. For example, for a classification task logistic regression may be a good benchmark, but if your actual model is logistic regression, you obviously would choose something simpler than that. Usual choice would be a simple model that is known to work for such problems, for example naive forecast for time-series, mentioned by Stephan Kolassa, or LSTM model for NLP task. If you were building a novel state-of-the-art model, you would benchmark against other state-of-the-art models. On another hand, it is always useful to have a trivial benchmark as a sanity check (predict mean, median, the most common value, last value, etc), because there is always risk that your simple benchmark is not good itself. | How simple should a Baseline model be? | I agree (+1) with the answers by Stephan Kolassa and Dikran Marsupial, but let me add my two cents.
What you need to consider as well is what is your target model. For example, for a classification ta | How simple should a Baseline model be?
I agree (+1) with the answers by Stephan Kolassa and Dikran Marsupial, but let me add my two cents.
What you need to consider as well is what is your target model. For example, for a classification task logistic regression may be a good benchmark, but if your actual model is logistic regression, you obviously would choose something simpler than that. Usual choice would be a simple model that is known to work for such problems, for example naive forecast for time-series, mentioned by Stephan Kolassa, or LSTM model for NLP task. If you were building a novel state-of-the-art model, you would benchmark against other state-of-the-art models. On another hand, it is always useful to have a trivial benchmark as a sanity check (predict mean, median, the most common value, last value, etc), because there is always risk that your simple benchmark is not good itself. | How simple should a Baseline model be?
I agree (+1) with the answers by Stephan Kolassa and Dikran Marsupial, but let me add my two cents.
What you need to consider as well is what is your target model. For example, for a classification ta |
20,981 | What is the meaning of double bars and 2 at the bottom in ordinary least squares? | You're talking about the $\ell_2$-norm (Euclidean norm) of the vector ($Xw - y$). If this foreign to you, briefly, the $\ell_p$-norm of a vector $u \in \mathbb{R}^{n}$, is:
$$\|u\|_p = \big(\sum_{i=1}^{n} |u_i|^p\big)^{\frac1p} $$
So in your case $\|u\|_2^2 = (\big(\sum\limits_{i=1}^{n} |u_i|^2\big)^{\frac12})^2 = \sum\limits_{i=1}^{n} u_i^2$ which is consistent with the sum of squared residuals for a linear regression. In the context of regression problems, you'll also see this a lot in mean squared error (MSE) calculations, and in ridge regression.
This is a common norm (among other reasons, it's mathematically convenient), so when it's obvious from the context, you'll see the lower $2$ omitted, and just $\|u\|^2$.
As mentioned in the comments, you may also see the $\ell_1$-norm:
$$\|u\|_1 = \sum_{i=1}^{n} |u_i| $$
Which corresponds to the absolute value. Again, you'll see this in mean absolute error (MAE) or lasso problems.
Other popular norms:
$\ell_0$-norm: Hamming distance, or # of non-zeros in a vector, i.e. in calculating the sparsity of a vector. Technically this isn't a norm (it's a cardinality function), because you have a $\frac{1}{0}$ term in the definition, but it has the form of a norm so we call it one.
This norm is the ideal norm used in inducing sparsity for regression problems since we really want to zero out coefficients, however computing $\ell_0$ regularization is NP-hard, so instead we approximate it with $\ell_1$ which is solvable via linear programming. It's also popular in Compressed Sensing.
$\ell_{\infty}$-norm: = $\underset{i} {\text{max}}$ $\{|x_i|\}$ for $i = 1, ..., n$
$\|A\|_F$: Frobenius (Euclidean) norm, applied to a matrix $A \in \mathbb{R}^{n\times m} = \sqrt{\sum \limits_{i=1}^{n}\sum \limits_{j=1}^{m}|a_{ij}|^2}$ | What is the meaning of double bars and 2 at the bottom in ordinary least squares? | You're talking about the $\ell_2$-norm (Euclidean norm) of the vector ($Xw - y$). If this foreign to you, briefly, the $\ell_p$-norm of a vector $u \in \mathbb{R}^{n}$, is:
$$\|u\|_p = \big(\sum_{i=1} | What is the meaning of double bars and 2 at the bottom in ordinary least squares?
You're talking about the $\ell_2$-norm (Euclidean norm) of the vector ($Xw - y$). If this foreign to you, briefly, the $\ell_p$-norm of a vector $u \in \mathbb{R}^{n}$, is:
$$\|u\|_p = \big(\sum_{i=1}^{n} |u_i|^p\big)^{\frac1p} $$
So in your case $\|u\|_2^2 = (\big(\sum\limits_{i=1}^{n} |u_i|^2\big)^{\frac12})^2 = \sum\limits_{i=1}^{n} u_i^2$ which is consistent with the sum of squared residuals for a linear regression. In the context of regression problems, you'll also see this a lot in mean squared error (MSE) calculations, and in ridge regression.
This is a common norm (among other reasons, it's mathematically convenient), so when it's obvious from the context, you'll see the lower $2$ omitted, and just $\|u\|^2$.
As mentioned in the comments, you may also see the $\ell_1$-norm:
$$\|u\|_1 = \sum_{i=1}^{n} |u_i| $$
Which corresponds to the absolute value. Again, you'll see this in mean absolute error (MAE) or lasso problems.
Other popular norms:
$\ell_0$-norm: Hamming distance, or # of non-zeros in a vector, i.e. in calculating the sparsity of a vector. Technically this isn't a norm (it's a cardinality function), because you have a $\frac{1}{0}$ term in the definition, but it has the form of a norm so we call it one.
This norm is the ideal norm used in inducing sparsity for regression problems since we really want to zero out coefficients, however computing $\ell_0$ regularization is NP-hard, so instead we approximate it with $\ell_1$ which is solvable via linear programming. It's also popular in Compressed Sensing.
$\ell_{\infty}$-norm: = $\underset{i} {\text{max}}$ $\{|x_i|\}$ for $i = 1, ..., n$
$\|A\|_F$: Frobenius (Euclidean) norm, applied to a matrix $A \in \mathbb{R}^{n\times m} = \sqrt{\sum \limits_{i=1}^{n}\sum \limits_{j=1}^{m}|a_{ij}|^2}$ | What is the meaning of double bars and 2 at the bottom in ordinary least squares?
You're talking about the $\ell_2$-norm (Euclidean norm) of the vector ($Xw - y$). If this foreign to you, briefly, the $\ell_p$-norm of a vector $u \in \mathbb{R}^{n}$, is:
$$\|u\|_p = \big(\sum_{i=1} |
20,982 | What areas of mathematical statistics are highly employable? | I'm answering as someone who routinely evaluates and hires data scientists.
As a person transitioning from academic study into a private sector career, you're not going to get hired on the strength of any specific skills you have. The world of academic study in statistics, and the domain of any given company's set of problems are far too vast to hire on the basis of very precisely defined specific skillsets.
Instead, you are going to get hired because you can demonstrate a general aptitude for precise thinking, a thirst and talent for problem solving, an ability to understand and communicate abstract and complex ideas, and a diverse set of practical and theoretical skills.
So, my advice, and I'm just one guy, do what you love and develop a thirst for problem solving, nuance, and complexity. Learn a diverse set of skills, and know your fundamentals well (better than your research topic)
Oh, and learn to program.
That makes a lot of sense, thanks a lot for the thoughtful reply. Are there any particular programming languages you'd recommend
Hard question to answer without being opinionated.
My personal opinion is that it doesn't really matter, so learn the one that you like and that motivates you to keep learning. Learning your first language really well is the big hurdle. After the first learning another (and another, and another) is much, much easier because you have already dealt with the hard conceptual challenges.
But learn the language well, learn how the language works and why it was designed the way it was. Write clean code that you are unafraid to return to. Take writing code as a serious responsibility, not a unfortunate reality. This makes it both more rewarding, and a real skill you can advertise.
If you still want specific advice, I would echo @ssdecontrol, prefer a general purpose language that can do stats over a stats language that can (kinda) do general purpose. | What areas of mathematical statistics are highly employable? | I'm answering as someone who routinely evaluates and hires data scientists.
As a person transitioning from academic study into a private sector career, you're not going to get hired on the strength of | What areas of mathematical statistics are highly employable?
I'm answering as someone who routinely evaluates and hires data scientists.
As a person transitioning from academic study into a private sector career, you're not going to get hired on the strength of any specific skills you have. The world of academic study in statistics, and the domain of any given company's set of problems are far too vast to hire on the basis of very precisely defined specific skillsets.
Instead, you are going to get hired because you can demonstrate a general aptitude for precise thinking, a thirst and talent for problem solving, an ability to understand and communicate abstract and complex ideas, and a diverse set of practical and theoretical skills.
So, my advice, and I'm just one guy, do what you love and develop a thirst for problem solving, nuance, and complexity. Learn a diverse set of skills, and know your fundamentals well (better than your research topic)
Oh, and learn to program.
That makes a lot of sense, thanks a lot for the thoughtful reply. Are there any particular programming languages you'd recommend
Hard question to answer without being opinionated.
My personal opinion is that it doesn't really matter, so learn the one that you like and that motivates you to keep learning. Learning your first language really well is the big hurdle. After the first learning another (and another, and another) is much, much easier because you have already dealt with the hard conceptual challenges.
But learn the language well, learn how the language works and why it was designed the way it was. Write clean code that you are unafraid to return to. Take writing code as a serious responsibility, not a unfortunate reality. This makes it both more rewarding, and a real skill you can advertise.
If you still want specific advice, I would echo @ssdecontrol, prefer a general purpose language that can do stats over a stats language that can (kinda) do general purpose. | What areas of mathematical statistics are highly employable?
I'm answering as someone who routinely evaluates and hires data scientists.
As a person transitioning from academic study into a private sector career, you're not going to get hired on the strength of |
20,983 | What areas of mathematical statistics are highly employable? | If your interest is in skills that are "marketable," I would say learn about a variety of modeling techniques (GLMs, survival models both continuous and discrete, random forests, boosted trees) with an emphasis on prediction over estimation. Mathematical statistics can occasionally get too bogged down in estimation under parametric models, trying to answer questions that become irrelevant when the model isn't literally true. So before delving too deeply into a problem consider whether or not it's still interesting and applicable when the model doesn't hold, because it never will. You should be able to find many such questions in the field of time series, if that's where one of your interests lies.
Also appreciate that there are challenges involved in the analysis of real world data that a statistics education alone may not prepare you for, so I would consider supplementing your education with the study of topics like relational databases and general computation. These fields can also be very fascinating and offer a refreshing perspective on data.
Finally, as Matthew Drury already pointed out it's essential to be able to program. I would work on becoming strong with R and / or Python, and start learning about SQL, which you will encounter inevitably. A lot of companies still use SAS, but do you really want to work for one? A compiled language such as C or Java also doesn't hurt, but this isn't really critical. | What areas of mathematical statistics are highly employable? | If your interest is in skills that are "marketable," I would say learn about a variety of modeling techniques (GLMs, survival models both continuous and discrete, random forests, boosted trees) with a | What areas of mathematical statistics are highly employable?
If your interest is in skills that are "marketable," I would say learn about a variety of modeling techniques (GLMs, survival models both continuous and discrete, random forests, boosted trees) with an emphasis on prediction over estimation. Mathematical statistics can occasionally get too bogged down in estimation under parametric models, trying to answer questions that become irrelevant when the model isn't literally true. So before delving too deeply into a problem consider whether or not it's still interesting and applicable when the model doesn't hold, because it never will. You should be able to find many such questions in the field of time series, if that's where one of your interests lies.
Also appreciate that there are challenges involved in the analysis of real world data that a statistics education alone may not prepare you for, so I would consider supplementing your education with the study of topics like relational databases and general computation. These fields can also be very fascinating and offer a refreshing perspective on data.
Finally, as Matthew Drury already pointed out it's essential to be able to program. I would work on becoming strong with R and / or Python, and start learning about SQL, which you will encounter inevitably. A lot of companies still use SAS, but do you really want to work for one? A compiled language such as C or Java also doesn't hurt, but this isn't really critical. | What areas of mathematical statistics are highly employable?
If your interest is in skills that are "marketable," I would say learn about a variety of modeling techniques (GLMs, survival models both continuous and discrete, random forests, boosted trees) with a |
20,984 | What areas of mathematical statistics are highly employable? | As someone who spent their post-doctoral career in industry, I'd say this.
Matthew Drury's response is first rate. dsaxton's remarks on prediction vs estimation are also good.
Learn to program using whatever will help you get through grad school with speed. Get good at it. Once you are very fluent in one language, other ones are easy to pick up and you can likely do so at your employer's expense.
Data bases aren't going to get any smaller, and probably won't get any cleaner. I'd predict that techniques to deal with gigantic, messy/missing data are a decent bet over the next two or three decades. | What areas of mathematical statistics are highly employable? | As someone who spent their post-doctoral career in industry, I'd say this.
Matthew Drury's response is first rate. dsaxton's remarks on prediction vs estimation are also good.
Learn to program using | What areas of mathematical statistics are highly employable?
As someone who spent their post-doctoral career in industry, I'd say this.
Matthew Drury's response is first rate. dsaxton's remarks on prediction vs estimation are also good.
Learn to program using whatever will help you get through grad school with speed. Get good at it. Once you are very fluent in one language, other ones are easy to pick up and you can likely do so at your employer's expense.
Data bases aren't going to get any smaller, and probably won't get any cleaner. I'd predict that techniques to deal with gigantic, messy/missing data are a decent bet over the next two or three decades. | What areas of mathematical statistics are highly employable?
As someone who spent their post-doctoral career in industry, I'd say this.
Matthew Drury's response is first rate. dsaxton's remarks on prediction vs estimation are also good.
Learn to program using |
20,985 | What areas of mathematical statistics are highly employable? | Most of the current answers are oriented "data science", which is definitely a highly employable area. As the original poster mentioned a particular interest in stochastic processes and time series, another area of mathematical statistics* that may be relevant is state-space estimation.
This is used to estimate models where the system evolves due to feedback between highly structured (quasi-)deterministic processes and stochastic forcing. For example state-space estimation is ubiquitous in autonomous vehicles.
(*This area is commonly considered to be part of engineering, or other domains, but certainly involves mathematical statistics.) | What areas of mathematical statistics are highly employable? | Most of the current answers are oriented "data science", which is definitely a highly employable area. As the original poster mentioned a particular interest in stochastic processes and time series, a | What areas of mathematical statistics are highly employable?
Most of the current answers are oriented "data science", which is definitely a highly employable area. As the original poster mentioned a particular interest in stochastic processes and time series, another area of mathematical statistics* that may be relevant is state-space estimation.
This is used to estimate models where the system evolves due to feedback between highly structured (quasi-)deterministic processes and stochastic forcing. For example state-space estimation is ubiquitous in autonomous vehicles.
(*This area is commonly considered to be part of engineering, or other domains, but certainly involves mathematical statistics.) | What areas of mathematical statistics are highly employable?
Most of the current answers are oriented "data science", which is definitely a highly employable area. As the original poster mentioned a particular interest in stochastic processes and time series, a |
20,986 | What areas of mathematical statistics are highly employable? | I wouldn't suggest something radically new, but as a professional data-scavenger myself, I would like to emphasis a few points.
All marketable skills are not just only bundle of single isolated skills, but they are a whole synchronized package. And by package, I mean,
A set of practical skills, with extremely high proficiency. Like you can form meaningful judgement given a pile of data. And for a PhD level guy (or for anyone who is coming to them) the employers would be more interested in bringing real-world cognitive match that you can bring with a given set of data. To clarify, as an example,
The set of skills that you may employ for data extraction from API, writing codecs and drivers in the process if you've found the process unyielding to the extent where you may not be able engage your full potential to it. Then using elements of the statistical analysis for a transformation of data into information. This process is so raw and so authentic that the more diverse and deep your learning is, the much better information(s), you can retrieve. I have been told once, that the mastering mathematics which can give an answer to the problem is one thing but to interpret that answer in the real world, is just another skill.
Lastly and extremely important, can you present visualizations of your conclusions for everyone to see and understand without anyone who is not of your related field not asking more than 3 follow-up questions. And this is where you would be giving your analogy to the real-world process(es). It is a bit difficult but once mastered, it usually pays good dividends, throughout your career.
For all these, from my point of view, a useful tip is to ask oneself consistently while studying new things that how it can be employed in the real world. Yes, it does get awkward at times when one delves deep into abstractions but nevertheless it is a habit very well worth it, and often it separates the super-employable from the merely highly educated. Good Luck! | What areas of mathematical statistics are highly employable? | I wouldn't suggest something radically new, but as a professional data-scavenger myself, I would like to emphasis a few points.
All marketable skills are not just only bundle of single isolated skill | What areas of mathematical statistics are highly employable?
I wouldn't suggest something radically new, but as a professional data-scavenger myself, I would like to emphasis a few points.
All marketable skills are not just only bundle of single isolated skills, but they are a whole synchronized package. And by package, I mean,
A set of practical skills, with extremely high proficiency. Like you can form meaningful judgement given a pile of data. And for a PhD level guy (or for anyone who is coming to them) the employers would be more interested in bringing real-world cognitive match that you can bring with a given set of data. To clarify, as an example,
The set of skills that you may employ for data extraction from API, writing codecs and drivers in the process if you've found the process unyielding to the extent where you may not be able engage your full potential to it. Then using elements of the statistical analysis for a transformation of data into information. This process is so raw and so authentic that the more diverse and deep your learning is, the much better information(s), you can retrieve. I have been told once, that the mastering mathematics which can give an answer to the problem is one thing but to interpret that answer in the real world, is just another skill.
Lastly and extremely important, can you present visualizations of your conclusions for everyone to see and understand without anyone who is not of your related field not asking more than 3 follow-up questions. And this is where you would be giving your analogy to the real-world process(es). It is a bit difficult but once mastered, it usually pays good dividends, throughout your career.
For all these, from my point of view, a useful tip is to ask oneself consistently while studying new things that how it can be employed in the real world. Yes, it does get awkward at times when one delves deep into abstractions but nevertheless it is a habit very well worth it, and often it separates the super-employable from the merely highly educated. Good Luck! | What areas of mathematical statistics are highly employable?
I wouldn't suggest something radically new, but as a professional data-scavenger myself, I would like to emphasis a few points.
All marketable skills are not just only bundle of single isolated skill |
20,987 | Can you multiply p-values if you perform the same test multiple times? | "I believe the interpretation of the p-value is that it is the probability of seeing your sample's test statistic under the null hypothesis."
No. It is the probability to see your sample's test statistic or something that is even less in line with the null hypothesis ($H_0$) under the $H_0$, which I write as $P_0\{T\ge t\}$, where $T$ is the test statistic and $t$ is its observed value, assuming here that a large value of $T$ provides evidence against $H_0$ (the argument can as well be made for the $\{T\le t\}$ or the two-sided case).
If you have, say, $p=0.06$ in one test $T_1$ with result $t_1$ and $p=0.6$ in the next ($T_2, t_2$; let's assume they were done on independent observations), if you multiply these two, what you get is the probability of $\{T_1\ge t_1\} \cap \{T_2\ge t_2\}$, i.e., the probability that $T_1$ and $T_2$ are large under the $H_0$. This is of course less likely than having at least one of them large. But there are cases with at least one of them large that count at least as strongly against the $H_0$, such as having $T_1$ extremely large even if $T_2$ doesn't indicate problems with the $H_0$, so the event $\{T_1\ge t_1\} \cap \{T_2\ge t_2\}$, of which you get the probability by multiplying the p-values, does not cover all possibilities to observe something that is even less in line with the $H_0$ than what you observed, and is therefore smaller than a valid "combined" p-value would need to be.
In my example above, surely after having observed $t_1$ with $P_0\{T_1\ge t_1\}=0.06$, observing $t_2$ with $P_0\{T_2\ge t_2\}=0.6$ doesn't make the overall result indicate any stronger against the $H_0$ (as multiplying the p-values would suggest), because observing something with $P_0\{T_2\ge t_2\}=0.6$ is perfectly reasonable under $H_0$; however observing $T_1$ even larger than $t_1$ would arguably count stronger against $H_0$ even with observing a smaller $T_2$.
The problem with combining p-values from more than one test is that if you only have a one-dimensional test statistic, as long as this statistic is suitably defined, it is clear how you can find all possible outcomes that are less in line with $H_0$ than your observation (depending on the test statistic either by looking at all larger, or all smaller values, or combining the two sides). However, with two or more values of the test statistic, in the higher dimensional space of possible outcomes it is much more difficult to define what "less in line with $H_0$" actually means. One possibility to play it safe is to look at $P_0(\{T_1\ge t_1\}\cup\{T_2\ge t_2\})$, the probability that at least one of $T_1$ and $T_2$ is too large. This for sure covers all possibilities that the pair $(T_1,T_2)$ is less in line with $H_0$ than the observations $(t_1,t_2)$. It actually covers far too much and is therefore very conservative. It may in fact be seen as useless, because its probability will always be bigger than $P_0\{T_1\ge t_1\}$, so this won't allow you to find a significance based on $(T_1,T_2)$ if you don't find one based on $T_1$ alone. If the two tests are independent, as apparently assumed here, $P_0(\{T_1\ge t_1\}\cup\{T_2\ge t_2\})=1-(1-P_0\{T_1\ge t_1\})(1-P_0\{T_2\ge t_1\})=0.624$ in the example, so there you have your multiplication.
Note that $2\min(P_0\{T_1\ge t_1\},P_0\{T_2\ge t_2\})=0.12$ in the example is the so-called Bonferroni-corrected p-value, which gives an upper bound on the probability that any of the two indicates at least as much against $H_0$ than the one that has the stronger indication, which is somewhat better than $P_0(\{T_1\ge t_1\}\cup\{T_2\ge t_2\})$, but still will not allow you to have an overall combined p-value that is smaller than all those you observe for the isolated tests. Under independence this can be improved to $1-(1-\min (P_0\{T_1\ge t_1\},P_0\{T_2\ge t_1\}))^2=0.116$, not much change here. (Edit: Fisher's method as linked in the answer of gunes will normally be better than this in the independence case.) | Can you multiply p-values if you perform the same test multiple times? | "I believe the interpretation of the p-value is that it is the probability of seeing your sample's test statistic under the null hypothesis."
No. It is the probability to see your sample's test statis | Can you multiply p-values if you perform the same test multiple times?
"I believe the interpretation of the p-value is that it is the probability of seeing your sample's test statistic under the null hypothesis."
No. It is the probability to see your sample's test statistic or something that is even less in line with the null hypothesis ($H_0$) under the $H_0$, which I write as $P_0\{T\ge t\}$, where $T$ is the test statistic and $t$ is its observed value, assuming here that a large value of $T$ provides evidence against $H_0$ (the argument can as well be made for the $\{T\le t\}$ or the two-sided case).
If you have, say, $p=0.06$ in one test $T_1$ with result $t_1$ and $p=0.6$ in the next ($T_2, t_2$; let's assume they were done on independent observations), if you multiply these two, what you get is the probability of $\{T_1\ge t_1\} \cap \{T_2\ge t_2\}$, i.e., the probability that $T_1$ and $T_2$ are large under the $H_0$. This is of course less likely than having at least one of them large. But there are cases with at least one of them large that count at least as strongly against the $H_0$, such as having $T_1$ extremely large even if $T_2$ doesn't indicate problems with the $H_0$, so the event $\{T_1\ge t_1\} \cap \{T_2\ge t_2\}$, of which you get the probability by multiplying the p-values, does not cover all possibilities to observe something that is even less in line with the $H_0$ than what you observed, and is therefore smaller than a valid "combined" p-value would need to be.
In my example above, surely after having observed $t_1$ with $P_0\{T_1\ge t_1\}=0.06$, observing $t_2$ with $P_0\{T_2\ge t_2\}=0.6$ doesn't make the overall result indicate any stronger against the $H_0$ (as multiplying the p-values would suggest), because observing something with $P_0\{T_2\ge t_2\}=0.6$ is perfectly reasonable under $H_0$; however observing $T_1$ even larger than $t_1$ would arguably count stronger against $H_0$ even with observing a smaller $T_2$.
The problem with combining p-values from more than one test is that if you only have a one-dimensional test statistic, as long as this statistic is suitably defined, it is clear how you can find all possible outcomes that are less in line with $H_0$ than your observation (depending on the test statistic either by looking at all larger, or all smaller values, or combining the two sides). However, with two or more values of the test statistic, in the higher dimensional space of possible outcomes it is much more difficult to define what "less in line with $H_0$" actually means. One possibility to play it safe is to look at $P_0(\{T_1\ge t_1\}\cup\{T_2\ge t_2\})$, the probability that at least one of $T_1$ and $T_2$ is too large. This for sure covers all possibilities that the pair $(T_1,T_2)$ is less in line with $H_0$ than the observations $(t_1,t_2)$. It actually covers far too much and is therefore very conservative. It may in fact be seen as useless, because its probability will always be bigger than $P_0\{T_1\ge t_1\}$, so this won't allow you to find a significance based on $(T_1,T_2)$ if you don't find one based on $T_1$ alone. If the two tests are independent, as apparently assumed here, $P_0(\{T_1\ge t_1\}\cup\{T_2\ge t_2\})=1-(1-P_0\{T_1\ge t_1\})(1-P_0\{T_2\ge t_1\})=0.624$ in the example, so there you have your multiplication.
Note that $2\min(P_0\{T_1\ge t_1\},P_0\{T_2\ge t_2\})=0.12$ in the example is the so-called Bonferroni-corrected p-value, which gives an upper bound on the probability that any of the two indicates at least as much against $H_0$ than the one that has the stronger indication, which is somewhat better than $P_0(\{T_1\ge t_1\}\cup\{T_2\ge t_2\})$, but still will not allow you to have an overall combined p-value that is smaller than all those you observe for the isolated tests. Under independence this can be improved to $1-(1-\min (P_0\{T_1\ge t_1\},P_0\{T_2\ge t_1\}))^2=0.116$, not much change here. (Edit: Fisher's method as linked in the answer of gunes will normally be better than this in the independence case.) | Can you multiply p-values if you perform the same test multiple times?
"I believe the interpretation of the p-value is that it is the probability of seeing your sample's test statistic under the null hypothesis."
No. It is the probability to see your sample's test statis |
20,988 | Can you multiply p-values if you perform the same test multiple times? | No, because then you could repeat any insignificant p-value and get a significant result, e.g. $0.9^{100}\approx 0.0000027$. Fisher's method is one way to combine multiple p-values. | Can you multiply p-values if you perform the same test multiple times? | No, because then you could repeat any insignificant p-value and get a significant result, e.g. $0.9^{100}\approx 0.0000027$. Fisher's method is one way to combine multiple p-values. | Can you multiply p-values if you perform the same test multiple times?
No, because then you could repeat any insignificant p-value and get a significant result, e.g. $0.9^{100}\approx 0.0000027$. Fisher's method is one way to combine multiple p-values. | Can you multiply p-values if you perform the same test multiple times?
No, because then you could repeat any insignificant p-value and get a significant result, e.g. $0.9^{100}\approx 0.0000027$. Fisher's method is one way to combine multiple p-values. |
20,989 | Can you multiply p-values if you perform the same test multiple times? | Let $X \sim N(\mu,\sigma^2)$ and $\{x_i\}$ and $\{y_i\}$ be two same size i.i.d samples from $X$.
Now we do z-tests (assuming variance is known) individually for the two samples and then together. In both cases the null hypothesis is same:
$$H_0: \mu=0$$
Let $p_x$ and $p_y$ be respective p-values for individual tests and $p_{xy}$ be the p-value for combined test:
We know that under null hpothesis $$\bar{X}, \bar{Y} \sim N(0,\sigma^2/n)$$
Now,
$$p_x=Pr\bigg(-\bigg|\frac{\bar{x}}{\sigma/\sqrt{n}}\bigg| \geq Z \geq \bigg|\frac{\bar{x}}{\sigma/\sqrt{n}}\bigg|\bigg) = 2\Phi\bigg(-\bigg|\frac{\bar{x}}{\sigma/\sqrt{n}}\bigg|\bigg)$$
where $\Phi(.)$ is the cdf for $N(0,1)$
So, $$p_xp_y=4\Phi\bigg(-\bigg|\frac{\bar{x}}{\sigma/\sqrt{n}}\bigg|\bigg)\Phi\bigg(-\bigg|\frac{\bar{y}}{\sigma/\sqrt{n}}\bigg|\bigg)$$
whereas in the combined test:
$$p_{xy}=2\Phi\bigg(-\bigg|\frac{(\bar{x}+\bar{y})/2}{\sigma/\sqrt{2n}}\bigg|\bigg)$$
Clearly, the two expressions are not same.
Now if I understand your question, you want to know what if we reject null based on $p_xp_y$ as compared to when we reject based on $p_{xy}$.
Under a true null hypothesis, p-value is uniformly distributed on $[0,1]$. So,
$$Pr(p_{xy} \leq 0.05) = 0.05$$
However, same is not true for $p_xp_y$ as it is not uniformly distributed. It's cdf is $z-z\ln{z}$. See this for derivation.
$$Pr(p_xp_y \leq 0.05) \approx 0.2$$
So you are clearly rejecting the null hypothesis much more often leading to higher type I error.
As such, I didn't need to assume anything about the distribution or test statistic. That was done just to illustrate that the two expressions are not the same.
The second part of the answer holds always because:
$$z-z\ln{z} > z \ \ \ \ \forall z \in [0,1)$$ | Can you multiply p-values if you perform the same test multiple times? | Let $X \sim N(\mu,\sigma^2)$ and $\{x_i\}$ and $\{y_i\}$ be two same size i.i.d samples from $X$.
Now we do z-tests (assuming variance is known) individually for the two samples and then together. In | Can you multiply p-values if you perform the same test multiple times?
Let $X \sim N(\mu,\sigma^2)$ and $\{x_i\}$ and $\{y_i\}$ be two same size i.i.d samples from $X$.
Now we do z-tests (assuming variance is known) individually for the two samples and then together. In both cases the null hypothesis is same:
$$H_0: \mu=0$$
Let $p_x$ and $p_y$ be respective p-values for individual tests and $p_{xy}$ be the p-value for combined test:
We know that under null hpothesis $$\bar{X}, \bar{Y} \sim N(0,\sigma^2/n)$$
Now,
$$p_x=Pr\bigg(-\bigg|\frac{\bar{x}}{\sigma/\sqrt{n}}\bigg| \geq Z \geq \bigg|\frac{\bar{x}}{\sigma/\sqrt{n}}\bigg|\bigg) = 2\Phi\bigg(-\bigg|\frac{\bar{x}}{\sigma/\sqrt{n}}\bigg|\bigg)$$
where $\Phi(.)$ is the cdf for $N(0,1)$
So, $$p_xp_y=4\Phi\bigg(-\bigg|\frac{\bar{x}}{\sigma/\sqrt{n}}\bigg|\bigg)\Phi\bigg(-\bigg|\frac{\bar{y}}{\sigma/\sqrt{n}}\bigg|\bigg)$$
whereas in the combined test:
$$p_{xy}=2\Phi\bigg(-\bigg|\frac{(\bar{x}+\bar{y})/2}{\sigma/\sqrt{2n}}\bigg|\bigg)$$
Clearly, the two expressions are not same.
Now if I understand your question, you want to know what if we reject null based on $p_xp_y$ as compared to when we reject based on $p_{xy}$.
Under a true null hypothesis, p-value is uniformly distributed on $[0,1]$. So,
$$Pr(p_{xy} \leq 0.05) = 0.05$$
However, same is not true for $p_xp_y$ as it is not uniformly distributed. It's cdf is $z-z\ln{z}$. See this for derivation.
$$Pr(p_xp_y \leq 0.05) \approx 0.2$$
So you are clearly rejecting the null hypothesis much more often leading to higher type I error.
As such, I didn't need to assume anything about the distribution or test statistic. That was done just to illustrate that the two expressions are not the same.
The second part of the answer holds always because:
$$z-z\ln{z} > z \ \ \ \ \forall z \in [0,1)$$ | Can you multiply p-values if you perform the same test multiple times?
Let $X \sim N(\mu,\sigma^2)$ and $\{x_i\}$ and $\{y_i\}$ be two same size i.i.d samples from $X$.
Now we do z-tests (assuming variance is known) individually for the two samples and then together. In |
20,990 | Can you multiply p-values if you perform the same test multiple times? | There are many ways to combine $p$-values, in fact we even have a tag for them combining-p-values. One method which is often used is Fisher's method which does, in effect, multiply the $p$-values. In fact logs are taken and summed which comes to the same thing. The crucial difference though is that this does not yield the new $p$-value directly but rather it yields a $\chi^2$ value from which the new $p$-value can be obtained. | Can you multiply p-values if you perform the same test multiple times? | There are many ways to combine $p$-values, in fact we even have a tag for them combining-p-values. One method which is often used is Fisher's method which does, in effect, multiply the $p$-values. In | Can you multiply p-values if you perform the same test multiple times?
There are many ways to combine $p$-values, in fact we even have a tag for them combining-p-values. One method which is often used is Fisher's method which does, in effect, multiply the $p$-values. In fact logs are taken and summed which comes to the same thing. The crucial difference though is that this does not yield the new $p$-value directly but rather it yields a $\chi^2$ value from which the new $p$-value can be obtained. | Can you multiply p-values if you perform the same test multiple times?
There are many ways to combine $p$-values, in fact we even have a tag for them combining-p-values. One method which is often used is Fisher's method which does, in effect, multiply the $p$-values. In |
20,991 | Can you multiply p-values if you perform the same test multiple times? | You can, I suppose, use a product of $p$-values $P \equiv \prod p_i$ as a measure of evidence if you like.
But it isn't itself a $p$-value, as for one thing it isn't uniformly distributed between 0 and 1 under the null, i.e., we don't have $P \sim U(0, 1)$ under the null. So it cannot be used to control type-1 errors in the usual manner. If we reject when $P \le \alpha$, we won't get a type-1 error rate of $\alpha$. | Can you multiply p-values if you perform the same test multiple times? | You can, I suppose, use a product of $p$-values $P \equiv \prod p_i$ as a measure of evidence if you like.
But it isn't itself a $p$-value, as for one thing it isn't uniformly distributed between 0 a | Can you multiply p-values if you perform the same test multiple times?
You can, I suppose, use a product of $p$-values $P \equiv \prod p_i$ as a measure of evidence if you like.
But it isn't itself a $p$-value, as for one thing it isn't uniformly distributed between 0 and 1 under the null, i.e., we don't have $P \sim U(0, 1)$ under the null. So it cannot be used to control type-1 errors in the usual manner. If we reject when $P \le \alpha$, we won't get a type-1 error rate of $\alpha$. | Can you multiply p-values if you perform the same test multiple times?
You can, I suppose, use a product of $p$-values $P \equiv \prod p_i$ as a measure of evidence if you like.
But it isn't itself a $p$-value, as for one thing it isn't uniformly distributed between 0 a |
20,992 | Can you multiply p-values if you perform the same test multiple times? | Could you use the multiplication rule from probability to multiply the
first p-value by the second, thus getting a new overall probability of
seeing your test statistic?
e.g. you do a t-test and get a p-value of 0.05, and then you perform
the same test with a completely different sample and get a p-value of
0.10. ...
[p-value= $ 0,05 * 0,1 = 0,005$?]
No, it is wrong. Even if the two sample are disjoint, inference is not so simple. The answer of gunes give us an interesting intuition. Another way for convincing you is that you can join the two sample and perform the same test. If the rule that you assume was correct, the result should be the same. If the $H_0$ is true, the p-value should increase with the number of data, otherwise it should decrease with it. Following your rule p-value decrease even if $H_0$ is true. | Can you multiply p-values if you perform the same test multiple times? | Could you use the multiplication rule from probability to multiply the
first p-value by the second, thus getting a new overall probability of
seeing your test statistic?
e.g. you do a t-test and get a | Can you multiply p-values if you perform the same test multiple times?
Could you use the multiplication rule from probability to multiply the
first p-value by the second, thus getting a new overall probability of
seeing your test statistic?
e.g. you do a t-test and get a p-value of 0.05, and then you perform
the same test with a completely different sample and get a p-value of
0.10. ...
[p-value= $ 0,05 * 0,1 = 0,005$?]
No, it is wrong. Even if the two sample are disjoint, inference is not so simple. The answer of gunes give us an interesting intuition. Another way for convincing you is that you can join the two sample and perform the same test. If the rule that you assume was correct, the result should be the same. If the $H_0$ is true, the p-value should increase with the number of data, otherwise it should decrease with it. Following your rule p-value decrease even if $H_0$ is true. | Can you multiply p-values if you perform the same test multiple times?
Could you use the multiplication rule from probability to multiply the
first p-value by the second, thus getting a new overall probability of
seeing your test statistic?
e.g. you do a t-test and get a |
20,993 | Using mean length and mean weight to calculate mean BMI? | Mathematically, it's not the case that these are necessarily close. It would work if it was the case that
$E(Y/X^2) = E(Y)/E(X)^2$ but this is false in general and in some particular situations it might be quite far out.
However, for a fairly realistic set of bivariate height and weight data it looks like the impact will be small.
For example, consider the model for US adult male height and weight in Brainard and Burmaster (1992) [1]; this model is a bivariate normal
in height and log(weight), which fits the height-weight data pretty well and makes it easy to get realistic simulations. A good model for females is a little more complicated, but I don't expect it would make all that much difference to the quality of the BMI approximation; I'm just going to do the males because a very simple model is quite good.
Converting the model there for male height and weight to metric and simulating 100,000 bivariate points in R before calculating individual BMIs and hence mean BMI, as well as calculating mean height on (mean weight)-squared, it turns out the result was that mean BMI was (to four figures) 25.21 and $\bar{h}/\bar{w}^2$ was 25.22, which looks pretty close.
Looking at the effect of varying the parameters, it looks like the impact of using the biased means-of-variables estimator for the women would probably be slightly larger but still not substantial enough that it's likely to be much of an issue.
Ideally something closer to whatever situation you want to use it for should be checked, but it's probably going to be pretty good.
So for a typical situation, it would seem it's unlikely to be much of a problem in practice.
[1]: Brainard, J. and Burmaster, D.E. (1992),
"Bivariate Distributions for Height and Weight of Men and Women in the United States",
Risk Analysis, Vol. 12, No. 2, p 267-275 | Using mean length and mean weight to calculate mean BMI? | Mathematically, it's not the case that these are necessarily close. It would work if it was the case that
$E(Y/X^2) = E(Y)/E(X)^2$ but this is false in general and in some particular situations it mi | Using mean length and mean weight to calculate mean BMI?
Mathematically, it's not the case that these are necessarily close. It would work if it was the case that
$E(Y/X^2) = E(Y)/E(X)^2$ but this is false in general and in some particular situations it might be quite far out.
However, for a fairly realistic set of bivariate height and weight data it looks like the impact will be small.
For example, consider the model for US adult male height and weight in Brainard and Burmaster (1992) [1]; this model is a bivariate normal
in height and log(weight), which fits the height-weight data pretty well and makes it easy to get realistic simulations. A good model for females is a little more complicated, but I don't expect it would make all that much difference to the quality of the BMI approximation; I'm just going to do the males because a very simple model is quite good.
Converting the model there for male height and weight to metric and simulating 100,000 bivariate points in R before calculating individual BMIs and hence mean BMI, as well as calculating mean height on (mean weight)-squared, it turns out the result was that mean BMI was (to four figures) 25.21 and $\bar{h}/\bar{w}^2$ was 25.22, which looks pretty close.
Looking at the effect of varying the parameters, it looks like the impact of using the biased means-of-variables estimator for the women would probably be slightly larger but still not substantial enough that it's likely to be much of an issue.
Ideally something closer to whatever situation you want to use it for should be checked, but it's probably going to be pretty good.
So for a typical situation, it would seem it's unlikely to be much of a problem in practice.
[1]: Brainard, J. and Burmaster, D.E. (1992),
"Bivariate Distributions for Height and Weight of Men and Women in the United States",
Risk Analysis, Vol. 12, No. 2, p 267-275 | Using mean length and mean weight to calculate mean BMI?
Mathematically, it's not the case that these are necessarily close. It would work if it was the case that
$E(Y/X^2) = E(Y)/E(X)^2$ but this is false in general and in some particular situations it mi |
20,994 | Using mean length and mean weight to calculate mean BMI? | It's not completely correct, but it will usually not make a huge difference.
For example, suppose your population has weights 80, 90 and 100kg, and is 1.7, 1.8 and 1.9m tall. Then the BMIs are 27.68, 27.78 and 27.70. The mean of the BMIs is 27.72. If you calculate the BMI from the means of the weights and heights, you get 27.78, which is slightly different, but should usually not make all that much of a difference. | Using mean length and mean weight to calculate mean BMI? | It's not completely correct, but it will usually not make a huge difference.
For example, suppose your population has weights 80, 90 and 100kg, and is 1.7, 1.8 and 1.9m tall. Then the BMIs are 27.68, | Using mean length and mean weight to calculate mean BMI?
It's not completely correct, but it will usually not make a huge difference.
For example, suppose your population has weights 80, 90 and 100kg, and is 1.7, 1.8 and 1.9m tall. Then the BMIs are 27.68, 27.78 and 27.70. The mean of the BMIs is 27.72. If you calculate the BMI from the means of the weights and heights, you get 27.78, which is slightly different, but should usually not make all that much of a difference. | Using mean length and mean weight to calculate mean BMI?
It's not completely correct, but it will usually not make a huge difference.
For example, suppose your population has weights 80, 90 and 100kg, and is 1.7, 1.8 and 1.9m tall. Then the BMIs are 27.68, |
20,995 | Using mean length and mean weight to calculate mean BMI? | Although I agree with the other answers that it is likely that this method will approximate the mean BMI, I would like to point out this is only an approximation.
I'm actually inclined to say you should not use the method you describe, as it is simply less accurate. It is trivial to calculate BMI's for each individual and then take the mean of that, giving you the real mean BMI.
Here I illustrate two extremes, where the means of weight and length remain the same, but the average BMI is actually different:
Using the following (matlab) code:
weight = [60, 61, 62, 100, 101, 102]; % OUR DATA
length = [1.5, 1.5, 1.5, 1.8, 1.8, 1.8;]; % OUR DATA
length = length.^2;
bmi = weight./length;
scatter(1:size(weight,2), bmi, 'filled');
yline(mean(bmi),'red','LineWidth',2);
yline(mean(weight)/mean(length),'blue','LineWidth',2);
xlabel('Person');
ylabel('BMI');
legend('BMI', 'mean(bmi)', 'mean(weight)/mean(length)', 'Location','northwest');
We get:
If we simply re-order the lengths, we get a different mean BMI while mean(weight)/mean(length^2) remains the same:
weight = [60, 61, 62, 100, 101, 102]; % OUR DATA
length = [1.8, 1.8, 1.8, 1.5, 1.5, 1.5;]; % OUR DATA (REORDERED)
... % rest is the same
Again, using real data it is likely that your method will approximate the real mean BMI, but why would you use a less accurate method?
Outside the scope of the question: It's always a good idea to visualise your data so you can actually see the distributions. If you notice certain clusters for example, you can also consider getting separate means for those clusters (e.g. separately for the first 3 and last 3 people in my example) | Using mean length and mean weight to calculate mean BMI? | Although I agree with the other answers that it is likely that this method will approximate the mean BMI, I would like to point out this is only an approximation.
I'm actually inclined to say you shou | Using mean length and mean weight to calculate mean BMI?
Although I agree with the other answers that it is likely that this method will approximate the mean BMI, I would like to point out this is only an approximation.
I'm actually inclined to say you should not use the method you describe, as it is simply less accurate. It is trivial to calculate BMI's for each individual and then take the mean of that, giving you the real mean BMI.
Here I illustrate two extremes, where the means of weight and length remain the same, but the average BMI is actually different:
Using the following (matlab) code:
weight = [60, 61, 62, 100, 101, 102]; % OUR DATA
length = [1.5, 1.5, 1.5, 1.8, 1.8, 1.8;]; % OUR DATA
length = length.^2;
bmi = weight./length;
scatter(1:size(weight,2), bmi, 'filled');
yline(mean(bmi),'red','LineWidth',2);
yline(mean(weight)/mean(length),'blue','LineWidth',2);
xlabel('Person');
ylabel('BMI');
legend('BMI', 'mean(bmi)', 'mean(weight)/mean(length)', 'Location','northwest');
We get:
If we simply re-order the lengths, we get a different mean BMI while mean(weight)/mean(length^2) remains the same:
weight = [60, 61, 62, 100, 101, 102]; % OUR DATA
length = [1.8, 1.8, 1.8, 1.5, 1.5, 1.5;]; % OUR DATA (REORDERED)
... % rest is the same
Again, using real data it is likely that your method will approximate the real mean BMI, but why would you use a less accurate method?
Outside the scope of the question: It's always a good idea to visualise your data so you can actually see the distributions. If you notice certain clusters for example, you can also consider getting separate means for those clusters (e.g. separately for the first 3 and last 3 people in my example) | Using mean length and mean weight to calculate mean BMI?
Although I agree with the other answers that it is likely that this method will approximate the mean BMI, I would like to point out this is only an approximation.
I'm actually inclined to say you shou |
20,996 | Best practice for encoding datetime in machine learning | You want to preserve the cyclical nature of your inputs. One approach is to cut the datetime variable into four variables: year, month, day, and hour. Then, decompose each of these (except for year) variables in two.
You create a sine and a cosine facet of each of these three variables (i.e., month, day, hour), which will retain the fact that hour 24 is closer to hour 0 than to hour 21, and that month 12 is closer to month 1 than to month 10.
A quick Google search got me a few links on how to do it:
https://ianlondon.github.io/blog/encoding-cyclical-features-24hour-time/
Optimal construction of day feature in neural networks
https://datascience.stackexchange.com/questions/5990/what-is-a-good-way-to-transform-cyclic-ordinal-attributes
https://medium.com/towards-data-science/top-6-errors-novice-machine-learning-engineers-make-e82273d394db | Best practice for encoding datetime in machine learning | You want to preserve the cyclical nature of your inputs. One approach is to cut the datetime variable into four variables: year, month, day, and hour. Then, decompose each of these (except for year) v | Best practice for encoding datetime in machine learning
You want to preserve the cyclical nature of your inputs. One approach is to cut the datetime variable into four variables: year, month, day, and hour. Then, decompose each of these (except for year) variables in two.
You create a sine and a cosine facet of each of these three variables (i.e., month, day, hour), which will retain the fact that hour 24 is closer to hour 0 than to hour 21, and that month 12 is closer to month 1 than to month 10.
A quick Google search got me a few links on how to do it:
https://ianlondon.github.io/blog/encoding-cyclical-features-24hour-time/
Optimal construction of day feature in neural networks
https://datascience.stackexchange.com/questions/5990/what-is-a-good-way-to-transform-cyclic-ordinal-attributes
https://medium.com/towards-data-science/top-6-errors-novice-machine-learning-engineers-make-e82273d394db | Best practice for encoding datetime in machine learning
You want to preserve the cyclical nature of your inputs. One approach is to cut the datetime variable into four variables: year, month, day, and hour. Then, decompose each of these (except for year) v |
20,997 | Best practice for encoding datetime in machine learning | I know I left a comment, but just to be explicit here is Feature-Engine's CylicalFeatures.
import pandas as pd
from sklearn.model_selection import train_test_split
from feature_engine.creation import CyclicalFeatures
df = pd.DataFrame({
'day': [6, 7, 5, 3, 1, 2, 4],
'months': [3, 7, 9, 12, 4, 6, 12],
})
cyclical = CyclicalFeatures(variables=None, drop_original=True)
X = cyclical.fit_transform(df)
print(X.head())
>>
day_sin day_cos months_sin months_cos
1 -0.78183 0.62349 1.0 0.0
2 0.0 1.0 -0.5 -0.86603
3 -0.97493 -0.222521 -1.0 -0.0
4 0.43388 -0.900969 0.0 1.0
5 0.78183 0.62349 0.86603 -0.5
6 0.97493 -0.222521 0.0 -1.0
7 -0.43388 -0.900969 0.0 1.0 | Best practice for encoding datetime in machine learning | I know I left a comment, but just to be explicit here is Feature-Engine's CylicalFeatures.
import pandas as pd
from sklearn.model_selection import train_test_split
from feature_engine.creation import | Best practice for encoding datetime in machine learning
I know I left a comment, but just to be explicit here is Feature-Engine's CylicalFeatures.
import pandas as pd
from sklearn.model_selection import train_test_split
from feature_engine.creation import CyclicalFeatures
df = pd.DataFrame({
'day': [6, 7, 5, 3, 1, 2, 4],
'months': [3, 7, 9, 12, 4, 6, 12],
})
cyclical = CyclicalFeatures(variables=None, drop_original=True)
X = cyclical.fit_transform(df)
print(X.head())
>>
day_sin day_cos months_sin months_cos
1 -0.78183 0.62349 1.0 0.0
2 0.0 1.0 -0.5 -0.86603
3 -0.97493 -0.222521 -1.0 -0.0
4 0.43388 -0.900969 0.0 1.0
5 0.78183 0.62349 0.86603 -0.5
6 0.97493 -0.222521 0.0 -1.0
7 -0.43388 -0.900969 0.0 1.0 | Best practice for encoding datetime in machine learning
I know I left a comment, but just to be explicit here is Feature-Engine's CylicalFeatures.
import pandas as pd
from sklearn.model_selection import train_test_split
from feature_engine.creation import |
20,998 | Why should/does(?) statistical sampling work for politics (e.g. Gallup)? | It seems like you're imagining a very simple sampling model.
The simplest model for sampling is called aptly Simple Random Sampling. You select a subset of the population (e.g., by dialing phone numbers at random) and ask whomever answers how they're voting. If 487 say Clinton, 463 say Trump, and the remainder give you some wacky answer, then the polling firm would report that 49% of voters prefer Clinton, while 46% prefer Trump. However, the polling firms do a lot more than this. A simple random sample gives equal weight to every data point. However, suppose your sample contains--by chance--600 men and 400 women, which clearly isn't representative of the population as a whole. If men as a group lean one way, while women lean the other, this will bias your result. However, since we have pretty good demographic statistics, you can weight* the responses by counting the women's responses a bit more and the men's a bit less, so that the weighted response represents the population better. Polling organizations have more complicated weighing models that can make a non-representative sample resemble a more representative one.
The idea of weighting the sampled responses is on pretty firm statistical ground, but there is some flexibility in choosing what factors contribute to the weights. Most pollsters do reweight based on demographic factors like gender, age, and race. Given this, you might think that party identification (Democratic, Republican, etc) should also be included, but it turns out that most polling firms do not use it in their weights: party (self)-identification is tangled up with the voter's choice in a way that makes it less useful.
Many polling outfits also report their results among "likely voters". In these, respondents are either selected or weighted based on the likelihood that they'll actually turn up to the polls. This model is undoubtedly data-driven too, but the precise choice of factors allows for some flexibility. For example, including interactions between the candidate and voter's race (or gender) wasn't even sensible until 2008 or 2016, but I suspect they have some predictive power now.
In theory, you could include all sorts of things as weighting factors: musical preference, eye color, etc. However, demographic factors are popular choices for weighting factors because:
Empirically, they correlate well with voter behavior. Obviously, there is no iron-clad law that 'forces' white men to be lean Republican, but over the last fifty years, they have tended to.
The population values are well known (e.g., from the census or Vital Records)
However, pollsters also see the same news everyone else does, and can adjust the weighting variables if necessary.
There are also some "fudge factors" that are sometimes invoked to explain poll results. For example, respondents sometimes are reluctant to give "socially-undesirable" answers. The Bradley Effect posits that white voters sometimes downplay their support for white candidates running against a minority to avoid appearing racist. It is named after Tom Bradley, an African-American gubernatorial candidate who narrowly lost the election despite leading comfortably in the polls.
Finally, you're completely correct that the very act of asking someone's opinion can change it. Polling firms try to write their questions in a neutral way. To avoid issues with the order of possible responses, the candidates' names might be listed in random order. Multiple versions of a question are also sometimes tested against each other. This effect can also be exploited for nefarious ends in a push poll, where the interviewer isn't actually interested in collecting responses but in influencing them. For example, a push poll might ask "Would you vote for [Candidate A] even if it was reported that he was a child molester?".
* You might also set explicit targets for your sample, like including 500 men and 500 women. This is called stratified sampling--the population is stratified into different groups, and each group is then sampled random. In practice, this isn't done very often for polls, because you'd need to stratify into a lot of exhaustive groups (e.g., college-educated men between 18-24 in Urban Texas). | Why should/does(?) statistical sampling work for politics (e.g. Gallup)? | It seems like you're imagining a very simple sampling model.
The simplest model for sampling is called aptly Simple Random Sampling. You select a subset of the population (e.g., by dialing phone numbe | Why should/does(?) statistical sampling work for politics (e.g. Gallup)?
It seems like you're imagining a very simple sampling model.
The simplest model for sampling is called aptly Simple Random Sampling. You select a subset of the population (e.g., by dialing phone numbers at random) and ask whomever answers how they're voting. If 487 say Clinton, 463 say Trump, and the remainder give you some wacky answer, then the polling firm would report that 49% of voters prefer Clinton, while 46% prefer Trump. However, the polling firms do a lot more than this. A simple random sample gives equal weight to every data point. However, suppose your sample contains--by chance--600 men and 400 women, which clearly isn't representative of the population as a whole. If men as a group lean one way, while women lean the other, this will bias your result. However, since we have pretty good demographic statistics, you can weight* the responses by counting the women's responses a bit more and the men's a bit less, so that the weighted response represents the population better. Polling organizations have more complicated weighing models that can make a non-representative sample resemble a more representative one.
The idea of weighting the sampled responses is on pretty firm statistical ground, but there is some flexibility in choosing what factors contribute to the weights. Most pollsters do reweight based on demographic factors like gender, age, and race. Given this, you might think that party identification (Democratic, Republican, etc) should also be included, but it turns out that most polling firms do not use it in their weights: party (self)-identification is tangled up with the voter's choice in a way that makes it less useful.
Many polling outfits also report their results among "likely voters". In these, respondents are either selected or weighted based on the likelihood that they'll actually turn up to the polls. This model is undoubtedly data-driven too, but the precise choice of factors allows for some flexibility. For example, including interactions between the candidate and voter's race (or gender) wasn't even sensible until 2008 or 2016, but I suspect they have some predictive power now.
In theory, you could include all sorts of things as weighting factors: musical preference, eye color, etc. However, demographic factors are popular choices for weighting factors because:
Empirically, they correlate well with voter behavior. Obviously, there is no iron-clad law that 'forces' white men to be lean Republican, but over the last fifty years, they have tended to.
The population values are well known (e.g., from the census or Vital Records)
However, pollsters also see the same news everyone else does, and can adjust the weighting variables if necessary.
There are also some "fudge factors" that are sometimes invoked to explain poll results. For example, respondents sometimes are reluctant to give "socially-undesirable" answers. The Bradley Effect posits that white voters sometimes downplay their support for white candidates running against a minority to avoid appearing racist. It is named after Tom Bradley, an African-American gubernatorial candidate who narrowly lost the election despite leading comfortably in the polls.
Finally, you're completely correct that the very act of asking someone's opinion can change it. Polling firms try to write their questions in a neutral way. To avoid issues with the order of possible responses, the candidates' names might be listed in random order. Multiple versions of a question are also sometimes tested against each other. This effect can also be exploited for nefarious ends in a push poll, where the interviewer isn't actually interested in collecting responses but in influencing them. For example, a push poll might ask "Would you vote for [Candidate A] even if it was reported that he was a child molester?".
* You might also set explicit targets for your sample, like including 500 men and 500 women. This is called stratified sampling--the population is stratified into different groups, and each group is then sampled random. In practice, this isn't done very often for polls, because you'd need to stratify into a lot of exhaustive groups (e.g., college-educated men between 18-24 in Urban Texas). | Why should/does(?) statistical sampling work for politics (e.g. Gallup)?
It seems like you're imagining a very simple sampling model.
The simplest model for sampling is called aptly Simple Random Sampling. You select a subset of the population (e.g., by dialing phone numbe |
20,999 | Why should/does(?) statistical sampling work for politics (e.g. Gallup)? | There's a mathematical theorem called the "law of large numbers." Imagine that you want to determine the probability that a coin will come up heads. The "population" of coin flips is infinity - much larger than the 300,000,000+ people in the United States. But according to the Law of Large Numbers, the more coin flips you do, the more accurate your estimate will be.
The ideal poll: In the ideal poll, the pollsters would randomly choose names from the U.S. Census, they would find out where those people live, then they would go and knock on their door. If the person says they're planning on voting, the pollster asks who they're voting for and records their answer. Polling like this is mathematically guaranteed to work and the amount of error in your measurement for any given confidence level can be calculated easily.
Here's what the error means: Suppose that based on your poll, you got that there's a 52 percent chance Candidate Awesome McPerfect is going to win, with a 3% error with 98% confidence. That means that you can be 98% confident that the true portion of voters who favor candidate Awesome McPerfect is between 49% and 55%.
A Note on Error and Confidence For a given sample size, the more confident you are, the bigger your error will be. Think about it - you're 100% confident that the true proportion that support canditate Awesome is between 0% and 100% (most error possible), and you're 0% confident that the true proportion that supports canditate Awesome is exactly 52.0932840985028390984308% (zero error). More confidence means more error, less confidence means less error. However, the relationship between confidence and error is NOT linear! (See: https://en.wikipedia.org/wiki/Confidence_interval)
Polls in the real world: Because it's expensive to helicopter pollsters out to all parts of the country to knock on the doors of random people (although I'd love to see that happen; if you're a billionare and you see this, please consider funding this), polls in the real world are more complex. Lets look at one of the more common strategies - calling up random voters and asking them who they'd vote for. It's a good strategy, but it does have some well-aknowledged failings:
People often choose not to answer the phone and respond to pollsters (ex. me)
Some demographics are more likely to have a landline (ex. older voters)
Some demographics are more likely to respond to pollsters (ex. older voters)
Because different demographics vote in different ways, pollsters have to do their best to control for the differences in their raw data (based on who decided to answer the phone) and the outcomes of actual elections. For example, if 10% of people who picked up the phone were hispanic, but 30% of voters in the last election were hispanic, then they're going to give three times the weight to hispanic voters in their poll. If 50% of people who answered the phone were older than 60, but only 30% of the people who voted in the last election were older than 60, they're going to give less weight to the older voters who responded. It's not perfect, but it can lead to some impressive feats of prediction (Nate Silver correctly predicted the results in each of the 50 states in the 2012 election using statistics, and he was correct in 49 out of the 50 states in the 2008 prediction).
A word of caution to the wise: Pollsters make the best predictions they can based on how things worked out in the past. Generally speaking, things work out about the same now as they did in the past, or at least the change is slow enough that the recent past (which they focus most on) will resemble the present. However, occasionally there are rapid shifts in the electorate and things go wrong. Maybe Trump voters are slightly less likely than your average voter to answer the phone, and weighting by demographics doesn't account for that. Or Maybe young people (who overwhelmingly support Hillary) are even more unlikely to answer the phone than the models predict, and the ones that do answer the phone are more likely to be republican. Or perhaps the opposite of both is true - we don't know. things like that are hidden variables that don't show up in commonly collected demographics.
We would know if we sent pollsters to knock on random doors (ahem, imaginary billionare reading this), since then we wouldn't have to weight things based on demographics, but until then, fingers crossed. | Why should/does(?) statistical sampling work for politics (e.g. Gallup)? | There's a mathematical theorem called the "law of large numbers." Imagine that you want to determine the probability that a coin will come up heads. The "population" of coin flips is infinity - much l | Why should/does(?) statistical sampling work for politics (e.g. Gallup)?
There's a mathematical theorem called the "law of large numbers." Imagine that you want to determine the probability that a coin will come up heads. The "population" of coin flips is infinity - much larger than the 300,000,000+ people in the United States. But according to the Law of Large Numbers, the more coin flips you do, the more accurate your estimate will be.
The ideal poll: In the ideal poll, the pollsters would randomly choose names from the U.S. Census, they would find out where those people live, then they would go and knock on their door. If the person says they're planning on voting, the pollster asks who they're voting for and records their answer. Polling like this is mathematically guaranteed to work and the amount of error in your measurement for any given confidence level can be calculated easily.
Here's what the error means: Suppose that based on your poll, you got that there's a 52 percent chance Candidate Awesome McPerfect is going to win, with a 3% error with 98% confidence. That means that you can be 98% confident that the true portion of voters who favor candidate Awesome McPerfect is between 49% and 55%.
A Note on Error and Confidence For a given sample size, the more confident you are, the bigger your error will be. Think about it - you're 100% confident that the true proportion that support canditate Awesome is between 0% and 100% (most error possible), and you're 0% confident that the true proportion that supports canditate Awesome is exactly 52.0932840985028390984308% (zero error). More confidence means more error, less confidence means less error. However, the relationship between confidence and error is NOT linear! (See: https://en.wikipedia.org/wiki/Confidence_interval)
Polls in the real world: Because it's expensive to helicopter pollsters out to all parts of the country to knock on the doors of random people (although I'd love to see that happen; if you're a billionare and you see this, please consider funding this), polls in the real world are more complex. Lets look at one of the more common strategies - calling up random voters and asking them who they'd vote for. It's a good strategy, but it does have some well-aknowledged failings:
People often choose not to answer the phone and respond to pollsters (ex. me)
Some demographics are more likely to have a landline (ex. older voters)
Some demographics are more likely to respond to pollsters (ex. older voters)
Because different demographics vote in different ways, pollsters have to do their best to control for the differences in their raw data (based on who decided to answer the phone) and the outcomes of actual elections. For example, if 10% of people who picked up the phone were hispanic, but 30% of voters in the last election were hispanic, then they're going to give three times the weight to hispanic voters in their poll. If 50% of people who answered the phone were older than 60, but only 30% of the people who voted in the last election were older than 60, they're going to give less weight to the older voters who responded. It's not perfect, but it can lead to some impressive feats of prediction (Nate Silver correctly predicted the results in each of the 50 states in the 2012 election using statistics, and he was correct in 49 out of the 50 states in the 2008 prediction).
A word of caution to the wise: Pollsters make the best predictions they can based on how things worked out in the past. Generally speaking, things work out about the same now as they did in the past, or at least the change is slow enough that the recent past (which they focus most on) will resemble the present. However, occasionally there are rapid shifts in the electorate and things go wrong. Maybe Trump voters are slightly less likely than your average voter to answer the phone, and weighting by demographics doesn't account for that. Or Maybe young people (who overwhelmingly support Hillary) are even more unlikely to answer the phone than the models predict, and the ones that do answer the phone are more likely to be republican. Or perhaps the opposite of both is true - we don't know. things like that are hidden variables that don't show up in commonly collected demographics.
We would know if we sent pollsters to knock on random doors (ahem, imaginary billionare reading this), since then we wouldn't have to weight things based on demographics, but until then, fingers crossed. | Why should/does(?) statistical sampling work for politics (e.g. Gallup)?
There's a mathematical theorem called the "law of large numbers." Imagine that you want to determine the probability that a coin will come up heads. The "population" of coin flips is infinity - much l |
21,000 | Why should/does(?) statistical sampling work for politics (e.g. Gallup)? | Firstly, this is aside from your main points but it's worth mentioning. In the medical trial you could have 1000 people testing a drug which can be given to the 10000 people who are sick annually. You might look at that and think "That's being tested on 10% of the population", in fact the population isn't 10000 people, its all future patients so the population size is infinite. 1000 people isn't large compared to the infinite potential users of the drug but these kinds of studies work. It's not important whether you test 10%, 1% or 0.1% of the population; what's important is the absolute size of the sample not how big it is compared to the population.
Next, your main point is that there are so many confounding variables which can influence people's voting. You're treating the 22000 districts of California like 22000 variables but really they are just a handful of variables (income and education like you mentioned). You don't need a representative sample from every district, you just need enough samples to cover the variation due to income, education, ect.
If you have $k$ confounding variables (age, gender, education, ect) and they all have similar effects then the variance of the vote increases by about $k$ times. If you sample $n$ people then the variance of the sample average decreases by a factor of $n$. Therefore, if the variation from each confounding variable is $\sigma^2$ then your sample average from $n$ people with $k$ confounding variables will be $\frac{k\sigma^2}{n}$.
You can probably think of 10 or so confounding variables but the sample size is 1000 so $k$ is a lot smaller than $n$. Therefore the variance of the sample average is quite small.
Edit:
The above formula was assuming that each confounding variable is equally important. If we want to consider hundreds of things that can add variance to the results then this assumption isn't valid (e.g. maybe twitter users support one candidate more, but we know that twitter use isn't as important as gender).
We could list all the confounding variables in order of importance (e.g. gender, age, income, ... , twitter use, ...). Let's assume that each variable is only 90% as important as the previous one. Now if gender adds a variance equal to $\sigma^2$ then age adds a variance equal to $0.9 \sigma^2$ and income adds $0.9^2 \sigma^2 $. If we include an infinite number of confounding variables then the total variability is $\sum_{n=0}^{\infty} \sigma^2 0.9^n = 10 \sigma^2$.
With this type of consideration for minor variables we've ended up with a variance with 10 times the variability of gender alone. So with $n$ samples the variation in the sample average is $\frac{10\sigma^2}{n}$. Of course $0.9$ was chosen arbitrarily but this conveys a point about how these infinite number of minor variables should add up to something small | Why should/does(?) statistical sampling work for politics (e.g. Gallup)? | Firstly, this is aside from your main points but it's worth mentioning. In the medical trial you could have 1000 people testing a drug which can be given to the 10000 people who are sick annually. You | Why should/does(?) statistical sampling work for politics (e.g. Gallup)?
Firstly, this is aside from your main points but it's worth mentioning. In the medical trial you could have 1000 people testing a drug which can be given to the 10000 people who are sick annually. You might look at that and think "That's being tested on 10% of the population", in fact the population isn't 10000 people, its all future patients so the population size is infinite. 1000 people isn't large compared to the infinite potential users of the drug but these kinds of studies work. It's not important whether you test 10%, 1% or 0.1% of the population; what's important is the absolute size of the sample not how big it is compared to the population.
Next, your main point is that there are so many confounding variables which can influence people's voting. You're treating the 22000 districts of California like 22000 variables but really they are just a handful of variables (income and education like you mentioned). You don't need a representative sample from every district, you just need enough samples to cover the variation due to income, education, ect.
If you have $k$ confounding variables (age, gender, education, ect) and they all have similar effects then the variance of the vote increases by about $k$ times. If you sample $n$ people then the variance of the sample average decreases by a factor of $n$. Therefore, if the variation from each confounding variable is $\sigma^2$ then your sample average from $n$ people with $k$ confounding variables will be $\frac{k\sigma^2}{n}$.
You can probably think of 10 or so confounding variables but the sample size is 1000 so $k$ is a lot smaller than $n$. Therefore the variance of the sample average is quite small.
Edit:
The above formula was assuming that each confounding variable is equally important. If we want to consider hundreds of things that can add variance to the results then this assumption isn't valid (e.g. maybe twitter users support one candidate more, but we know that twitter use isn't as important as gender).
We could list all the confounding variables in order of importance (e.g. gender, age, income, ... , twitter use, ...). Let's assume that each variable is only 90% as important as the previous one. Now if gender adds a variance equal to $\sigma^2$ then age adds a variance equal to $0.9 \sigma^2$ and income adds $0.9^2 \sigma^2 $. If we include an infinite number of confounding variables then the total variability is $\sum_{n=0}^{\infty} \sigma^2 0.9^n = 10 \sigma^2$.
With this type of consideration for minor variables we've ended up with a variance with 10 times the variability of gender alone. So with $n$ samples the variation in the sample average is $\frac{10\sigma^2}{n}$. Of course $0.9$ was chosen arbitrarily but this conveys a point about how these infinite number of minor variables should add up to something small | Why should/does(?) statistical sampling work for politics (e.g. Gallup)?
Firstly, this is aside from your main points but it's worth mentioning. In the medical trial you could have 1000 people testing a drug which can be given to the 10000 people who are sick annually. You |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.