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
|
|---|---|---|---|---|---|---|
16,801
|
The correct way to normalize time series data
|
You should stick to the first approach. Or its variation when you calculate the separate scale for each series. That's a short answer, there are nuances though.
Your scale must be constant if your model doesn't have a scale in it. For instance, take a look at Heston model in finance. Just look at the equations, ignore the context. You see how the valatility changes with time. The first equation models the returns, and the second one models the volatility (standard deviation). The model explicitly models volatility.
In this case I could see dynamic scaling working, because then you'd have other parts of your model that are modeling the scale itself. Your model doesn't have to be stochastic volatility like Heston's but it must explicitly account for the fact that volatility changes over time somehow. Otherwise, if your scale changes and you don't deal with it, I doubt you'll get a sensible result.
On the second question of whether to use the training set to scale. Ideally it shouldn't even matter, because your scale is constant, right? So, if it's constant then your scale shouldn't change if you calculated it on subsamples. In reality it will move a little bit, and if the change causes issues it means that your training set is different from the test set. The macro characteristics such as means and standard deviation should not change too much between subsamples. If this happens it's a sampling or data size problem. Also, if the change in scale is small, but the model breaks down it means that the model is not robust to small disturbances, a problem in and of itself, in my opinion.
|
The correct way to normalize time series data
|
You should stick to the first approach. Or its variation when you calculate the separate scale for each series. That's a short answer, there are nuances though.
Your scale must be constant if your mo
|
The correct way to normalize time series data
You should stick to the first approach. Or its variation when you calculate the separate scale for each series. That's a short answer, there are nuances though.
Your scale must be constant if your model doesn't have a scale in it. For instance, take a look at Heston model in finance. Just look at the equations, ignore the context. You see how the valatility changes with time. The first equation models the returns, and the second one models the volatility (standard deviation). The model explicitly models volatility.
In this case I could see dynamic scaling working, because then you'd have other parts of your model that are modeling the scale itself. Your model doesn't have to be stochastic volatility like Heston's but it must explicitly account for the fact that volatility changes over time somehow. Otherwise, if your scale changes and you don't deal with it, I doubt you'll get a sensible result.
On the second question of whether to use the training set to scale. Ideally it shouldn't even matter, because your scale is constant, right? So, if it's constant then your scale shouldn't change if you calculated it on subsamples. In reality it will move a little bit, and if the change causes issues it means that your training set is different from the test set. The macro characteristics such as means and standard deviation should not change too much between subsamples. If this happens it's a sampling or data size problem. Also, if the change in scale is small, but the model breaks down it means that the model is not robust to small disturbances, a problem in and of itself, in my opinion.
|
The correct way to normalize time series data
You should stick to the first approach. Or its variation when you calculate the separate scale for each series. That's a short answer, there are nuances though.
Your scale must be constant if your mo
|
16,802
|
Bayesian lasso vs spike and slab
|
Both of these methods (LASSO vs. spike-and-slab) can be interpreted as Bayesian estimation problems where you are specifying different parameters. One of the main differences is that the LASSO method does not put any point-mass on zero for the prior (i.e., the parameters are almost surely non-zero a priori), whereas the spike-and-slab puts a substantial point-mass on zero.
In my humble opinion, the main advantage of the spike-and-slab method is that it is well-suited to problems where the number of parameters is more than the number of data points, and you want to completely eliminate a substantial number of parameters from the model. Because this method puts a large point-mass on zero in the prior, it will yield posterior estimates that tend to involve only a small proportion of the parameters, hopefully avoiding over-fitting of the data.
When your professor tells you that the former is not performing a variable selection method, what he probably means is this. Under LASSO, each of the parameters is almost surely non-zero a priori (i.e., they are all in the model). Since the likelihood is also non-zero over the parameter support, this will also mean that each is are almost surely non-zero a priori (i.e., they are all in the model). Now, you might supplement this with a hypothesis test, and rule parameters out of the model that way, but that would be an additional test imposed on top of the Bayesian model.
The results of Bayesian estimation will reflect a contribution from the data and a contribution from the prior. Naturally, a prior distribution that is more closely concentrated around zero (like the spike-and-slab) will indeed "shrink" the resultant parameter estimators, relative to a prior that is less concentrated (like the LASSO). Of course, this "shrinking" is merely the effect of the prior information you have specified. The shape of the LASSO prior means that it is shrinking all parameter estimates towards the mean, relative to a flatter prior.
|
Bayesian lasso vs spike and slab
|
Both of these methods (LASSO vs. spike-and-slab) can be interpreted as Bayesian estimation problems where you are specifying different parameters. One of the main differences is that the LASSO method
|
Bayesian lasso vs spike and slab
Both of these methods (LASSO vs. spike-and-slab) can be interpreted as Bayesian estimation problems where you are specifying different parameters. One of the main differences is that the LASSO method does not put any point-mass on zero for the prior (i.e., the parameters are almost surely non-zero a priori), whereas the spike-and-slab puts a substantial point-mass on zero.
In my humble opinion, the main advantage of the spike-and-slab method is that it is well-suited to problems where the number of parameters is more than the number of data points, and you want to completely eliminate a substantial number of parameters from the model. Because this method puts a large point-mass on zero in the prior, it will yield posterior estimates that tend to involve only a small proportion of the parameters, hopefully avoiding over-fitting of the data.
When your professor tells you that the former is not performing a variable selection method, what he probably means is this. Under LASSO, each of the parameters is almost surely non-zero a priori (i.e., they are all in the model). Since the likelihood is also non-zero over the parameter support, this will also mean that each is are almost surely non-zero a priori (i.e., they are all in the model). Now, you might supplement this with a hypothesis test, and rule parameters out of the model that way, but that would be an additional test imposed on top of the Bayesian model.
The results of Bayesian estimation will reflect a contribution from the data and a contribution from the prior. Naturally, a prior distribution that is more closely concentrated around zero (like the spike-and-slab) will indeed "shrink" the resultant parameter estimators, relative to a prior that is less concentrated (like the LASSO). Of course, this "shrinking" is merely the effect of the prior information you have specified. The shape of the LASSO prior means that it is shrinking all parameter estimates towards the mean, relative to a flatter prior.
|
Bayesian lasso vs spike and slab
Both of these methods (LASSO vs. spike-and-slab) can be interpreted as Bayesian estimation problems where you are specifying different parameters. One of the main differences is that the LASSO method
|
16,803
|
Bayesian lasso vs spike and slab
|
I second @Ben's answer. In my simplified perspective, the spike and slab is well suited to high dimensional datasets since the spike is concentrated at zero rather having a broadened normal or laplacian prior that would shrink the posterior regressor variables less than the spike and slab prior. Hence, spike and slab produces sparser set of regressors that can help reduce likelihood of overfitting.
|
Bayesian lasso vs spike and slab
|
I second @Ben's answer. In my simplified perspective, the spike and slab is well suited to high dimensional datasets since the spike is concentrated at zero rather having a broadened normal or laplaci
|
Bayesian lasso vs spike and slab
I second @Ben's answer. In my simplified perspective, the spike and slab is well suited to high dimensional datasets since the spike is concentrated at zero rather having a broadened normal or laplacian prior that would shrink the posterior regressor variables less than the spike and slab prior. Hence, spike and slab produces sparser set of regressors that can help reduce likelihood of overfitting.
|
Bayesian lasso vs spike and slab
I second @Ben's answer. In my simplified perspective, the spike and slab is well suited to high dimensional datasets since the spike is concentrated at zero rather having a broadened normal or laplaci
|
16,804
|
Significance test based on precision/recall/F1
|
Intuitively, getting a high P/R/F1 on a small data set, or on a very uniform/predictable dataset is probably easier than getting a high P/R/F1 on larger or more chaotic datasets. Therefore, an improvement in P/R/F1 on a larger and more chaotic dataset is more significant.
Following this intuition, you would probably need access to the output of the "black-box" methods in order to measure the difference in the distribution of results, while taking into account the size and variety in that set. The P/R/F1 alone are probably too little information.
Significance testing in this setting is usually done by forming a null hypothesis (the two algorithms produce always the same output) and then calculating the probability of observing the difference in output that you are observing if the algorithms were indeed the same. If the probability is less than .05 for example, you reject the null hypothesis and conclude that the improvement is significant.
This paper has relevant discussions:
http://www.aclweb.org/anthology/C00-2137
|
Significance test based on precision/recall/F1
|
Intuitively, getting a high P/R/F1 on a small data set, or on a very uniform/predictable dataset is probably easier than getting a high P/R/F1 on larger or more chaotic datasets. Therefore, an improve
|
Significance test based on precision/recall/F1
Intuitively, getting a high P/R/F1 on a small data set, or on a very uniform/predictable dataset is probably easier than getting a high P/R/F1 on larger or more chaotic datasets. Therefore, an improvement in P/R/F1 on a larger and more chaotic dataset is more significant.
Following this intuition, you would probably need access to the output of the "black-box" methods in order to measure the difference in the distribution of results, while taking into account the size and variety in that set. The P/R/F1 alone are probably too little information.
Significance testing in this setting is usually done by forming a null hypothesis (the two algorithms produce always the same output) and then calculating the probability of observing the difference in output that you are observing if the algorithms were indeed the same. If the probability is less than .05 for example, you reject the null hypothesis and conclude that the improvement is significant.
This paper has relevant discussions:
http://www.aclweb.org/anthology/C00-2137
|
Significance test based on precision/recall/F1
Intuitively, getting a high P/R/F1 on a small data set, or on a very uniform/predictable dataset is probably easier than getting a high P/R/F1 on larger or more chaotic datasets. Therefore, an improve
|
16,805
|
Zero-inflated negative binomial mixed-effects model in R
|
I think this is the package you need: glmmADMB.
I downloaded it here: http://otter-rsch.com/admbre/examples/glmmadmb/glmmADMB.html
But I still had some problems to get it to run, so I followed the instructions provided in this link and now it works fine http://glmmadmb.r-forge.r-project.org/
Hope this helps!
|
Zero-inflated negative binomial mixed-effects model in R
|
I think this is the package you need: glmmADMB.
I downloaded it here: http://otter-rsch.com/admbre/examples/glmmadmb/glmmADMB.html
But I still had some problems to get it to run, so I followed the in
|
Zero-inflated negative binomial mixed-effects model in R
I think this is the package you need: glmmADMB.
I downloaded it here: http://otter-rsch.com/admbre/examples/glmmadmb/glmmADMB.html
But I still had some problems to get it to run, so I followed the instructions provided in this link and now it works fine http://glmmadmb.r-forge.r-project.org/
Hope this helps!
|
Zero-inflated negative binomial mixed-effects model in R
I think this is the package you need: glmmADMB.
I downloaded it here: http://otter-rsch.com/admbre/examples/glmmadmb/glmmADMB.html
But I still had some problems to get it to run, so I followed the in
|
16,806
|
Zero-inflated negative binomial mixed-effects model in R
|
The pscl package provides for a zero inflated Poisson model. I don't think that it can do a negative binomial model, but it might be a place to start. The linked JSS article also discusses related packages, which may lead you to what you're looking for.
|
Zero-inflated negative binomial mixed-effects model in R
|
The pscl package provides for a zero inflated Poisson model. I don't think that it can do a negative binomial model, but it might be a place to start. The linked JSS article also discusses related pac
|
Zero-inflated negative binomial mixed-effects model in R
The pscl package provides for a zero inflated Poisson model. I don't think that it can do a negative binomial model, but it might be a place to start. The linked JSS article also discusses related packages, which may lead you to what you're looking for.
|
Zero-inflated negative binomial mixed-effects model in R
The pscl package provides for a zero inflated Poisson model. I don't think that it can do a negative binomial model, but it might be a place to start. The linked JSS article also discusses related pac
|
16,807
|
Zero-inflated negative binomial mixed-effects model in R
|
Depending on what you're trying to do, you might want to look at the aster package. Aster models allow joint analysis of multiple variables that have different probability distributions, and recently have been updated to allow for random effects. They were designed for life history analysis and will work in situations where you can split your response into distinct parts with different distributions, (e.g. survival = Bernoulli, reproduction = Poisson). They can handle "zero-inflation" by modeling the majority of zeroes as bernoulli, and the remainder of the response as negative binomial.
You'll find plenty of documentation here:
http://www.stat.umn.edu/geyer/aster/
|
Zero-inflated negative binomial mixed-effects model in R
|
Depending on what you're trying to do, you might want to look at the aster package. Aster models allow joint analysis of multiple variables that have different probability distributions, and recently
|
Zero-inflated negative binomial mixed-effects model in R
Depending on what you're trying to do, you might want to look at the aster package. Aster models allow joint analysis of multiple variables that have different probability distributions, and recently have been updated to allow for random effects. They were designed for life history analysis and will work in situations where you can split your response into distinct parts with different distributions, (e.g. survival = Bernoulli, reproduction = Poisson). They can handle "zero-inflation" by modeling the majority of zeroes as bernoulli, and the remainder of the response as negative binomial.
You'll find plenty of documentation here:
http://www.stat.umn.edu/geyer/aster/
|
Zero-inflated negative binomial mixed-effects model in R
Depending on what you're trying to do, you might want to look at the aster package. Aster models allow joint analysis of multiple variables that have different probability distributions, and recently
|
16,808
|
Zero-inflated negative binomial mixed-effects model in R
|
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
There are a lot of packages available. This link might be helpful:
https://journal.r-project.org/archive/2017/RJ-2017-066/RJ-2017-066.pdf
|
Zero-inflated negative binomial mixed-effects model in R
|
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
Zero-inflated negative binomial mixed-effects model in R
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
There are a lot of packages available. This link might be helpful:
https://journal.r-project.org/archive/2017/RJ-2017-066/RJ-2017-066.pdf
|
Zero-inflated negative binomial mixed-effects model in R
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
16,809
|
What are the stationarity requirements of using regression with ARIMA errors for inference?
|
My reading of the SAS text, corresponds with Hyndman and Athansopoulos.
In short: Go with Hyndman and Athansopoulos.
The first two paragraphs of the SAS text seem to just be talking about regression without any ARMA.
The last paragraph of the SAS text seems to correspond to the last paragraph of Hyndman and Athansolpoulos.
Regarding the comment: "unwarranted usage [of differencing] can create statistical/econometric nonsense"
I am guessing that this is differencing when there is no unit root.
Regarding the comment: "while the original series exhibit non-stationarity this does not necessarily imply that differencing is needed in a causal model."
I think that this is in line with the second paragraph of Hyndman and Athansopoulos.
Note that so far, we have just discussed non-seasonal differencing. There also exists seasonal differencing. There are tests for this such as OCSB, HEGY and Kunst (1997). I recall that D. Osborne once wrote that it is better to seasonally difference when a time series is "on the cusp".
So in summary, this should be your approach:
Are any of the variable co-integrated?
If yes, then those ones should not be differenced
Make the non co-integrated variables stationary.
|
What are the stationarity requirements of using regression with ARIMA errors for inference?
|
My reading of the SAS text, corresponds with Hyndman and Athansopoulos.
In short: Go with Hyndman and Athansopoulos.
The first two paragraphs of the SAS text seem to just be talking about regression w
|
What are the stationarity requirements of using regression with ARIMA errors for inference?
My reading of the SAS text, corresponds with Hyndman and Athansopoulos.
In short: Go with Hyndman and Athansopoulos.
The first two paragraphs of the SAS text seem to just be talking about regression without any ARMA.
The last paragraph of the SAS text seems to correspond to the last paragraph of Hyndman and Athansolpoulos.
Regarding the comment: "unwarranted usage [of differencing] can create statistical/econometric nonsense"
I am guessing that this is differencing when there is no unit root.
Regarding the comment: "while the original series exhibit non-stationarity this does not necessarily imply that differencing is needed in a causal model."
I think that this is in line with the second paragraph of Hyndman and Athansopoulos.
Note that so far, we have just discussed non-seasonal differencing. There also exists seasonal differencing. There are tests for this such as OCSB, HEGY and Kunst (1997). I recall that D. Osborne once wrote that it is better to seasonally difference when a time series is "on the cusp".
So in summary, this should be your approach:
Are any of the variable co-integrated?
If yes, then those ones should not be differenced
Make the non co-integrated variables stationary.
|
What are the stationarity requirements of using regression with ARIMA errors for inference?
My reading of the SAS text, corresponds with Hyndman and Athansopoulos.
In short: Go with Hyndman and Athansopoulos.
The first two paragraphs of the SAS text seem to just be talking about regression w
|
16,810
|
What are the stationarity requirements of using regression with ARIMA errors for inference?
|
According to David Giles, "if the tests that you've used to test for stationarity / non-stationarity have led you to a wrong conclusion, differencing everything is a conservative, but relatively safe way to proceed. You don't to unwittingly fail to difference a variable that is I(1). The "costs" of doing so are substantial. On the other hand, unnecessarily differencing a variable that is actually I(0) incurs a relatively low "cost"."
http://davegiles.blogspot.com/2015/04/question-from-reader.html
|
What are the stationarity requirements of using regression with ARIMA errors for inference?
|
According to David Giles, "if the tests that you've used to test for stationarity / non-stationarity have led you to a wrong conclusion, differencing everything is a conservative, but relatively safe
|
What are the stationarity requirements of using regression with ARIMA errors for inference?
According to David Giles, "if the tests that you've used to test for stationarity / non-stationarity have led you to a wrong conclusion, differencing everything is a conservative, but relatively safe way to proceed. You don't to unwittingly fail to difference a variable that is I(1). The "costs" of doing so are substantial. On the other hand, unnecessarily differencing a variable that is actually I(0) incurs a relatively low "cost"."
http://davegiles.blogspot.com/2015/04/question-from-reader.html
|
What are the stationarity requirements of using regression with ARIMA errors for inference?
According to David Giles, "if the tests that you've used to test for stationarity / non-stationarity have led you to a wrong conclusion, differencing everything is a conservative, but relatively safe
|
16,811
|
Using mutual information to estimate correlation between a continuous variable and a categorical variable
|
There is a simpler and better way to deal with this problem. A categorical variable is effectively just a set of indicator variable. It is a basic idea of measurement theory that such a variable is invariant to relabelling of the categories, so it does not make sense to use the numerical labelling of the categories in any measure of the relationship between another variable (e.g., 'correlation'). For this reason, and measure of the relationship between a continuous variable and a categorical variable should be based entirely on the indicator variables derived from the latter.
Given that you want a measure of 'correlation' between the two variables, it makes sense to look at the correlation between a continuous random variable $X$ and an indicator random variable $I$ derived from t a categorical variable. Letting $\phi \equiv \mathbb{P}(I=1)$ we have:
$$\mathbb{Cov}(I,X) = \mathbb{E}(IX) - \mathbb{E}(I) \mathbb{E}(X) = \phi \left[ \mathbb{E}(X|I=1) - \mathbb{E}(X) \right] ,$$
which gives:
$$\mathbb{Corr}(I,X) = \sqrt{\frac{\phi}{1-\phi}} \cdot \frac{\mathbb{E}(X|I=1) - \mathbb{E}(X)}{\mathbb{S}(X)} .$$
So the correlation between a continuous random variable $X$ and an indicator random variable $I$ is a fairly simple function of the indicator probability $\phi$ and the standardised gain in expected value of $X$ from conditioning on $I=1$. Note that this correlation does not require any discretization of the continuous random variable.
For a general categorical variable $C$ with range $1, ..., m$ you would then just extend this idea to have a vector of correlation values for each outcome of the categorical variable. For any outcome $C=k$ we can define the corresponding indicator $I_k \equiv \mathbb{I}(C=k)$ and we have:
$$\mathbb{Corr}(I_k,X) = \sqrt{\frac{\phi_k}{1-\phi_k}} \cdot \frac{\mathbb{E}(X|C=k) - \mathbb{E}(X)}{\mathbb{S}(X)} .$$
We can then define $\mathbb{Corr}(C,X) \equiv (\mathbb{Corr}(I_1,X), ..., \mathbb{Corr}(I_m,X))$ as the vector of correlation values for each category of the categorical random variable. This is really the only sense in which it makes sense to talk about 'correlation' for a categorical random variable.
(Note: It is trivial to show that $\sum_k \mathbb{Cov}(I_k,X) = 0$ and so the correlation vector for a categorical random variable is subject to this constraint. This means that given knowledge of the probability vector for the categorical random variable, and the standard deviation of $X$, you can derive the vector from any $m-1$ of its elements.)
The above exposition is for the true correlation values, but obviously these must be estimated in a given analysis. Estimating the indicator correlations from sample data is simple, and can be done by substitution of appropriate estimates for each of the parts. (You could use fancier estimation methods if you prefer.) Given sample data $(x_1, c_1), ..., (x_n, c_n)$ we can estimate the parts of the correlation equation as:
$$\hat{\phi}_k \equiv \frac{1}{n} \sum_{i=1}^n \mathbb{I}(c_i=k).$$
$$\hat{\mathbb{E}}(X) \equiv \bar{x} \equiv \frac{1}{n} \sum_{i=1}^n x_i.$$
$$\hat{\mathbb{E}}(X|C=k) \equiv \bar{x}_k \equiv \frac{1}{n} \sum_{i=1}^n x_i \mathbb{I}(c_i=k) \Bigg/ \hat{\phi}_k .$$
$$\hat{\mathbb{S}}(X) \equiv s_X \equiv \sqrt{\frac{1}{n-1} \sum_{i=1}^n (x_i - \bar{x})^2}.$$
Substitution of these estimates would yield a basic estimate of the correlation vector. If you have parametric information on $X$ then you could estimate the correlation vector directly by maximum likelihood or some other technique.
|
Using mutual information to estimate correlation between a continuous variable and a categorical var
|
There is a simpler and better way to deal with this problem. A categorical variable is effectively just a set of indicator variable. It is a basic idea of measurement theory that such a variable is
|
Using mutual information to estimate correlation between a continuous variable and a categorical variable
There is a simpler and better way to deal with this problem. A categorical variable is effectively just a set of indicator variable. It is a basic idea of measurement theory that such a variable is invariant to relabelling of the categories, so it does not make sense to use the numerical labelling of the categories in any measure of the relationship between another variable (e.g., 'correlation'). For this reason, and measure of the relationship between a continuous variable and a categorical variable should be based entirely on the indicator variables derived from the latter.
Given that you want a measure of 'correlation' between the two variables, it makes sense to look at the correlation between a continuous random variable $X$ and an indicator random variable $I$ derived from t a categorical variable. Letting $\phi \equiv \mathbb{P}(I=1)$ we have:
$$\mathbb{Cov}(I,X) = \mathbb{E}(IX) - \mathbb{E}(I) \mathbb{E}(X) = \phi \left[ \mathbb{E}(X|I=1) - \mathbb{E}(X) \right] ,$$
which gives:
$$\mathbb{Corr}(I,X) = \sqrt{\frac{\phi}{1-\phi}} \cdot \frac{\mathbb{E}(X|I=1) - \mathbb{E}(X)}{\mathbb{S}(X)} .$$
So the correlation between a continuous random variable $X$ and an indicator random variable $I$ is a fairly simple function of the indicator probability $\phi$ and the standardised gain in expected value of $X$ from conditioning on $I=1$. Note that this correlation does not require any discretization of the continuous random variable.
For a general categorical variable $C$ with range $1, ..., m$ you would then just extend this idea to have a vector of correlation values for each outcome of the categorical variable. For any outcome $C=k$ we can define the corresponding indicator $I_k \equiv \mathbb{I}(C=k)$ and we have:
$$\mathbb{Corr}(I_k,X) = \sqrt{\frac{\phi_k}{1-\phi_k}} \cdot \frac{\mathbb{E}(X|C=k) - \mathbb{E}(X)}{\mathbb{S}(X)} .$$
We can then define $\mathbb{Corr}(C,X) \equiv (\mathbb{Corr}(I_1,X), ..., \mathbb{Corr}(I_m,X))$ as the vector of correlation values for each category of the categorical random variable. This is really the only sense in which it makes sense to talk about 'correlation' for a categorical random variable.
(Note: It is trivial to show that $\sum_k \mathbb{Cov}(I_k,X) = 0$ and so the correlation vector for a categorical random variable is subject to this constraint. This means that given knowledge of the probability vector for the categorical random variable, and the standard deviation of $X$, you can derive the vector from any $m-1$ of its elements.)
The above exposition is for the true correlation values, but obviously these must be estimated in a given analysis. Estimating the indicator correlations from sample data is simple, and can be done by substitution of appropriate estimates for each of the parts. (You could use fancier estimation methods if you prefer.) Given sample data $(x_1, c_1), ..., (x_n, c_n)$ we can estimate the parts of the correlation equation as:
$$\hat{\phi}_k \equiv \frac{1}{n} \sum_{i=1}^n \mathbb{I}(c_i=k).$$
$$\hat{\mathbb{E}}(X) \equiv \bar{x} \equiv \frac{1}{n} \sum_{i=1}^n x_i.$$
$$\hat{\mathbb{E}}(X|C=k) \equiv \bar{x}_k \equiv \frac{1}{n} \sum_{i=1}^n x_i \mathbb{I}(c_i=k) \Bigg/ \hat{\phi}_k .$$
$$\hat{\mathbb{S}}(X) \equiv s_X \equiv \sqrt{\frac{1}{n-1} \sum_{i=1}^n (x_i - \bar{x})^2}.$$
Substitution of these estimates would yield a basic estimate of the correlation vector. If you have parametric information on $X$ then you could estimate the correlation vector directly by maximum likelihood or some other technique.
|
Using mutual information to estimate correlation between a continuous variable and a categorical var
There is a simpler and better way to deal with this problem. A categorical variable is effectively just a set of indicator variable. It is a basic idea of measurement theory that such a variable is
|
16,812
|
Why don't statisticians use mutual information as a measure of association?
|
I think you should distinguish between categorical (discrete) data and continuous data.
For continuous data, Pearson correlation measures a linear (monotonic) relationship, rank correlation a monotonic relationship.
MI on the other hand "detects" any relationship. This is normally not what you are interested in and/or is likely to be noise.
In particular, you have to estimate the density of the distribution. But since it is continuous, you would first create a histogram [discrete bins], and then calculate MI. But since MI allows for any relationship, the MI will change as you use smaller bins (i.e. so you allow more wiggles). So you can see that the estimation of MI will be very unstable, not allowing you to put any confidence intervals on the estimate etc. [Same goes if you do a continuous density estimate.] Basically there are too many things to estimate before actually calculating the MI.
Categorical data on the other hand fits quite nicely into MI framework (see G-test), and there is not much to choose between G-test and chi-squared.
|
Why don't statisticians use mutual information as a measure of association?
|
I think you should distinguish between categorical (discrete) data and continuous data.
For continuous data, Pearson correlation measures a linear (monotonic) relationship, rank correlation a monoton
|
Why don't statisticians use mutual information as a measure of association?
I think you should distinguish between categorical (discrete) data and continuous data.
For continuous data, Pearson correlation measures a linear (monotonic) relationship, rank correlation a monotonic relationship.
MI on the other hand "detects" any relationship. This is normally not what you are interested in and/or is likely to be noise.
In particular, you have to estimate the density of the distribution. But since it is continuous, you would first create a histogram [discrete bins], and then calculate MI. But since MI allows for any relationship, the MI will change as you use smaller bins (i.e. so you allow more wiggles). So you can see that the estimation of MI will be very unstable, not allowing you to put any confidence intervals on the estimate etc. [Same goes if you do a continuous density estimate.] Basically there are too many things to estimate before actually calculating the MI.
Categorical data on the other hand fits quite nicely into MI framework (see G-test), and there is not much to choose between G-test and chi-squared.
|
Why don't statisticians use mutual information as a measure of association?
I think you should distinguish between categorical (discrete) data and continuous data.
For continuous data, Pearson correlation measures a linear (monotonic) relationship, rank correlation a monoton
|
16,813
|
"Zero-inflated" predictors in regression?
|
So it's important to think of the source of zero-inflation. Two sources that come to mind are:
floor effect: your measurement instrument cannot detect values below a certain threshold and so the instrument simply returns zero. Think of a scale with 40 questions supposedly measuring "high-end math knowledge", so the test is really difficult. For each question, you could be incorrect (0 score) or correct (1 score). A test-taker could be incorrect on all 40 questions resulting in a total score of 0. Assuming the scale is indeed unidimensional/valid for high end math knowledge, this 0 score does not mean the respondent has zero math knowledge. But it suggests their math knowledge is at a level below which the test can detect. If someone administered this test to the general population, you might get a high proportion of zero scores. This scenario can occur in many different contexts. Sometimes, a measurement instrument can only detect differences beyond a threshold, and several respondents are below that threshold. Instruments for physical quantities might simply return a < X score, where X is that threshold.
true zero: Sometimes, people really have a zero score. For example, this can happen with counts, e.g. how many homes do you own? And sometimes, there is something fundamentally different between someone who does not own their home and someone who owns one or more homes.
So it's important to think of the source of zeroes and what you're trying to measure.
In the floor effect situation, I might claim that the math scores would be approximately normally distributed but for the floor effect. So I'd assume we have a normally distributed variable that has been censored at 0. The effect of analyzing with the predictor as is is range restriction which - all other factors held constant - can reduce power. So you could build a model that accommodates a censored predictor - Bayesian modeling should make this easy.
In the true zero situation, I might decide to dichotomize the variable to create two predictors: one binary (homeowner or not) and one continuous (how many homes). Then use both predictors in my model, allowing you to measure the effect of home ownership separate from owning more homes.
These are just two scenarios that come to mind. Also, it's never clear cut. Number of homes could also be a proxy for another variable, where number of homes is a proxy that cannot detect levels of that variable beneath a threshold. If your interest is in measuring the relation between the outcome and the true variable number of homes is a proxy for, you have another example of a censored predictor.
In all, having a predictor with many zeroes welcomes you to think about why that might be happening. And what you might want to do about it. Also, the easiest viewpoint to take is regression places no assumption on predictor distributions and just proceed with the predictor as is.
|
"Zero-inflated" predictors in regression?
|
So it's important to think of the source of zero-inflation. Two sources that come to mind are:
floor effect: your measurement instrument cannot detect values below a certain threshold and so the inst
|
"Zero-inflated" predictors in regression?
So it's important to think of the source of zero-inflation. Two sources that come to mind are:
floor effect: your measurement instrument cannot detect values below a certain threshold and so the instrument simply returns zero. Think of a scale with 40 questions supposedly measuring "high-end math knowledge", so the test is really difficult. For each question, you could be incorrect (0 score) or correct (1 score). A test-taker could be incorrect on all 40 questions resulting in a total score of 0. Assuming the scale is indeed unidimensional/valid for high end math knowledge, this 0 score does not mean the respondent has zero math knowledge. But it suggests their math knowledge is at a level below which the test can detect. If someone administered this test to the general population, you might get a high proportion of zero scores. This scenario can occur in many different contexts. Sometimes, a measurement instrument can only detect differences beyond a threshold, and several respondents are below that threshold. Instruments for physical quantities might simply return a < X score, where X is that threshold.
true zero: Sometimes, people really have a zero score. For example, this can happen with counts, e.g. how many homes do you own? And sometimes, there is something fundamentally different between someone who does not own their home and someone who owns one or more homes.
So it's important to think of the source of zeroes and what you're trying to measure.
In the floor effect situation, I might claim that the math scores would be approximately normally distributed but for the floor effect. So I'd assume we have a normally distributed variable that has been censored at 0. The effect of analyzing with the predictor as is is range restriction which - all other factors held constant - can reduce power. So you could build a model that accommodates a censored predictor - Bayesian modeling should make this easy.
In the true zero situation, I might decide to dichotomize the variable to create two predictors: one binary (homeowner or not) and one continuous (how many homes). Then use both predictors in my model, allowing you to measure the effect of home ownership separate from owning more homes.
These are just two scenarios that come to mind. Also, it's never clear cut. Number of homes could also be a proxy for another variable, where number of homes is a proxy that cannot detect levels of that variable beneath a threshold. If your interest is in measuring the relation between the outcome and the true variable number of homes is a proxy for, you have another example of a censored predictor.
In all, having a predictor with many zeroes welcomes you to think about why that might be happening. And what you might want to do about it. Also, the easiest viewpoint to take is regression places no assumption on predictor distributions and just proceed with the predictor as is.
|
"Zero-inflated" predictors in regression?
So it's important to think of the source of zero-inflation. Two sources that come to mind are:
floor effect: your measurement instrument cannot detect values below a certain threshold and so the inst
|
16,814
|
"Zero-inflated" predictors in regression?
|
Zero-inflation is a probabilistic concept, and it means something different than "the distribution has a lot of zeroes". For instance, a Poisson or negative binomial model can use parameters so that 90% or 99% of the values are 0, but that doesn't "make" it zero-inflated. Zero-inflation is a mixture of a known probability model and a 0 constant "variable".
In statistics, when you consider the whole host of multimodal distributions out there, and collecting a sample like what you describe, and declaring a. that you know what distribution it's supposed to be and b. that it did not fit that distribution because it's zero-inflated... well the plausibility goes almost surely to 0.
If we broaden the scope, there's a more illustrative question to consider: when do we care about the impact of the distribution of the covariates $X$ when conducting a regression analysis? The answer is: almost never. More precisely, most default regression methods make no use whatsoever of the distribution of the covariates. The exceptions would be in cases of correcting biased sampling with weights, measurement error methods, indirect standardization, performing expectation maximization to handle truncation, or parametric bootstrap: i.e. advanced methods. However OLS, for instance, geometrically is a projection so that the residuals are orthogonal to the predictors, this does not guarantee that the error term and the regressors are independent hence the need for detailed diagnostic plots and analyses.
Lastly, your finding is not surprising. Dichotomizing a variable is still a bad idea for irregular covariates for the same reason it's a bad idea for nicely behaved covariates. Reducing the variability of $X$ reduces the precision of the analysis. In fact, a nice formula to recall is the following:
$$ \text{SE}(\hat{\beta}) = \sigma^{2} / \text{var}(X)$$
(a bivariate result that extends more or less to higher dimensional analyses).
In other words, the confidence interval for $\hat{\beta}$ and $p$-value for the statistical test of the hypothesis $\mathcal{H}_0: \beta=0$ shrink when considering designs where $X$ is more variable. Dichotomizing a variable fundamentally reduces its variability.
|
"Zero-inflated" predictors in regression?
|
Zero-inflation is a probabilistic concept, and it means something different than "the distribution has a lot of zeroes". For instance, a Poisson or negative binomial model can use parameters so that 9
|
"Zero-inflated" predictors in regression?
Zero-inflation is a probabilistic concept, and it means something different than "the distribution has a lot of zeroes". For instance, a Poisson or negative binomial model can use parameters so that 90% or 99% of the values are 0, but that doesn't "make" it zero-inflated. Zero-inflation is a mixture of a known probability model and a 0 constant "variable".
In statistics, when you consider the whole host of multimodal distributions out there, and collecting a sample like what you describe, and declaring a. that you know what distribution it's supposed to be and b. that it did not fit that distribution because it's zero-inflated... well the plausibility goes almost surely to 0.
If we broaden the scope, there's a more illustrative question to consider: when do we care about the impact of the distribution of the covariates $X$ when conducting a regression analysis? The answer is: almost never. More precisely, most default regression methods make no use whatsoever of the distribution of the covariates. The exceptions would be in cases of correcting biased sampling with weights, measurement error methods, indirect standardization, performing expectation maximization to handle truncation, or parametric bootstrap: i.e. advanced methods. However OLS, for instance, geometrically is a projection so that the residuals are orthogonal to the predictors, this does not guarantee that the error term and the regressors are independent hence the need for detailed diagnostic plots and analyses.
Lastly, your finding is not surprising. Dichotomizing a variable is still a bad idea for irregular covariates for the same reason it's a bad idea for nicely behaved covariates. Reducing the variability of $X$ reduces the precision of the analysis. In fact, a nice formula to recall is the following:
$$ \text{SE}(\hat{\beta}) = \sigma^{2} / \text{var}(X)$$
(a bivariate result that extends more or less to higher dimensional analyses).
In other words, the confidence interval for $\hat{\beta}$ and $p$-value for the statistical test of the hypothesis $\mathcal{H}_0: \beta=0$ shrink when considering designs where $X$ is more variable. Dichotomizing a variable fundamentally reduces its variability.
|
"Zero-inflated" predictors in regression?
Zero-inflation is a probabilistic concept, and it means something different than "the distribution has a lot of zeroes". For instance, a Poisson or negative binomial model can use parameters so that 9
|
16,815
|
What is the expected value of modified Dirichlet distribution? (integration problem)
|
Just an initial remark, if you want computational speed you usually have to sacrifice accuracy. "More accuracy" = "More time" in general. Anyways here is a second order approximation, should improve on the "crude" approx you suggested in your comment above:
$$E\Bigg(\frac{X_{j}}{\sum_{i}X_{i}}\Bigg)\approx
\frac{E[X_{j}]}{E[\sum_{i}X_{i}]}
-\frac{cov[\sum_{i}X_{i},X_{j}]}{E[\sum_{i}X_{i}]^2}
+\frac{E[X_{j}]}{E[\sum_{i}X_{i}]^3} Var[\sum_{i}X_{i}]
$$
$$= \frac{\alpha_{j}}{\sum_{i} \frac{\beta_{j}}{\beta_{i}}\alpha_{i}}\times\Bigg[1 - \frac{1}{\Bigg(\sum_{i} \frac{\beta_{j}}{\beta_{i}}\alpha_{i}\Bigg)}
+ \frac{1}{\Bigg(\sum_{i} \frac{\alpha_{i}}{\beta_{i}}\Bigg)^2}\Bigg(\sum_{i} \frac{\alpha_{i}}{\beta_{i}^2}\Bigg)\Bigg]
$$
EDIT An explanation for the above expansion was requested. The short answer is wikipedia. The long answer is given below.
write $f(x,y)=\frac{x}{y}$. Now we need all the "second order" derivatives of $f$. The first order derivatives will "cancel" because they will all involve multiples $X-E(X)$ and $Y-E(Y)$ which are both zero when taking expectations.
$$\frac{\partial^2 f}{\partial x^2}=0$$
$$\frac{\partial^2 f}{\partial x \partial y}=-\frac{1}{y^2}$$
$$\frac{\partial^2 f}{\partial y^2}=2\frac{x}{y^3}$$
And so the taylor series up to second order is given by:
$$\frac{x}{y} \approx \frac{\mu_x}{\mu_y}+\frac{1}{2}\Bigg(-\frac{1}{\mu_y^2}2(x-\mu_x)(y-\mu_y) + 2\frac{\mu_x}{\mu_y^3}(y-\mu_y)^2 \Bigg)$$
Taking expectations yields:
$$E\Big[\frac{x}{y}\Big] \approx \frac{\mu_x}{\mu_y}-\frac{1}{\mu_y^2}E\Big[(x-\mu_x)(y-\mu_y)\Big] + \frac{\mu_x}{\mu_y^3}E\Big[(y-\mu_y)^2\Big]$$
Which is the answer I gave. (although I initially forgot the minus sign in the second term)
|
What is the expected value of modified Dirichlet distribution? (integration problem)
|
Just an initial remark, if you want computational speed you usually have to sacrifice accuracy. "More accuracy" = "More time" in general. Anyways here is a second order approximation, should improve
|
What is the expected value of modified Dirichlet distribution? (integration problem)
Just an initial remark, if you want computational speed you usually have to sacrifice accuracy. "More accuracy" = "More time" in general. Anyways here is a second order approximation, should improve on the "crude" approx you suggested in your comment above:
$$E\Bigg(\frac{X_{j}}{\sum_{i}X_{i}}\Bigg)\approx
\frac{E[X_{j}]}{E[\sum_{i}X_{i}]}
-\frac{cov[\sum_{i}X_{i},X_{j}]}{E[\sum_{i}X_{i}]^2}
+\frac{E[X_{j}]}{E[\sum_{i}X_{i}]^3} Var[\sum_{i}X_{i}]
$$
$$= \frac{\alpha_{j}}{\sum_{i} \frac{\beta_{j}}{\beta_{i}}\alpha_{i}}\times\Bigg[1 - \frac{1}{\Bigg(\sum_{i} \frac{\beta_{j}}{\beta_{i}}\alpha_{i}\Bigg)}
+ \frac{1}{\Bigg(\sum_{i} \frac{\alpha_{i}}{\beta_{i}}\Bigg)^2}\Bigg(\sum_{i} \frac{\alpha_{i}}{\beta_{i}^2}\Bigg)\Bigg]
$$
EDIT An explanation for the above expansion was requested. The short answer is wikipedia. The long answer is given below.
write $f(x,y)=\frac{x}{y}$. Now we need all the "second order" derivatives of $f$. The first order derivatives will "cancel" because they will all involve multiples $X-E(X)$ and $Y-E(Y)$ which are both zero when taking expectations.
$$\frac{\partial^2 f}{\partial x^2}=0$$
$$\frac{\partial^2 f}{\partial x \partial y}=-\frac{1}{y^2}$$
$$\frac{\partial^2 f}{\partial y^2}=2\frac{x}{y^3}$$
And so the taylor series up to second order is given by:
$$\frac{x}{y} \approx \frac{\mu_x}{\mu_y}+\frac{1}{2}\Bigg(-\frac{1}{\mu_y^2}2(x-\mu_x)(y-\mu_y) + 2\frac{\mu_x}{\mu_y^3}(y-\mu_y)^2 \Bigg)$$
Taking expectations yields:
$$E\Big[\frac{x}{y}\Big] \approx \frac{\mu_x}{\mu_y}-\frac{1}{\mu_y^2}E\Big[(x-\mu_x)(y-\mu_y)\Big] + \frac{\mu_x}{\mu_y^3}E\Big[(y-\mu_y)^2\Big]$$
Which is the answer I gave. (although I initially forgot the minus sign in the second term)
|
What is the expected value of modified Dirichlet distribution? (integration problem)
Just an initial remark, if you want computational speed you usually have to sacrifice accuracy. "More accuracy" = "More time" in general. Anyways here is a second order approximation, should improve
|
16,816
|
Sequential hypothesis testing in basic science
|
I don't know much of sequential tests and their application outside of interim analysis (Jennison and Turnbull, 2000) and computerized adaptive testing (van der Linden and Glas, 2010). One exception is in some fMRI studies that are associated to large costs and difficulty to enroll subjects. Basically, in this case sequential testing primarily aims at stopping the experiment earlier. So, I am not surprised that these very tailored approaches are not taught in usual statistical classes.
Sequential tests are not without their pitfalls, though (type I and II error have to be specified in advance, choice of the stopping rule and multiple look at results should be justified, p-values are not uniformly distributed under the null as in a fixed sample design, etc.). In most design, we work with a pre-specified experimental setting or a preliminary power study was carried out, to optimize some kind of cost-effectiveness criterion, in which case standard testing procedures apply.
I found, however, the following paper from Maik Dierkes about fixed vs. open sample design very interesting: A claim for sequential designs of experiments.
|
Sequential hypothesis testing in basic science
|
I don't know much of sequential tests and their application outside of interim analysis (Jennison and Turnbull, 2000) and computerized adaptive testing (van der Linden and Glas, 2010). One exception i
|
Sequential hypothesis testing in basic science
I don't know much of sequential tests and their application outside of interim analysis (Jennison and Turnbull, 2000) and computerized adaptive testing (van der Linden and Glas, 2010). One exception is in some fMRI studies that are associated to large costs and difficulty to enroll subjects. Basically, in this case sequential testing primarily aims at stopping the experiment earlier. So, I am not surprised that these very tailored approaches are not taught in usual statistical classes.
Sequential tests are not without their pitfalls, though (type I and II error have to be specified in advance, choice of the stopping rule and multiple look at results should be justified, p-values are not uniformly distributed under the null as in a fixed sample design, etc.). In most design, we work with a pre-specified experimental setting or a preliminary power study was carried out, to optimize some kind of cost-effectiveness criterion, in which case standard testing procedures apply.
I found, however, the following paper from Maik Dierkes about fixed vs. open sample design very interesting: A claim for sequential designs of experiments.
|
Sequential hypothesis testing in basic science
I don't know much of sequential tests and their application outside of interim analysis (Jennison and Turnbull, 2000) and computerized adaptive testing (van der Linden and Glas, 2010). One exception i
|
16,817
|
Why isn't "Saddle-Free Newton" descent algorithm used in practice?
|
Better optimization does not necessarily mean a better model. In the end what we care about is how well the model generalizes, and not necessarily how good the performance on the training set is. Fancier optimization techniques usually perform better and converge faster on the training set, but do not always generalize as well as basic algorithms. For example this paper shows that SGD can generalize better than ADAM optimizer. This can also be the case with some second order optimization algorithms.
[Edit] Removed the first point as it does not apply here. Thanks to bayerj for pointing this out.
|
Why isn't "Saddle-Free Newton" descent algorithm used in practice?
|
Better optimization does not necessarily mean a better model. In the end what we care about is how well the model generalizes, and not necessarily how good the performance on the training set is. Fanc
|
Why isn't "Saddle-Free Newton" descent algorithm used in practice?
Better optimization does not necessarily mean a better model. In the end what we care about is how well the model generalizes, and not necessarily how good the performance on the training set is. Fancier optimization techniques usually perform better and converge faster on the training set, but do not always generalize as well as basic algorithms. For example this paper shows that SGD can generalize better than ADAM optimizer. This can also be the case with some second order optimization algorithms.
[Edit] Removed the first point as it does not apply here. Thanks to bayerj for pointing this out.
|
Why isn't "Saddle-Free Newton" descent algorithm used in practice?
Better optimization does not necessarily mean a better model. In the end what we care about is how well the model generalizes, and not necessarily how good the performance on the training set is. Fanc
|
16,818
|
What is the meaning of the eigenvectors of a mutual information matrix?
|
While it is not a direct answer (as it is about pointwise mutual information), look at paper relating word2vec to a singular value decomposition of PMI matrix:
O. Levy, Y. Goldberg, Neural Word Embedding as Implicit Matrix Factorization
We analyze skip-gram with negative-sampling (SGNS), a word embedding
method introduced by Mikolov et al., and show that it is implicitly factorizing
a word-context matrix, whose cells are the pointwise mutual information (PMI) of
the respective word and context pairs, shifted by a global constant. We find that
another embedding method, NCE, is implicitly factorizing a similar matrix, where
each cell is the (shifted) log conditional probability of a word given its context.
We show that using a sparse Shifted Positive PMI word-context matrix to represent
words improves results on two word similarity tasks and one of two analogy tasks.
When dense low-dimensional vectors are preferred, exact factorization with SVD
can achieve solutions that are at least as good as SGNS’s solutions for word similarity
tasks. On analogy questions SGNS remains superior to SVD. We conjecture
that this stems from the weighted nature of SGNS’s factorization.
|
What is the meaning of the eigenvectors of a mutual information matrix?
|
While it is not a direct answer (as it is about pointwise mutual information), look at paper relating word2vec to a singular value decomposition of PMI matrix:
O. Levy, Y. Goldberg, Neural Word Embed
|
What is the meaning of the eigenvectors of a mutual information matrix?
While it is not a direct answer (as it is about pointwise mutual information), look at paper relating word2vec to a singular value decomposition of PMI matrix:
O. Levy, Y. Goldberg, Neural Word Embedding as Implicit Matrix Factorization
We analyze skip-gram with negative-sampling (SGNS), a word embedding
method introduced by Mikolov et al., and show that it is implicitly factorizing
a word-context matrix, whose cells are the pointwise mutual information (PMI) of
the respective word and context pairs, shifted by a global constant. We find that
another embedding method, NCE, is implicitly factorizing a similar matrix, where
each cell is the (shifted) log conditional probability of a word given its context.
We show that using a sparse Shifted Positive PMI word-context matrix to represent
words improves results on two word similarity tasks and one of two analogy tasks.
When dense low-dimensional vectors are preferred, exact factorization with SVD
can achieve solutions that are at least as good as SGNS’s solutions for word similarity
tasks. On analogy questions SGNS remains superior to SVD. We conjecture
that this stems from the weighted nature of SGNS’s factorization.
|
What is the meaning of the eigenvectors of a mutual information matrix?
While it is not a direct answer (as it is about pointwise mutual information), look at paper relating word2vec to a singular value decomposition of PMI matrix:
O. Levy, Y. Goldberg, Neural Word Embed
|
16,819
|
Survival Model for Predicting Churn - Time-varying predictors?
|
Thank you for the clarification, B_Miner. I don't do a lot of forecasting myself, so take what follows with a pinch of salt. Here is what I would do as at least a first cut at the data.
First, formulate and estimate a model that explains your TVCs. Do all of the cross-validation, error checking, etc., to make sure you have a decent model for the data.
Second, formulate and estimate a survival model (of whatever flavor). Do all of the cross-validation, error checking, to make sure this model is reasonable as well.
Third, settle on a method of using the forecasts from the TVCs model as the basis of forecasting risks of churn and whatever else you want. Once again, verify that the predictions are reasonable using your sample.
Once you have a model that you think is reasonable, I would suggest bootstrapping the data as a way to incorporate the error in the first TVC model into the second model. Basically, apply steps 1-3 N times, each time taking a bootstrap sample from the data and producing a set of forecasts. When you have a reasonable number of forecasts, summarize them in any way you think is appropriate for your task; e.g., provide mean risk of churn for each individual or covariate profile of interest as well as 95% confidence intervals.
|
Survival Model for Predicting Churn - Time-varying predictors?
|
Thank you for the clarification, B_Miner. I don't do a lot of forecasting myself, so take what follows with a pinch of salt. Here is what I would do as at least a first cut at the data.
First, formul
|
Survival Model for Predicting Churn - Time-varying predictors?
Thank you for the clarification, B_Miner. I don't do a lot of forecasting myself, so take what follows with a pinch of salt. Here is what I would do as at least a first cut at the data.
First, formulate and estimate a model that explains your TVCs. Do all of the cross-validation, error checking, etc., to make sure you have a decent model for the data.
Second, formulate and estimate a survival model (of whatever flavor). Do all of the cross-validation, error checking, to make sure this model is reasonable as well.
Third, settle on a method of using the forecasts from the TVCs model as the basis of forecasting risks of churn and whatever else you want. Once again, verify that the predictions are reasonable using your sample.
Once you have a model that you think is reasonable, I would suggest bootstrapping the data as a way to incorporate the error in the first TVC model into the second model. Basically, apply steps 1-3 N times, each time taking a bootstrap sample from the data and producing a set of forecasts. When you have a reasonable number of forecasts, summarize them in any way you think is appropriate for your task; e.g., provide mean risk of churn for each individual or covariate profile of interest as well as 95% confidence intervals.
|
Survival Model for Predicting Churn - Time-varying predictors?
Thank you for the clarification, B_Miner. I don't do a lot of forecasting myself, so take what follows with a pinch of salt. Here is what I would do as at least a first cut at the data.
First, formul
|
16,820
|
Survival Model for Predicting Churn - Time-varying predictors?
|
As I see it there are two survival analysis paradigms that could be used. The Cox regression framework allows time varying covariates and would produce an estimate for the risk of cancellation conditioned on any particular set of covariates relative to the mean level of cancellation. The glm framework with Poisson errors is also a proportional hazards model and is particularly suited to discrete intervals. JVM has pointed out that there is potential error in using incomplete data in the current month, but the sense I get is that you want an estimate that is conditional on the latest value of a co-variate or set of covariates. Better description of the data situation could yield better worked examples....
|
Survival Model for Predicting Churn - Time-varying predictors?
|
As I see it there are two survival analysis paradigms that could be used. The Cox regression framework allows time varying covariates and would produce an estimate for the risk of cancellation condit
|
Survival Model for Predicting Churn - Time-varying predictors?
As I see it there are two survival analysis paradigms that could be used. The Cox regression framework allows time varying covariates and would produce an estimate for the risk of cancellation conditioned on any particular set of covariates relative to the mean level of cancellation. The glm framework with Poisson errors is also a proportional hazards model and is particularly suited to discrete intervals. JVM has pointed out that there is potential error in using incomplete data in the current month, but the sense I get is that you want an estimate that is conditional on the latest value of a co-variate or set of covariates. Better description of the data situation could yield better worked examples....
|
Survival Model for Predicting Churn - Time-varying predictors?
As I see it there are two survival analysis paradigms that could be used. The Cox regression framework allows time varying covariates and would produce an estimate for the risk of cancellation condit
|
16,821
|
The role of scale parameter in GEE
|
Q1
If you use the sandwich estimator for the covariance, GEE's coefficients and standard errors are consistent even if your working models for $\alpha$ and $\phi$ are wrong. This is well-covered elsewhere, e.g. Sandwich estimator intuition .
Q2
I don't know if it was the same back in 2012, but nowadays at least, scale.value is only used if scale.fix is TRUE.
Q3
Yes, you're exactly right. The scale parameter $\phi$ is distinct from the NB dispersion $\varphi$. They are similar in a vague sense -- "addressing overdispersion" -- but different quantitatively. For example, if $\mu=1$, then $\varphi$ adds itself to the variance, whereas $\phi$ multiplies itself by the variance.
One key qualitative difference is that $\phi$ does not help re-weight observations to lend more credence to those with lower variance, whereas $\varphi$ does. You can plug in anything for $\phi$ and get the same coefficients out. Not so for $\varphi$; huge values will cause your estimates to depend overly on observations with small fitted values (for $\mu$). There is a nice recap of closely related techniques in this paper, which, as a bonus, involves a cute kind of animal (harbor seals).
|
The role of scale parameter in GEE
|
Q1
If you use the sandwich estimator for the covariance, GEE's coefficients and standard errors are consistent even if your working models for $\alpha$ and $\phi$ are wrong. This is well-covered elsew
|
The role of scale parameter in GEE
Q1
If you use the sandwich estimator for the covariance, GEE's coefficients and standard errors are consistent even if your working models for $\alpha$ and $\phi$ are wrong. This is well-covered elsewhere, e.g. Sandwich estimator intuition .
Q2
I don't know if it was the same back in 2012, but nowadays at least, scale.value is only used if scale.fix is TRUE.
Q3
Yes, you're exactly right. The scale parameter $\phi$ is distinct from the NB dispersion $\varphi$. They are similar in a vague sense -- "addressing overdispersion" -- but different quantitatively. For example, if $\mu=1$, then $\varphi$ adds itself to the variance, whereas $\phi$ multiplies itself by the variance.
One key qualitative difference is that $\phi$ does not help re-weight observations to lend more credence to those with lower variance, whereas $\varphi$ does. You can plug in anything for $\phi$ and get the same coefficients out. Not so for $\varphi$; huge values will cause your estimates to depend overly on observations with small fitted values (for $\mu$). There is a nice recap of closely related techniques in this paper, which, as a bonus, involves a cute kind of animal (harbor seals).
|
The role of scale parameter in GEE
Q1
If you use the sandwich estimator for the covariance, GEE's coefficients and standard errors are consistent even if your working models for $\alpha$ and $\phi$ are wrong. This is well-covered elsew
|
16,822
|
How to account for the impact of holidays in forecast
|
Couldn't you create a dummy variable for holiday, one for holiday+1 and one for holiday+2 and only set them to 1 as long as they fall on a weekday?
As for Thanksgiving and Christmas, introducing separate dummy variables for these holidays seems to be your worst case option (since you only have six years of data). To a certain extent, that might be your only option though - people simply behave differently on those holidays than they do on, say, Fourth of July (and if you are studying e.g. retail sales patterns, then you definitely simply have to live with those being "special" holidays and would definitely want to analyze them separately). However, maybe the below ideas are helpful to you:
Thanksgiving. Shouldn't the fact that it always falls on the same day of the week (Thursday) make it easier? I.e. a Thanksgiving dummy might just be workable even in a six-year data set because the weekday pattern will always be the same.
Christmas. It appears to me from looking at your graph that the main issue is that the effect lasts longer than after other holidays - if you define "Christmas" as Christmas Eve (Dec 24th), then that will be because many people will also stay home on Christmas Day (Dec 25th) (and even Boxing Day (Dec 26th) in some places). I'll think some more about this.
I hope this helps.
|
How to account for the impact of holidays in forecast
|
Couldn't you create a dummy variable for holiday, one for holiday+1 and one for holiday+2 and only set them to 1 as long as they fall on a weekday?
As for Thanksgiving and Christmas, introducing separ
|
How to account for the impact of holidays in forecast
Couldn't you create a dummy variable for holiday, one for holiday+1 and one for holiday+2 and only set them to 1 as long as they fall on a weekday?
As for Thanksgiving and Christmas, introducing separate dummy variables for these holidays seems to be your worst case option (since you only have six years of data). To a certain extent, that might be your only option though - people simply behave differently on those holidays than they do on, say, Fourth of July (and if you are studying e.g. retail sales patterns, then you definitely simply have to live with those being "special" holidays and would definitely want to analyze them separately). However, maybe the below ideas are helpful to you:
Thanksgiving. Shouldn't the fact that it always falls on the same day of the week (Thursday) make it easier? I.e. a Thanksgiving dummy might just be workable even in a six-year data set because the weekday pattern will always be the same.
Christmas. It appears to me from looking at your graph that the main issue is that the effect lasts longer than after other holidays - if you define "Christmas" as Christmas Eve (Dec 24th), then that will be because many people will also stay home on Christmas Day (Dec 25th) (and even Boxing Day (Dec 26th) in some places). I'll think some more about this.
I hope this helps.
|
How to account for the impact of holidays in forecast
Couldn't you create a dummy variable for holiday, one for holiday+1 and one for holiday+2 and only set them to 1 as long as they fall on a weekday?
As for Thanksgiving and Christmas, introducing separ
|
16,823
|
Writing out the mathematical equation for a multilevel mixed effects model
|
If I understood the code correctly, why not simply writing something like
$$y_{i} = \Big(\alpha + \nu_{j[i]}^{(\alpha)} + \eta_{k[i]}^{(\alpha)}\Big) + \Big(\beta + \nu_{j[i]}^{(\beta)} + \eta_{k[i]}^{(\beta)}\Big)T_{i} + \Big(\delta + \nu_{j[i]}^{(\delta)} + \eta_{k[i]}^{(\delta)}\Big)(T_{i} * Z_{i}) + \epsilon_i$$
with
$$\begin{aligned}
\Big[\nu_{j}^{(\alpha)}, \nu_j^{(\beta)}, \nu_j^{(\delta)}\Big] &\sim \text{Multi-Normal}(\mathbf 0, \boldsymbol \Sigma_\nu) \\
\Big[\eta_{j}^{(\alpha)}, \eta_j^{(\beta)}, \eta_j^{(\delta)}\Big] &\sim \text{Multi-Normal}(\mathbf 0, \boldsymbol \Sigma_\eta)\\
\epsilon_i & \sim \text{Normal}(0, \sigma_\epsilon)
\end{aligned}
$$
or, if the first equation is too long, something like
$$y_{i} = \alpha_{j[i],k[i]} + \beta_{j[i],k[i]}T_{i} + \delta_{j[i],k[i]}(T_i * Z_i) + \epsilon_i$$
and
$$\begin{aligned}
\alpha_{j[i],k[i]} &= \alpha + \nu_{j}^{(\alpha)} + \eta_{k}^{(\alpha)} \\
\beta_{j[i],k[i]}&=\beta + \nu_{j}^{(\beta)} + \eta_{k}^{(\beta)}\\
\delta_{j[i],k[i]}&=\delta + \nu_{j}^{(\delta)} + \eta_{k}^{(\delta)}\\
\end{aligned}$$
with the same covariance structure as above? It shows the nested structure of the data as well as which coefficients vary across which levels.
|
Writing out the mathematical equation for a multilevel mixed effects model
|
If I understood the code correctly, why not simply writing something like
$$y_{i} = \Big(\alpha + \nu_{j[i]}^{(\alpha)} + \eta_{k[i]}^{(\alpha)}\Big) + \Big(\beta + \nu_{j[i]}^{(\beta)} + \eta_{k[i]}^
|
Writing out the mathematical equation for a multilevel mixed effects model
If I understood the code correctly, why not simply writing something like
$$y_{i} = \Big(\alpha + \nu_{j[i]}^{(\alpha)} + \eta_{k[i]}^{(\alpha)}\Big) + \Big(\beta + \nu_{j[i]}^{(\beta)} + \eta_{k[i]}^{(\beta)}\Big)T_{i} + \Big(\delta + \nu_{j[i]}^{(\delta)} + \eta_{k[i]}^{(\delta)}\Big)(T_{i} * Z_{i}) + \epsilon_i$$
with
$$\begin{aligned}
\Big[\nu_{j}^{(\alpha)}, \nu_j^{(\beta)}, \nu_j^{(\delta)}\Big] &\sim \text{Multi-Normal}(\mathbf 0, \boldsymbol \Sigma_\nu) \\
\Big[\eta_{j}^{(\alpha)}, \eta_j^{(\beta)}, \eta_j^{(\delta)}\Big] &\sim \text{Multi-Normal}(\mathbf 0, \boldsymbol \Sigma_\eta)\\
\epsilon_i & \sim \text{Normal}(0, \sigma_\epsilon)
\end{aligned}
$$
or, if the first equation is too long, something like
$$y_{i} = \alpha_{j[i],k[i]} + \beta_{j[i],k[i]}T_{i} + \delta_{j[i],k[i]}(T_i * Z_i) + \epsilon_i$$
and
$$\begin{aligned}
\alpha_{j[i],k[i]} &= \alpha + \nu_{j}^{(\alpha)} + \eta_{k}^{(\alpha)} \\
\beta_{j[i],k[i]}&=\beta + \nu_{j}^{(\beta)} + \eta_{k}^{(\beta)}\\
\delta_{j[i],k[i]}&=\delta + \nu_{j}^{(\delta)} + \eta_{k}^{(\delta)}\\
\end{aligned}$$
with the same covariance structure as above? It shows the nested structure of the data as well as which coefficients vary across which levels.
|
Writing out the mathematical equation for a multilevel mixed effects model
If I understood the code correctly, why not simply writing something like
$$y_{i} = \Big(\alpha + \nu_{j[i]}^{(\alpha)} + \eta_{k[i]}^{(\alpha)}\Big) + \Big(\beta + \nu_{j[i]}^{(\beta)} + \eta_{k[i]}^
|
16,824
|
In statistical learning theory, isn't there a problem of overfitting on a test set?
|
Among those two inequalities, I think the later is wrong. In brief, what's wrong here is the identity $g=h_1$ given that $g$ is a function of the test data while $h_1$ is a model that is independent of test data.
In fact, $g$ is one of the 8 models in $H_{trained} = \{ h_1, h_2,..., h_8 \}$ that best predicts test set $D_{test}$.
Therefore, $g$ is a function of $D_{test}$. For a specific test set, $D^*_{test}$ (like the one you mentioned), it could happens that $g(D^*_{test}) = h_1$, but in general, depending on the test set, $g(D_{test})$ could take any value in $H_{trained}$. On the other hand $h_1$ is just one value in $H_{trained}$.
For the other question:
If the latter is wrong, what is the right way to apply the VC bound for finite hypothesis sets in this case?
Just don't replace $g$ by $h_1$, you will get the correct bound (for $g$, of course) and it will have no conflict with the other bound (which is for $h_1$).
|
In statistical learning theory, isn't there a problem of overfitting on a test set?
|
Among those two inequalities, I think the later is wrong. In brief, what's wrong here is the identity $g=h_1$ given that $g$ is a function of the test data while $h_1$ is a model that is independent o
|
In statistical learning theory, isn't there a problem of overfitting on a test set?
Among those two inequalities, I think the later is wrong. In brief, what's wrong here is the identity $g=h_1$ given that $g$ is a function of the test data while $h_1$ is a model that is independent of test data.
In fact, $g$ is one of the 8 models in $H_{trained} = \{ h_1, h_2,..., h_8 \}$ that best predicts test set $D_{test}$.
Therefore, $g$ is a function of $D_{test}$. For a specific test set, $D^*_{test}$ (like the one you mentioned), it could happens that $g(D^*_{test}) = h_1$, but in general, depending on the test set, $g(D_{test})$ could take any value in $H_{trained}$. On the other hand $h_1$ is just one value in $H_{trained}$.
For the other question:
If the latter is wrong, what is the right way to apply the VC bound for finite hypothesis sets in this case?
Just don't replace $g$ by $h_1$, you will get the correct bound (for $g$, of course) and it will have no conflict with the other bound (which is for $h_1$).
|
In statistical learning theory, isn't there a problem of overfitting on a test set?
Among those two inequalities, I think the later is wrong. In brief, what's wrong here is the identity $g=h_1$ given that $g$ is a function of the test data while $h_1$ is a model that is independent o
|
16,825
|
Training a basic Markov Random Field for classifying pixels in an image
|
Diagnosis
This sounds like an initialization problem.
The MRF model that you are using is non-convex and, as such, has multiple local minima. As far as I know, all existing optimization techniques are sensitive to initialization, meaning that the quality of the final solution is highly affected by where you start the optimization procedure from.
Suggested Solution
I suggest trying different strategies to initialize the model. For example, one strategy that comes to my mind is the following:
train a model for $p(y | x)$ first and ignore the prior term for now; that is fix $p(x)$ to be uniform, for example, by setting $\alpha = \beta = 0$ and keeping them fixed. If you want to be fancier, you can fix $p(x)$ to be a mutinomimal distribution that represents the relative frequencies of labels in the training set. You can do this by setting $\alpha$ values appropriately.
unfreeze the unary and pairwise terms in the MRF model; that is, let your optimizer change the value of $\alpha$ and $\beta$.
The suggested initialization is, by no means, the best way to initialize your optimization, but rather, just one possible option.
Finally, as Roman Shapovalov suggested, you can consider regularizing your prior parameters; for example, by putting a Gaussian prior on them: $\lambda_\alpha ||\alpha||^2 + \lambda_\beta ||\beta||^2$ where $\lambda_\alpha$ and $\lambda_\beta$ are hyper-parameters that can be interpreted as the variances of the Gaussian priors.
|
Training a basic Markov Random Field for classifying pixels in an image
|
Diagnosis
This sounds like an initialization problem.
The MRF model that you are using is non-convex and, as such, has multiple local minima. As far as I know, all existing optimization techniques ar
|
Training a basic Markov Random Field for classifying pixels in an image
Diagnosis
This sounds like an initialization problem.
The MRF model that you are using is non-convex and, as such, has multiple local minima. As far as I know, all existing optimization techniques are sensitive to initialization, meaning that the quality of the final solution is highly affected by where you start the optimization procedure from.
Suggested Solution
I suggest trying different strategies to initialize the model. For example, one strategy that comes to my mind is the following:
train a model for $p(y | x)$ first and ignore the prior term for now; that is fix $p(x)$ to be uniform, for example, by setting $\alpha = \beta = 0$ and keeping them fixed. If you want to be fancier, you can fix $p(x)$ to be a mutinomimal distribution that represents the relative frequencies of labels in the training set. You can do this by setting $\alpha$ values appropriately.
unfreeze the unary and pairwise terms in the MRF model; that is, let your optimizer change the value of $\alpha$ and $\beta$.
The suggested initialization is, by no means, the best way to initialize your optimization, but rather, just one possible option.
Finally, as Roman Shapovalov suggested, you can consider regularizing your prior parameters; for example, by putting a Gaussian prior on them: $\lambda_\alpha ||\alpha||^2 + \lambda_\beta ||\beta||^2$ where $\lambda_\alpha$ and $\lambda_\beta$ are hyper-parameters that can be interpreted as the variances of the Gaussian priors.
|
Training a basic Markov Random Field for classifying pixels in an image
Diagnosis
This sounds like an initialization problem.
The MRF model that you are using is non-convex and, as such, has multiple local minima. As far as I know, all existing optimization techniques ar
|
16,826
|
I want to build a crime index and political instability index based in news stories
|
Consider variations on the GINI score.
http://en.wikipedia.org/wiki/Gini_coefficient
http://mathworld.wolfram.com/GiniCoefficient.html
It is normalized, and its output ranges from 0 to 1.
EDIT:
Why GINI is "cool" or at least potentially appropriate:
It is a measure of inequality or inequity. It is used as a scale free measure to characterize the heterogeneity of scale-free networks, including infinite and random networks. It is useful in building CART trees because it is the measure of splitting power of a particular data-split.
Because of its range:
there is less roundoff errors. Ranges far away from 1.0 tend to suffer numeric issues.
it is human readable, and more human accessible. Humans have a more concrete grasp of ones of objects than they do of billions.
Because it is normalized:
comparisons of scores are meaningful, a 0.9 in one country means the same level of relative non-uniformity as a 0.9 in any other country.
It is normalized against the Lorenz curve for perfect uniformity therefore the values are relevant indicators of the relationship of the distribution of values of interest to the Lorenz curve.
References:
[1] http://data.worldbank.org/indicator/SI.POV.GINI
[2] http://research3.bus.wisc.edu/file.php/129/Papers/Gini27April2011.pdf
[3] http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm#giniimp
[4] http://www2.unine.ch/files/content/sites/imi/files/shared/documents/papers/Gini_index_fulltext.pdf
|
I want to build a crime index and political instability index based in news stories
|
Consider variations on the GINI score.
http://en.wikipedia.org/wiki/Gini_coefficient
http://mathworld.wolfram.com/GiniCoefficient.html
It is normalized, and its output ranges from 0 to 1.
EDIT:
|
I want to build a crime index and political instability index based in news stories
Consider variations on the GINI score.
http://en.wikipedia.org/wiki/Gini_coefficient
http://mathworld.wolfram.com/GiniCoefficient.html
It is normalized, and its output ranges from 0 to 1.
EDIT:
Why GINI is "cool" or at least potentially appropriate:
It is a measure of inequality or inequity. It is used as a scale free measure to characterize the heterogeneity of scale-free networks, including infinite and random networks. It is useful in building CART trees because it is the measure of splitting power of a particular data-split.
Because of its range:
there is less roundoff errors. Ranges far away from 1.0 tend to suffer numeric issues.
it is human readable, and more human accessible. Humans have a more concrete grasp of ones of objects than they do of billions.
Because it is normalized:
comparisons of scores are meaningful, a 0.9 in one country means the same level of relative non-uniformity as a 0.9 in any other country.
It is normalized against the Lorenz curve for perfect uniformity therefore the values are relevant indicators of the relationship of the distribution of values of interest to the Lorenz curve.
References:
[1] http://data.worldbank.org/indicator/SI.POV.GINI
[2] http://research3.bus.wisc.edu/file.php/129/Papers/Gini27April2011.pdf
[3] http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm#giniimp
[4] http://www2.unine.ch/files/content/sites/imi/files/shared/documents/papers/Gini_index_fulltext.pdf
|
I want to build a crime index and political instability index based in news stories
Consider variations on the GINI score.
http://en.wikipedia.org/wiki/Gini_coefficient
http://mathworld.wolfram.com/GiniCoefficient.html
It is normalized, and its output ranges from 0 to 1.
EDIT:
|
16,827
|
How can I measure model performance with weighted logistic regression?
|
When working with survey data that uses probability weights, it is important to be mindful of the fact that traditional likelihood-based tests and fit statistics may not be valid. This is because probability weights can introduce a level of complexity into the data that can affect the assumptions underlying these methods.
There are alternative methods that can be used to compare models in the context of weighted MLE:
Design-based methods: These methods take into account the survey design and account for the complex sampling structure. For example, you can use the Rao-Scott chi-squared test, which is a modified version of the chi-squared test that is appropriate for survey data.
Bootstrap methods: Bootstrap methods are a family of non-parametric resampling techniques that can be used to make inferences about a population from a sample. You can use bootstrapping to estimate standard errors, confidence intervals, and p-values for model parameters and test statistics.
Weighted least squares: One of the alternative is to use weighted least squares instead of Maximum likelihood. It's often used when data has heteroskedasticity or when data is correlated.
Comparison of predicted probabilities: Another alternative is to compare the predicted probabilities from different models to evaluate their performance. A common method is to calculate the average absolute difference in predicted probabilities, which is a measure of the average absolute difference between the predicted probabilities of the two models.
Information criterion: There are alternative information criterion such as “Weighted Akaike information criterion (AIC)” or “Weighted Bayesian information criterion (BIC)” that take into account the complex sampling structure of survey data by incorporating the weights into the formula.
It's important to note that no single method will be the best choice for all cases, and the choice of method will depend on the specifics of your data and research question.
|
How can I measure model performance with weighted logistic regression?
|
When working with survey data that uses probability weights, it is important to be mindful of the fact that traditional likelihood-based tests and fit statistics may not be valid. This is because prob
|
How can I measure model performance with weighted logistic regression?
When working with survey data that uses probability weights, it is important to be mindful of the fact that traditional likelihood-based tests and fit statistics may not be valid. This is because probability weights can introduce a level of complexity into the data that can affect the assumptions underlying these methods.
There are alternative methods that can be used to compare models in the context of weighted MLE:
Design-based methods: These methods take into account the survey design and account for the complex sampling structure. For example, you can use the Rao-Scott chi-squared test, which is a modified version of the chi-squared test that is appropriate for survey data.
Bootstrap methods: Bootstrap methods are a family of non-parametric resampling techniques that can be used to make inferences about a population from a sample. You can use bootstrapping to estimate standard errors, confidence intervals, and p-values for model parameters and test statistics.
Weighted least squares: One of the alternative is to use weighted least squares instead of Maximum likelihood. It's often used when data has heteroskedasticity or when data is correlated.
Comparison of predicted probabilities: Another alternative is to compare the predicted probabilities from different models to evaluate their performance. A common method is to calculate the average absolute difference in predicted probabilities, which is a measure of the average absolute difference between the predicted probabilities of the two models.
Information criterion: There are alternative information criterion such as “Weighted Akaike information criterion (AIC)” or “Weighted Bayesian information criterion (BIC)” that take into account the complex sampling structure of survey data by incorporating the weights into the formula.
It's important to note that no single method will be the best choice for all cases, and the choice of method will depend on the specifics of your data and research question.
|
How can I measure model performance with weighted logistic regression?
When working with survey data that uses probability weights, it is important to be mindful of the fact that traditional likelihood-based tests and fit statistics may not be valid. This is because prob
|
16,828
|
Are two standard normal random variables always independent?
|
The answer is no. For example, if $X$ is a standard random variable, then $Y=-X$ follows the same statistics, but $X$ and $Y$ are clearly dependent.
|
Are two standard normal random variables always independent?
|
The answer is no. For example, if $X$ is a standard random variable, then $Y=-X$ follows the same statistics, but $X$ and $Y$ are clearly dependent.
|
Are two standard normal random variables always independent?
The answer is no. For example, if $X$ is a standard random variable, then $Y=-X$ follows the same statistics, but $X$ and $Y$ are clearly dependent.
|
Are two standard normal random variables always independent?
The answer is no. For example, if $X$ is a standard random variable, then $Y=-X$ follows the same statistics, but $X$ and $Y$ are clearly dependent.
|
16,829
|
Are two standard normal random variables always independent?
|
No, there is no reason to believe that any two standard gaussians are independent.
Here's a simple mathematical construction. Suppose that $X$ and $Y$ are two independent standard normal variables. Then the pair
$$ X, \frac{X + Y}{\sqrt{2}}$$
are two dependent standard normal variables. So, as long as their are two independent normal variables, there must be two dependent ones.
The second variable is normal because any linear combination of independent normal variables is again normal. The $\sqrt{2}$ is there to make the variance equal to $1$.
$$ V \left(\frac{X + Y}{\sqrt{2}} \right) = \frac{1}{\sqrt{2}^2} (V(X) + V(Y)) = 1 $$
Intuitively, these are dependent because knowing the value of $X$ gives you additional information you can use to predict the value of the second variable. For example, if you know that $X = x$, then the conditional expectation of the second variable is
$$ E \left[\frac{X + Y}{\sqrt{2}} \mid X = x \right] = \frac{x}{\sqrt{2}} $$
|
Are two standard normal random variables always independent?
|
No, there is no reason to believe that any two standard gaussians are independent.
Here's a simple mathematical construction. Suppose that $X$ and $Y$ are two independent standard normal variables.
|
Are two standard normal random variables always independent?
No, there is no reason to believe that any two standard gaussians are independent.
Here's a simple mathematical construction. Suppose that $X$ and $Y$ are two independent standard normal variables. Then the pair
$$ X, \frac{X + Y}{\sqrt{2}}$$
are two dependent standard normal variables. So, as long as their are two independent normal variables, there must be two dependent ones.
The second variable is normal because any linear combination of independent normal variables is again normal. The $\sqrt{2}$ is there to make the variance equal to $1$.
$$ V \left(\frac{X + Y}{\sqrt{2}} \right) = \frac{1}{\sqrt{2}^2} (V(X) + V(Y)) = 1 $$
Intuitively, these are dependent because knowing the value of $X$ gives you additional information you can use to predict the value of the second variable. For example, if you know that $X = x$, then the conditional expectation of the second variable is
$$ E \left[\frac{X + Y}{\sqrt{2}} \mid X = x \right] = \frac{x}{\sqrt{2}} $$
|
Are two standard normal random variables always independent?
No, there is no reason to believe that any two standard gaussians are independent.
Here's a simple mathematical construction. Suppose that $X$ and $Y$ are two independent standard normal variables.
|
16,830
|
Are two standard normal random variables always independent?
|
Here's a fairly wide answer:
Let $X,Y$ be jointly Gaussian random variables (i.e. for any $a,b$ real numbers, $a X + bY$ has a Gaussian distribution). Then, $X$ and $Y$ are independent if and only if $E[(X-E[X])(Y-E[Y])]=0$ (i.e. they are uncorrelated). See these notes, for example, for details.
How can you generate standard normal random variables which are not independent? Pick your favorite matrix of the form $\Sigma=\begin{bmatrix} 1 & p \\ p & 1 \end{bmatrix}$ such that $(\lambda-1)^2 - p^2$ has positive roots in $\lambda$. Then, apply the Cholesky decompositon to $\Sigma= R R^T$. Then, take two independent standard normal random variables $U,V$ and then the vector $R \begin{bmatrix} U \\ V \end{bmatrix}$ has standard normal components, but the components are independent if and only if $p=0$.
|
Are two standard normal random variables always independent?
|
Here's a fairly wide answer:
Let $X,Y$ be jointly Gaussian random variables (i.e. for any $a,b$ real numbers, $a X + bY$ has a Gaussian distribution). Then, $X$ and $Y$ are independent if and only if
|
Are two standard normal random variables always independent?
Here's a fairly wide answer:
Let $X,Y$ be jointly Gaussian random variables (i.e. for any $a,b$ real numbers, $a X + bY$ has a Gaussian distribution). Then, $X$ and $Y$ are independent if and only if $E[(X-E[X])(Y-E[Y])]=0$ (i.e. they are uncorrelated). See these notes, for example, for details.
How can you generate standard normal random variables which are not independent? Pick your favorite matrix of the form $\Sigma=\begin{bmatrix} 1 & p \\ p & 1 \end{bmatrix}$ such that $(\lambda-1)^2 - p^2$ has positive roots in $\lambda$. Then, apply the Cholesky decompositon to $\Sigma= R R^T$. Then, take two independent standard normal random variables $U,V$ and then the vector $R \begin{bmatrix} U \\ V \end{bmatrix}$ has standard normal components, but the components are independent if and only if $p=0$.
|
Are two standard normal random variables always independent?
Here's a fairly wide answer:
Let $X,Y$ be jointly Gaussian random variables (i.e. for any $a,b$ real numbers, $a X + bY$ has a Gaussian distribution). Then, $X$ and $Y$ are independent if and only if
|
16,831
|
Are two standard normal random variables always independent?
|
A non-bivariate normal example (as Michael Chernick suggests in the comments):
Let $f_{X,Y}(x,y) = \begin{cases} \frac{1}{\pi} e^{-\frac{x^2+y^2}{2}} & xy\geq 0 \\
0 & o.w.
\end{cases}$.
This is not a bivariate normal distribution, but a simple integral shows that both marginals are standard normal. They're obviously not independent since $f_{X,Y}(x,y) \neq f_X(x) f_Y(y)$.
|
Are two standard normal random variables always independent?
|
A non-bivariate normal example (as Michael Chernick suggests in the comments):
Let $f_{X,Y}(x,y) = \begin{cases} \frac{1}{\pi} e^{-\frac{x^2+y^2}{2}} & xy\geq 0 \\
0 & o.w.
\end{cases}$.
This is no
|
Are two standard normal random variables always independent?
A non-bivariate normal example (as Michael Chernick suggests in the comments):
Let $f_{X,Y}(x,y) = \begin{cases} \frac{1}{\pi} e^{-\frac{x^2+y^2}{2}} & xy\geq 0 \\
0 & o.w.
\end{cases}$.
This is not a bivariate normal distribution, but a simple integral shows that both marginals are standard normal. They're obviously not independent since $f_{X,Y}(x,y) \neq f_X(x) f_Y(y)$.
|
Are two standard normal random variables always independent?
A non-bivariate normal example (as Michael Chernick suggests in the comments):
Let $f_{X,Y}(x,y) = \begin{cases} \frac{1}{\pi} e^{-\frac{x^2+y^2}{2}} & xy\geq 0 \\
0 & o.w.
\end{cases}$.
This is no
|
16,832
|
Way to get started with and learn R?
|
I think the only way to get into it is the next time you you need to do something in SAS or SPSS fire up R instead. It is tough at the beginning and at first you will spend a lot of time on simple tasks. When you get stuck google the problem and you will probably find a solution. You can check your results with SPSS or SAS.
Eventually you start to get the hang of it and jobs start going quicker. Referencing old code always helps. Hopefully you find some sense of pride in the progress you make.
Then as you become more advanced and read blogs plus this site you start to learn the true power of R, the tricks, and what all is possible with it.
|
Way to get started with and learn R?
|
I think the only way to get into it is the next time you you need to do something in SAS or SPSS fire up R instead. It is tough at the beginning and at first you will spend a lot of time on simple ta
|
Way to get started with and learn R?
I think the only way to get into it is the next time you you need to do something in SAS or SPSS fire up R instead. It is tough at the beginning and at first you will spend a lot of time on simple tasks. When you get stuck google the problem and you will probably find a solution. You can check your results with SPSS or SAS.
Eventually you start to get the hang of it and jobs start going quicker. Referencing old code always helps. Hopefully you find some sense of pride in the progress you make.
Then as you become more advanced and read blogs plus this site you start to learn the true power of R, the tricks, and what all is possible with it.
|
Way to get started with and learn R?
I think the only way to get into it is the next time you you need to do something in SAS or SPSS fire up R instead. It is tough at the beginning and at first you will spend a lot of time on simple ta
|
16,833
|
Way to get started with and learn R?
|
A few pointers:
The answer by @Glen is key. You need to force yourself to do something in R, even when you know you could do it easily with SPSS.
A few months ago I made a list of R programming books that didn't try to teach statistics, rather they just described R.
Subscribe to the RSS feeds of r-bloggers.com and the stackoverflow R tag. I find it very helpful just to skim read the articles to get hints and tips.
|
Way to get started with and learn R?
|
A few pointers:
The answer by @Glen is key. You need to force yourself to do something in R, even when you know you could do it easily with SPSS.
A few months ago I made a list of R programming books
|
Way to get started with and learn R?
A few pointers:
The answer by @Glen is key. You need to force yourself to do something in R, even when you know you could do it easily with SPSS.
A few months ago I made a list of R programming books that didn't try to teach statistics, rather they just described R.
Subscribe to the RSS feeds of r-bloggers.com and the stackoverflow R tag. I find it very helpful just to skim read the articles to get hints and tips.
|
Way to get started with and learn R?
A few pointers:
The answer by @Glen is key. You need to force yourself to do something in R, even when you know you could do it easily with SPSS.
A few months ago I made a list of R programming books
|
16,834
|
Way to get started with and learn R?
|
Plenty of good advice here, but I think the single most helpful thing you could do would be to just sit down with someone who knows R for a couple of hours. I probably took years off my life learning R alone; just having someone to say, "Nah, it's much easier to do it this way" would have saved me so much grief. I think this is especially crucial with regard to learning to do R things, rather than SPSS things in R, as StasK mentions, but it will also stop you from spending hours chasing around stupid little syntax errors.
It doesn't look like Pittsburgh has an R User Group, which baffles me, but there must be many Rgonauts in the vicinity. Try to find them. Bribe someone to just hang out with you while you work through anything described above - translating an old project into R sounds especially good.
|
Way to get started with and learn R?
|
Plenty of good advice here, but I think the single most helpful thing you could do would be to just sit down with someone who knows R for a couple of hours. I probably took years off my life learning
|
Way to get started with and learn R?
Plenty of good advice here, but I think the single most helpful thing you could do would be to just sit down with someone who knows R for a couple of hours. I probably took years off my life learning R alone; just having someone to say, "Nah, it's much easier to do it this way" would have saved me so much grief. I think this is especially crucial with regard to learning to do R things, rather than SPSS things in R, as StasK mentions, but it will also stop you from spending hours chasing around stupid little syntax errors.
It doesn't look like Pittsburgh has an R User Group, which baffles me, but there must be many Rgonauts in the vicinity. Try to find them. Bribe someone to just hang out with you while you work through anything described above - translating an old project into R sounds especially good.
|
Way to get started with and learn R?
Plenty of good advice here, but I think the single most helpful thing you could do would be to just sit down with someone who knows R for a couple of hours. I probably took years off my life learning
|
16,835
|
Way to get started with and learn R?
|
This book might be right down your alley: R. Muenchen (2008). R for SAS and SPSS Users.
I've had very similar experiences starting R several times. I am a Stata user though. Muenchen and Hilbe (a lo-ong time editor in charge of statistical software section of The American Statistician) have a similar book R for Stata users, and I found it entertaining at times, when they provide a 20-line segment of code for something that is doable in three lines in Stata. (On the other hand, there are of course situations when you just simply cannot do an object-oriented thing meaningfully in Stata.) I guess the message is, you should abstract from your SPSS and SAS experience, as R thinks in totally different terms about nearly everything. Your prior experience will likely be more of a hindrance, at least in the case of R (you can probably relearn from SPSS to Stata quite quickly if you had to). There are no more rectangular data sets, and there are no CARDS to read from. You would need to eventually learn to do R things, rather than trying to do SPSS things in R.
|
Way to get started with and learn R?
|
This book might be right down your alley: R. Muenchen (2008). R for SAS and SPSS Users.
I've had very similar experiences starting R several times. I am a Stata user though. Muenchen and Hilbe (a lo-o
|
Way to get started with and learn R?
This book might be right down your alley: R. Muenchen (2008). R for SAS and SPSS Users.
I've had very similar experiences starting R several times. I am a Stata user though. Muenchen and Hilbe (a lo-ong time editor in charge of statistical software section of The American Statistician) have a similar book R for Stata users, and I found it entertaining at times, when they provide a 20-line segment of code for something that is doable in three lines in Stata. (On the other hand, there are of course situations when you just simply cannot do an object-oriented thing meaningfully in Stata.) I guess the message is, you should abstract from your SPSS and SAS experience, as R thinks in totally different terms about nearly everything. Your prior experience will likely be more of a hindrance, at least in the case of R (you can probably relearn from SPSS to Stata quite quickly if you had to). There are no more rectangular data sets, and there are no CARDS to read from. You would need to eventually learn to do R things, rather than trying to do SPSS things in R.
|
Way to get started with and learn R?
This book might be right down your alley: R. Muenchen (2008). R for SAS and SPSS Users.
I've had very similar experiences starting R several times. I am a Stata user though. Muenchen and Hilbe (a lo-o
|
16,836
|
Way to get started with and learn R?
|
I've been in your shoes - indeed am probably still in your shoes - as I use both R and SAS regularly for different tasks. As mentioned above, there's "R for SAS Users", and you might also want to consider looking at the "SAS and R" blog: http://sas-and-r.blogspot.com/ and the accompanying book, which provides worked examples in both SAS and R.
Generally speaking, the experience in switching between SAS and R is somewhat disorienting, because they're different philosophically. At its core, SAS isn't a programming language - it's a powerful command line interface. R...is a programming language. R made more sense to me when I started learning Python and C than when I knew SAS. Admittedly its a programming language built for statistics, but there you have it.
While the approach of forcing yourself to fire up R instead of SAS is a decent one, I would suggest something else when you first start out, as plunging feet first into new project and new software is scary as hell. Repeat an old analysis. Take a paper you've written, a problem set you've done, whatever in SAS (or SPSS) and repeat it in R. Step by step, Googling and asking questions here as you go. This has three advantages:
You won't accidentally kill a new project with a "I should learn a new language" decision.
You know the answer already. This means you can be sure you've arrived at the correct answer in R.
It will illustrate the differences between the different languages better. "Wow, that was way easier to do in R...", "I'd never really looked at that kind of graph", etc.
|
Way to get started with and learn R?
|
I've been in your shoes - indeed am probably still in your shoes - as I use both R and SAS regularly for different tasks. As mentioned above, there's "R for SAS Users", and you might also want to cons
|
Way to get started with and learn R?
I've been in your shoes - indeed am probably still in your shoes - as I use both R and SAS regularly for different tasks. As mentioned above, there's "R for SAS Users", and you might also want to consider looking at the "SAS and R" blog: http://sas-and-r.blogspot.com/ and the accompanying book, which provides worked examples in both SAS and R.
Generally speaking, the experience in switching between SAS and R is somewhat disorienting, because they're different philosophically. At its core, SAS isn't a programming language - it's a powerful command line interface. R...is a programming language. R made more sense to me when I started learning Python and C than when I knew SAS. Admittedly its a programming language built for statistics, but there you have it.
While the approach of forcing yourself to fire up R instead of SAS is a decent one, I would suggest something else when you first start out, as plunging feet first into new project and new software is scary as hell. Repeat an old analysis. Take a paper you've written, a problem set you've done, whatever in SAS (or SPSS) and repeat it in R. Step by step, Googling and asking questions here as you go. This has three advantages:
You won't accidentally kill a new project with a "I should learn a new language" decision.
You know the answer already. This means you can be sure you've arrived at the correct answer in R.
It will illustrate the differences between the different languages better. "Wow, that was way easier to do in R...", "I'd never really looked at that kind of graph", etc.
|
Way to get started with and learn R?
I've been in your shoes - indeed am probably still in your shoes - as I use both R and SAS regularly for different tasks. As mentioned above, there's "R for SAS Users", and you might also want to cons
|
16,837
|
Way to get started with and learn R?
|
I agree with @Matt Parker that there is plenty of good advice. One thing I want to stress in my answer is that it's vital to understand basic programming if you want to work with R.
Basic programming
My favourite site for learning new things is Khan Academy that has some videos on Python scripting that is very similar to R and there is actually a plugin that allows you to use Python in SPSS that you can find here. I've used the Python plugin a lot doing complex merges, counting occurences, creating custom tables etc. It's a very good way to get started with programming.
What's the deal with R?
I know several different programming languages and the thing that makes R special is it's vectors/matrices and it's graphical output. I recommend learning the different ways of manipulating vectors because they're the basis of dataframes and most of the data that you will use, here's a good tutorial. When it comes to the graphical output there are good functions for most of the available graphs and you probably don't need to worry about this part.
Another fundamental part of R is the install.packages("my_package_name") function that makes fetching new components and installing them hassle free - something that a lot of other languages make considerable harder.
Getting started in R
My favourit R site is Quick-R and I would suggest on trying out some of their code. Once you've gotten the same graph try to change colors, number of columns, xlabel etc. There are also plenty of R-tutorials on YouTube that probably can help you get started.
Learning by examining others code
An excellent way to learn R is to try to understand how different functions work. Write the functions name (without parenthesis), press enter and you get the code - look at it's code and try to understand what it does. The debug() function can also be of help when trying to understand how stuff works.
Using R without coding
Yes, you can choose to use R in a SPSS similar environment:
install.packages("Rcmdr")
library(Rcmdr)
R compared with SAS
I've also worked some with SAS that is a very unintuitive language that differs a lot from all other programming languages and unfortunately you'll probably have very little that you can use from your SAS experience when your work with R. That said, R is much easier that SAS ;-)
GUI
It is nice to have a good environment to work with when you use R, my recommendation to beginners is RStudio.
Good luck!
|
Way to get started with and learn R?
|
I agree with @Matt Parker that there is plenty of good advice. One thing I want to stress in my answer is that it's vital to understand basic programming if you want to work with R.
Basic programming
|
Way to get started with and learn R?
I agree with @Matt Parker that there is plenty of good advice. One thing I want to stress in my answer is that it's vital to understand basic programming if you want to work with R.
Basic programming
My favourite site for learning new things is Khan Academy that has some videos on Python scripting that is very similar to R and there is actually a plugin that allows you to use Python in SPSS that you can find here. I've used the Python plugin a lot doing complex merges, counting occurences, creating custom tables etc. It's a very good way to get started with programming.
What's the deal with R?
I know several different programming languages and the thing that makes R special is it's vectors/matrices and it's graphical output. I recommend learning the different ways of manipulating vectors because they're the basis of dataframes and most of the data that you will use, here's a good tutorial. When it comes to the graphical output there are good functions for most of the available graphs and you probably don't need to worry about this part.
Another fundamental part of R is the install.packages("my_package_name") function that makes fetching new components and installing them hassle free - something that a lot of other languages make considerable harder.
Getting started in R
My favourit R site is Quick-R and I would suggest on trying out some of their code. Once you've gotten the same graph try to change colors, number of columns, xlabel etc. There are also plenty of R-tutorials on YouTube that probably can help you get started.
Learning by examining others code
An excellent way to learn R is to try to understand how different functions work. Write the functions name (without parenthesis), press enter and you get the code - look at it's code and try to understand what it does. The debug() function can also be of help when trying to understand how stuff works.
Using R without coding
Yes, you can choose to use R in a SPSS similar environment:
install.packages("Rcmdr")
library(Rcmdr)
R compared with SAS
I've also worked some with SAS that is a very unintuitive language that differs a lot from all other programming languages and unfortunately you'll probably have very little that you can use from your SAS experience when your work with R. That said, R is much easier that SAS ;-)
GUI
It is nice to have a good environment to work with when you use R, my recommendation to beginners is RStudio.
Good luck!
|
Way to get started with and learn R?
I agree with @Matt Parker that there is plenty of good advice. One thing I want to stress in my answer is that it's vital to understand basic programming if you want to work with R.
Basic programming
|
16,838
|
Way to get started with and learn R?
|
I think the answer mentioned by @Glen is very imporntant however you do need some books to start with.
With regards to R I believe you need 3 books.
First, for doing statistics with R i can recommend you R in Action . Robert maintains a very active R site and blog (http://www.statmethods.net/) and his book and efforts are fantastic.
Second, you may need a book for programming in R, as R is not only a statistics program but also a mighty language. Programming is very helpful when doing complex analyses or when combining analysis, or for writing functions that perform the same thing on different datasets. I can only recommend you The Art of R Programming . No major statistics are presented here, but you will get a grip how to combine, connect and automate your analyses.
Third, you will need a reference book, an encyclopedia. I can recommend you The R Book . This is not the book you will read from start to finish but its the book you open now and then to see if some things are possible, if there are other ways to analyse data etc.
And most important stop using anything else and try to tackle all your problems in R. Solving problems in the best way to learn.
Also, before I forget. There are some wonderful blogs from some fantastic people writing about all sort of stuff one can do in R. Search and you will find. Highly recommended is the aggregation site http://www.r-bloggers.com/ where R relevant blogs are gathered.
Have fun!
|
Way to get started with and learn R?
|
I think the answer mentioned by @Glen is very imporntant however you do need some books to start with.
With regards to R I believe you need 3 books.
First, for doing statistics with R i can recommend
|
Way to get started with and learn R?
I think the answer mentioned by @Glen is very imporntant however you do need some books to start with.
With regards to R I believe you need 3 books.
First, for doing statistics with R i can recommend you R in Action . Robert maintains a very active R site and blog (http://www.statmethods.net/) and his book and efforts are fantastic.
Second, you may need a book for programming in R, as R is not only a statistics program but also a mighty language. Programming is very helpful when doing complex analyses or when combining analysis, or for writing functions that perform the same thing on different datasets. I can only recommend you The Art of R Programming . No major statistics are presented here, but you will get a grip how to combine, connect and automate your analyses.
Third, you will need a reference book, an encyclopedia. I can recommend you The R Book . This is not the book you will read from start to finish but its the book you open now and then to see if some things are possible, if there are other ways to analyse data etc.
And most important stop using anything else and try to tackle all your problems in R. Solving problems in the best way to learn.
Also, before I forget. There are some wonderful blogs from some fantastic people writing about all sort of stuff one can do in R. Search and you will find. Highly recommended is the aggregation site http://www.r-bloggers.com/ where R relevant blogs are gathered.
Have fun!
|
Way to get started with and learn R?
I think the answer mentioned by @Glen is very imporntant however you do need some books to start with.
With regards to R I believe you need 3 books.
First, for doing statistics with R i can recommend
|
16,839
|
Way to get started with and learn R?
|
If I could add two item to the many good suggestions here already;
1)Find an R group. I know in the Boston area there is a fairly strong R group. It is sponsored by RStudio, which by the way is one of the BEST IDE around.
Go on Meetup or Google group or RSeek.org to search them out.
2)One more thing, I found learning R on my own a steep climb but my general advice is keep looking for books that help AND DON'T STOP until you find the right one.
|
Way to get started with and learn R?
|
If I could add two item to the many good suggestions here already;
1)Find an R group. I know in the Boston area there is a fairly strong R group. It is sponsored by RStudio, which by the way is one
|
Way to get started with and learn R?
If I could add two item to the many good suggestions here already;
1)Find an R group. I know in the Boston area there is a fairly strong R group. It is sponsored by RStudio, which by the way is one of the BEST IDE around.
Go on Meetup or Google group or RSeek.org to search them out.
2)One more thing, I found learning R on my own a steep climb but my general advice is keep looking for books that help AND DON'T STOP until you find the right one.
|
Way to get started with and learn R?
If I could add two item to the many good suggestions here already;
1)Find an R group. I know in the Boston area there is a fairly strong R group. It is sponsored by RStudio, which by the way is one
|
16,840
|
Way to get started with and learn R?
|
MarketingEngineer:
I know your issues as the best & worst thing of R is too functional until we don't know where to start with.
First, you need to know what's purpose you learn R. If you're just for learning a new language then, I think SAS and R Blog might be useful, as a SAS/SPSS user.
However, R is not that hard if compared to SAS or SPSS, it's just looked complex due to the ever increasing packages and functions. So, I suggest you can learn from scratch using any manuals or webs suggested, such as Quick-R, by the author of R in Action.
Note: R in Action is a good book to start with.
What if, you used R for specific purposes, then it's better you have a look of the R Book list at R Project Web. There are 129 R and S related books in specific applications, such as Econometric, Graphical, Modelling, ... so on.
Recently, I'm thinking of Interactive R Language Online Learning Platform and I had asked for feedback here too. It's open source (not yet released) project. I had started making a working prototype with 3 R Language basic lessons. You can give it a try.
Hope it help :-)
|
Way to get started with and learn R?
|
MarketingEngineer:
I know your issues as the best & worst thing of R is too functional until we don't know where to start with.
First, you need to know what's purpose you learn R. If you're just for l
|
Way to get started with and learn R?
MarketingEngineer:
I know your issues as the best & worst thing of R is too functional until we don't know where to start with.
First, you need to know what's purpose you learn R. If you're just for learning a new language then, I think SAS and R Blog might be useful, as a SAS/SPSS user.
However, R is not that hard if compared to SAS or SPSS, it's just looked complex due to the ever increasing packages and functions. So, I suggest you can learn from scratch using any manuals or webs suggested, such as Quick-R, by the author of R in Action.
Note: R in Action is a good book to start with.
What if, you used R for specific purposes, then it's better you have a look of the R Book list at R Project Web. There are 129 R and S related books in specific applications, such as Econometric, Graphical, Modelling, ... so on.
Recently, I'm thinking of Interactive R Language Online Learning Platform and I had asked for feedback here too. It's open source (not yet released) project. I had started making a working prototype with 3 R Language basic lessons. You can give it a try.
Hope it help :-)
|
Way to get started with and learn R?
MarketingEngineer:
I know your issues as the best & worst thing of R is too functional until we don't know where to start with.
First, you need to know what's purpose you learn R. If you're just for l
|
16,841
|
Way to get started with and learn R?
|
Some Helpful R Links from the Dallas R Users Group
http://www.meetup.com/Dallas-R-Users-Group/pages/R_Helpful_Links/
|
Way to get started with and learn R?
|
Some Helpful R Links from the Dallas R Users Group
http://www.meetup.com/Dallas-R-Users-Group/pages/R_Helpful_Links/
|
Way to get started with and learn R?
Some Helpful R Links from the Dallas R Users Group
http://www.meetup.com/Dallas-R-Users-Group/pages/R_Helpful_Links/
|
Way to get started with and learn R?
Some Helpful R Links from the Dallas R Users Group
http://www.meetup.com/Dallas-R-Users-Group/pages/R_Helpful_Links/
|
16,842
|
Way to get started with and learn R?
|
There's a free early version of R for SAS and SPSS Users at http://r4stats.com. That site also has many of the book examples now displayed as web pages. If you have access to a university library, they usually have all the Springer R books online for free.
|
Way to get started with and learn R?
|
There's a free early version of R for SAS and SPSS Users at http://r4stats.com. That site also has many of the book examples now displayed as web pages. If you have access to a university library, the
|
Way to get started with and learn R?
There's a free early version of R for SAS and SPSS Users at http://r4stats.com. That site also has many of the book examples now displayed as web pages. If you have access to a university library, they usually have all the Springer R books online for free.
|
Way to get started with and learn R?
There's a free early version of R for SAS and SPSS Users at http://r4stats.com. That site also has many of the book examples now displayed as web pages. If you have access to a university library, the
|
16,843
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binary encoding instead of one-hot encoding?
|
For one, the predictor variables would not be orthogonal. Generally, linear regressions work better (i.e., have tighter error estimates) when predictors are close to orthogonal (which can be quantified using the condition number of the Gram matrix $X^tX$). But the bigger issue with this proposed coding scheme is that it introduces similarity structure to the features that is completely arbitrary. For example the first row and the second row are less similar than the first row and the third row (as measured by, e.g., dot product similarity), but in a categorical variable the labeling of the values (or what is the same thing, the ordering of the rows of the encoding matrix) has no inherent meaning. So combining these two considerations, the only way that really makes sense to code a categorical variable with $K$ values is to choose $k$ orthogonal vectors, which requires a space of dimension $>=K$ (or really, $>=K-1$ since you can absorb one of them into the intercept). The typical coding using one-hotes is a particularly simple way to accomplish this, although in principle you could also use any set of $K$ orthogonal vectors.
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binar
|
For one, the predictor variables would not be orthogonal. Generally, linear regressions work better (i.e., have tighter error estimates) when predictors are close to orthogonal (which can be quantifie
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binary encoding instead of one-hot encoding?
For one, the predictor variables would not be orthogonal. Generally, linear regressions work better (i.e., have tighter error estimates) when predictors are close to orthogonal (which can be quantified using the condition number of the Gram matrix $X^tX$). But the bigger issue with this proposed coding scheme is that it introduces similarity structure to the features that is completely arbitrary. For example the first row and the second row are less similar than the first row and the third row (as measured by, e.g., dot product similarity), but in a categorical variable the labeling of the values (or what is the same thing, the ordering of the rows of the encoding matrix) has no inherent meaning. So combining these two considerations, the only way that really makes sense to code a categorical variable with $K$ values is to choose $k$ orthogonal vectors, which requires a space of dimension $>=K$ (or really, $>=K-1$ since you can absorb one of them into the intercept). The typical coding using one-hotes is a particularly simple way to accomplish this, although in principle you could also use any set of $K$ orthogonal vectors.
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binar
For one, the predictor variables would not be orthogonal. Generally, linear regressions work better (i.e., have tighter error estimates) when predictors are close to orthogonal (which can be quantifie
|
16,844
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binary encoding instead of one-hot encoding?
|
You need a dummy variable for each level so that each level can have its own coefficient, independent of the other levels.
Think about how linear models work. The predicted value is
$$
\hat{y}_i = \sum_j \beta_j x_{ji}
$$
With dummy variables (aka "one-hot encoding"), for each $i$, only one of the $\beta$, the one corresponding to the level of the categorical variable, is added to the sum. Thus, each level gets its own coefficient that defines the outcome's response when the categorical variable takes on that value$^\star$.
Now, consider what happens with your proposed encoding. Levels 1 and 2 each get their own response, but Level 3 is constrained to be the sum of the responses for levels 1 and 2. There is no reason to suppose that this should be the case, so you shouldn't build that constraint into the model. Having a separate dummy variable for each level allows each level to have its own response that does not depend in any way on the other levels.
$^\star$ Well, except for the one special level that gets its response rolled into the intercept term, but you shouldn't do that. If there are $k$ levels, use $k$ dummy variables and no intercept instead of $k-1$ plus an intercept. For example, if you're doing the model in R, use $y\sim x+0$ instead of $y\sim x$.
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binar
|
You need a dummy variable for each level so that each level can have its own coefficient, independent of the other levels.
Think about how linear models work. The predicted value is
$$
\hat{y}_i = \s
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binary encoding instead of one-hot encoding?
You need a dummy variable for each level so that each level can have its own coefficient, independent of the other levels.
Think about how linear models work. The predicted value is
$$
\hat{y}_i = \sum_j \beta_j x_{ji}
$$
With dummy variables (aka "one-hot encoding"), for each $i$, only one of the $\beta$, the one corresponding to the level of the categorical variable, is added to the sum. Thus, each level gets its own coefficient that defines the outcome's response when the categorical variable takes on that value$^\star$.
Now, consider what happens with your proposed encoding. Levels 1 and 2 each get their own response, but Level 3 is constrained to be the sum of the responses for levels 1 and 2. There is no reason to suppose that this should be the case, so you shouldn't build that constraint into the model. Having a separate dummy variable for each level allows each level to have its own response that does not depend in any way on the other levels.
$^\star$ Well, except for the one special level that gets its response rolled into the intercept term, but you shouldn't do that. If there are $k$ levels, use $k$ dummy variables and no intercept instead of $k-1$ plus an intercept. For example, if you're doing the model in R, use $y\sim x+0$ instead of $y\sim x$.
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binar
You need a dummy variable for each level so that each level can have its own coefficient, independent of the other levels.
Think about how linear models work. The predicted value is
$$
\hat{y}_i = \s
|
16,845
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binary encoding instead of one-hot encoding?
|
When you do the standard encoding, you are using $0$ and $1$ as “off” and “on”. When you give a $1$, you turn on the effect of being in the corresponding category over (or under, or maybe neither) the baseline category that is subsumed by the intercept.
With your encoding, that interpretation is lost. For instance, what is the difference between $001$ and $101$ in your coding scheme? Further, what does it mean if $x_1=1?$
Arguably (much) worse, the model performance depends on how you do the coding.
set.seed(2022)
N <- 100
categories <- rep(c("a", "b", "c", "d", "e", "f", "g", "h"), rep(N, 8))
y <- seq(1, length(categories), 1) #rnorm(length(categories))
x1_1 <- x2_1 <- x3_1 <- x1_2 <- x2_2 <- x3_2 <- rep(NA, length(y))
for (i in 1:length(y)){
if (categories[i] == "a"){
x1_1[i] <- 0
x2_1[i] <- 0
x3_1[i] <- 1
x1_2[i] <- 0
x2_2[i] <- 0
x3_2[i] <- 0
}
if (categories[i] == "b"){
x1_1[i] <- 0
x2_1[i] <- 1
x3_1[i] <- 0
x1_2[i] <- 0
x2_2[i] <- 0
x3_2[i] <- 1
}
if (categories[i] == "c"){
x1_1[i] <- 0
x2_1[i] <- 1
x3_1[i] <- 1
x1_2[i] <- 0
x2_2[i] <- 1
x3_2[i] <- 0
}
if (categories[i] == "d"){
x1_1[i] <- 1
x2_1[i] <- 0
x3_1[i] <- 0
x1_2[i] <- 0
x2_2[i] <- 1
x3_2[i] <- 1
}
if (categories[i] == "e"){
x1_1[i] <- 1
x2_1[i] <- 0
x3_1[i] <- 1
x1_2[i] <- 1
x2_2[i] <- 0
x3_2[i] <- 0
}
if (categories[i] == "f"){
x1_1[i] <- 1
x2_1[i] <- 1
x3_1[i] <- 0
x1_2[i] <- 1
x2_2[i] <- 0
x3_2[i] <- 1
}
if (categories[i] == "g"){
x1_1[i] <- 1
x2_1[i] <- 1
x3_1[i] <- 1
x1_2[i] <- 1
x2_2[i] <- 1
x3_2[i] <- 0
}
if (categories[i] == "h"){
x1_1[i] <- 0
x2_1[i] <- 0
x3_1[i] <- 0
x1_2[i] <- 1
x2_2[i] <- 1
x3_2[i] <- 1
}
}
L1 <- lm(y ~ x1_1 + x2_1 + x3_1) # R^2 = 0.2344, p < 2.2e-16
L2 <- lm(y ~ x1_2 + x2_2 + x3_2) # R^2 = 0.9844, p < 2.2e-16
L3 <- lm(y ~ categories) # R^2 = 0.9844, p < 2.2e-16
By coincidence, the coding that I did as an alternative to the coding in the OP resulted in the same $R^2$ as the standard way of encoding the categorical variable. However, I had no way of knowing that when I started doing the alternative coding.
It is worth a mention that, when I change the y variable, that coincidence vanishes. Additionally, the p-values for the overall $F$-test differ between all three models. (This was probably true with the first simulation, but the p-values were so small that R cannot distinguish between them.)
set.seed(2022)
N <- 100
categories <- rep(c("a", "b", "c", "d", "e", "f", "g", "h"), rep(N, 8))
y <- rnorm(length(categories))
x1_1 <- x2_1 <- x3_1 <- x1_2 <- x2_2 <- x3_2 <- rep(NA, length(y))
for (i in 1:length(y)){
if (categories[i] == "a"){
x1_1[i] <- 0
x2_1[i] <- 0
x3_1[i] <- 1
x1_2[i] <- 0
x2_2[i] <- 0
x3_2[i] <- 0
}
if (categories[i] == "b"){
x1_1[i] <- 0
x2_1[i] <- 1
x3_1[i] <- 0
x1_2[i] <- 0
x2_2[i] <- 0
x3_2[i] <- 1
}
if (categories[i] == "c"){
x1_1[i] <- 0
x2_1[i] <- 1
x3_1[i] <- 1
x1_2[i] <- 0
x2_2[i] <- 1
x3_2[i] <- 0
}
if (categories[i] == "d"){
x1_1[i] <- 1
x2_1[i] <- 0
x3_1[i] <- 0
x1_2[i] <- 0
x2_2[i] <- 1
x3_2[i] <- 1
}
if (categories[i] == "e"){
x1_1[i] <- 1
x2_1[i] <- 0
x3_1[i] <- 1
x1_2[i] <- 1
x2_2[i] <- 0
x3_2[i] <- 0
}
if (categories[i] == "f"){
x1_1[i] <- 1
x2_1[i] <- 1
x3_1[i] <- 0
x1_2[i] <- 1
x2_2[i] <- 0
x3_2[i] <- 1
}
if (categories[i] == "g"){
x1_1[i] <- 1
x2_1[i] <- 1
x3_1[i] <- 1
x1_2[i] <- 1
x2_2[i] <- 1
x3_2[i] <- 0
}
if (categories[i] == "h"){
x1_1[i] <- 0
x2_1[i] <- 0
x3_1[i] <- 0
x1_2[i] <- 1
x2_2[i] <- 1
x3_2[i] <- 1
}
}
L1 <- lm(y ~ x1_1 + x2_1 + x3_1) # R^2 = 0.005842, p = 0.1979
L2 <- lm(y ~ x1_2 + x2_2 + x3_2) # R^2 = 0.001438, p = 0.7659
L3 <- lm(y ~ categories) # R^2 = 0.0123, p = 0.1981
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binar
|
When you do the standard encoding, you are using $0$ and $1$ as “off” and “on”. When you give a $1$, you turn on the effect of being in the corresponding category over (or under, or maybe neither) the
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binary encoding instead of one-hot encoding?
When you do the standard encoding, you are using $0$ and $1$ as “off” and “on”. When you give a $1$, you turn on the effect of being in the corresponding category over (or under, or maybe neither) the baseline category that is subsumed by the intercept.
With your encoding, that interpretation is lost. For instance, what is the difference between $001$ and $101$ in your coding scheme? Further, what does it mean if $x_1=1?$
Arguably (much) worse, the model performance depends on how you do the coding.
set.seed(2022)
N <- 100
categories <- rep(c("a", "b", "c", "d", "e", "f", "g", "h"), rep(N, 8))
y <- seq(1, length(categories), 1) #rnorm(length(categories))
x1_1 <- x2_1 <- x3_1 <- x1_2 <- x2_2 <- x3_2 <- rep(NA, length(y))
for (i in 1:length(y)){
if (categories[i] == "a"){
x1_1[i] <- 0
x2_1[i] <- 0
x3_1[i] <- 1
x1_2[i] <- 0
x2_2[i] <- 0
x3_2[i] <- 0
}
if (categories[i] == "b"){
x1_1[i] <- 0
x2_1[i] <- 1
x3_1[i] <- 0
x1_2[i] <- 0
x2_2[i] <- 0
x3_2[i] <- 1
}
if (categories[i] == "c"){
x1_1[i] <- 0
x2_1[i] <- 1
x3_1[i] <- 1
x1_2[i] <- 0
x2_2[i] <- 1
x3_2[i] <- 0
}
if (categories[i] == "d"){
x1_1[i] <- 1
x2_1[i] <- 0
x3_1[i] <- 0
x1_2[i] <- 0
x2_2[i] <- 1
x3_2[i] <- 1
}
if (categories[i] == "e"){
x1_1[i] <- 1
x2_1[i] <- 0
x3_1[i] <- 1
x1_2[i] <- 1
x2_2[i] <- 0
x3_2[i] <- 0
}
if (categories[i] == "f"){
x1_1[i] <- 1
x2_1[i] <- 1
x3_1[i] <- 0
x1_2[i] <- 1
x2_2[i] <- 0
x3_2[i] <- 1
}
if (categories[i] == "g"){
x1_1[i] <- 1
x2_1[i] <- 1
x3_1[i] <- 1
x1_2[i] <- 1
x2_2[i] <- 1
x3_2[i] <- 0
}
if (categories[i] == "h"){
x1_1[i] <- 0
x2_1[i] <- 0
x3_1[i] <- 0
x1_2[i] <- 1
x2_2[i] <- 1
x3_2[i] <- 1
}
}
L1 <- lm(y ~ x1_1 + x2_1 + x3_1) # R^2 = 0.2344, p < 2.2e-16
L2 <- lm(y ~ x1_2 + x2_2 + x3_2) # R^2 = 0.9844, p < 2.2e-16
L3 <- lm(y ~ categories) # R^2 = 0.9844, p < 2.2e-16
By coincidence, the coding that I did as an alternative to the coding in the OP resulted in the same $R^2$ as the standard way of encoding the categorical variable. However, I had no way of knowing that when I started doing the alternative coding.
It is worth a mention that, when I change the y variable, that coincidence vanishes. Additionally, the p-values for the overall $F$-test differ between all three models. (This was probably true with the first simulation, but the p-values were so small that R cannot distinguish between them.)
set.seed(2022)
N <- 100
categories <- rep(c("a", "b", "c", "d", "e", "f", "g", "h"), rep(N, 8))
y <- rnorm(length(categories))
x1_1 <- x2_1 <- x3_1 <- x1_2 <- x2_2 <- x3_2 <- rep(NA, length(y))
for (i in 1:length(y)){
if (categories[i] == "a"){
x1_1[i] <- 0
x2_1[i] <- 0
x3_1[i] <- 1
x1_2[i] <- 0
x2_2[i] <- 0
x3_2[i] <- 0
}
if (categories[i] == "b"){
x1_1[i] <- 0
x2_1[i] <- 1
x3_1[i] <- 0
x1_2[i] <- 0
x2_2[i] <- 0
x3_2[i] <- 1
}
if (categories[i] == "c"){
x1_1[i] <- 0
x2_1[i] <- 1
x3_1[i] <- 1
x1_2[i] <- 0
x2_2[i] <- 1
x3_2[i] <- 0
}
if (categories[i] == "d"){
x1_1[i] <- 1
x2_1[i] <- 0
x3_1[i] <- 0
x1_2[i] <- 0
x2_2[i] <- 1
x3_2[i] <- 1
}
if (categories[i] == "e"){
x1_1[i] <- 1
x2_1[i] <- 0
x3_1[i] <- 1
x1_2[i] <- 1
x2_2[i] <- 0
x3_2[i] <- 0
}
if (categories[i] == "f"){
x1_1[i] <- 1
x2_1[i] <- 1
x3_1[i] <- 0
x1_2[i] <- 1
x2_2[i] <- 0
x3_2[i] <- 1
}
if (categories[i] == "g"){
x1_1[i] <- 1
x2_1[i] <- 1
x3_1[i] <- 1
x1_2[i] <- 1
x2_2[i] <- 1
x3_2[i] <- 0
}
if (categories[i] == "h"){
x1_1[i] <- 0
x2_1[i] <- 0
x3_1[i] <- 0
x1_2[i] <- 1
x2_2[i] <- 1
x3_2[i] <- 1
}
}
L1 <- lm(y ~ x1_1 + x2_1 + x3_1) # R^2 = 0.005842, p = 0.1979
L2 <- lm(y ~ x1_2 + x2_2 + x3_2) # R^2 = 0.001438, p = 0.7659
L3 <- lm(y ~ categories) # R^2 = 0.0123, p = 0.1981
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binar
When you do the standard encoding, you are using $0$ and $1$ as “off” and “on”. When you give a $1$, you turn on the effect of being in the corresponding category over (or under, or maybe neither) the
|
16,846
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binary encoding instead of one-hot encoding?
|
The problem is not to encode the different id values of the categories.
if there are 8 categories, why don't we code them as
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1?
Instead, the problem is to encode the different effects of the categories.
Your suggestion is to use only three dummy variables to model the effect as
$$\text{effect of category $=$ $\alpha_1$ (if category $=$ A, C, E, G) + $\alpha_2$ (if category $=$ A, B, E, F) + $\alpha_3$ (if category $=$ A, B, C, D)}$$
In this way you can indeed encode eight category values by a binary 3 bit binary number.
If we choose $\alpha_1 = 1$, $\alpha_2 = 2$ and $\alpha_3 = 4$ then we can get the values of the 8 id values
$$\begin{array}{}
A & 1\alpha_1 + 1\alpha_2 + 1\alpha_3 = 7 \\
B & 0\alpha_1 + 1\alpha_2 + 1\alpha_3 = 6 \\
C & 1\alpha_1 + 0\alpha_2 + 1\alpha_3 = 5 \\
D & 0\alpha_1 + 0\alpha_2 + 1\alpha_3 = 4 \\
E & 1\alpha_1 + 1\alpha_2 + 0\alpha_3 = 3 \\
F & 0\alpha_1 + 1\alpha_2 + 0\alpha_3 = 2 \\
G & 1\alpha_1 + 0\alpha_2 + 0\alpha_3 = 1 \\
H & 0\alpha_1 + 0\alpha_2 + 0\alpha_3 = 0 \\
\end{array}$$
But we are not interested in modelling the id-values 7,6,5,4,3,2,1,0. Instead we want to model the entire possible space of effects. That space is 8-dimensional and not 3-dimensional.
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binar
|
The problem is not to encode the different id values of the categories.
if there are 8 categories, why don't we code them as
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1?
Instead, the problem is to en
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binary encoding instead of one-hot encoding?
The problem is not to encode the different id values of the categories.
if there are 8 categories, why don't we code them as
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1?
Instead, the problem is to encode the different effects of the categories.
Your suggestion is to use only three dummy variables to model the effect as
$$\text{effect of category $=$ $\alpha_1$ (if category $=$ A, C, E, G) + $\alpha_2$ (if category $=$ A, B, E, F) + $\alpha_3$ (if category $=$ A, B, C, D)}$$
In this way you can indeed encode eight category values by a binary 3 bit binary number.
If we choose $\alpha_1 = 1$, $\alpha_2 = 2$ and $\alpha_3 = 4$ then we can get the values of the 8 id values
$$\begin{array}{}
A & 1\alpha_1 + 1\alpha_2 + 1\alpha_3 = 7 \\
B & 0\alpha_1 + 1\alpha_2 + 1\alpha_3 = 6 \\
C & 1\alpha_1 + 0\alpha_2 + 1\alpha_3 = 5 \\
D & 0\alpha_1 + 0\alpha_2 + 1\alpha_3 = 4 \\
E & 1\alpha_1 + 1\alpha_2 + 0\alpha_3 = 3 \\
F & 0\alpha_1 + 1\alpha_2 + 0\alpha_3 = 2 \\
G & 1\alpha_1 + 0\alpha_2 + 0\alpha_3 = 1 \\
H & 0\alpha_1 + 0\alpha_2 + 0\alpha_3 = 0 \\
\end{array}$$
But we are not interested in modelling the id-values 7,6,5,4,3,2,1,0. Instead we want to model the entire possible space of effects. That space is 8-dimensional and not 3-dimensional.
|
Why do we need so many dummy variables in a regression with categorical predictor? Why not use binar
The problem is not to encode the different id values of the categories.
if there are 8 categories, why don't we code them as
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1?
Instead, the problem is to en
|
16,847
|
Can a neural network with only $1$ hidden layer solve any problem?
|
The question asks about "arbitrary functions" and "any problem"; the accepted answer talks only about continuous functions.
The answer to the question as stated now, in both versions, is clearly "no". Some fun counterexamples:
"Any problem" includes Turing's Entscheidungsproblem, which is famously unsolvable.
"Arbitrary functions", if you wish to go to a more "mathematical" class of problems, can be very weird. The Ackermann Function is a nice example for a function with a relatively benign definition which can be calculated readily by any kid with basic maths skills (and a lot of time) but which grows at a huge rate (much faster than exponential). It is not primitive recursive, that is, it cannot be computed by a program which consists only of for loops, i.e. where the number of iteration for every loops is known at the beginning of the loop. A neural net with its very simple structure of linear summing neurons and some multiplications is restricted to primitive-recursive functions (at least over an unbounded domain) and cannot approximate that.
There are discontinous functions which certainly work well as a counter-example too, for example the Dirichlet function.
As per the comments, and to come down to earth a bit, a simple sin function will do the job of providing a counterexample regarding UATs, as well.
|
Can a neural network with only $1$ hidden layer solve any problem?
|
The question asks about "arbitrary functions" and "any problem"; the accepted answer talks only about continuous functions.
The answer to the question as stated now, in both versions, is clearly "no".
|
Can a neural network with only $1$ hidden layer solve any problem?
The question asks about "arbitrary functions" and "any problem"; the accepted answer talks only about continuous functions.
The answer to the question as stated now, in both versions, is clearly "no". Some fun counterexamples:
"Any problem" includes Turing's Entscheidungsproblem, which is famously unsolvable.
"Arbitrary functions", if you wish to go to a more "mathematical" class of problems, can be very weird. The Ackermann Function is a nice example for a function with a relatively benign definition which can be calculated readily by any kid with basic maths skills (and a lot of time) but which grows at a huge rate (much faster than exponential). It is not primitive recursive, that is, it cannot be computed by a program which consists only of for loops, i.e. where the number of iteration for every loops is known at the beginning of the loop. A neural net with its very simple structure of linear summing neurons and some multiplications is restricted to primitive-recursive functions (at least over an unbounded domain) and cannot approximate that.
There are discontinous functions which certainly work well as a counter-example too, for example the Dirichlet function.
As per the comments, and to come down to earth a bit, a simple sin function will do the job of providing a counterexample regarding UATs, as well.
|
Can a neural network with only $1$ hidden layer solve any problem?
The question asks about "arbitrary functions" and "any problem"; the accepted answer talks only about continuous functions.
The answer to the question as stated now, in both versions, is clearly "no".
|
16,848
|
Can a neural network with only $1$ hidden layer solve any problem?
|
The questions as stated ask "Can a neural network solve and problem?" and "Can a neural network approximate any arbitrary function?" The answer to both of these questions is "No, there is no such theorem."
However, it's common for people learning about neural networks for the first time to mis-state the so-called "universal approximation theorems," which provide the specific technical conditions under which a neural network can approximate a function. OP's questions appear to allude to some version of the Cybenko UAT. Here's a statement of the Cybenko UAT from Wikipedia.
Fix a continuous function $\sigma:\mathbb{R}\rightarrow \mathbb{R}$(activation function) and positive integers $d,D$. The function $\sigma$ is not a polynomial if and only if, for every continuous function function $f:\mathbb{R}^d\to\mathbb{R}^D$ (target function), every compact subset $K$ of $\mathbb{R}^d$, and every $\epsilon >0 $ there exists a continuous function $f_{\epsilon}:\mathbb{R}^d\to\mathbb{R}^D$ (the layer output) with representation: $$
f_{\epsilon} = W_2 \circ \sigma \circ W_1,
$$
where $W_2,W_1$ are composable affine maps and $\circ$ denotes component-wise composition, such that the approximation bound:
$$
\sup_{x \in K}\, \| f( x ) - f_{\epsilon} ( x ) \| < \varepsilon
$$
holds for any $\epsilon$ arbitrarily small (distance from $f$ to $f_\epsilon$ can be infinitely small).
So it's not that any function can be approximated -- the function must be continuous. The error is only smaller than $\epsilon$ on a certain compact subset $K$, and for some unspecified $D$.
In a practical setting where you have some data and you'd like to estimate a neural network, the Cybenko UAT is silent -- it doesn't tell you how to go about estimating $W_2, W_1$, nor does it tell you how to choose the width $D$ of the hidden layer, to achieve this precision.
And finally, achieving small approximation error to certain kinds of functions is not the same as "solving any problem."
(There are a number of approximation theorems for NNs, which reach different conclusions (but are similar in theme) and have different hypotheses.)
|
Can a neural network with only $1$ hidden layer solve any problem?
|
The questions as stated ask "Can a neural network solve and problem?" and "Can a neural network approximate any arbitrary function?" The answer to both of these questions is "No, there is no such theo
|
Can a neural network with only $1$ hidden layer solve any problem?
The questions as stated ask "Can a neural network solve and problem?" and "Can a neural network approximate any arbitrary function?" The answer to both of these questions is "No, there is no such theorem."
However, it's common for people learning about neural networks for the first time to mis-state the so-called "universal approximation theorems," which provide the specific technical conditions under which a neural network can approximate a function. OP's questions appear to allude to some version of the Cybenko UAT. Here's a statement of the Cybenko UAT from Wikipedia.
Fix a continuous function $\sigma:\mathbb{R}\rightarrow \mathbb{R}$(activation function) and positive integers $d,D$. The function $\sigma$ is not a polynomial if and only if, for every continuous function function $f:\mathbb{R}^d\to\mathbb{R}^D$ (target function), every compact subset $K$ of $\mathbb{R}^d$, and every $\epsilon >0 $ there exists a continuous function $f_{\epsilon}:\mathbb{R}^d\to\mathbb{R}^D$ (the layer output) with representation: $$
f_{\epsilon} = W_2 \circ \sigma \circ W_1,
$$
where $W_2,W_1$ are composable affine maps and $\circ$ denotes component-wise composition, such that the approximation bound:
$$
\sup_{x \in K}\, \| f( x ) - f_{\epsilon} ( x ) \| < \varepsilon
$$
holds for any $\epsilon$ arbitrarily small (distance from $f$ to $f_\epsilon$ can be infinitely small).
So it's not that any function can be approximated -- the function must be continuous. The error is only smaller than $\epsilon$ on a certain compact subset $K$, and for some unspecified $D$.
In a practical setting where you have some data and you'd like to estimate a neural network, the Cybenko UAT is silent -- it doesn't tell you how to go about estimating $W_2, W_1$, nor does it tell you how to choose the width $D$ of the hidden layer, to achieve this precision.
And finally, achieving small approximation error to certain kinds of functions is not the same as "solving any problem."
(There are a number of approximation theorems for NNs, which reach different conclusions (but are similar in theme) and have different hypotheses.)
|
Can a neural network with only $1$ hidden layer solve any problem?
The questions as stated ask "Can a neural network solve and problem?" and "Can a neural network approximate any arbitrary function?" The answer to both of these questions is "No, there is no such theo
|
16,849
|
Can a neural network with only $1$ hidden layer solve any problem?
|
The other answers have already mentioned the Universal approximation theorem and that, in strictly mathematical sense, it does not apply to all the functions and it approximates only to the predefined level of error.
However, there is a different way to interpret the question: if a single layer network can approximate any function (satisfying criteria of the UAT) to any required degree of precision, why do we use multilayer networks? The answer is that, given a specified precision, the single layer network may have to be very big and/or may take a very long time to train. Multilayer networks can be smaller and can be trained faster (provided that we use appropriate techniques, such as the backpropagation algorithm).
|
Can a neural network with only $1$ hidden layer solve any problem?
|
The other answers have already mentioned the Universal approximation theorem and that, in strictly mathematical sense, it does not apply to all the functions and it approximates only to the predefined
|
Can a neural network with only $1$ hidden layer solve any problem?
The other answers have already mentioned the Universal approximation theorem and that, in strictly mathematical sense, it does not apply to all the functions and it approximates only to the predefined level of error.
However, there is a different way to interpret the question: if a single layer network can approximate any function (satisfying criteria of the UAT) to any required degree of precision, why do we use multilayer networks? The answer is that, given a specified precision, the single layer network may have to be very big and/or may take a very long time to train. Multilayer networks can be smaller and can be trained faster (provided that we use appropriate techniques, such as the backpropagation algorithm).
|
Can a neural network with only $1$ hidden layer solve any problem?
The other answers have already mentioned the Universal approximation theorem and that, in strictly mathematical sense, it does not apply to all the functions and it approximates only to the predefined
|
16,850
|
Can a neural network with only $1$ hidden layer solve any problem?
|
The canonical paper for this is Hornik, (1989), for a pdf.
The paper demonstrates that given a neural net with a single layer of sufficient number of nodes, where the activation function is a 'squashing' function, we may approximate any Borel measurable function to arbitrary accuracy.
NB. a net with ReLU activation functions does have this property, as we can make a squashing function from a pair of ReLU function https://papers.nips.cc/paper/2018/file/03bfc1d4783966c69cc6aef8247e0103-Paper.pdf
|
Can a neural network with only $1$ hidden layer solve any problem?
|
The canonical paper for this is Hornik, (1989), for a pdf.
The paper demonstrates that given a neural net with a single layer of sufficient number of nodes, where the activation function is a 'squashi
|
Can a neural network with only $1$ hidden layer solve any problem?
The canonical paper for this is Hornik, (1989), for a pdf.
The paper demonstrates that given a neural net with a single layer of sufficient number of nodes, where the activation function is a 'squashing' function, we may approximate any Borel measurable function to arbitrary accuracy.
NB. a net with ReLU activation functions does have this property, as we can make a squashing function from a pair of ReLU function https://papers.nips.cc/paper/2018/file/03bfc1d4783966c69cc6aef8247e0103-Paper.pdf
|
Can a neural network with only $1$ hidden layer solve any problem?
The canonical paper for this is Hornik, (1989), for a pdf.
The paper demonstrates that given a neural net with a single layer of sufficient number of nodes, where the activation function is a 'squashi
|
16,851
|
Can a neural network with only $1$ hidden layer solve any problem?
|
More comments about "network’s error approaches 0"
There is an important concept about Bayes error rate. Even most powerful model may achieve very high error rates, just because there are large irreducible error.
As an example example, think about if we have large amount of data that have exactly same feature but different label.
|
Can a neural network with only $1$ hidden layer solve any problem?
|
More comments about "network’s error approaches 0"
There is an important concept about Bayes error rate. Even most powerful model may achieve very high error rates, just because there are large irredu
|
Can a neural network with only $1$ hidden layer solve any problem?
More comments about "network’s error approaches 0"
There is an important concept about Bayes error rate. Even most powerful model may achieve very high error rates, just because there are large irreducible error.
As an example example, think about if we have large amount of data that have exactly same feature but different label.
|
Can a neural network with only $1$ hidden layer solve any problem?
More comments about "network’s error approaches 0"
There is an important concept about Bayes error rate. Even most powerful model may achieve very high error rates, just because there are large irredu
|
16,852
|
Is there more than one "median" formula?
|
TL;DR - I'm not aware of specific names being given to different estimators of sample medians. Methods to estimate sample statistics from some data are rather fussy and different resources give different definitions.
In Hogg, McKean and Craig's Introduction to Mathematical Statistics, the authors provide a definition of medians of random samples, but only in the case that there are an odd number of samples! The authors write
Certain functions of the order statistics are important statistics themselves... if $n$ is odd, $Y_{(n+1)/2}$ ... is called the median of the random sample.
The authors provide no guidance on what to do if you have an even number of samples. (Note that $Y_i$ is the $i$th smallest datum.)
But this seems unnecessarily restrictive; I would prefer to be able to define a median of a random sample for even or odd $n$. Moreover, I would like the median to be unique. Given these two requirements, I have to make some decisions about how to best find a unique sample median. Both Algorithm A and Algorithm B satisfy these requirements. Imposing additional requirements could eliminate either or both from consideration.
Algorithm B has the property that half the data fall above the value, and half the data fall below the value. In light of the definition of the median of a random variable, this seems nice.
Whether or not a particular estimator breaks unit tests is a property of the unit tests -- unit tests written against a specific estimator won't necessarily hold when you substitute another estimator. In the ideal case, the unit tests were chosen because they reflect the critical needs of your organization, not because of a doctrinaire argument over definitions.
|
Is there more than one "median" formula?
|
TL;DR - I'm not aware of specific names being given to different estimators of sample medians. Methods to estimate sample statistics from some data are rather fussy and different resources give differ
|
Is there more than one "median" formula?
TL;DR - I'm not aware of specific names being given to different estimators of sample medians. Methods to estimate sample statistics from some data are rather fussy and different resources give different definitions.
In Hogg, McKean and Craig's Introduction to Mathematical Statistics, the authors provide a definition of medians of random samples, but only in the case that there are an odd number of samples! The authors write
Certain functions of the order statistics are important statistics themselves... if $n$ is odd, $Y_{(n+1)/2}$ ... is called the median of the random sample.
The authors provide no guidance on what to do if you have an even number of samples. (Note that $Y_i$ is the $i$th smallest datum.)
But this seems unnecessarily restrictive; I would prefer to be able to define a median of a random sample for even or odd $n$. Moreover, I would like the median to be unique. Given these two requirements, I have to make some decisions about how to best find a unique sample median. Both Algorithm A and Algorithm B satisfy these requirements. Imposing additional requirements could eliminate either or both from consideration.
Algorithm B has the property that half the data fall above the value, and half the data fall below the value. In light of the definition of the median of a random variable, this seems nice.
Whether or not a particular estimator breaks unit tests is a property of the unit tests -- unit tests written against a specific estimator won't necessarily hold when you substitute another estimator. In the ideal case, the unit tests were chosen because they reflect the critical needs of your organization, not because of a doctrinaire argument over definitions.
|
Is there more than one "median" formula?
TL;DR - I'm not aware of specific names being given to different estimators of sample medians. Methods to estimate sample statistics from some data are rather fussy and different resources give differ
|
16,853
|
Is there more than one "median" formula?
|
What @Sycorax says.
As a matter of fact, there are surprisingly many definitions of general quantiles, so in particular also of medians. Hyndman & Fan (1996, The American Statistician) give an overview that is, AFAIK, still comprehensive. The different types do not have formal names. You may simply need to be clear on which type you are using. (It often does not make a big difference with data sets of realistic sizes.)
Note that it is commonly accepted to have a value that is not present in the data set as the median, e.g., 5.5 as a median for (4, 5, 6, 7). This is the default behavior for R:
> median(4:7)
[1] 5.5
R's median() by default uses type 7 of Hyndman & Fan's classification.
|
Is there more than one "median" formula?
|
What @Sycorax says.
As a matter of fact, there are surprisingly many definitions of general quantiles, so in particular also of medians. Hyndman & Fan (1996, The American Statistician) give an overvie
|
Is there more than one "median" formula?
What @Sycorax says.
As a matter of fact, there are surprisingly many definitions of general quantiles, so in particular also of medians. Hyndman & Fan (1996, The American Statistician) give an overview that is, AFAIK, still comprehensive. The different types do not have formal names. You may simply need to be clear on which type you are using. (It often does not make a big difference with data sets of realistic sizes.)
Note that it is commonly accepted to have a value that is not present in the data set as the median, e.g., 5.5 as a median for (4, 5, 6, 7). This is the default behavior for R:
> median(4:7)
[1] 5.5
R's median() by default uses type 7 of Hyndman & Fan's classification.
|
Is there more than one "median" formula?
What @Sycorax says.
As a matter of fact, there are surprisingly many definitions of general quantiles, so in particular also of medians. Hyndman & Fan (1996, The American Statistician) give an overvie
|
16,854
|
Is there more than one "median" formula?
|
In R's mad function, it uses the terms "lo-median" to describe your algorithm A, "hi-median" to describe rounding up instead, and just "median" to describe your algorithm B (which, as others have noted is by far the most common definition).
Curiously, there is no such option on R's median() function! (But R's quantile() has type for fine control.)
|
Is there more than one "median" formula?
|
In R's mad function, it uses the terms "lo-median" to describe your algorithm A, "hi-median" to describe rounding up instead, and just "median" to describe your algorithm B (which, as others have note
|
Is there more than one "median" formula?
In R's mad function, it uses the terms "lo-median" to describe your algorithm A, "hi-median" to describe rounding up instead, and just "median" to describe your algorithm B (which, as others have noted is by far the most common definition).
Curiously, there is no such option on R's median() function! (But R's quantile() has type for fine control.)
|
Is there more than one "median" formula?
In R's mad function, it uses the terms "lo-median" to describe your algorithm A, "hi-median" to describe rounding up instead, and just "median" to describe your algorithm B (which, as others have note
|
16,855
|
How to plot decision boundary in R for logistic regression model?
|
set.seed(1234)
x1 <- rnorm(20, 1, 2)
x2 <- rnorm(20)
y <- sign(-1 - 2 * x1 + 4 * x2 )
y[ y == -1] <- 0
df <- cbind.data.frame( y, x1, x2)
mdl <- glm( y ~ . , data = df , family=binomial)
slope <- coef(mdl)[2]/(-coef(mdl)[3])
intercept <- coef(mdl)[1]/(-coef(mdl)[3])
library(lattice)
xyplot( x2 ~ x1 , data = df, groups = y,
panel=function(...){
panel.xyplot(...)
panel.abline(intercept , slope)
panel.grid(...)
})
I must remark that perfect separation occurs here, therefore the glm function gives you a warning. But that is not important here as the purpose is to illustrate how to draw the linear boundary and the observations colored according to their covariates.
|
How to plot decision boundary in R for logistic regression model?
|
set.seed(1234)
x1 <- rnorm(20, 1, 2)
x2 <- rnorm(20)
y <- sign(-1 - 2 * x1 + 4 * x2 )
y[ y == -1] <- 0
df <- cbind.data.frame( y, x1, x2)
mdl <- glm( y ~ . , data = df , family=binomial)
slope <
|
How to plot decision boundary in R for logistic regression model?
set.seed(1234)
x1 <- rnorm(20, 1, 2)
x2 <- rnorm(20)
y <- sign(-1 - 2 * x1 + 4 * x2 )
y[ y == -1] <- 0
df <- cbind.data.frame( y, x1, x2)
mdl <- glm( y ~ . , data = df , family=binomial)
slope <- coef(mdl)[2]/(-coef(mdl)[3])
intercept <- coef(mdl)[1]/(-coef(mdl)[3])
library(lattice)
xyplot( x2 ~ x1 , data = df, groups = y,
panel=function(...){
panel.xyplot(...)
panel.abline(intercept , slope)
panel.grid(...)
})
I must remark that perfect separation occurs here, therefore the glm function gives you a warning. But that is not important here as the purpose is to illustrate how to draw the linear boundary and the observations colored according to their covariates.
|
How to plot decision boundary in R for logistic regression model?
set.seed(1234)
x1 <- rnorm(20, 1, 2)
x2 <- rnorm(20)
y <- sign(-1 - 2 * x1 + 4 * x2 )
y[ y == -1] <- 0
df <- cbind.data.frame( y, x1, x2)
mdl <- glm( y ~ . , data = df , family=binomial)
slope <
|
16,856
|
How to plot decision boundary in R for logistic regression model?
|
Wanted to address the question in comment to the accepted answer above from Fernando: Can someone explain the logic behind the slope and intercept?
The hypothesis for logistics regression takes the form of:
$$h_{\theta} = g(z)$$
where, $g(z)$ is the sigmoid function and where $z$ is of the form:
$$z = \theta_{0} + \theta_{1}x_{1} + \theta_{2}x_{2}$$
Given we are classifying between 0 and 1, $y = 1$ when $h_{\theta} \geq 0.5$ which
given the sigmoid function is true when:
$$\theta_{0} + \theta_{1}x_{1} + \theta_{2}x_{2} \geq 0$$
the above is the decision boundary and can be rearranged as:
$$x_{2} \geq \frac{-\theta_{0}}{\theta_{2}} + \frac{-\theta_{1}}{\theta_{2}}x_{1}$$
This is an equation in the form of $y = mx + b$ and you can see then why $m$ and $b$ are calculated the way they are in the accepted answer
|
How to plot decision boundary in R for logistic regression model?
|
Wanted to address the question in comment to the accepted answer above from Fernando: Can someone explain the logic behind the slope and intercept?
The hypothesis for logistics regression takes the fo
|
How to plot decision boundary in R for logistic regression model?
Wanted to address the question in comment to the accepted answer above from Fernando: Can someone explain the logic behind the slope and intercept?
The hypothesis for logistics regression takes the form of:
$$h_{\theta} = g(z)$$
where, $g(z)$ is the sigmoid function and where $z$ is of the form:
$$z = \theta_{0} + \theta_{1}x_{1} + \theta_{2}x_{2}$$
Given we are classifying between 0 and 1, $y = 1$ when $h_{\theta} \geq 0.5$ which
given the sigmoid function is true when:
$$\theta_{0} + \theta_{1}x_{1} + \theta_{2}x_{2} \geq 0$$
the above is the decision boundary and can be rearranged as:
$$x_{2} \geq \frac{-\theta_{0}}{\theta_{2}} + \frac{-\theta_{1}}{\theta_{2}}x_{1}$$
This is an equation in the form of $y = mx + b$ and you can see then why $m$ and $b$ are calculated the way they are in the accepted answer
|
How to plot decision boundary in R for logistic regression model?
Wanted to address the question in comment to the accepted answer above from Fernando: Can someone explain the logic behind the slope and intercept?
The hypothesis for logistics regression takes the fo
|
16,857
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
|
Wald test
One standard approach is the Wald test. This is what the Stata command test does after a logit or probit regression. Let's see how this works in R by looking at an example:
mydata <- read.csv("http://www.ats.ucla.edu/stat/data/binary.csv") # Load dataset from the web
mydata$rank <- factor(mydata$rank)
mylogit <- glm(admit ~ gre + gpa + rank, data = mydata, family = "binomial") # calculate the logistic regression
summary(mylogit)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.989979 1.139951 -3.500 0.000465 ***
gre 0.002264 0.001094 2.070 0.038465 *
gpa 0.804038 0.331819 2.423 0.015388 *
rank2 -0.675443 0.316490 -2.134 0.032829 *
rank3 -1.340204 0.345306 -3.881 0.000104 ***
rank4 -1.551464 0.417832 -3.713 0.000205 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Say, you want to test the hypothesis $\beta_{gre}=\beta_{gpa}$ vs. $\beta_{gre}\neq \beta_{gpa}$. This is equivalent of testing $\beta_{gre} - \beta_{gpa} = 0$. The Wald test statistic is:
$$
W=\frac{(\hat{\beta}-\beta_{0})}{\widehat{\operatorname{se}}(\hat{\beta})}\sim \mathcal{N}(0,1)
$$
or
$$
W^2 = \frac{(\hat{\theta}-\theta_{0})^2}{\operatorname{Var}(\hat{\theta})}\sim \chi_{1}^2
$$
Our $\widehat{\theta}$ here is $\beta_{gre} - \beta_{gpa}$ and $\theta_{0}=0$. So all we need is the standard error of $\beta_{gre} - \beta_{gpa}$. We can calculate the standard error with the Delta method:
$$
\hat{se}(\beta_{gre} - \beta_{gpa})\approx \sqrt{\operatorname{Var}(\beta_{gre}) + \operatorname{Var}(\beta_{gpa}) - 2\cdot \operatorname{Cov}(\beta_{gre},\beta_{gpa})}
$$
So we also need the covariance of $\beta_{gre}$ and $\beta_{gpa}$. The variance-covariance matrix can be extracted with the vcov command after running the logistic regression:
var.mat <- vcov(mylogit)[c("gre", "gpa"),c("gre", "gpa")]
colnames(var.mat) <- rownames(var.mat) <- c("gre", "gpa")
gre gpa
gre 1.196831e-06 -0.0001241775
gpa -1.241775e-04 0.1101040465
Finally, we can calculate the standard error:
se <- sqrt(1.196831e-06 + 0.1101040465 -2*-0.0001241775)
se
[1] 0.3321951
So your Wald $z$-value is
wald.z <- (gre-gpa)/se
wald.z
[1] -2.413564
To get a $p$-value, just use the standard normal distribution:
2*pnorm(-2.413564)
[1] 0.01579735
In this case we have evidence that the coefficients are different from each other. This approach can be extended to more than two coefficients.
Using multcomp
This rather tedious calculations can be conveniently done in R using the multcomp package. Here is the same example as above but done with multcomp:
library(multcomp)
glht.mod <- glht(mylogit, linfct = c("gre - gpa = 0"))
summary(glht.mod)
Linear Hypotheses:
Estimate Std. Error z value Pr(>|z|)
gre - gpa == 0 -0.8018 0.3322 -2.414 0.0158 *
confint(glht.mod)
A confidence interval for the difference of the coefficients can also be calculated:
Quantile = 1.96
95% family-wise confidence level
Linear Hypotheses:
Estimate lwr upr
gre - gpa == 0 -0.8018 -1.4529 -0.1507
For additional examples of multcomp, see here or here.
Likelihood ratio test (LRT)
The coefficients of a logistic regression are found by maximum likelihood. But because the likelihood function involves a lot of products, the log-likelihood is maximized which turns the products into sums. The model that fits better has a higher log-likelihood. The model involving more variables has at least the same likelihood as the null model. Denote the log-likelihood of the alternative model (model containing more variables) with $LL_{a}$ and the log-likelihood of the null model with $LL_{0}$, the likelihood ratio test statistic is:
$$
D=2\cdot (LL_{a} - LL_{0})\sim \chi_{df1-df2}^{2}
$$
The likelihood ratio test statistic follows a $\chi^{2}$-distribution with the degrees of freedom being the difference in number of variables. In our case, this is 2.
To perform the likelihood ratio test, we also need to fit the model with the constraint $\beta_{gre}=\beta_{gpa}$ to be able to compare the two likelihoods. The full model has the form $$\log\left(\frac{p_{i}}{1-p_{i}}\right)=\beta_{0}+\beta_{1}\cdot \mathrm{gre} + \beta_{2}\cdot \mathrm{gpa}+\beta_{3}\cdot \mathrm{rank_{2}} + \beta_{4}\cdot \mathrm{rank_{3}}+\beta_{5}\cdot \mathrm{rank_{4}}$$. Our constraint model has the form: $$\log\left(\frac{p_{i}}{1-p_{i}}\right)=\beta_{0}+\beta_{1}\cdot (\mathrm{gre} + \mathrm{gpa})+\beta_{2}\cdot \mathrm{rank_{2}} + \beta_{3}\cdot \mathrm{rank_{3}}+\beta_{4}\cdot \mathrm{rank_{4}}$$.
mylogit2 <- glm(admit ~ I(gre + gpa) + rank, data = mydata, family = "binomial")
In our case, we can use logLik to extract the log-likelihood of the two models after a logistic regression:
L1 <- logLik(mylogit)
L1
'log Lik.' -229.2587 (df=6)
L2 <- logLik(mylogit2)
L2
'log Lik.' -232.2416 (df=5)
The model containing the constraint on gre and gpa has a slightly higher log-likelihood (-232.24) compared to the full model (-229.26). Our likelihood ratio test statistic is:
D <- 2*(L1 - L2)
D
[1] 16.44923
We can now use the CDF of the $\chi^{2}_{2}$ to calculate the $p$-value:
1-pchisq(D, df=1)
[1] 0.01458625
The $p$-value is very small indicating that the coefficients are different.
R has the likelihood ratio test built in; we can use the anova function to calculate the likelhood ratio test:
anova(mylogit2, mylogit, test="LRT")
Analysis of Deviance Table
Model 1: admit ~ I(gre + gpa) + rank
Model 2: admit ~ gre + gpa + rank
Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1 395 464.48
2 394 458.52 1 5.9658 0.01459 *
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Again, we have strong evidence that the coefficients of gre and gpa are significantly different from each other.
Score test (aka Rao's Score test aka Lagrange multiplier test)
The Score function $U(\theta)$ is the derivative of the log-likelihood function ($\text{log} L(\theta|x)$) where $\theta$ are the parameters and $x$ the data (the univariate case is shown here for illustration purposes):
$$
U(\theta) = \frac{\partial \text{log} L(\theta|x)}{\partial \theta}
$$
This is basically the slope of the log-likelihood function. Further, let $I(\theta)$ be the Fisher information matrix which is the negative expectation of the second derivative of the log-likelihood function with respect to $\theta$. The score test statistics is:
$$
S(\theta_{0})=\frac{U(\theta_{0}^{2})}{I(\theta_{0})}\sim\chi^{2}_{1}
$$
The score test can also be calculated using anova (the score test statistics is called "Rao"):
anova(mylogit2, mylogit, test="Rao")
Analysis of Deviance Table
Model 1: admit ~ I(gre + gpa) + rank
Model 2: admit ~ gre + gpa + rank
Resid. Df Resid. Dev Df Deviance Rao Pr(>Chi)
1 395 464.48
2 394 458.52 1 5.9658 5.9144 0.01502 *
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
The conclusion is the same as before.
Note
An interesting relationship between the different test statistics when the model is linear is (Johnston and DiNardo (1997): Econometric Methods): Wald $\geq$ LR $\geq$ Score.
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
|
Wald test
One standard approach is the Wald test. This is what the Stata command test does after a logit or probit regression. Let's see how this works in R by looking at an example:
mydata <- read.cs
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
Wald test
One standard approach is the Wald test. This is what the Stata command test does after a logit or probit regression. Let's see how this works in R by looking at an example:
mydata <- read.csv("http://www.ats.ucla.edu/stat/data/binary.csv") # Load dataset from the web
mydata$rank <- factor(mydata$rank)
mylogit <- glm(admit ~ gre + gpa + rank, data = mydata, family = "binomial") # calculate the logistic regression
summary(mylogit)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.989979 1.139951 -3.500 0.000465 ***
gre 0.002264 0.001094 2.070 0.038465 *
gpa 0.804038 0.331819 2.423 0.015388 *
rank2 -0.675443 0.316490 -2.134 0.032829 *
rank3 -1.340204 0.345306 -3.881 0.000104 ***
rank4 -1.551464 0.417832 -3.713 0.000205 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Say, you want to test the hypothesis $\beta_{gre}=\beta_{gpa}$ vs. $\beta_{gre}\neq \beta_{gpa}$. This is equivalent of testing $\beta_{gre} - \beta_{gpa} = 0$. The Wald test statistic is:
$$
W=\frac{(\hat{\beta}-\beta_{0})}{\widehat{\operatorname{se}}(\hat{\beta})}\sim \mathcal{N}(0,1)
$$
or
$$
W^2 = \frac{(\hat{\theta}-\theta_{0})^2}{\operatorname{Var}(\hat{\theta})}\sim \chi_{1}^2
$$
Our $\widehat{\theta}$ here is $\beta_{gre} - \beta_{gpa}$ and $\theta_{0}=0$. So all we need is the standard error of $\beta_{gre} - \beta_{gpa}$. We can calculate the standard error with the Delta method:
$$
\hat{se}(\beta_{gre} - \beta_{gpa})\approx \sqrt{\operatorname{Var}(\beta_{gre}) + \operatorname{Var}(\beta_{gpa}) - 2\cdot \operatorname{Cov}(\beta_{gre},\beta_{gpa})}
$$
So we also need the covariance of $\beta_{gre}$ and $\beta_{gpa}$. The variance-covariance matrix can be extracted with the vcov command after running the logistic regression:
var.mat <- vcov(mylogit)[c("gre", "gpa"),c("gre", "gpa")]
colnames(var.mat) <- rownames(var.mat) <- c("gre", "gpa")
gre gpa
gre 1.196831e-06 -0.0001241775
gpa -1.241775e-04 0.1101040465
Finally, we can calculate the standard error:
se <- sqrt(1.196831e-06 + 0.1101040465 -2*-0.0001241775)
se
[1] 0.3321951
So your Wald $z$-value is
wald.z <- (gre-gpa)/se
wald.z
[1] -2.413564
To get a $p$-value, just use the standard normal distribution:
2*pnorm(-2.413564)
[1] 0.01579735
In this case we have evidence that the coefficients are different from each other. This approach can be extended to more than two coefficients.
Using multcomp
This rather tedious calculations can be conveniently done in R using the multcomp package. Here is the same example as above but done with multcomp:
library(multcomp)
glht.mod <- glht(mylogit, linfct = c("gre - gpa = 0"))
summary(glht.mod)
Linear Hypotheses:
Estimate Std. Error z value Pr(>|z|)
gre - gpa == 0 -0.8018 0.3322 -2.414 0.0158 *
confint(glht.mod)
A confidence interval for the difference of the coefficients can also be calculated:
Quantile = 1.96
95% family-wise confidence level
Linear Hypotheses:
Estimate lwr upr
gre - gpa == 0 -0.8018 -1.4529 -0.1507
For additional examples of multcomp, see here or here.
Likelihood ratio test (LRT)
The coefficients of a logistic regression are found by maximum likelihood. But because the likelihood function involves a lot of products, the log-likelihood is maximized which turns the products into sums. The model that fits better has a higher log-likelihood. The model involving more variables has at least the same likelihood as the null model. Denote the log-likelihood of the alternative model (model containing more variables) with $LL_{a}$ and the log-likelihood of the null model with $LL_{0}$, the likelihood ratio test statistic is:
$$
D=2\cdot (LL_{a} - LL_{0})\sim \chi_{df1-df2}^{2}
$$
The likelihood ratio test statistic follows a $\chi^{2}$-distribution with the degrees of freedom being the difference in number of variables. In our case, this is 2.
To perform the likelihood ratio test, we also need to fit the model with the constraint $\beta_{gre}=\beta_{gpa}$ to be able to compare the two likelihoods. The full model has the form $$\log\left(\frac{p_{i}}{1-p_{i}}\right)=\beta_{0}+\beta_{1}\cdot \mathrm{gre} + \beta_{2}\cdot \mathrm{gpa}+\beta_{3}\cdot \mathrm{rank_{2}} + \beta_{4}\cdot \mathrm{rank_{3}}+\beta_{5}\cdot \mathrm{rank_{4}}$$. Our constraint model has the form: $$\log\left(\frac{p_{i}}{1-p_{i}}\right)=\beta_{0}+\beta_{1}\cdot (\mathrm{gre} + \mathrm{gpa})+\beta_{2}\cdot \mathrm{rank_{2}} + \beta_{3}\cdot \mathrm{rank_{3}}+\beta_{4}\cdot \mathrm{rank_{4}}$$.
mylogit2 <- glm(admit ~ I(gre + gpa) + rank, data = mydata, family = "binomial")
In our case, we can use logLik to extract the log-likelihood of the two models after a logistic regression:
L1 <- logLik(mylogit)
L1
'log Lik.' -229.2587 (df=6)
L2 <- logLik(mylogit2)
L2
'log Lik.' -232.2416 (df=5)
The model containing the constraint on gre and gpa has a slightly higher log-likelihood (-232.24) compared to the full model (-229.26). Our likelihood ratio test statistic is:
D <- 2*(L1 - L2)
D
[1] 16.44923
We can now use the CDF of the $\chi^{2}_{2}$ to calculate the $p$-value:
1-pchisq(D, df=1)
[1] 0.01458625
The $p$-value is very small indicating that the coefficients are different.
R has the likelihood ratio test built in; we can use the anova function to calculate the likelhood ratio test:
anova(mylogit2, mylogit, test="LRT")
Analysis of Deviance Table
Model 1: admit ~ I(gre + gpa) + rank
Model 2: admit ~ gre + gpa + rank
Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1 395 464.48
2 394 458.52 1 5.9658 0.01459 *
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Again, we have strong evidence that the coefficients of gre and gpa are significantly different from each other.
Score test (aka Rao's Score test aka Lagrange multiplier test)
The Score function $U(\theta)$ is the derivative of the log-likelihood function ($\text{log} L(\theta|x)$) where $\theta$ are the parameters and $x$ the data (the univariate case is shown here for illustration purposes):
$$
U(\theta) = \frac{\partial \text{log} L(\theta|x)}{\partial \theta}
$$
This is basically the slope of the log-likelihood function. Further, let $I(\theta)$ be the Fisher information matrix which is the negative expectation of the second derivative of the log-likelihood function with respect to $\theta$. The score test statistics is:
$$
S(\theta_{0})=\frac{U(\theta_{0}^{2})}{I(\theta_{0})}\sim\chi^{2}_{1}
$$
The score test can also be calculated using anova (the score test statistics is called "Rao"):
anova(mylogit2, mylogit, test="Rao")
Analysis of Deviance Table
Model 1: admit ~ I(gre + gpa) + rank
Model 2: admit ~ gre + gpa + rank
Resid. Df Resid. Dev Df Deviance Rao Pr(>Chi)
1 395 464.48
2 394 458.52 1 5.9658 5.9144 0.01502 *
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
The conclusion is the same as before.
Note
An interesting relationship between the different test statistics when the model is linear is (Johnston and DiNardo (1997): Econometric Methods): Wald $\geq$ LR $\geq$ Score.
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
Wald test
One standard approach is the Wald test. This is what the Stata command test does after a logit or probit regression. Let's see how this works in R by looking at an example:
mydata <- read.cs
|
16,858
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
|
You did not specify your variables, if they are binary or something else. I think you talk about binary variables. There also exist multinomial versions of the probit and logit model.
In general, you can use the complete trinity of test approaches, i.e.
Likelihood-Ratio-test
LM-Test
Wald-Test
Each test uses different test-statistics. The standard approach would be to take one of the three tests. All three can be used to do joint tests.
The LR test uses the differnce of the log-likelihood of a restricted and the unrestricted model. So the restricted model is the model, in which the specified coefficients are set to zero. The unrestricted is the "normal" model. The Wald test has the advantage, that only the unrestriced model is estimated. It basically asks, if the restriction is nearly satisfied if it is evaluated at the unrestriced MLE. In case of the Lagrange-Multiplier test only the restricted model has to be estimated. The restricted ML estimator is used to calculate the score of the unrestricted model. This score will be usually not zero, so this discrepancy is the basis of the LR test. The LM-Test can in your context also be used to test for heteroscedasticity.
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
|
You did not specify your variables, if they are binary or something else. I think you talk about binary variables. There also exist multinomial versions of the probit and logit model.
In general, you
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
You did not specify your variables, if they are binary or something else. I think you talk about binary variables. There also exist multinomial versions of the probit and logit model.
In general, you can use the complete trinity of test approaches, i.e.
Likelihood-Ratio-test
LM-Test
Wald-Test
Each test uses different test-statistics. The standard approach would be to take one of the three tests. All three can be used to do joint tests.
The LR test uses the differnce of the log-likelihood of a restricted and the unrestricted model. So the restricted model is the model, in which the specified coefficients are set to zero. The unrestricted is the "normal" model. The Wald test has the advantage, that only the unrestriced model is estimated. It basically asks, if the restriction is nearly satisfied if it is evaluated at the unrestriced MLE. In case of the Lagrange-Multiplier test only the restricted model has to be estimated. The restricted ML estimator is used to calculate the score of the unrestricted model. This score will be usually not zero, so this discrepancy is the basis of the LR test. The LM-Test can in your context also be used to test for heteroscedasticity.
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
You did not specify your variables, if they are binary or something else. I think you talk about binary variables. There also exist multinomial versions of the probit and logit model.
In general, you
|
16,859
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
|
The standard approaches are the Wald test, the likelihood ratio test and the score test. Asymptotically they should be the same. In my experience the likelihood ratio tests tends to perform slightly better in simulations on finite samples, but the cases where this matters would be in very extreme (small sample) scenarios where I would take all of these tests as a rough approximation only. However, depending on your model (number of covariates, presence of interaction effects) and your data (multicolinearity, the marginal distribution of your dependent variable), the "wonderful kingdom of Asymptotia" can be well approximated by a surprisingly small number of observations.
Below is an example of such a simulation in Stata using the Wald, likelihood ratio and score test in a sample of only 150 observations. Even in such a small sample the three test produce fairly similar p-values and the sampling distribution of the p-values when the null hypothesis is true does seem to follow a uniform distribution as it should (or at least the deviations from the uniform distribution are no larger than one would expect due to the randomness inherrit in a Monte Carlo experiment).
clear all
set more off
// data preparation
sysuse nlsw88, clear
gen byte edcat = cond(grade < 12, 1, ///
cond(grade == 12, 2, 3)) ///
if grade < .
label define edcat 1 "less than high school" ///
2 "high school" ///
3 "more than high school"
label value edcat edcat
label variable edcat "education in categories"
// create cascading dummies, i.e.
// edcat2 compares high school with less than high school
// edcat3 compares more than high school with high school
gen byte edcat2 = (edcat >= 2) if edcat < .
gen byte edcat3 = (edcat >= 3) if edcat < .
keep union edcat2 edcat3 race south
bsample 150 if !missing(union, edcat2, edcat3, race, south)
// constraining edcat2 = edcat3 is equivalent to adding
// a linear effect (in the log odds) of edcat
constraint define 1 edcat2 = edcat3
// estimate the constrained model
logit union edcat2 edcat3 i.race i.south, constraint(1)
// predict the probabilities
predict pr
gen byte ysim = .
gen w = .
program define sim, rclass
// create a dependent variable such that the null hypothesis is true
replace ysim = runiform() < pr
// estimate the constrained model
logit ysim edcat2 edcat3 i.race i.south, constraint(1)
est store constr
// score test
tempname b0
matrix `b0' = e(b)
logit ysim edcat2 edcat3 i.race i.south, from(`b0') iter(0)
matrix chi = e(gradient)*e(V)*e(gradient)'
return scalar p_score = chi2tail(1,chi[1,1])
// estimate unconstrained model
logit ysim edcat2 edcat3 i.race i.south
est store full
// Wald test
test edcat2 = edcat3
return scalar p_Wald = r(p)
// likelihood ratio test
lrtest full constr
return scalar p_lr = r(p)
end
simulate p_score=r(p_score) p_Wald=r(p_Wald) p_lr=r(p_lr), reps(2000) : sim
simpplot p*, overall reps(20000) scheme(s2color) ylab(,angle(horizontal))
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
|
The standard approaches are the Wald test, the likelihood ratio test and the score test. Asymptotically they should be the same. In my experience the likelihood ratio tests tends to perform slightly b
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
The standard approaches are the Wald test, the likelihood ratio test and the score test. Asymptotically they should be the same. In my experience the likelihood ratio tests tends to perform slightly better in simulations on finite samples, but the cases where this matters would be in very extreme (small sample) scenarios where I would take all of these tests as a rough approximation only. However, depending on your model (number of covariates, presence of interaction effects) and your data (multicolinearity, the marginal distribution of your dependent variable), the "wonderful kingdom of Asymptotia" can be well approximated by a surprisingly small number of observations.
Below is an example of such a simulation in Stata using the Wald, likelihood ratio and score test in a sample of only 150 observations. Even in such a small sample the three test produce fairly similar p-values and the sampling distribution of the p-values when the null hypothesis is true does seem to follow a uniform distribution as it should (or at least the deviations from the uniform distribution are no larger than one would expect due to the randomness inherrit in a Monte Carlo experiment).
clear all
set more off
// data preparation
sysuse nlsw88, clear
gen byte edcat = cond(grade < 12, 1, ///
cond(grade == 12, 2, 3)) ///
if grade < .
label define edcat 1 "less than high school" ///
2 "high school" ///
3 "more than high school"
label value edcat edcat
label variable edcat "education in categories"
// create cascading dummies, i.e.
// edcat2 compares high school with less than high school
// edcat3 compares more than high school with high school
gen byte edcat2 = (edcat >= 2) if edcat < .
gen byte edcat3 = (edcat >= 3) if edcat < .
keep union edcat2 edcat3 race south
bsample 150 if !missing(union, edcat2, edcat3, race, south)
// constraining edcat2 = edcat3 is equivalent to adding
// a linear effect (in the log odds) of edcat
constraint define 1 edcat2 = edcat3
// estimate the constrained model
logit union edcat2 edcat3 i.race i.south, constraint(1)
// predict the probabilities
predict pr
gen byte ysim = .
gen w = .
program define sim, rclass
// create a dependent variable such that the null hypothesis is true
replace ysim = runiform() < pr
// estimate the constrained model
logit ysim edcat2 edcat3 i.race i.south, constraint(1)
est store constr
// score test
tempname b0
matrix `b0' = e(b)
logit ysim edcat2 edcat3 i.race i.south, from(`b0') iter(0)
matrix chi = e(gradient)*e(V)*e(gradient)'
return scalar p_score = chi2tail(1,chi[1,1])
// estimate unconstrained model
logit ysim edcat2 edcat3 i.race i.south
est store full
// Wald test
test edcat2 = edcat3
return scalar p_Wald = r(p)
// likelihood ratio test
lrtest full constr
return scalar p_lr = r(p)
end
simulate p_score=r(p_score) p_Wald=r(p_Wald) p_lr=r(p_lr), reps(2000) : sim
simpplot p*, overall reps(20000) scheme(s2color) ylab(,angle(horizontal))
|
How to test for simultaneous equality of choosen coefficients in logit or probit model?
The standard approaches are the Wald test, the likelihood ratio test and the score test. Asymptotically they should be the same. In my experience the likelihood ratio tests tends to perform slightly b
|
16,860
|
Generating random points uniformly on a disk [duplicate]
|
The problem is due to the fact that the radius is not uniformly distributed. Namely, if $(X,Y)$ is uniformly distributed over
$$\left\{ (x,y);\ x^2+y^2\le 1\right\}$$
then the (polar coordinates) change of variables
$$R=(X^2+Y^2)^{1/2}\qquad A=\text{sign}(Y)\arccos(X/R)$$
has the density
$$\frac{1}{\pi} \mathbb{I}_{(0,1)}(r)\left|\frac{\text{d}(X,Y)}{\text{d}(R,A)}(r,\alpha)\right|\mathbb{I}_{(0,2\pi)}(\alpha)$$
Using $x = r \cos \alpha$ and $y = r \sin \alpha$ leads to
$$\left|\frac{\text{d}(X,Y)}{\text{d}(R,A)}(r,\alpha)\right|=r(\sin^2\alpha+\cos^2\alpha)=r$$
Therefore, the angle $A$ is distributed uniformly over $(0,2\pi)$ but the radius $R$ has density $f(r)=2r\mathbb{I}_{(0,1)}(r)$ and cdf $F(r)=r^2$ over $(0,1)$. As one can check by running
r <- sqrt(runif(1000, min=0, max=1) )
alpha <- runif(1000, min=0, max=2*pi)
x <- r*cos(alpha)
y <- r*sin(alpha)
plot(x,y, pch=19, col=rgb(0,0,0,0.05), asp=1)
where the radius is simulated by the inverse cdf representation, which makes it the square root of a Uniform variate, the random repartition of the 10³ simulated points is compatible with a uniform:
|
Generating random points uniformly on a disk [duplicate]
|
The problem is due to the fact that the radius is not uniformly distributed. Namely, if $(X,Y)$ is uniformly distributed over
$$\left\{ (x,y);\ x^2+y^2\le 1\right\}$$
then the (polar coordinates) chan
|
Generating random points uniformly on a disk [duplicate]
The problem is due to the fact that the radius is not uniformly distributed. Namely, if $(X,Y)$ is uniformly distributed over
$$\left\{ (x,y);\ x^2+y^2\le 1\right\}$$
then the (polar coordinates) change of variables
$$R=(X^2+Y^2)^{1/2}\qquad A=\text{sign}(Y)\arccos(X/R)$$
has the density
$$\frac{1}{\pi} \mathbb{I}_{(0,1)}(r)\left|\frac{\text{d}(X,Y)}{\text{d}(R,A)}(r,\alpha)\right|\mathbb{I}_{(0,2\pi)}(\alpha)$$
Using $x = r \cos \alpha$ and $y = r \sin \alpha$ leads to
$$\left|\frac{\text{d}(X,Y)}{\text{d}(R,A)}(r,\alpha)\right|=r(\sin^2\alpha+\cos^2\alpha)=r$$
Therefore, the angle $A$ is distributed uniformly over $(0,2\pi)$ but the radius $R$ has density $f(r)=2r\mathbb{I}_{(0,1)}(r)$ and cdf $F(r)=r^2$ over $(0,1)$. As one can check by running
r <- sqrt(runif(1000, min=0, max=1) )
alpha <- runif(1000, min=0, max=2*pi)
x <- r*cos(alpha)
y <- r*sin(alpha)
plot(x,y, pch=19, col=rgb(0,0,0,0.05), asp=1)
where the radius is simulated by the inverse cdf representation, which makes it the square root of a Uniform variate, the random repartition of the 10³ simulated points is compatible with a uniform:
|
Generating random points uniformly on a disk [duplicate]
The problem is due to the fact that the radius is not uniformly distributed. Namely, if $(X,Y)$ is uniformly distributed over
$$\left\{ (x,y);\ x^2+y^2\le 1\right\}$$
then the (polar coordinates) chan
|
16,861
|
Generating random points uniformly on a disk [duplicate]
|
The simplest and least error-prone approach would be rejection sampling: generate uniformly distributed points in the square around your circle, and only keep those that are in the circle.
nn <- 1e4
radius <- 1
set.seed(1) # for reproducibility
foo <- cbind(runif(nn,-radius,radius),runif(nn,-radius,radius))
plot(foo[rowSums(foo^2)<radius^2,],pch=19,cex=0.6,xlab="x",ylab="y")
Of course, you will only keep a fraction of your generated data points, around $\frac{\pi}{4}$ (which is the ratio of the areas of the circumscribed square to the disk). So you can either start with $\frac{4n}{\pi}$ points, or generate points until you keep your target number $n$ of them.
|
Generating random points uniformly on a disk [duplicate]
|
The simplest and least error-prone approach would be rejection sampling: generate uniformly distributed points in the square around your circle, and only keep those that are in the circle.
nn <- 1e4
|
Generating random points uniformly on a disk [duplicate]
The simplest and least error-prone approach would be rejection sampling: generate uniformly distributed points in the square around your circle, and only keep those that are in the circle.
nn <- 1e4
radius <- 1
set.seed(1) # for reproducibility
foo <- cbind(runif(nn,-radius,radius),runif(nn,-radius,radius))
plot(foo[rowSums(foo^2)<radius^2,],pch=19,cex=0.6,xlab="x",ylab="y")
Of course, you will only keep a fraction of your generated data points, around $\frac{\pi}{4}$ (which is the ratio of the areas of the circumscribed square to the disk). So you can either start with $\frac{4n}{\pi}$ points, or generate points until you keep your target number $n$ of them.
|
Generating random points uniformly on a disk [duplicate]
The simplest and least error-prone approach would be rejection sampling: generate uniformly distributed points in the square around your circle, and only keep those that are in the circle.
nn <- 1e4
|
16,862
|
Generating random points uniformly on a disk [duplicate]
|
You can find the mathematics of this situation in a related question here. The method is set out in Xi'an's excellent answer, and it can be summarised by the following requirements:
$$\begin{matrix}
R^2 \sim \text{U}(0,1) \quad \ \ & & & X = R \cos (\theta), \\[6pt]
\theta \sim \text{U}(0, 2\pi) & & & Y = R \sin(\theta). \\[6pt]
\end{matrix}$$
Following on from that other answer, when you come up with these solutions, it is often useful to try to generalise them into functions that can generate random values for a particular class of problems. A natural generalisation in this case is to look at randomly generated points on a circle with an arbitrary centre and radius. Using the same basic method as in the existing answer, here is a general function to produce random points uniformly over a circle with arbitrary centre and radius.
runifcircle <- function(n, centre = c(0, 0), center = centre, radius = 1) {
#Check inputs
if (!missing(centre) && !missing(center)) {
if (sum((centre - center)^2) < 1e-15) {
warning("specify 'centre' or 'center' but not both") } else {
stop("Error: specify 'centre' or 'center' but not both") } }
if (radius < 0) { stop("Error: radius must be non-negative") }
#Create output matrix
OUT <- matrix(0, nrow = 2, ncol = n)
rownames(OUT) <- c('x', 'y')
#Generate uniform values on circle
r2 <- runif(n, min = 0, max = radius^2)
theta <- runif(n, min = 0, max = 2*pi)
OUT[1, ] <- center[1] + sqrt(r2)*cos(theta)
OUT[2, ] <- center[2] + sqrt(r2)*sin(theta)
OUT }
Creating this function allows you to easily generate any number of points over an arbitrary circle. (If you want an interesting exercise that extends this problem, try modifying the above function to create a new function runifball that generates uniform random values on a hypersphere with an arbitrary centre and radius.) We can easily verify that this function works correctly by plotting the results for a large number of sample values.
#Generate points uniformly on a circle
set.seed(1)
n <- 10^5
CENTRE <- c(5, 3)
RADIUS <- 3
UNIF <- runifcircle(n, centre = CENTRE, radius = RADIUS)
#Plot the points
plot(UNIF[1, ], UNIF[2, ],
col = rgb(0, 0, 0, 0.05), pch = 16, asp = 1,
main = 'Points distributed uniformly over a circle', xlab = 'x', ylab = 'y')
points(x = CENTRE[1], y = CENTRE[2], col = 'red', pch = 16)
|
Generating random points uniformly on a disk [duplicate]
|
You can find the mathematics of this situation in a related question here. The method is set out in Xi'an's excellent answer, and it can be summarised by the following requirements:
$$\begin{matrix}
|
Generating random points uniformly on a disk [duplicate]
You can find the mathematics of this situation in a related question here. The method is set out in Xi'an's excellent answer, and it can be summarised by the following requirements:
$$\begin{matrix}
R^2 \sim \text{U}(0,1) \quad \ \ & & & X = R \cos (\theta), \\[6pt]
\theta \sim \text{U}(0, 2\pi) & & & Y = R \sin(\theta). \\[6pt]
\end{matrix}$$
Following on from that other answer, when you come up with these solutions, it is often useful to try to generalise them into functions that can generate random values for a particular class of problems. A natural generalisation in this case is to look at randomly generated points on a circle with an arbitrary centre and radius. Using the same basic method as in the existing answer, here is a general function to produce random points uniformly over a circle with arbitrary centre and radius.
runifcircle <- function(n, centre = c(0, 0), center = centre, radius = 1) {
#Check inputs
if (!missing(centre) && !missing(center)) {
if (sum((centre - center)^2) < 1e-15) {
warning("specify 'centre' or 'center' but not both") } else {
stop("Error: specify 'centre' or 'center' but not both") } }
if (radius < 0) { stop("Error: radius must be non-negative") }
#Create output matrix
OUT <- matrix(0, nrow = 2, ncol = n)
rownames(OUT) <- c('x', 'y')
#Generate uniform values on circle
r2 <- runif(n, min = 0, max = radius^2)
theta <- runif(n, min = 0, max = 2*pi)
OUT[1, ] <- center[1] + sqrt(r2)*cos(theta)
OUT[2, ] <- center[2] + sqrt(r2)*sin(theta)
OUT }
Creating this function allows you to easily generate any number of points over an arbitrary circle. (If you want an interesting exercise that extends this problem, try modifying the above function to create a new function runifball that generates uniform random values on a hypersphere with an arbitrary centre and radius.) We can easily verify that this function works correctly by plotting the results for a large number of sample values.
#Generate points uniformly on a circle
set.seed(1)
n <- 10^5
CENTRE <- c(5, 3)
RADIUS <- 3
UNIF <- runifcircle(n, centre = CENTRE, radius = RADIUS)
#Plot the points
plot(UNIF[1, ], UNIF[2, ],
col = rgb(0, 0, 0, 0.05), pch = 16, asp = 1,
main = 'Points distributed uniformly over a circle', xlab = 'x', ylab = 'y')
points(x = CENTRE[1], y = CENTRE[2], col = 'red', pch = 16)
|
Generating random points uniformly on a disk [duplicate]
You can find the mathematics of this situation in a related question here. The method is set out in Xi'an's excellent answer, and it can be summarised by the following requirements:
$$\begin{matrix}
|
16,863
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
By keeping track of things you can get an exact formula.
Let $p=1/3$ be the probability of success and $k=8$ be the number of successes in a row you want to count. These are fixed for the problem. Variable values are $m$, the number of trials left in the block; and $j$, the number of successive successes already observed. Let the chance of eventually achieving $k$ successes in a row before $m$ trials are exhausted be written $f_{p,k}(j,m)$. We seek $f_{1/3,8}(0,25)$.
Suppose we have just seen our $j^\text{th}$ success in a row with $m\gt0$ trials to go. The next trial is either a success, with probability $p$--in which case $j$ is increased to $j+1$--; or else it is a failure, with probability $1-p$--in which case $j$ is reset to $0$. In either case, $m$ decreases by $1$. Whence
$$f_{p,k}(j,m) = p f_{p,k}(j+1,m-1) + (1-p)f_{p,k}(0,m-1).$$
As starting conditions we have the obvious results $f_{p,k}(k,m)=1$ for $m \ge 0$ (i.e., we have already seen $k$ in a row) and $f_{p,k}(j,m)=0$ for $k-j \gt m$ (i.e., there aren't enough trials left to get $k$ in a row). It is now fast and straightforward (using dynamic programming or, because this problem's parameters are so small, recursion) to compute
$$f_{p,8}(0,25) = 18p^8 - 17p^9 - 45p^{16} + 81p^{17}-36p^{18}.$$
When $p=1/3$ this yields $80897 / 43046721 \approx 0.0018793$.
Relatively fast R code to simulate this is
hits8 <- function() {
x <- rbinom(26, 1, 1/3) # 25 Binomial trials
x[1] <- 0 # ... and a 0 to get started with `diff`
if(sum(x) >= 8) { # Are there at least 8 successes?
max(diff(cumsum(x), lag=8)) >= 8 # Are there 8 successes in a row anywhere?
} else {
FALSE # Not enough successes for 8 in a row
}
}
set.seed(17)
mean(replicate(10^5, hits8()))
After 3 seconds of calculation, the output is $0.00213$. Although this looks high, it's only 1.7 standard errors off. I ran another $10^6$ iterations, yielding $0.001867$: only $0.3$ standard errors less than expected. (As a double-check, because an earlier version of this code had a subtle bug, I also ran 400,000 iterations in Mathematica, obtaining an estimate of $0.0018475$.)
This result is less than one-tenth the estimate of $1-(1-(1/3)^8)^{136} \approx 0.0205$ in the question. But perhaps I have not fully understood it: another interpretation of "you have 8 total blocks ... to get 8 trials correct in a row" is that the answer being sought equals $1 - (1 - f_{1/3,8}(0,25))^8) = 0.0149358...$.
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
By keeping track of things you can get an exact formula.
Let $p=1/3$ be the probability of success and $k=8$ be the number of successes in a row you want to count. These are fixed for the problem. V
|
Probability of a run of k successes in a sequence of n Bernoulli trials
By keeping track of things you can get an exact formula.
Let $p=1/3$ be the probability of success and $k=8$ be the number of successes in a row you want to count. These are fixed for the problem. Variable values are $m$, the number of trials left in the block; and $j$, the number of successive successes already observed. Let the chance of eventually achieving $k$ successes in a row before $m$ trials are exhausted be written $f_{p,k}(j,m)$. We seek $f_{1/3,8}(0,25)$.
Suppose we have just seen our $j^\text{th}$ success in a row with $m\gt0$ trials to go. The next trial is either a success, with probability $p$--in which case $j$ is increased to $j+1$--; or else it is a failure, with probability $1-p$--in which case $j$ is reset to $0$. In either case, $m$ decreases by $1$. Whence
$$f_{p,k}(j,m) = p f_{p,k}(j+1,m-1) + (1-p)f_{p,k}(0,m-1).$$
As starting conditions we have the obvious results $f_{p,k}(k,m)=1$ for $m \ge 0$ (i.e., we have already seen $k$ in a row) and $f_{p,k}(j,m)=0$ for $k-j \gt m$ (i.e., there aren't enough trials left to get $k$ in a row). It is now fast and straightforward (using dynamic programming or, because this problem's parameters are so small, recursion) to compute
$$f_{p,8}(0,25) = 18p^8 - 17p^9 - 45p^{16} + 81p^{17}-36p^{18}.$$
When $p=1/3$ this yields $80897 / 43046721 \approx 0.0018793$.
Relatively fast R code to simulate this is
hits8 <- function() {
x <- rbinom(26, 1, 1/3) # 25 Binomial trials
x[1] <- 0 # ... and a 0 to get started with `diff`
if(sum(x) >= 8) { # Are there at least 8 successes?
max(diff(cumsum(x), lag=8)) >= 8 # Are there 8 successes in a row anywhere?
} else {
FALSE # Not enough successes for 8 in a row
}
}
set.seed(17)
mean(replicate(10^5, hits8()))
After 3 seconds of calculation, the output is $0.00213$. Although this looks high, it's only 1.7 standard errors off. I ran another $10^6$ iterations, yielding $0.001867$: only $0.3$ standard errors less than expected. (As a double-check, because an earlier version of this code had a subtle bug, I also ran 400,000 iterations in Mathematica, obtaining an estimate of $0.0018475$.)
This result is less than one-tenth the estimate of $1-(1-(1/3)^8)^{136} \approx 0.0205$ in the question. But perhaps I have not fully understood it: another interpretation of "you have 8 total blocks ... to get 8 trials correct in a row" is that the answer being sought equals $1 - (1 - f_{1/3,8}(0,25))^8) = 0.0149358...$.
|
Probability of a run of k successes in a sequence of n Bernoulli trials
By keeping track of things you can get an exact formula.
Let $p=1/3$ be the probability of success and $k=8$ be the number of successes in a row you want to count. These are fixed for the problem. V
|
16,864
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
While @whuber's excellent dynamic programming solution is well worth a read, its runtime is $\mathcal O(k^2m)$ with respect to total number of trials $m$ and the desired trial length $k$ whereas the matrix exponentiation method is $\mathcal O(k^3\log(m))$. If $m$ is much larger than $k$, the following method is faster.
Both solutions consider the problem as a Markov chain with states representing the number of correct trials at the end of the string so far, and a state for achieving the desired correct trials in a row. The transition matrix is such that seeing a failure with probability $p$ sends you back to state 0, and otherwise with probability $1-p$ advances you to the next state (the final state is an absorbing state). By raising this matrix to the $n$th power, the value in the first row, and last column is the probability of seeing $k=8$ heads in a row. In Python:
import numpy as np
def heads_in_a_row(flips, p, want):
a = np.zeros((want + 1, want + 1))
for i in range(want):
a[i, 0] = 1 - p
a[i, i + 1] = p
a[want, want] = 1.0
return np.linalg.matrix_power(a, flips)[0, want]
print(heads_in_a_row(flips=25, p=1.0 / 3.0, want=8))
yields 0.00187928367413 as desired.
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
While @whuber's excellent dynamic programming solution is well worth a read, its runtime is $\mathcal O(k^2m)$ with respect to total number of trials $m$ and the desired trial length $k$ whereas the m
|
Probability of a run of k successes in a sequence of n Bernoulli trials
While @whuber's excellent dynamic programming solution is well worth a read, its runtime is $\mathcal O(k^2m)$ with respect to total number of trials $m$ and the desired trial length $k$ whereas the matrix exponentiation method is $\mathcal O(k^3\log(m))$. If $m$ is much larger than $k$, the following method is faster.
Both solutions consider the problem as a Markov chain with states representing the number of correct trials at the end of the string so far, and a state for achieving the desired correct trials in a row. The transition matrix is such that seeing a failure with probability $p$ sends you back to state 0, and otherwise with probability $1-p$ advances you to the next state (the final state is an absorbing state). By raising this matrix to the $n$th power, the value in the first row, and last column is the probability of seeing $k=8$ heads in a row. In Python:
import numpy as np
def heads_in_a_row(flips, p, want):
a = np.zeros((want + 1, want + 1))
for i in range(want):
a[i, 0] = 1 - p
a[i, i + 1] = p
a[want, want] = 1.0
return np.linalg.matrix_power(a, flips)[0, want]
print(heads_in_a_row(flips=25, p=1.0 / 3.0, want=8))
yields 0.00187928367413 as desired.
|
Probability of a run of k successes in a sequence of n Bernoulli trials
While @whuber's excellent dynamic programming solution is well worth a read, its runtime is $\mathcal O(k^2m)$ with respect to total number of trials $m$ and the desired trial length $k$ whereas the m
|
16,865
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
According to this answer, I will explain the Markov-Chain approach by @Neil G a bit more and provide a general solution to such problems in R. Let's denote the desired number of correct trials in a row by $k$, the number of trials as $n$ and a correct trial by $W$ (win) and an incorrect trial by $F$ (fail). In the process of keeping track of the trials, you want to know whether you already had a streak of 8 correct trials and the number of correct trials at the end of your current sequence. There are 9 states ($k+1$):
$A$: We have not had $8$ correct trials in a row yet, and the last trial was $F$.
$B$: We have not had $8$ correct trials in a row yet, and the last two trials were $FW$.
$C$: We have not had $8$ correct trials in a row yet, and the last three trials were $FWW$.
$\ldots$
$H$: We have not had $8$ correct trials in a row yet, and the last eight trials were $FWWWWWWW$.
$I$: We've had $8$ correct trials in a row!
The probability of moving to state $B$ from state $A$ is $p=1/3$ and with probability $1-p=2/3$ we stay in state $A$. From state $B$, the probability of moving to state $C$ is $1/3$ and with probability $2/3$ we move back to $A$. And so on. If we are in state $I$, we stay there.
From this, we can construct a $9\times9$ transition matrix $M$ (as each column of $M$ sums to $1$ and all entries are positive, $M$ is called a left stochastic matrix):
$$
M=
\begin{pmatrix}
2/3 & 2/3 & 2/3 & 2/3 & 2/3 & 2/3 & 2/3 & 2/3 & 0 \\
1/3 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1/3 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 1/3 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1/3 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 1/3 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 1/3 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 1/3 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1/3 & 1
\end{pmatrix}
$$
Each column and row corresponds to one state. After $n$ trials, the entries of $M^{n}$ give the probability of getting from state $j$ (column) to state $i$ (row) in $n$ trials. The rightmost column corresponds to the state $I$ and the only entry is $1$ in the right lower corner. This means that once we are in state $I$, the probability to stay in $I$ is $1$. We are interested in the probability of getting to state $I$ from state $A$ in $n=25$ steps which corresponds to the lower left entry of $M^{25}$ (i.e. $M^{25}_{91}$). All we have to do now is calculating $M^{25}$. We can do that in R with the matrix power function from the expm package:
library(expm)
k <- 8 # desired number of correct trials in a row
p <- 1/3 # probability of getting a correct trial
n <- 25 # Total number of trials
# Set up the transition matrix M
M <- matrix(0, k+1, k+1)
M[ 1, 1:k ] <- (1-p)
M[ k+1, k+1 ] <- 1
for( i in 2:(k+1) ) {
M[i, i-1] <- p
}
# Name the columns and rows according to the states (A-I)
colnames(M) <- rownames(M) <- LETTERS[ 1:(k+1) ]
round(M,2)
A B C D E F G H I
A 0.67 0.67 0.67 0.67 0.67 0.67 0.67 0.67 0
B 0.33 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0
C 0.00 0.33 0.00 0.00 0.00 0.00 0.00 0.00 0
D 0.00 0.00 0.33 0.00 0.00 0.00 0.00 0.00 0
E 0.00 0.00 0.00 0.33 0.00 0.00 0.00 0.00 0
F 0.00 0.00 0.00 0.00 0.33 0.00 0.00 0.00 0
G 0.00 0.00 0.00 0.00 0.00 0.33 0.00 0.00 0
H 0.00 0.00 0.00 0.00 0.00 0.00 0.33 0.00 0
I 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.33 1
# Calculate M^25
Mn <- M%^%n
Mn[ (k+1), 1 ]
[1] 0.001879284
The probability of getting from state $A$ to state $I$ in 25 steps is $0.001879284$, as established by the other answers.
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
According to this answer, I will explain the Markov-Chain approach by @Neil G a bit more and provide a general solution to such problems in R. Let's denote the desired number of correct trials in a ro
|
Probability of a run of k successes in a sequence of n Bernoulli trials
According to this answer, I will explain the Markov-Chain approach by @Neil G a bit more and provide a general solution to such problems in R. Let's denote the desired number of correct trials in a row by $k$, the number of trials as $n$ and a correct trial by $W$ (win) and an incorrect trial by $F$ (fail). In the process of keeping track of the trials, you want to know whether you already had a streak of 8 correct trials and the number of correct trials at the end of your current sequence. There are 9 states ($k+1$):
$A$: We have not had $8$ correct trials in a row yet, and the last trial was $F$.
$B$: We have not had $8$ correct trials in a row yet, and the last two trials were $FW$.
$C$: We have not had $8$ correct trials in a row yet, and the last three trials were $FWW$.
$\ldots$
$H$: We have not had $8$ correct trials in a row yet, and the last eight trials were $FWWWWWWW$.
$I$: We've had $8$ correct trials in a row!
The probability of moving to state $B$ from state $A$ is $p=1/3$ and with probability $1-p=2/3$ we stay in state $A$. From state $B$, the probability of moving to state $C$ is $1/3$ and with probability $2/3$ we move back to $A$. And so on. If we are in state $I$, we stay there.
From this, we can construct a $9\times9$ transition matrix $M$ (as each column of $M$ sums to $1$ and all entries are positive, $M$ is called a left stochastic matrix):
$$
M=
\begin{pmatrix}
2/3 & 2/3 & 2/3 & 2/3 & 2/3 & 2/3 & 2/3 & 2/3 & 0 \\
1/3 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1/3 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 1/3 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1/3 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 1/3 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 1/3 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 1/3 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1/3 & 1
\end{pmatrix}
$$
Each column and row corresponds to one state. After $n$ trials, the entries of $M^{n}$ give the probability of getting from state $j$ (column) to state $i$ (row) in $n$ trials. The rightmost column corresponds to the state $I$ and the only entry is $1$ in the right lower corner. This means that once we are in state $I$, the probability to stay in $I$ is $1$. We are interested in the probability of getting to state $I$ from state $A$ in $n=25$ steps which corresponds to the lower left entry of $M^{25}$ (i.e. $M^{25}_{91}$). All we have to do now is calculating $M^{25}$. We can do that in R with the matrix power function from the expm package:
library(expm)
k <- 8 # desired number of correct trials in a row
p <- 1/3 # probability of getting a correct trial
n <- 25 # Total number of trials
# Set up the transition matrix M
M <- matrix(0, k+1, k+1)
M[ 1, 1:k ] <- (1-p)
M[ k+1, k+1 ] <- 1
for( i in 2:(k+1) ) {
M[i, i-1] <- p
}
# Name the columns and rows according to the states (A-I)
colnames(M) <- rownames(M) <- LETTERS[ 1:(k+1) ]
round(M,2)
A B C D E F G H I
A 0.67 0.67 0.67 0.67 0.67 0.67 0.67 0.67 0
B 0.33 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0
C 0.00 0.33 0.00 0.00 0.00 0.00 0.00 0.00 0
D 0.00 0.00 0.33 0.00 0.00 0.00 0.00 0.00 0
E 0.00 0.00 0.00 0.33 0.00 0.00 0.00 0.00 0
F 0.00 0.00 0.00 0.00 0.33 0.00 0.00 0.00 0
G 0.00 0.00 0.00 0.00 0.00 0.33 0.00 0.00 0
H 0.00 0.00 0.00 0.00 0.00 0.00 0.33 0.00 0
I 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.33 1
# Calculate M^25
Mn <- M%^%n
Mn[ (k+1), 1 ]
[1] 0.001879284
The probability of getting from state $A$ to state $I$ in 25 steps is $0.001879284$, as established by the other answers.
|
Probability of a run of k successes in a sequence of n Bernoulli trials
According to this answer, I will explain the Markov-Chain approach by @Neil G a bit more and provide a general solution to such problems in R. Let's denote the desired number of correct trials in a ro
|
16,866
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
Here is some R code that I wrote to simulate this:
tmpfun <- function() {
x <- rbinom(25, 1, 1/3)
rx <- rle(x)
any( rx$lengths[ rx$values==1 ] >= 8 )
}
tmpfun2 <- function() {
any( replicate(8, tmpfun()) )
}
mean(replicate(100000, tmpfun2()))
I am getting values a little smaller than your formula, so one of us may have made a mistake somewhere.
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
Here is some R code that I wrote to simulate this:
tmpfun <- function() {
x <- rbinom(25, 1, 1/3)
rx <- rle(x)
any( rx$lengths[ rx$values==1 ] >= 8 )
}
tmpfun2 <- function() {
an
|
Probability of a run of k successes in a sequence of n Bernoulli trials
Here is some R code that I wrote to simulate this:
tmpfun <- function() {
x <- rbinom(25, 1, 1/3)
rx <- rle(x)
any( rx$lengths[ rx$values==1 ] >= 8 )
}
tmpfun2 <- function() {
any( replicate(8, tmpfun()) )
}
mean(replicate(100000, tmpfun2()))
I am getting values a little smaller than your formula, so one of us may have made a mistake somewhere.
|
Probability of a run of k successes in a sequence of n Bernoulli trials
Here is some R code that I wrote to simulate this:
tmpfun <- function() {
x <- rbinom(25, 1, 1/3)
rx <- rle(x)
any( rx$lengths[ rx$values==1 ] >= 8 )
}
tmpfun2 <- function() {
an
|
16,867
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
Here is a Mathematica simulation for the Markov chain approach, note that Mathematica indexes by $1$ not $0$:
M = Table[e[i, j] /. {
e[9, 1] :> 0,
e[9, 9] :> 1,
e[_, 1] :> (1 - p),
e[_, _] /; j == i + 1 :> p,
e[_, _] :> 0
}, {i, 1, 9}, {j, 1, 9}];
x = MatrixPower[M, 25][[1, 9]] // Expand
This would yield the analytical answer:
$$18 p^8 - 17 p^9 - 45 p^{16} + 81 p^{17} - 36 p^{18}$$
Evaluating at $p=\frac{1.0}{3.0}$
x /. p -> 1/3 // N
Will return $0.00187928$
This can also be evaluated directly using builtin Probability and DiscreteMarkovProcess Mathematica functions:
Probability[k[25] == 9, Distributed[k, DiscreteMarkovProcess[1, M /. p -> 1/3]]] // N
Which will get us the same answer: $0.00187928$
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
Here is a Mathematica simulation for the Markov chain approach, note that Mathematica indexes by $1$ not $0$:
M = Table[e[i, j] /. {
e[9, 1] :> 0,
e[9, 9] :> 1,
e[_, 1] :> (1 - p),
e[_
|
Probability of a run of k successes in a sequence of n Bernoulli trials
Here is a Mathematica simulation for the Markov chain approach, note that Mathematica indexes by $1$ not $0$:
M = Table[e[i, j] /. {
e[9, 1] :> 0,
e[9, 9] :> 1,
e[_, 1] :> (1 - p),
e[_, _] /; j == i + 1 :> p,
e[_, _] :> 0
}, {i, 1, 9}, {j, 1, 9}];
x = MatrixPower[M, 25][[1, 9]] // Expand
This would yield the analytical answer:
$$18 p^8 - 17 p^9 - 45 p^{16} + 81 p^{17} - 36 p^{18}$$
Evaluating at $p=\frac{1.0}{3.0}$
x /. p -> 1/3 // N
Will return $0.00187928$
This can also be evaluated directly using builtin Probability and DiscreteMarkovProcess Mathematica functions:
Probability[k[25] == 9, Distributed[k, DiscreteMarkovProcess[1, M /. p -> 1/3]]] // N
Which will get us the same answer: $0.00187928$
|
Probability of a run of k successes in a sequence of n Bernoulli trials
Here is a Mathematica simulation for the Markov chain approach, note that Mathematica indexes by $1$ not $0$:
M = Table[e[i, j] /. {
e[9, 1] :> 0,
e[9, 9] :> 1,
e[_, 1] :> (1 - p),
e[_
|
16,868
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
As stated in my comment, there is an analytical formula for this problem in https://math.stackexchange.com/a/59749/51275.
The accepted answer, translated into Python looks like this:
import numpy as np
from scipy.special import binom
def theoretical_distr2(N, p, run_length)->float:
# Mathematica code: Sum[(-1)^(j + 1) * (p + (n - j*m + 1)/j*(1 - p))*Binomial[n - j m, j - 1] p^(j*m)*(1 - p)^(j - 1), {j, 1, Floor[n/m]}]
# where n = N, m = run_length, p = p
ans = 0
for j in range(1, N // run_length + 1):
ans += (-1) ** (j + 1) * (p + (N - j * run_length + 1) / j * (1 - p)) * binom(N - j * run_length, j - 1) * p ** (j * run_length) * (1 - p) ** (j - 1)
return ans
I don't deserve a credit. I just found the other solution and translated it into a code. There's an obvious issue with the code: for large N binom explodes to infinity, yielding a NaN answer. The @Neil's code is more stable.
For large N we can use the approximate formula (source: https://www.maa.org/sites/default/files/pdf/upload%5flibrary/22/Polya/07468342.di020742.02p0021g.pdf)
def theoretical_distr3(N, p, run_length)->float:
# Mathematica code: -E^-p^(0.5 + m - Log[n - n p]/Log[1/p]) p^(0.5 + m - Log[n - n p]/Log[1/p]) Log[p]
# -Exp[-p^(0.5 + i - Log[n (1 - p)]/Log[1/p])] p^(0.5 + i - Log[n (1 - p)]/Log[1/p]) Log[p]
ans = 1
for i in range(1, run_length):
ans -= -np.exp(-p ** (0.5 + i - np.log(N * (1 - p)) / np.log(1 / p))) * p ** (0.5 + i - np.log(N * (1-p)) / np.log(1 / p)) * np.log(p)
return ans
|
Probability of a run of k successes in a sequence of n Bernoulli trials
|
As stated in my comment, there is an analytical formula for this problem in https://math.stackexchange.com/a/59749/51275.
The accepted answer, translated into Python looks like this:
import numpy as n
|
Probability of a run of k successes in a sequence of n Bernoulli trials
As stated in my comment, there is an analytical formula for this problem in https://math.stackexchange.com/a/59749/51275.
The accepted answer, translated into Python looks like this:
import numpy as np
from scipy.special import binom
def theoretical_distr2(N, p, run_length)->float:
# Mathematica code: Sum[(-1)^(j + 1) * (p + (n - j*m + 1)/j*(1 - p))*Binomial[n - j m, j - 1] p^(j*m)*(1 - p)^(j - 1), {j, 1, Floor[n/m]}]
# where n = N, m = run_length, p = p
ans = 0
for j in range(1, N // run_length + 1):
ans += (-1) ** (j + 1) * (p + (N - j * run_length + 1) / j * (1 - p)) * binom(N - j * run_length, j - 1) * p ** (j * run_length) * (1 - p) ** (j - 1)
return ans
I don't deserve a credit. I just found the other solution and translated it into a code. There's an obvious issue with the code: for large N binom explodes to infinity, yielding a NaN answer. The @Neil's code is more stable.
For large N we can use the approximate formula (source: https://www.maa.org/sites/default/files/pdf/upload%5flibrary/22/Polya/07468342.di020742.02p0021g.pdf)
def theoretical_distr3(N, p, run_length)->float:
# Mathematica code: -E^-p^(0.5 + m - Log[n - n p]/Log[1/p]) p^(0.5 + m - Log[n - n p]/Log[1/p]) Log[p]
# -Exp[-p^(0.5 + i - Log[n (1 - p)]/Log[1/p])] p^(0.5 + i - Log[n (1 - p)]/Log[1/p]) Log[p]
ans = 1
for i in range(1, run_length):
ans -= -np.exp(-p ** (0.5 + i - np.log(N * (1 - p)) / np.log(1 / p))) * p ** (0.5 + i - np.log(N * (1-p)) / np.log(1 / p)) * np.log(p)
return ans
|
Probability of a run of k successes in a sequence of n Bernoulli trials
As stated in my comment, there is an analytical formula for this problem in https://math.stackexchange.com/a/59749/51275.
The accepted answer, translated into Python looks like this:
import numpy as n
|
16,869
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics?
|
A more productive question might be "why was it not used in the classical statistics I learned?"
Depending on the level(s) at which it was taught, the course content (and time available) that choice may be due to a combination of various factors. Often important topics are left aside because other material must be taught for one reason or another, with the hope that they might be covered in later subjects.
In some senses at least, the notion has long been used by a variety of people. It was more common in some areas than others. Many uses of statistics don't have prediction or model selection as a major component (or in some cases, even at all), and in that case, the use of holdout samples may be less critical than when prediction is the main point. Arguably, it ought to have gained more widespread use at an earlier stage in some relevant applications than it did, but that's not the same thing as being unknown.
If you look at areas that focus on prediction, the notion of model assessment by predicting data you didn't use to estimate your model was certainly around (though not universal). I was certainly doing it with time series modelling I was doing in the 1980s, for example, where out-of-sample predictive performance of the most recent data was particularly important. It certainly wasn't a novel idea then, there was plenty of examples of that sort of notion around at the time.
The notion of leaving out at least some data was used in regression (deleted residuals, PRESS, the jacknife, and so on), and in outlier analysis, for example.
Some of these ideas data back a good deal earlier still. Stone (1974)[1] refers to papers on cross-validation (with the word in the title) from the 1950s and 60s. Perhaps even closer to your intent, he mentions Simon (1971)'s use of the terms "construction sample" and "validation sample" -- but also points out that "Larson (1931) employed random division of the sample in an educational multiple-regression study".
Topics like cross validation, and the use of statistics based on prediction and so on, were becoming substantially more frequent in the statistics literature in the 70s and through the 80s, for example, but many of the basic ideas been around for quite some time even then.
[1]: Stone, M., (1974)
"Cross-Validatory Choice and Assessment of Statistical Predictions,"
Journal of the Royal Statistical Society. Series B (Methodological), Vol. 36, No. 2., pp. 111-147
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics
|
A more productive question might be "why was it not used in the classical statistics I learned?"
Depending on the level(s) at which it was taught, the course content (and time available) that choice m
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics?
A more productive question might be "why was it not used in the classical statistics I learned?"
Depending on the level(s) at which it was taught, the course content (and time available) that choice may be due to a combination of various factors. Often important topics are left aside because other material must be taught for one reason or another, with the hope that they might be covered in later subjects.
In some senses at least, the notion has long been used by a variety of people. It was more common in some areas than others. Many uses of statistics don't have prediction or model selection as a major component (or in some cases, even at all), and in that case, the use of holdout samples may be less critical than when prediction is the main point. Arguably, it ought to have gained more widespread use at an earlier stage in some relevant applications than it did, but that's not the same thing as being unknown.
If you look at areas that focus on prediction, the notion of model assessment by predicting data you didn't use to estimate your model was certainly around (though not universal). I was certainly doing it with time series modelling I was doing in the 1980s, for example, where out-of-sample predictive performance of the most recent data was particularly important. It certainly wasn't a novel idea then, there was plenty of examples of that sort of notion around at the time.
The notion of leaving out at least some data was used in regression (deleted residuals, PRESS, the jacknife, and so on), and in outlier analysis, for example.
Some of these ideas data back a good deal earlier still. Stone (1974)[1] refers to papers on cross-validation (with the word in the title) from the 1950s and 60s. Perhaps even closer to your intent, he mentions Simon (1971)'s use of the terms "construction sample" and "validation sample" -- but also points out that "Larson (1931) employed random division of the sample in an educational multiple-regression study".
Topics like cross validation, and the use of statistics based on prediction and so on, were becoming substantially more frequent in the statistics literature in the 70s and through the 80s, for example, but many of the basic ideas been around for quite some time even then.
[1]: Stone, M., (1974)
"Cross-Validatory Choice and Assessment of Statistical Predictions,"
Journal of the Royal Statistical Society. Series B (Methodological), Vol. 36, No. 2., pp. 111-147
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics
A more productive question might be "why was it not used in the classical statistics I learned?"
Depending on the level(s) at which it was taught, the course content (and time available) that choice m
|
16,870
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics?
|
To complement on the answer by Glen_b, classical statistics often had/have emphasis on optimal use of the data, optimal tests, optimal estimators, sufficiency, and so on, and in that theoretical framework it is difficult to justify not using part of the information! Part of that tradition is emphasis on situations with small samples, where hold-out is practically difficult.
Fisher worked, for instance, mainly with genetics and agricultural experimentation, and in those fields small number of observations was the rule. So he was mainly exposed to such problems with small data sets.
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics
|
To complement on the answer by Glen_b, classical statistics often had/have emphasis on optimal use of the data, optimal tests, optimal estimators, sufficiency, and so on, and in that theoretical fram
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics?
To complement on the answer by Glen_b, classical statistics often had/have emphasis on optimal use of the data, optimal tests, optimal estimators, sufficiency, and so on, and in that theoretical framework it is difficult to justify not using part of the information! Part of that tradition is emphasis on situations with small samples, where hold-out is practically difficult.
Fisher worked, for instance, mainly with genetics and agricultural experimentation, and in those fields small number of observations was the rule. So he was mainly exposed to such problems with small data sets.
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics
To complement on the answer by Glen_b, classical statistics often had/have emphasis on optimal use of the data, optimal tests, optimal estimators, sufficiency, and so on, and in that theoretical fram
|
16,871
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics?
|
I'll answer from an applied field that is maybe in between classical statistics and machine learning: chemometrics, i.e. statistics for chemical analyses. I'll add two different scenarios where hold-out is not as important as it is in typical machine learning classes.
Scenario 1:
I think one crucial point here is to realize that there is a fundamental difference in what is small sample size for training vs. testing:
For training, typically the ratio of number of cases : model complexity (number of parameters) matters (degrees of freedom)
For testing, the absolute number of test cases matters.
(The quality of the testing procedure must be independent of the model: that is treated as a black box by validation with independent test cases)
The second point I'm going to need for my argumentation is that the situation where independent test cases are crucial is overfitting. If the model is not complex enough (bias $\gg$ variance, so underfitting), residuals can tell you as much about total prediction error as independent cases.
Now, statistics lectures on "classical" linear models often emphasise univariate models very much. For a univariate linear model, the training sample size is likely not small: training sample sizes are typically judged in comparison to model complexity, and the linear model has just two parameters, offset and slope. In analytical chemistry, we actually have a norm that states you should have at least 10 calibration samples for your univariate linear calibration. This ensures a situation where model instability is reliably not an issue, so hold-out is not needed.
However, in machine learning, as well as with modern multi-channel detectors in chemical analysis (sometimes 10⁴ "channels" e.g. in mass spectrometry), model stability (i.e. variance) is an important issue. Thus, hold-out or better resampling is needed.
Scenario 2:
A completely different situation is that hold-out may be skipped in favor of a combination of an easier (residuals) plus a more sophisticated performance measurement.
Note that hold-out in the sense of (randomly) setting aside part of a data set and excluding this from training is not equivalent to what independent testing can achieve. In analytical chemistry, dedicated validation experiments may be conducted that will include e.g. measuring the performance degradation over time (instrument drift) which cannot be measured by hold-out and establishing e.g. the performance of the sensor in the actual industrial environment (whereas the sensor calibration was done in the lab on calibration samples).
See also https://stats.stackexchange.com/a/104750/4598 for more details on independent testing vs. hold-out.
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics
|
I'll answer from an applied field that is maybe in between classical statistics and machine learning: chemometrics, i.e. statistics for chemical analyses. I'll add two different scenarios where hold-o
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics?
I'll answer from an applied field that is maybe in between classical statistics and machine learning: chemometrics, i.e. statistics for chemical analyses. I'll add two different scenarios where hold-out is not as important as it is in typical machine learning classes.
Scenario 1:
I think one crucial point here is to realize that there is a fundamental difference in what is small sample size for training vs. testing:
For training, typically the ratio of number of cases : model complexity (number of parameters) matters (degrees of freedom)
For testing, the absolute number of test cases matters.
(The quality of the testing procedure must be independent of the model: that is treated as a black box by validation with independent test cases)
The second point I'm going to need for my argumentation is that the situation where independent test cases are crucial is overfitting. If the model is not complex enough (bias $\gg$ variance, so underfitting), residuals can tell you as much about total prediction error as independent cases.
Now, statistics lectures on "classical" linear models often emphasise univariate models very much. For a univariate linear model, the training sample size is likely not small: training sample sizes are typically judged in comparison to model complexity, and the linear model has just two parameters, offset and slope. In analytical chemistry, we actually have a norm that states you should have at least 10 calibration samples for your univariate linear calibration. This ensures a situation where model instability is reliably not an issue, so hold-out is not needed.
However, in machine learning, as well as with modern multi-channel detectors in chemical analysis (sometimes 10⁴ "channels" e.g. in mass spectrometry), model stability (i.e. variance) is an important issue. Thus, hold-out or better resampling is needed.
Scenario 2:
A completely different situation is that hold-out may be skipped in favor of a combination of an easier (residuals) plus a more sophisticated performance measurement.
Note that hold-out in the sense of (randomly) setting aside part of a data set and excluding this from training is not equivalent to what independent testing can achieve. In analytical chemistry, dedicated validation experiments may be conducted that will include e.g. measuring the performance degradation over time (instrument drift) which cannot be measured by hold-out and establishing e.g. the performance of the sensor in the actual industrial environment (whereas the sensor calibration was done in the lab on calibration samples).
See also https://stats.stackexchange.com/a/104750/4598 for more details on independent testing vs. hold-out.
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics
I'll answer from an applied field that is maybe in between classical statistics and machine learning: chemometrics, i.e. statistics for chemical analyses. I'll add two different scenarios where hold-o
|
16,872
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics?
|
Besides the excellent discussion above, there are other reasons why holdout samples were not and still are not frequently used in statistics. Holding out data from discovery and model fitting is inefficient and wasteful of information, and in some cases we have analytic results that efficiently provide what you need, e.g., an estimate of likely future model performance. The simplest example is residual $\sigma^2$ in linear models where we've long had an estimate that is unbiased by overfitting. $R^{2}_{\mathrm{addj}}$ is another example. Then there is resampling which is an invention from the field of statistics. 100 repeats of 10-fold cross-validation is a very unbiased and 9/10 efficient procedure. The bootstrap is an almost unbiased and fully efficient procedure. Both of these estimate the likely future performance on observations from the same stream of observations used to build the model.
This discussion touches on independent sample validation vs. rigorous internal validation a la resampling. And it is a common mistake to label estimated performance on a holdout sample as "external validation" which it's usually not. This is discussed here.
Bayesian modeling thinks of this in yet another way where prior information starts the process and the parameter "estimates" (actually distributions) are trusted based on that information and there is no overfitting per se.
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics
|
Besides the excellent discussion above, there are other reasons why holdout samples were not and still are not frequently used in statistics. Holding out data from discovery and model fitting is inef
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics?
Besides the excellent discussion above, there are other reasons why holdout samples were not and still are not frequently used in statistics. Holding out data from discovery and model fitting is inefficient and wasteful of information, and in some cases we have analytic results that efficiently provide what you need, e.g., an estimate of likely future model performance. The simplest example is residual $\sigma^2$ in linear models where we've long had an estimate that is unbiased by overfitting. $R^{2}_{\mathrm{addj}}$ is another example. Then there is resampling which is an invention from the field of statistics. 100 repeats of 10-fold cross-validation is a very unbiased and 9/10 efficient procedure. The bootstrap is an almost unbiased and fully efficient procedure. Both of these estimate the likely future performance on observations from the same stream of observations used to build the model.
This discussion touches on independent sample validation vs. rigorous internal validation a la resampling. And it is a common mistake to label estimated performance on a holdout sample as "external validation" which it's usually not. This is discussed here.
Bayesian modeling thinks of this in yet another way where prior information starts the process and the parameter "estimates" (actually distributions) are trusted based on that information and there is no overfitting per se.
|
Why isn't the holdout method (splitting data into training and testing) used in classical statistics
Besides the excellent discussion above, there are other reasons why holdout samples were not and still are not frequently used in statistics. Holding out data from discovery and model fitting is inef
|
16,873
|
Is Cauchy distribution somehow an "unpredictable" distribution?
|
While a number of posts on site address various properties of the Cauchy, I didn't manage to locate one that really laid them out together. Hopefully this might be a good place to collect some. I may expand this.
Heavy tails
While the Cauchy is symmetric and roughly bell shaped, somewhat like the normal distribution, it has much heavier tails (and less of a "shoulder"). For example, there's a small but distinct probability that a Cauchy random variable will lay more than 1000 interquartile ranges from the median -- roughly of the same order as a normal random variable being at least 2.67 interquartile ranges from its median.
Variance
The variance of the Cauchy is infinite.
Edit: J.G. says in comments that it's undefined. If we take the variance as the average of half the squared distance between pairs of values - which is identical to the variance when both exist, then it would be infinite. However, by the usual definition J.G. is correct. [Nevertheless by contrast with sample means, which don't really converge to anything as n becomes large, the distribution of sample variances keep growing in size as the sample size increases; the scale increases proportionally to n, or equivalently the distribution of log variance grows linearly with sample size. It seems productive to actually consider that version of variance that yields infinity is telling us something.]
Sample standard deviations exist, of course, but the larger the sample the larger they tend to be (e.g. the median sample standard deviation at n=10 is in the vicinity of 3.67 times the scale parameter (half the IQR), but at n=100 it's about 11.9).
Mean
The Cauchy distribution doesn't even have a finite mean; the integral for the mean doesn't converge. As a result, even the laws of large numbers don't apply -- as n grows, sample means don't converge to some fixed quantity (indeed there's nothing for them to converge to).
In fact, the distribution of the sample mean from a Cauchy distribution is the same as the distribution of a single observation(!). The tail is so heavy that adding more values into the sum makes a really extreme value likely enough as to just compensate for dividing by a larger denominator when taking the mean.
Predictability
You can certainly produce perfectly sensible prediction intervals for observations from a Cauchy distribution; there are simple, fairly efficient estimators that perform well for estimating location and scale and approximate prediction intervals can be constructed -- so in that sense, at least, Cauchy variates are 'predictable'. However, the tail extends very far, so that if you want a high-probability interval, it may be quite wide.
If you're trying to predict the center of the distribution (e.g. in a regression type model), that may in some sense be relatively easy to predict; the Cauchy is quite peaked (there's a lot of the distribution "close" to the center for a typical measure of scale), so the center can be relatively well-estimated if you have an appropriate estimator.
Here's an example:
I generated data from a linear relationship with standard Cauchy errors (100 observations, intercept=3, slope=1.5), and estimated regression lines by three
methods that are reasonably robust to y-outliers: Tukey 3 group line (red), Theil regression (dark green) and L1-regression (blue). None are especially efficient at the Cauchy - though they would all make excellent starting points for a more efficient approach.
Nevertheless the three are almost coincident compared to the noisiness of the data and lay very close to the centre of where the data runs; in that sense the Cauchy is clearly "predictable".
The median of the absolute residuals is only a little larger than 1 for any of the lines (most of the data lay quite close to the estimated line); in that sense as well, the Cauchy is "predictable".
For the plot on the left there's a large outlier. In order to see the data better I narrowed the scale on the y-axis down on the right.
|
Is Cauchy distribution somehow an "unpredictable" distribution?
|
While a number of posts on site address various properties of the Cauchy, I didn't manage to locate one that really laid them out together. Hopefully this might be a good place to collect some. I may
|
Is Cauchy distribution somehow an "unpredictable" distribution?
While a number of posts on site address various properties of the Cauchy, I didn't manage to locate one that really laid them out together. Hopefully this might be a good place to collect some. I may expand this.
Heavy tails
While the Cauchy is symmetric and roughly bell shaped, somewhat like the normal distribution, it has much heavier tails (and less of a "shoulder"). For example, there's a small but distinct probability that a Cauchy random variable will lay more than 1000 interquartile ranges from the median -- roughly of the same order as a normal random variable being at least 2.67 interquartile ranges from its median.
Variance
The variance of the Cauchy is infinite.
Edit: J.G. says in comments that it's undefined. If we take the variance as the average of half the squared distance between pairs of values - which is identical to the variance when both exist, then it would be infinite. However, by the usual definition J.G. is correct. [Nevertheless by contrast with sample means, which don't really converge to anything as n becomes large, the distribution of sample variances keep growing in size as the sample size increases; the scale increases proportionally to n, or equivalently the distribution of log variance grows linearly with sample size. It seems productive to actually consider that version of variance that yields infinity is telling us something.]
Sample standard deviations exist, of course, but the larger the sample the larger they tend to be (e.g. the median sample standard deviation at n=10 is in the vicinity of 3.67 times the scale parameter (half the IQR), but at n=100 it's about 11.9).
Mean
The Cauchy distribution doesn't even have a finite mean; the integral for the mean doesn't converge. As a result, even the laws of large numbers don't apply -- as n grows, sample means don't converge to some fixed quantity (indeed there's nothing for them to converge to).
In fact, the distribution of the sample mean from a Cauchy distribution is the same as the distribution of a single observation(!). The tail is so heavy that adding more values into the sum makes a really extreme value likely enough as to just compensate for dividing by a larger denominator when taking the mean.
Predictability
You can certainly produce perfectly sensible prediction intervals for observations from a Cauchy distribution; there are simple, fairly efficient estimators that perform well for estimating location and scale and approximate prediction intervals can be constructed -- so in that sense, at least, Cauchy variates are 'predictable'. However, the tail extends very far, so that if you want a high-probability interval, it may be quite wide.
If you're trying to predict the center of the distribution (e.g. in a regression type model), that may in some sense be relatively easy to predict; the Cauchy is quite peaked (there's a lot of the distribution "close" to the center for a typical measure of scale), so the center can be relatively well-estimated if you have an appropriate estimator.
Here's an example:
I generated data from a linear relationship with standard Cauchy errors (100 observations, intercept=3, slope=1.5), and estimated regression lines by three
methods that are reasonably robust to y-outliers: Tukey 3 group line (red), Theil regression (dark green) and L1-regression (blue). None are especially efficient at the Cauchy - though they would all make excellent starting points for a more efficient approach.
Nevertheless the three are almost coincident compared to the noisiness of the data and lay very close to the centre of where the data runs; in that sense the Cauchy is clearly "predictable".
The median of the absolute residuals is only a little larger than 1 for any of the lines (most of the data lay quite close to the estimated line); in that sense as well, the Cauchy is "predictable".
For the plot on the left there's a large outlier. In order to see the data better I narrowed the scale on the y-axis down on the right.
|
Is Cauchy distribution somehow an "unpredictable" distribution?
While a number of posts on site address various properties of the Cauchy, I didn't manage to locate one that really laid them out together. Hopefully this might be a good place to collect some. I may
|
16,874
|
Is Cauchy distribution somehow an "unpredictable" distribution?
|
No, the Cauchy distribution is a very predictable distribution in the sense that the fractiles are well defined. If you know $\mu$ and $\sigma$, then the location probability that an observation will appear between any two points, from a sample size where $n\to\infty$ is well defined. However, while 50% of the data will appear in $\mu\pm\sigma$, the central 99.95% of the data will be $\mu\pm{636.62}\sigma$.
In addition, $\sigma$ is not a standard deviation; it is a scale parameter. There is no defined mean, so the higher moments do not exist either. It is often said that the mean and variance are infinite and under one definition of the integral that is almost true, but in another understanding of the integral, they simply do not exist. You may want to think of a variance or a mean as a property that some distributions have, but not others. Just as noses are a property of vertebrates, if you see a tree with a nose, then it is not a tree. If you see a distribution with a variance, then it is not the Cauchy distribution.
The Cauchy distribution appears quite a bit in nature, particularly where you have some form of growth. It also appears where things spin, such as rocks rolling down hills. You will find it as the core distribution of an ugly mixture of distributions in stock market returns, though not in returns for things like antiques sold in auctions. Returns on antiques also belong to a distribution without a mean or a variance, but not a Cauchy distribution. The differences are created by the differences in the rules of the auction. If you changed the rules of the NYSE, then the Cauchy distribution would disappear, and a different one would appear.
To understand why it is usually present, imagine you were a bidder in a very large set of bidders and potential bidders. Because stocks are sold in a double auction, the winner's curse does not apply. In equilibrium, the rational behavior is to bid your expected value. An expectation is a form of the mean. A distribution of mean estimates will converge to normality as the sample size goes to infinity.
So prices, if the firm isn't going to go bankrupt or become bought out in a merger, will be normally distributed if there is no cost for liquidity (which there is). If the quantity of shares do not change, then the return for investing at time t is $$r_t=\frac{p_{t+1}}{p_t}$$. That makes it the ratio of two normal distributions. If the integration happens around the equilibrium prices, rather than at (0,0), you will end up with a truncated Cauchy distribution. If you disaggregate returns into individual transactions over the 20th century, you will find that a truncated Cauchy closely matches the actually observed returns once you remove mergers, liquidity costs, and bankruptcies.
This makes the stock market very volatile, if one thinks that the stock market should have a normal or log-normal distribution, but not unexpectedly volatile if you are expecting the heavy tails.
I have constructed both the Bayesian and the Frequentist predictive distributions for the Cauchy distribution and given their assumptions they work well. The Bayesian prediction minimizes the Kullback-Leibler divergence, meaning it is as close as you can get to nature in a prediction, for a given data set. The Frequentist prediction minimizes the average Kullback-Leibler divergence over many independent predictions from many independent samples. It doesn't necessarily perform well, though, for any one sample as one would expect with average coverage. The tails do converge, but they converge slowly.
The multivariate Cauchy has even more upsetting properties. For example, while it obviously cannot covary since there is no mean, it has nothing similar to a covariance matrix. Cauchy errors are always spherical if nothing else is going on in the system. In addition, while nothing covaries, nothing is independent either. To understand how important that could be in a practical sense, imagine two countries that are both growing and that they trade with each other. The errors in one are not independent of the errors in the other. My mistakes influence your mistakes. If one country is taken over by a madman, the mistakes of that madman are felt everywhere. On the other hand, since the effects are not linear as one would expect with a covariance matrix, the other countries can sever relationships to minimize the impact. North Korea is an example of this.
This is also what makes Trump's trade war so dangerous. The world's second-largest economy after the European Union declared economic war through trade against every other single economy and is financing that war by borrowing the money to fight it from the nations it declared war on. If those dependencies are forced to unwind, it will be ugly in a way that nobody has a living memory of. We hadn't had a similar problem since the Jackson Administration when the Bank of England embargoed the Atlantic trade.
The Cauchy distribution is fascinating because it appears in exponential and S-curve growing systems. They confuse people because their day to day life is filled with densities that do have a mean and usually have a variance. It makes decision making very difficult because the wrong lessons are learned.
|
Is Cauchy distribution somehow an "unpredictable" distribution?
|
No, the Cauchy distribution is a very predictable distribution in the sense that the fractiles are well defined. If you know $\mu$ and $\sigma$, then the location probability that an observation will
|
Is Cauchy distribution somehow an "unpredictable" distribution?
No, the Cauchy distribution is a very predictable distribution in the sense that the fractiles are well defined. If you know $\mu$ and $\sigma$, then the location probability that an observation will appear between any two points, from a sample size where $n\to\infty$ is well defined. However, while 50% of the data will appear in $\mu\pm\sigma$, the central 99.95% of the data will be $\mu\pm{636.62}\sigma$.
In addition, $\sigma$ is not a standard deviation; it is a scale parameter. There is no defined mean, so the higher moments do not exist either. It is often said that the mean and variance are infinite and under one definition of the integral that is almost true, but in another understanding of the integral, they simply do not exist. You may want to think of a variance or a mean as a property that some distributions have, but not others. Just as noses are a property of vertebrates, if you see a tree with a nose, then it is not a tree. If you see a distribution with a variance, then it is not the Cauchy distribution.
The Cauchy distribution appears quite a bit in nature, particularly where you have some form of growth. It also appears where things spin, such as rocks rolling down hills. You will find it as the core distribution of an ugly mixture of distributions in stock market returns, though not in returns for things like antiques sold in auctions. Returns on antiques also belong to a distribution without a mean or a variance, but not a Cauchy distribution. The differences are created by the differences in the rules of the auction. If you changed the rules of the NYSE, then the Cauchy distribution would disappear, and a different one would appear.
To understand why it is usually present, imagine you were a bidder in a very large set of bidders and potential bidders. Because stocks are sold in a double auction, the winner's curse does not apply. In equilibrium, the rational behavior is to bid your expected value. An expectation is a form of the mean. A distribution of mean estimates will converge to normality as the sample size goes to infinity.
So prices, if the firm isn't going to go bankrupt or become bought out in a merger, will be normally distributed if there is no cost for liquidity (which there is). If the quantity of shares do not change, then the return for investing at time t is $$r_t=\frac{p_{t+1}}{p_t}$$. That makes it the ratio of two normal distributions. If the integration happens around the equilibrium prices, rather than at (0,0), you will end up with a truncated Cauchy distribution. If you disaggregate returns into individual transactions over the 20th century, you will find that a truncated Cauchy closely matches the actually observed returns once you remove mergers, liquidity costs, and bankruptcies.
This makes the stock market very volatile, if one thinks that the stock market should have a normal or log-normal distribution, but not unexpectedly volatile if you are expecting the heavy tails.
I have constructed both the Bayesian and the Frequentist predictive distributions for the Cauchy distribution and given their assumptions they work well. The Bayesian prediction minimizes the Kullback-Leibler divergence, meaning it is as close as you can get to nature in a prediction, for a given data set. The Frequentist prediction minimizes the average Kullback-Leibler divergence over many independent predictions from many independent samples. It doesn't necessarily perform well, though, for any one sample as one would expect with average coverage. The tails do converge, but they converge slowly.
The multivariate Cauchy has even more upsetting properties. For example, while it obviously cannot covary since there is no mean, it has nothing similar to a covariance matrix. Cauchy errors are always spherical if nothing else is going on in the system. In addition, while nothing covaries, nothing is independent either. To understand how important that could be in a practical sense, imagine two countries that are both growing and that they trade with each other. The errors in one are not independent of the errors in the other. My mistakes influence your mistakes. If one country is taken over by a madman, the mistakes of that madman are felt everywhere. On the other hand, since the effects are not linear as one would expect with a covariance matrix, the other countries can sever relationships to minimize the impact. North Korea is an example of this.
This is also what makes Trump's trade war so dangerous. The world's second-largest economy after the European Union declared economic war through trade against every other single economy and is financing that war by borrowing the money to fight it from the nations it declared war on. If those dependencies are forced to unwind, it will be ugly in a way that nobody has a living memory of. We hadn't had a similar problem since the Jackson Administration when the Bank of England embargoed the Atlantic trade.
The Cauchy distribution is fascinating because it appears in exponential and S-curve growing systems. They confuse people because their day to day life is filled with densities that do have a mean and usually have a variance. It makes decision making very difficult because the wrong lessons are learned.
|
Is Cauchy distribution somehow an "unpredictable" distribution?
No, the Cauchy distribution is a very predictable distribution in the sense that the fractiles are well defined. If you know $\mu$ and $\sigma$, then the location probability that an observation will
|
16,875
|
Testing random variate generation algorithms
|
The Diehard Test Suite is something close to a Golden Standard for testing random number generators. It includes a number of tests where a good random number generator should produce result distributed according to some know distribution against which the outcome using the tested generator can then be compared.
EDIT
I have to update this since I was not exactly right:
Diehard might still be used a lot, but it is no longer maintained and not state-of-the-art anymore. NIST has come up with a set of improved tests since.
|
Testing random variate generation algorithms
|
The Diehard Test Suite is something close to a Golden Standard for testing random number generators. It includes a number of tests where a good random number generator should produce result distribute
|
Testing random variate generation algorithms
The Diehard Test Suite is something close to a Golden Standard for testing random number generators. It includes a number of tests where a good random number generator should produce result distributed according to some know distribution against which the outcome using the tested generator can then be compared.
EDIT
I have to update this since I was not exactly right:
Diehard might still be used a lot, but it is no longer maintained and not state-of-the-art anymore. NIST has come up with a set of improved tests since.
|
Testing random variate generation algorithms
The Diehard Test Suite is something close to a Golden Standard for testing random number generators. It includes a number of tests where a good random number generator should produce result distribute
|
16,876
|
Testing random variate generation algorithms
|
Just to add a bit to honk's answer, the Diehard Test Suite (developed by George Marsaglia) are the standard tests for PRNG.
There's a nice Diehard C library that gives you access to these tests. As well as the standard Diehard tests it also provides functions for a few other PRNG tests involving (amongst other things) checking bit order. There is also a facilty for testing the speed of the RNG and writing your own tests.
There is a R interface to the Dieharder library, called RDieHarder:
library(RDieHarder)
dhtest = dieharder(rng="randu", test=10, psamples=100, seed=12345)
print(dhtest)
Diehard Count the 1s Test (byte)
data: Created by RNG `randu' with seed=12345,
sample of size 100 p-value < 2.2e-16
This shows that the RANDU RNG generator fails the minimum-distance / 2dsphere test.
|
Testing random variate generation algorithms
|
Just to add a bit to honk's answer, the Diehard Test Suite (developed by George Marsaglia) are the standard tests for PRNG.
There's a nice Diehard C library that gives you access to these tests. As we
|
Testing random variate generation algorithms
Just to add a bit to honk's answer, the Diehard Test Suite (developed by George Marsaglia) are the standard tests for PRNG.
There's a nice Diehard C library that gives you access to these tests. As well as the standard Diehard tests it also provides functions for a few other PRNG tests involving (amongst other things) checking bit order. There is also a facilty for testing the speed of the RNG and writing your own tests.
There is a R interface to the Dieharder library, called RDieHarder:
library(RDieHarder)
dhtest = dieharder(rng="randu", test=10, psamples=100, seed=12345)
print(dhtest)
Diehard Count the 1s Test (byte)
data: Created by RNG `randu' with seed=12345,
sample of size 100 p-value < 2.2e-16
This shows that the RANDU RNG generator fails the minimum-distance / 2dsphere test.
|
Testing random variate generation algorithms
Just to add a bit to honk's answer, the Diehard Test Suite (developed by George Marsaglia) are the standard tests for PRNG.
There's a nice Diehard C library that gives you access to these tests. As we
|
16,877
|
Testing random variate generation algorithms
|
For testing the numbers produced by random number generators the Diehard tests are a practical approach. But those tests seem kind of arbitrary and one is may be left wondering if more should be included or if there is any way to really check the randomness.
The best candidate for a definition of a random sequence seems to be the Martin-Löf randomness. The main idea for this kind of randomness, is beautifully developed in Knuth, section 3.5, is to test for uniformity for all types of sub-sequences of the sequence of random numbers. Getting that all type of subsequences definition right turned out to be be really hard even when one uses notions of computability.
The Diehard tests are just some of the possible subsequences one may consider and their failure would exclude Martin-Löf randomness.
|
Testing random variate generation algorithms
|
For testing the numbers produced by random number generators the Diehard tests are a practical approach. But those tests seem kind of arbitrary and one is may be left wondering if more should be inclu
|
Testing random variate generation algorithms
For testing the numbers produced by random number generators the Diehard tests are a practical approach. But those tests seem kind of arbitrary and one is may be left wondering if more should be included or if there is any way to really check the randomness.
The best candidate for a definition of a random sequence seems to be the Martin-Löf randomness. The main idea for this kind of randomness, is beautifully developed in Knuth, section 3.5, is to test for uniformity for all types of sub-sequences of the sequence of random numbers. Getting that all type of subsequences definition right turned out to be be really hard even when one uses notions of computability.
The Diehard tests are just some of the possible subsequences one may consider and their failure would exclude Martin-Löf randomness.
|
Testing random variate generation algorithms
For testing the numbers produced by random number generators the Diehard tests are a practical approach. But those tests seem kind of arbitrary and one is may be left wondering if more should be inclu
|
16,878
|
Testing random variate generation algorithms
|
You cannot prove, because it is impossible; you can only check if there are no any embarrassing autocorrelations or distribution disturbances, and indeed Diehard is a standard for it. This is for statistics/physics, cryptographers will also mainly check (among other things) how hard is it to fit the generator to the data to obtain the future values.
|
Testing random variate generation algorithms
|
You cannot prove, because it is impossible; you can only check if there are no any embarrassing autocorrelations or distribution disturbances, and indeed Diehard is a standard for it. This is for stat
|
Testing random variate generation algorithms
You cannot prove, because it is impossible; you can only check if there are no any embarrassing autocorrelations or distribution disturbances, and indeed Diehard is a standard for it. This is for statistics/physics, cryptographers will also mainly check (among other things) how hard is it to fit the generator to the data to obtain the future values.
|
Testing random variate generation algorithms
You cannot prove, because it is impossible; you can only check if there are no any embarrassing autocorrelations or distribution disturbances, and indeed Diehard is a standard for it. This is for stat
|
16,879
|
Testing random variate generation algorithms
|
Small correction to Colin's post: the CRAN package
RDieHarder is an interface to
DieHarder, the Diehard rewrite / extension / overhaul done by Robert G. Brown (who kindly lists me as a coauthor based on my RDieHarder wrappers) with recent contribution by David Bauer.
Among other things, DieHarder includes the NIST battery of tests mentioned in Mark's post as well as some new ones. This is ongoing research and has been for a while. I gave a talk at useR! 2007 about RDieHarder which you can get from here.
|
Testing random variate generation algorithms
|
Small correction to Colin's post: the CRAN package
RDieHarder is an interface to
DieHarder, the Diehard rewrite / extension / overhaul done by Robert G. Brown (who kindly lists me as a coauthor base
|
Testing random variate generation algorithms
Small correction to Colin's post: the CRAN package
RDieHarder is an interface to
DieHarder, the Diehard rewrite / extension / overhaul done by Robert G. Brown (who kindly lists me as a coauthor based on my RDieHarder wrappers) with recent contribution by David Bauer.
Among other things, DieHarder includes the NIST battery of tests mentioned in Mark's post as well as some new ones. This is ongoing research and has been for a while. I gave a talk at useR! 2007 about RDieHarder which you can get from here.
|
Testing random variate generation algorithms
Small correction to Colin's post: the CRAN package
RDieHarder is an interface to
DieHarder, the Diehard rewrite / extension / overhaul done by Robert G. Brown (who kindly lists me as a coauthor base
|
16,880
|
Testing random variate generation algorithms
|
It's seldom useful to conclude that something is "random" in the abstract. More often you want to test whether it has a certain kind of random structure. For example, you might want to test whether something has a uniform distribution, with all values in a certain range equally likely. Or you might want to test whether something has a normal distribution, etc. To test whether data has a particular distribution, you can use a goodness of fit test such as the chi square test or the Kolmogorov-Smirnov test.
|
Testing random variate generation algorithms
|
It's seldom useful to conclude that something is "random" in the abstract. More often you want to test whether it has a certain kind of random structure. For example, you might want to test whether
|
Testing random variate generation algorithms
It's seldom useful to conclude that something is "random" in the abstract. More often you want to test whether it has a certain kind of random structure. For example, you might want to test whether something has a uniform distribution, with all values in a certain range equally likely. Or you might want to test whether something has a normal distribution, etc. To test whether data has a particular distribution, you can use a goodness of fit test such as the chi square test or the Kolmogorov-Smirnov test.
|
Testing random variate generation algorithms
It's seldom useful to conclude that something is "random" in the abstract. More often you want to test whether it has a certain kind of random structure. For example, you might want to test whether
|
16,881
|
Testing random variate generation algorithms
|
There are two parts to testing a random number generator. If you're only concerned with testing a uniform generator, then yes, something like the DIEHARD test suite is a good idea.
But often you need to test a transformation of a uniform generator. For example, you might use a uniform generator to create exponentially or normally distributed values. You may have a high-quality uniform generator -- say you have a trusted implementation of a well-known algorithm such as Mersenne Twister -- but you need to test whether the transformed output has the right distribution. In that case you need to do some sort of goodness of fit test such as Kolmogorov-Smirnov. But for starters, you could verify that the sample mean and variance have the values you expect.
Most people don't -- and shouldn't -- write their own uniform random number generator from scratch. It's hard to write a good generator and easy to fool yourself into thinking you've written a good one when you haven't. For example, Donald Knuth tells the story in TAOCP volume 2 of a random number generator he wrote that turned out to be awful. But it's common for people to have to write their own code to produce random values from a new distribution.
|
Testing random variate generation algorithms
|
There are two parts to testing a random number generator. If you're only concerned with testing a uniform generator, then yes, something like the DIEHARD test suite is a good idea.
But often you need
|
Testing random variate generation algorithms
There are two parts to testing a random number generator. If you're only concerned with testing a uniform generator, then yes, something like the DIEHARD test suite is a good idea.
But often you need to test a transformation of a uniform generator. For example, you might use a uniform generator to create exponentially or normally distributed values. You may have a high-quality uniform generator -- say you have a trusted implementation of a well-known algorithm such as Mersenne Twister -- but you need to test whether the transformed output has the right distribution. In that case you need to do some sort of goodness of fit test such as Kolmogorov-Smirnov. But for starters, you could verify that the sample mean and variance have the values you expect.
Most people don't -- and shouldn't -- write their own uniform random number generator from scratch. It's hard to write a good generator and easy to fool yourself into thinking you've written a good one when you haven't. For example, Donald Knuth tells the story in TAOCP volume 2 of a random number generator he wrote that turned out to be awful. But it's common for people to have to write their own code to produce random values from a new distribution.
|
Testing random variate generation algorithms
There are two parts to testing a random number generator. If you're only concerned with testing a uniform generator, then yes, something like the DIEHARD test suite is a good idea.
But often you need
|
16,882
|
Testing random variate generation algorithms
|
The NIST publishes a list of statistical tests with a reference implementation in C.
There is also TestU01 by some smart folks, including respected PRNG researcher Pierre L'Ecuyer. Again, there is a reference implementation in C.
As pointed out by other commenters, these are for testing the generation of pseudo random bits. If you transform these bits into a different random variable (e.g. Box-Muller transform from uniform to Normal), you'll need additional tests to confirm the correctness of the transform algorithm.
|
Testing random variate generation algorithms
|
The NIST publishes a list of statistical tests with a reference implementation in C.
There is also TestU01 by some smart folks, including respected PRNG researcher Pierre L'Ecuyer. Again, there is a r
|
Testing random variate generation algorithms
The NIST publishes a list of statistical tests with a reference implementation in C.
There is also TestU01 by some smart folks, including respected PRNG researcher Pierre L'Ecuyer. Again, there is a reference implementation in C.
As pointed out by other commenters, these are for testing the generation of pseudo random bits. If you transform these bits into a different random variable (e.g. Box-Muller transform from uniform to Normal), you'll need additional tests to confirm the correctness of the transform algorithm.
|
Testing random variate generation algorithms
The NIST publishes a list of statistical tests with a reference implementation in C.
There is also TestU01 by some smart folks, including respected PRNG researcher Pierre L'Ecuyer. Again, there is a r
|
16,883
|
Why is gradient descent required?
|
Even in the case of, say, linear models, where you have an analytical solution, it may still be best to use such an iterative solver.
As an example, if we consider linear regression, the explicit solution requires inverting a matrix which has complexity $O(N^3)$. This becomes prohibitive in the context of big data.
Also, a lot of problems in machine learning are convex, so using gradients ensure that we will get to the extrema.
As already pointed out, there are still relevant non-convex problems, like neural networks, where gradient methods (backpropagation) provide an efficient solver. Again this is specially relevant for the case of deep learning.
|
Why is gradient descent required?
|
Even in the case of, say, linear models, where you have an analytical solution, it may still be best to use such an iterative solver.
As an example, if we consider linear regression, the explicit sol
|
Why is gradient descent required?
Even in the case of, say, linear models, where you have an analytical solution, it may still be best to use such an iterative solver.
As an example, if we consider linear regression, the explicit solution requires inverting a matrix which has complexity $O(N^3)$. This becomes prohibitive in the context of big data.
Also, a lot of problems in machine learning are convex, so using gradients ensure that we will get to the extrema.
As already pointed out, there are still relevant non-convex problems, like neural networks, where gradient methods (backpropagation) provide an efficient solver. Again this is specially relevant for the case of deep learning.
|
Why is gradient descent required?
Even in the case of, say, linear models, where you have an analytical solution, it may still be best to use such an iterative solver.
As an example, if we consider linear regression, the explicit sol
|
16,884
|
Why is gradient descent required?
|
Gradient descent is not required. It turns out gradient descent is often a horribly inefficient optimization algorithm! For iterative methods, it is often possible to find a better direction to move in than where the gradient is steepest.
That's a bit of a flip answer though. Your question really should be, "why do we need iterative methods?" Eg. why not go straight to the solution if the problem is convex, Slater's condition holds, and the first order conditions are necessary and sufficient conditions for an optimum? That is, when the solution can be described as the solution to a system of equations, why not simply solve the system? The answer is that:
For a quadratic optimization problem, the first order condition is a system of linear equations, and we can go almost directly to the solution because linear systems can be efficiently solved! We do use the first order conditions and solve the system (eg. with QR decomposition, caveat below).
More generally though, the first order conditions define a non-linear system of equations and a non-linear system may be quite difficult to solve! In fact, the way you often solve a system of non-linear equations numerically is you reformulate it as an optimization problem...
For extremely large linear systems, solving the system directly with QR decomposition and partial pivoting becomes infeasible. What do people do?! Iterative methods! (eg. iterative Krylov subspace methods...)
|
Why is gradient descent required?
|
Gradient descent is not required. It turns out gradient descent is often a horribly inefficient optimization algorithm! For iterative methods, it is often possible to find a better direction to move i
|
Why is gradient descent required?
Gradient descent is not required. It turns out gradient descent is often a horribly inefficient optimization algorithm! For iterative methods, it is often possible to find a better direction to move in than where the gradient is steepest.
That's a bit of a flip answer though. Your question really should be, "why do we need iterative methods?" Eg. why not go straight to the solution if the problem is convex, Slater's condition holds, and the first order conditions are necessary and sufficient conditions for an optimum? That is, when the solution can be described as the solution to a system of equations, why not simply solve the system? The answer is that:
For a quadratic optimization problem, the first order condition is a system of linear equations, and we can go almost directly to the solution because linear systems can be efficiently solved! We do use the first order conditions and solve the system (eg. with QR decomposition, caveat below).
More generally though, the first order conditions define a non-linear system of equations and a non-linear system may be quite difficult to solve! In fact, the way you often solve a system of non-linear equations numerically is you reformulate it as an optimization problem...
For extremely large linear systems, solving the system directly with QR decomposition and partial pivoting becomes infeasible. What do people do?! Iterative methods! (eg. iterative Krylov subspace methods...)
|
Why is gradient descent required?
Gradient descent is not required. It turns out gradient descent is often a horribly inefficient optimization algorithm! For iterative methods, it is often possible to find a better direction to move i
|
16,885
|
Why is gradient descent required?
|
In calculus 101 we learned about how to optimize a function using "analytical method": we just need to get the derivative of cost function and set the derivative to 0 then solve the equation. This is really a toy problem and will almost never happen in real world.
In real world, many cost functions are not have derivative everywhere (Further, the cost function may be discrete and do not have any derivative at all). In addition, even you can calculate the derivative, you cannot just solve the equation analytically (for example, think about how to solve $x^7+x^3-5^2+e^x+log(x+x^2)+1/x=0$ analytically? I can tell you the numerical answer is $x=1.4786$, but do not know analytical solution). We must use some numerical methods (check why here on polynomial cases Abel Ruffin Theorem).
Iterative methods are great to use, and very intuitive to understand. Suppose you want to optimize one function, instead of solving an equation and get the answer, you try to improve your answer by number of iterations /steps after enough iteration, you will get the answer close to "true answer". Say if you use calculus to minimize $f(x)=x^2$, you directly get $x=0$, but using numerical methods, you may get $x=1.1234\times10^{-20}$.
Now, it is important to understand how these iterative methods work. The key concept is knowing how to update your input parameters to get a better solution. Suppose you want to minimize $f(x_1,x_2)=x_1^2+x_2^2+|x_1+x_2|$ (note this cost function is not differentiable everywhere, but differentiable have at "most places", this is good enough for us, since we know how to update at "most places".), currently you are at $(1,1)$, and the cost is $4.0$, now you want to update $(x_1,x_2)$ to make objective function smaller. How would you do that? You may say I want to decrease both $x_1$ $x_2$, but why? In fact you are implicit using the concept of gradient "changing small amount of $x$, what will happen on $y$".. In $(1,1)$, the derivative is $(3,3)$, so negative gradient times a learning rate say $\alpha=0.001$, is $(-0.003,-0.003)$, so we updated our solution from $1, 1$ to $(0.997, 0.997)$ which have better cost.
|
Why is gradient descent required?
|
In calculus 101 we learned about how to optimize a function using "analytical method": we just need to get the derivative of cost function and set the derivative to 0 then solve the equation. This is
|
Why is gradient descent required?
In calculus 101 we learned about how to optimize a function using "analytical method": we just need to get the derivative of cost function and set the derivative to 0 then solve the equation. This is really a toy problem and will almost never happen in real world.
In real world, many cost functions are not have derivative everywhere (Further, the cost function may be discrete and do not have any derivative at all). In addition, even you can calculate the derivative, you cannot just solve the equation analytically (for example, think about how to solve $x^7+x^3-5^2+e^x+log(x+x^2)+1/x=0$ analytically? I can tell you the numerical answer is $x=1.4786$, but do not know analytical solution). We must use some numerical methods (check why here on polynomial cases Abel Ruffin Theorem).
Iterative methods are great to use, and very intuitive to understand. Suppose you want to optimize one function, instead of solving an equation and get the answer, you try to improve your answer by number of iterations /steps after enough iteration, you will get the answer close to "true answer". Say if you use calculus to minimize $f(x)=x^2$, you directly get $x=0$, but using numerical methods, you may get $x=1.1234\times10^{-20}$.
Now, it is important to understand how these iterative methods work. The key concept is knowing how to update your input parameters to get a better solution. Suppose you want to minimize $f(x_1,x_2)=x_1^2+x_2^2+|x_1+x_2|$ (note this cost function is not differentiable everywhere, but differentiable have at "most places", this is good enough for us, since we know how to update at "most places".), currently you are at $(1,1)$, and the cost is $4.0$, now you want to update $(x_1,x_2)$ to make objective function smaller. How would you do that? You may say I want to decrease both $x_1$ $x_2$, but why? In fact you are implicit using the concept of gradient "changing small amount of $x$, what will happen on $y$".. In $(1,1)$, the derivative is $(3,3)$, so negative gradient times a learning rate say $\alpha=0.001$, is $(-0.003,-0.003)$, so we updated our solution from $1, 1$ to $(0.997, 0.997)$ which have better cost.
|
Why is gradient descent required?
In calculus 101 we learned about how to optimize a function using "analytical method": we just need to get the derivative of cost function and set the derivative to 0 then solve the equation. This is
|
16,886
|
Why is gradient descent required?
|
The approach you mentioned can only be used to solve a set of linear equations for example in the case of linear regression, but say for solving a set of non linear equations, in cases such as neural networks with sigmoid activations, gradient descent is the approach to go for. Thus Gradient Descent is a more generic approach.
Even for linear equations, the size of the matrices given by the set of linear equations i huge, and can be hard to constrain the memory requirement.
|
Why is gradient descent required?
|
The approach you mentioned can only be used to solve a set of linear equations for example in the case of linear regression, but say for solving a set of non linear equations, in cases such as neural
|
Why is gradient descent required?
The approach you mentioned can only be used to solve a set of linear equations for example in the case of linear regression, but say for solving a set of non linear equations, in cases such as neural networks with sigmoid activations, gradient descent is the approach to go for. Thus Gradient Descent is a more generic approach.
Even for linear equations, the size of the matrices given by the set of linear equations i huge, and can be hard to constrain the memory requirement.
|
Why is gradient descent required?
The approach you mentioned can only be used to solve a set of linear equations for example in the case of linear regression, but say for solving a set of non linear equations, in cases such as neural
|
16,887
|
How to get ellipse region from bivariate normal distributed data?
|
Corsario provides a good solution in a comment: use the kernel density function to test for inclusion within a level set.
Another interpretation of the question is that it requests a procedure to test for inclusion within the ellipses created by a bivariate normal approximation to the data. To get started, let's generate some data that look like the illustration in the question:
library(mvtnorm) # References rmvnorm()
set.seed(17)
p <- rmvnorm(1000, c(250000, 20000), matrix(c(100000^2, 22000^2, 22000^2, 6000^2),2,2))
The ellipses are determined by the first and second moments of the data:
center <- apply(p, 2, mean)
sigma <- cov(p)
The formula requires inversion of the variance-covariance matrix:
sigma.inv = solve(sigma, matrix(c(1,0,0,1),2,2))
The ellipse "height" function is the negative of the logarithm of the bivariate normal density:
ellipse <- function(s,t) {u<-c(s,t)-center; u %*% sigma.inv %*% u / 2}
(I have ignored an additive constant equal to $\log(2\pi\sqrt{\det(\Sigma)})$.)
To test this, let's draw some of its contours. That requires generating a grid of points in the x and y directions:
n <- 50
x <- (0:(n-1)) * (500000/(n-1))
y <- (0:(n-1)) * (50000/(n-1))
Compute the height function at this grid and plot it:
z <- mapply(ellipse, as.vector(rep(x,n)), as.vector(outer(rep(0,n), y, `+`)))
plot(p, pch=20, xlim=c(0,500000), ylim=c(0,50000), xlab="Packets", ylab="Flows")
contour(x,y,matrix(z,n,n), levels=(0:10), col = terrain.colors(11), add=TRUE)
Evidently it works. Therefore, the test to determine whether a point $(s,t)$ lies inside an elliptical contour at level $c$ is
ellipse(s,t) <= c
Mathematica does the job in the same way: compute the variance-covariance matrix of the data, invert that, construct the ellipse function, and you're all set.
|
How to get ellipse region from bivariate normal distributed data?
|
Corsario provides a good solution in a comment: use the kernel density function to test for inclusion within a level set.
Another interpretation of the question is that it requests a procedure to test
|
How to get ellipse region from bivariate normal distributed data?
Corsario provides a good solution in a comment: use the kernel density function to test for inclusion within a level set.
Another interpretation of the question is that it requests a procedure to test for inclusion within the ellipses created by a bivariate normal approximation to the data. To get started, let's generate some data that look like the illustration in the question:
library(mvtnorm) # References rmvnorm()
set.seed(17)
p <- rmvnorm(1000, c(250000, 20000), matrix(c(100000^2, 22000^2, 22000^2, 6000^2),2,2))
The ellipses are determined by the first and second moments of the data:
center <- apply(p, 2, mean)
sigma <- cov(p)
The formula requires inversion of the variance-covariance matrix:
sigma.inv = solve(sigma, matrix(c(1,0,0,1),2,2))
The ellipse "height" function is the negative of the logarithm of the bivariate normal density:
ellipse <- function(s,t) {u<-c(s,t)-center; u %*% sigma.inv %*% u / 2}
(I have ignored an additive constant equal to $\log(2\pi\sqrt{\det(\Sigma)})$.)
To test this, let's draw some of its contours. That requires generating a grid of points in the x and y directions:
n <- 50
x <- (0:(n-1)) * (500000/(n-1))
y <- (0:(n-1)) * (50000/(n-1))
Compute the height function at this grid and plot it:
z <- mapply(ellipse, as.vector(rep(x,n)), as.vector(outer(rep(0,n), y, `+`)))
plot(p, pch=20, xlim=c(0,500000), ylim=c(0,50000), xlab="Packets", ylab="Flows")
contour(x,y,matrix(z,n,n), levels=(0:10), col = terrain.colors(11), add=TRUE)
Evidently it works. Therefore, the test to determine whether a point $(s,t)$ lies inside an elliptical contour at level $c$ is
ellipse(s,t) <= c
Mathematica does the job in the same way: compute the variance-covariance matrix of the data, invert that, construct the ellipse function, and you're all set.
|
How to get ellipse region from bivariate normal distributed data?
Corsario provides a good solution in a comment: use the kernel density function to test for inclusion within a level set.
Another interpretation of the question is that it requests a procedure to test
|
16,888
|
How to get ellipse region from bivariate normal distributed data?
|
The plot is straightforward with the ellipse() function of the mixtools package for R:
library(mixtools)
library(mvtnorm)
set.seed(17)
p <- rmvnorm(1000, c(250000, 20000), matrix(c(100000^2, 22000^2, 22000^2, 6000^2),2,2))
plot(p, pch=20, xlim=c(0,500000), ylim=c(0,50000), xlab="Packets", ylab="Flows")
ellipse(mu=colMeans(p), sigma=cov(p), alpha = .05, npoints = 250, col="red")
|
How to get ellipse region from bivariate normal distributed data?
|
The plot is straightforward with the ellipse() function of the mixtools package for R:
library(mixtools)
library(mvtnorm)
set.seed(17)
p <- rmvnorm(1000, c(250000, 20000), matrix(c(100000^2, 22000^2,
|
How to get ellipse region from bivariate normal distributed data?
The plot is straightforward with the ellipse() function of the mixtools package for R:
library(mixtools)
library(mvtnorm)
set.seed(17)
p <- rmvnorm(1000, c(250000, 20000), matrix(c(100000^2, 22000^2, 22000^2, 6000^2),2,2))
plot(p, pch=20, xlim=c(0,500000), ylim=c(0,50000), xlab="Packets", ylab="Flows")
ellipse(mu=colMeans(p), sigma=cov(p), alpha = .05, npoints = 250, col="red")
|
How to get ellipse region from bivariate normal distributed data?
The plot is straightforward with the ellipse() function of the mixtools package for R:
library(mixtools)
library(mvtnorm)
set.seed(17)
p <- rmvnorm(1000, c(250000, 20000), matrix(c(100000^2, 22000^2,
|
16,889
|
How to get ellipse region from bivariate normal distributed data?
|
First approach
You might try this approach in Mathematica.
Let's generate some bivariate data:
data = Table[RandomVariate[BinormalDistribution[{50, 50}, {5, 10}, .8]], {1000}];
Then we need to load this package:
Needs["MultivariateStatistics`"]
And, now:
ellPar=EllipsoidQuantile[data, {0.9}]
gives an output that defines a 90% confidence ellipse. The values you obtain from this output are in the following format:
{Ellipsoid[{x1, x2}, {r1, r2}, {{d1, d2}, {d3, d4}}]}
x1 and x2 specify the point at which the ellipse in centered, r1 and r2 specify the semi-axis radii, and d1, d2, d3 and d4 specify the alignment direction.
You can also plot this:
Show[{ListPlot[data, PlotRange -> {{0, 100}, {0, 100}}, AspectRatio -> 1], Graphics[EllipsoidQuantile[data, 0.9]]}]
The general parametric form of the ellipse is:
ell[t_, xc_, yc_, a_, b_, angle_] := {xc + a Cos[t] Cos[angle] - b Sin[t] Sin[angle],
yc + a Cos[t] Sin[angle] + b Sin[t] Cos[angle]}
And you can plot it in this way:
ParametricPlot[
ell[t, ellPar[[1, 1, 1]], ellPar[[1, 1, 2]], ellPar[[1, 2, 1]], ellPar[[1, 2, 2]],
ArcTan[ellPar[[1, 3, 1, 2]]/ellPar[[1, 3, 1, 1]]]], {t, 0, 2 \[Pi]},
PlotRange -> {{0, 100}, {0, 100}}]
You could perform a check based on pure geometric information: if the Euclidean distance between the center of the ellipse (ellPar[[1,1]]) and your data point is larger than the distance between the center of the ellipse and the border of the ellipse (obviously, in the same direction in which your point is located), then that data point is outside the ellipse.
Second approach
This approach is based on the smooth kernel distribution.
These are some data distributed in a similar way to your data:
data1 = RandomVariate[BinormalDistribution[{.3, .7}, {.2, .3}, .8], 500];
data2 = RandomVariate[BinormalDistribution[{.6, .3}, {.4, .15}, .8], 500];
data = Partition[Flatten[Join[{data1, data2}]], 2];
We obtain a smooth kernel distribution on these data values:
skd = SmoothKernelDistribution[data];
We obtain a numeric result for each data point:
eval = Table[{data[[i]], PDF[skd, data[[i]]]}, {i, Length[data]}];
We fix a threshold and we select all the data that are higher than this threshold:
threshold = 1.2;
dataIn = Select[eval, #1[[2]] > threshold &][[All, 1]];
Here we get the data that fall outside the region:
dataOut = Complement[data, dataIn];
And now we can plot all the data:
Show[ContourPlot[Evaluate@PDF[skd, {x, y}], {x, 0, 1}, {y, 0, 1}, PlotRange -> {{0, 1}, {0, 1}}, PlotPoints -> 50],
ListPlot[dataIn, PlotStyle -> Darker[Green]],
ListPlot[dataOut, PlotStyle -> Red]]
The green colored points are those above the threshold and the red colored points are those below the threshold.
|
How to get ellipse region from bivariate normal distributed data?
|
First approach
You might try this approach in Mathematica.
Let's generate some bivariate data:
data = Table[RandomVariate[BinormalDistribution[{50, 50}, {5, 10}, .8]], {1000}];
Then we need to load t
|
How to get ellipse region from bivariate normal distributed data?
First approach
You might try this approach in Mathematica.
Let's generate some bivariate data:
data = Table[RandomVariate[BinormalDistribution[{50, 50}, {5, 10}, .8]], {1000}];
Then we need to load this package:
Needs["MultivariateStatistics`"]
And, now:
ellPar=EllipsoidQuantile[data, {0.9}]
gives an output that defines a 90% confidence ellipse. The values you obtain from this output are in the following format:
{Ellipsoid[{x1, x2}, {r1, r2}, {{d1, d2}, {d3, d4}}]}
x1 and x2 specify the point at which the ellipse in centered, r1 and r2 specify the semi-axis radii, and d1, d2, d3 and d4 specify the alignment direction.
You can also plot this:
Show[{ListPlot[data, PlotRange -> {{0, 100}, {0, 100}}, AspectRatio -> 1], Graphics[EllipsoidQuantile[data, 0.9]]}]
The general parametric form of the ellipse is:
ell[t_, xc_, yc_, a_, b_, angle_] := {xc + a Cos[t] Cos[angle] - b Sin[t] Sin[angle],
yc + a Cos[t] Sin[angle] + b Sin[t] Cos[angle]}
And you can plot it in this way:
ParametricPlot[
ell[t, ellPar[[1, 1, 1]], ellPar[[1, 1, 2]], ellPar[[1, 2, 1]], ellPar[[1, 2, 2]],
ArcTan[ellPar[[1, 3, 1, 2]]/ellPar[[1, 3, 1, 1]]]], {t, 0, 2 \[Pi]},
PlotRange -> {{0, 100}, {0, 100}}]
You could perform a check based on pure geometric information: if the Euclidean distance between the center of the ellipse (ellPar[[1,1]]) and your data point is larger than the distance between the center of the ellipse and the border of the ellipse (obviously, in the same direction in which your point is located), then that data point is outside the ellipse.
Second approach
This approach is based on the smooth kernel distribution.
These are some data distributed in a similar way to your data:
data1 = RandomVariate[BinormalDistribution[{.3, .7}, {.2, .3}, .8], 500];
data2 = RandomVariate[BinormalDistribution[{.6, .3}, {.4, .15}, .8], 500];
data = Partition[Flatten[Join[{data1, data2}]], 2];
We obtain a smooth kernel distribution on these data values:
skd = SmoothKernelDistribution[data];
We obtain a numeric result for each data point:
eval = Table[{data[[i]], PDF[skd, data[[i]]]}, {i, Length[data]}];
We fix a threshold and we select all the data that are higher than this threshold:
threshold = 1.2;
dataIn = Select[eval, #1[[2]] > threshold &][[All, 1]];
Here we get the data that fall outside the region:
dataOut = Complement[data, dataIn];
And now we can plot all the data:
Show[ContourPlot[Evaluate@PDF[skd, {x, y}], {x, 0, 1}, {y, 0, 1}, PlotRange -> {{0, 1}, {0, 1}}, PlotPoints -> 50],
ListPlot[dataIn, PlotStyle -> Darker[Green]],
ListPlot[dataOut, PlotStyle -> Red]]
The green colored points are those above the threshold and the red colored points are those below the threshold.
|
How to get ellipse region from bivariate normal distributed data?
First approach
You might try this approach in Mathematica.
Let's generate some bivariate data:
data = Table[RandomVariate[BinormalDistribution[{50, 50}, {5, 10}, .8]], {1000}];
Then we need to load t
|
16,890
|
How to get ellipse region from bivariate normal distributed data?
|
The ellipse function in the ellipse package for R will generate these ellipses (actually a polygon approximating the ellipse). You could use that ellipse.
What might actually be easier is to compute the height of the density at your point and see if it is higher (inside the ellipse) or lower (outside the ellipse) than the contour value at the ellipse. The ellipse function internals use a $\chi^2$ value to create the ellipse, you could start there for finding the height to use.
|
How to get ellipse region from bivariate normal distributed data?
|
The ellipse function in the ellipse package for R will generate these ellipses (actually a polygon approximating the ellipse). You could use that ellipse.
What might actually be easier is to compute
|
How to get ellipse region from bivariate normal distributed data?
The ellipse function in the ellipse package for R will generate these ellipses (actually a polygon approximating the ellipse). You could use that ellipse.
What might actually be easier is to compute the height of the density at your point and see if it is higher (inside the ellipse) or lower (outside the ellipse) than the contour value at the ellipse. The ellipse function internals use a $\chi^2$ value to create the ellipse, you could start there for finding the height to use.
|
How to get ellipse region from bivariate normal distributed data?
The ellipse function in the ellipse package for R will generate these ellipses (actually a polygon approximating the ellipse). You could use that ellipse.
What might actually be easier is to compute
|
16,891
|
How to get ellipse region from bivariate normal distributed data?
|
I found the answer at: https://stackoverflow.com/questions/2397097/how-can-a-data-ellipse-be-superimposed-on-a-ggplot2-scatterplot
#bootstrap
set.seed(101)
n <- 1000
x <- rnorm(n, mean=2)
y <- 1.5 + 0.4*x + rnorm(n)
df <- data.frame(x=x, y=y, group="A")
x <- rnorm(n, mean=2)
y <- 1.5*x + 0.4 + rnorm(n)
df <- rbind(df, data.frame(x=x, y=y, group="B"))
#calculating ellipses
library(ellipse)
df_ell <- data.frame()
for(g in levels(df$group)){
df_ell <- rbind(df_ell, cbind(as.data.frame(with(df[df$group==g,], ellipse(cor(x, y),
scale=c(sd(x),sd(y)),
centre=c(mean(x),mean(y))))),group=g))
}
#drawing
library(ggplot2)
p <- ggplot(data=df, aes(x=x, y=y,colour=group)) + geom_point(size=1.5, alpha=.6) +
geom_path(data=df_ell, aes(x=x, y=y,colour=group), size=1, linetype=2)
|
How to get ellipse region from bivariate normal distributed data?
|
I found the answer at: https://stackoverflow.com/questions/2397097/how-can-a-data-ellipse-be-superimposed-on-a-ggplot2-scatterplot
#bootstrap
set.seed(101)
n <- 1000
x <- rnorm(n, mean=2)
y <- 1.5 +
|
How to get ellipse region from bivariate normal distributed data?
I found the answer at: https://stackoverflow.com/questions/2397097/how-can-a-data-ellipse-be-superimposed-on-a-ggplot2-scatterplot
#bootstrap
set.seed(101)
n <- 1000
x <- rnorm(n, mean=2)
y <- 1.5 + 0.4*x + rnorm(n)
df <- data.frame(x=x, y=y, group="A")
x <- rnorm(n, mean=2)
y <- 1.5*x + 0.4 + rnorm(n)
df <- rbind(df, data.frame(x=x, y=y, group="B"))
#calculating ellipses
library(ellipse)
df_ell <- data.frame()
for(g in levels(df$group)){
df_ell <- rbind(df_ell, cbind(as.data.frame(with(df[df$group==g,], ellipse(cor(x, y),
scale=c(sd(x),sd(y)),
centre=c(mean(x),mean(y))))),group=g))
}
#drawing
library(ggplot2)
p <- ggplot(data=df, aes(x=x, y=y,colour=group)) + geom_point(size=1.5, alpha=.6) +
geom_path(data=df_ell, aes(x=x, y=y,colour=group), size=1, linetype=2)
|
How to get ellipse region from bivariate normal distributed data?
I found the answer at: https://stackoverflow.com/questions/2397097/how-can-a-data-ellipse-be-superimposed-on-a-ggplot2-scatterplot
#bootstrap
set.seed(101)
n <- 1000
x <- rnorm(n, mean=2)
y <- 1.5 +
|
16,892
|
Alternative to One-way ANOVA unequal variance
|
@JeremyMiles is right. First, there's a rule of thumb that the ANOVA is robust to heterogeneity of variance so long as the largest variance is not more than 4 times the smallest variance. Furthermore, the general effect of heterogeneity of variance is to make the ANOVA less efficient. That is, you would have lower power. Since you have a significant effect anyway, there is less reason to be concerned here.
Update:
I demonstrate my point about lower efficiency / power here: Efficiency of beta estimates with heteroscedasticity
I have a comprehensive overview of strategies for dealing with problematic heteroscedasticity in one-way ANOVAs here: Alternatives to one-way ANOVA for heteroscedastic data
|
Alternative to One-way ANOVA unequal variance
|
@JeremyMiles is right. First, there's a rule of thumb that the ANOVA is robust to heterogeneity of variance so long as the largest variance is not more than 4 times the smallest variance. Furthermor
|
Alternative to One-way ANOVA unequal variance
@JeremyMiles is right. First, there's a rule of thumb that the ANOVA is robust to heterogeneity of variance so long as the largest variance is not more than 4 times the smallest variance. Furthermore, the general effect of heterogeneity of variance is to make the ANOVA less efficient. That is, you would have lower power. Since you have a significant effect anyway, there is less reason to be concerned here.
Update:
I demonstrate my point about lower efficiency / power here: Efficiency of beta estimates with heteroscedasticity
I have a comprehensive overview of strategies for dealing with problematic heteroscedasticity in one-way ANOVAs here: Alternatives to one-way ANOVA for heteroscedastic data
|
Alternative to One-way ANOVA unequal variance
@JeremyMiles is right. First, there's a rule of thumb that the ANOVA is robust to heterogeneity of variance so long as the largest variance is not more than 4 times the smallest variance. Furthermor
|
16,893
|
Alternative to One-way ANOVA unequal variance
|
(1) "The means of each group are normally distributed" - on what basis can you make such an assertion?
(2) your difference in variance sounds pretty small, and if sample sizes are nearly equal would cause little concern, as others have mentioned,
(3) Welch-type adjustments* for degrees of freedom exist for ANOVA just as with two-sample t-tests; and just as with their use in two sample t-tests, there's little reason not to use them as a matter of course. Indeed, the oneway.test function in R does this by default.
*B. L. Welch (1951), On the comparison of several mean values: an alternative approach.
Biometrika, 38, 330–336.
|
Alternative to One-way ANOVA unequal variance
|
(1) "The means of each group are normally distributed" - on what basis can you make such an assertion?
(2) your difference in variance sounds pretty small, and if sample sizes are nearly equal would
|
Alternative to One-way ANOVA unequal variance
(1) "The means of each group are normally distributed" - on what basis can you make such an assertion?
(2) your difference in variance sounds pretty small, and if sample sizes are nearly equal would cause little concern, as others have mentioned,
(3) Welch-type adjustments* for degrees of freedom exist for ANOVA just as with two-sample t-tests; and just as with their use in two sample t-tests, there's little reason not to use them as a matter of course. Indeed, the oneway.test function in R does this by default.
*B. L. Welch (1951), On the comparison of several mean values: an alternative approach.
Biometrika, 38, 330–336.
|
Alternative to One-way ANOVA unequal variance
(1) "The means of each group are normally distributed" - on what basis can you make such an assertion?
(2) your difference in variance sounds pretty small, and if sample sizes are nearly equal would
|
16,894
|
Alternative to One-way ANOVA unequal variance
|
I suggest to employ Bayesian ANOVA, which does not assume the variances are necessarily the same across groups.
John K. Kruschke has made an excellent example, available here:
http://doingbayesiandataanalysis.blogspot.mx/2011/04/anova-with-non-homogeneous-variances.html
|
Alternative to One-way ANOVA unequal variance
|
I suggest to employ Bayesian ANOVA, which does not assume the variances are necessarily the same across groups.
John K. Kruschke has made an excellent example, available here:
http://doingbayesianda
|
Alternative to One-way ANOVA unequal variance
I suggest to employ Bayesian ANOVA, which does not assume the variances are necessarily the same across groups.
John K. Kruschke has made an excellent example, available here:
http://doingbayesiandataanalysis.blogspot.mx/2011/04/anova-with-non-homogeneous-variances.html
|
Alternative to One-way ANOVA unequal variance
I suggest to employ Bayesian ANOVA, which does not assume the variances are necessarily the same across groups.
John K. Kruschke has made an excellent example, available here:
http://doingbayesianda
|
16,895
|
Gradient boosting machine accuracy decreases as number of iterations increases
|
In general, boosting error can increase with the number of iterations, specifically when the data is noisy (e.g. mislabeled cases). I wouldn't be able to say if this is your problem without knowing more about your data
Basically, boosting can 'focus' on correctly predicting cases that contain misinformation, and in the process, deteriorate the average performance on other cases that are more substantive.
This link (Boosting and Noise) shows a better description than I can provide of the issue.
This paper (Random Classification Noise) by Long and Servedio provides more technical details of the issue.
|
Gradient boosting machine accuracy decreases as number of iterations increases
|
In general, boosting error can increase with the number of iterations, specifically when the data is noisy (e.g. mislabeled cases). I wouldn't be able to say if this is your problem without knowing m
|
Gradient boosting machine accuracy decreases as number of iterations increases
In general, boosting error can increase with the number of iterations, specifically when the data is noisy (e.g. mislabeled cases). I wouldn't be able to say if this is your problem without knowing more about your data
Basically, boosting can 'focus' on correctly predicting cases that contain misinformation, and in the process, deteriorate the average performance on other cases that are more substantive.
This link (Boosting and Noise) shows a better description than I can provide of the issue.
This paper (Random Classification Noise) by Long and Servedio provides more technical details of the issue.
|
Gradient boosting machine accuracy decreases as number of iterations increases
In general, boosting error can increase with the number of iterations, specifically when the data is noisy (e.g. mislabeled cases). I wouldn't be able to say if this is your problem without knowing m
|
16,896
|
Gradient boosting machine accuracy decreases as number of iterations increases
|
What you have displayed is a classic example of overfitting. The small uptick in error comes from poorer performance on the validation portion of your cross-validated data set. More iterations should nearly always improve the error on the training set, but the opposite is true for the validation/test set.
|
Gradient boosting machine accuracy decreases as number of iterations increases
|
What you have displayed is a classic example of overfitting. The small uptick in error comes from poorer performance on the validation portion of your cross-validated data set. More iterations should
|
Gradient boosting machine accuracy decreases as number of iterations increases
What you have displayed is a classic example of overfitting. The small uptick in error comes from poorer performance on the validation portion of your cross-validated data set. More iterations should nearly always improve the error on the training set, but the opposite is true for the validation/test set.
|
Gradient boosting machine accuracy decreases as number of iterations increases
What you have displayed is a classic example of overfitting. The small uptick in error comes from poorer performance on the validation portion of your cross-validated data set. More iterations should
|
16,897
|
Gradient boosting machine accuracy decreases as number of iterations increases
|
Codes to reproduce a similar result, without grid search,
mod = gbm(admit ~ .,
data = mydata[,-5],
n.trees=100000,
shrinkage=0.001,
interaction.depth=2,
n.minobsinnode=10,
cv.folds=5,
verbose=TRUE,
n.cores=2)
best.iter <- gbm.perf(mod, method="OOB", plot.it=TRUE, oobag.curve=TRUE, overlay=TRUE)
print(best.iter)
[1] 1487
pred = as.integer(predict(mod, newdata=mydata[,-5], n.trees=best.iter) > 0)
y = mydata[,1]
sum(pred == y)/length(y)
[1] 0.7225
|
Gradient boosting machine accuracy decreases as number of iterations increases
|
Codes to reproduce a similar result, without grid search,
mod = gbm(admit ~ .,
data = mydata[,-5],
n.trees=100000,
shrinkage=0.001,
interaction.depth=2,
n.minobsinnode=10
|
Gradient boosting machine accuracy decreases as number of iterations increases
Codes to reproduce a similar result, without grid search,
mod = gbm(admit ~ .,
data = mydata[,-5],
n.trees=100000,
shrinkage=0.001,
interaction.depth=2,
n.minobsinnode=10,
cv.folds=5,
verbose=TRUE,
n.cores=2)
best.iter <- gbm.perf(mod, method="OOB", plot.it=TRUE, oobag.curve=TRUE, overlay=TRUE)
print(best.iter)
[1] 1487
pred = as.integer(predict(mod, newdata=mydata[,-5], n.trees=best.iter) > 0)
y = mydata[,1]
sum(pred == y)/length(y)
[1] 0.7225
|
Gradient boosting machine accuracy decreases as number of iterations increases
Codes to reproduce a similar result, without grid search,
mod = gbm(admit ~ .,
data = mydata[,-5],
n.trees=100000,
shrinkage=0.001,
interaction.depth=2,
n.minobsinnode=10
|
16,898
|
Gradient boosting machine accuracy decreases as number of iterations increases
|
The gbm package has a function to estimate the optimal # of iterations (= # of trees, or # of basis functions),
gbm.perf(mod, method="OOB", plot.it=TRUE, oobag=TRUE, overlay=TRUE)
You don't need caret's train for that.
|
Gradient boosting machine accuracy decreases as number of iterations increases
|
The gbm package has a function to estimate the optimal # of iterations (= # of trees, or # of basis functions),
gbm.perf(mod, method="OOB", plot.it=TRUE, oobag=TRUE, overlay=TRUE)
You don't need care
|
Gradient boosting machine accuracy decreases as number of iterations increases
The gbm package has a function to estimate the optimal # of iterations (= # of trees, or # of basis functions),
gbm.perf(mod, method="OOB", plot.it=TRUE, oobag=TRUE, overlay=TRUE)
You don't need caret's train for that.
|
Gradient boosting machine accuracy decreases as number of iterations increases
The gbm package has a function to estimate the optimal # of iterations (= # of trees, or # of basis functions),
gbm.perf(mod, method="OOB", plot.it=TRUE, oobag=TRUE, overlay=TRUE)
You don't need care
|
16,899
|
Pitfalls to avoid when transforming data?
|
You can't really compare $R^2$ before and after, because the underlying variability in $Y$ is different. So you literally can take no comfort whatever from the change in $R^2$. That tells you nothing of value in comparing the two models.
The two models are different in several ways, so they mean different things -- they assume very different things about the shape of the relationship and the variability of the error term (when considered in terms of the relationship between $Y$ and $X$). So if you're interested in modelling $Y$ (if $Y$ itself is meaningful), produce a good model for that. If you're interested in modelling $\sqrt Y$ (/$\sqrt Y$ is meaningful), produce a good model for that. If $\sqrt{Y/X}$ carries meaning, then make a good model for that. But compare any competing models on comparable scales. $R^2$ on different responses simply aren't comparable.
If you're just trying different relationships in the hope of finding a transformation with a high $R^2$ -- or any other measure of 'good fit' -- the properties of any inference you might like to conduct will be impacted by the existence of that search process.
Estimates will tend to be biased away from zero, standard errors will be too small, p-values will be too small, confidence intervals too narrow. Your models will on average appear to be 'too good' (in the sense that their out-of-sample behavior will be disappointing compared to in-sample behavior).
To avoid this kind of overfitting, you need, if possible, to do the model-identification and estimation on different subsets of the data (and model evaluation on a third). If you repeat this kind of procedure on many "splits" of the data taken at random, you get a better sense of how reproducible your results are.
There are many posts here with relevant points on these issues: it might be worth trying some searches.
(If you have good a priori reasons for choosing a particular transformation, that's a different issue. But searching the space of transformations to find something that fits carries all manner of 'data snooping' type problems with it.)
|
Pitfalls to avoid when transforming data?
|
You can't really compare $R^2$ before and after, because the underlying variability in $Y$ is different. So you literally can take no comfort whatever from the change in $R^2$. That tells you nothing
|
Pitfalls to avoid when transforming data?
You can't really compare $R^2$ before and after, because the underlying variability in $Y$ is different. So you literally can take no comfort whatever from the change in $R^2$. That tells you nothing of value in comparing the two models.
The two models are different in several ways, so they mean different things -- they assume very different things about the shape of the relationship and the variability of the error term (when considered in terms of the relationship between $Y$ and $X$). So if you're interested in modelling $Y$ (if $Y$ itself is meaningful), produce a good model for that. If you're interested in modelling $\sqrt Y$ (/$\sqrt Y$ is meaningful), produce a good model for that. If $\sqrt{Y/X}$ carries meaning, then make a good model for that. But compare any competing models on comparable scales. $R^2$ on different responses simply aren't comparable.
If you're just trying different relationships in the hope of finding a transformation with a high $R^2$ -- or any other measure of 'good fit' -- the properties of any inference you might like to conduct will be impacted by the existence of that search process.
Estimates will tend to be biased away from zero, standard errors will be too small, p-values will be too small, confidence intervals too narrow. Your models will on average appear to be 'too good' (in the sense that their out-of-sample behavior will be disappointing compared to in-sample behavior).
To avoid this kind of overfitting, you need, if possible, to do the model-identification and estimation on different subsets of the data (and model evaluation on a third). If you repeat this kind of procedure on many "splits" of the data taken at random, you get a better sense of how reproducible your results are.
There are many posts here with relevant points on these issues: it might be worth trying some searches.
(If you have good a priori reasons for choosing a particular transformation, that's a different issue. But searching the space of transformations to find something that fits carries all manner of 'data snooping' type problems with it.)
|
Pitfalls to avoid when transforming data?
You can't really compare $R^2$ before and after, because the underlying variability in $Y$ is different. So you literally can take no comfort whatever from the change in $R^2$. That tells you nothing
|
16,900
|
Pitfalls to avoid when transforming data?
|
There's a bigger problem than the ones identified by @Glen_b .
set.seed(123)
x <- rnorm(100, 20, 2)
y <- rnorm(100, 20, 2)
dv <- (y/x)^.5
iv <- x^.5
m1 <- lm(dv~iv)
summary(m1)
And I get an $R^2$ of 0.49 and a P-value that is $5.5 \times 10^{-16}$.
You have $X$ on both sides of the equation.
|
Pitfalls to avoid when transforming data?
|
There's a bigger problem than the ones identified by @Glen_b .
set.seed(123)
x <- rnorm(100, 20, 2)
y <- rnorm(100, 20, 2)
dv <- (y/x)^.5
iv <- x^.5
m1 <- lm(dv~iv)
summary(m1)
And I get an $R^2$ of
|
Pitfalls to avoid when transforming data?
There's a bigger problem than the ones identified by @Glen_b .
set.seed(123)
x <- rnorm(100, 20, 2)
y <- rnorm(100, 20, 2)
dv <- (y/x)^.5
iv <- x^.5
m1 <- lm(dv~iv)
summary(m1)
And I get an $R^2$ of 0.49 and a P-value that is $5.5 \times 10^{-16}$.
You have $X$ on both sides of the equation.
|
Pitfalls to avoid when transforming data?
There's a bigger problem than the ones identified by @Glen_b .
set.seed(123)
x <- rnorm(100, 20, 2)
y <- rnorm(100, 20, 2)
dv <- (y/x)^.5
iv <- x^.5
m1 <- lm(dv~iv)
summary(m1)
And I get an $R^2$ of
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.