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
40,901
How do I setup up repeated measures data for analysis with nlme()?
NLME relies on a "univariate" as opposed to "multi-variate" data structure. See the description below, copied from my response to another question here: Data manipulation in R for functional data analysis As to how you would get the data into R and into one of these formats, we'd need to know more about what your input file looks like and the format that it is in. However, here are some general tips on formatting the type of data that you have for analysis in any system. Singer (Applied Longitudinal Data Analysis) suggests two generally useful layouts for the statistical analysis of longitudinal data: the person-level (mutlivariate) structure or the person-period (univariate) structure. The latter is generally preferrable for a number of reasons. The person-level data structure (or the multivariate format) contains one row of data for each observational unit (such as persons) and a variable for each measurement period. Age would not be included in the data set and would be implicit in the levels of your time factor (e.g., in a repeated measures ANOVA). This structure can lead naturally to summaries that aren't very meaningful, is less efficient than it could be, and cannot account for your unequally spaced observations (differing age intervals between observations) or time-varying covariates. That data setup might look something like this... Mutlivariate ID Gender height1 height2 height3 height4 height5 1 Boy 76.2 74.6 78.2 77.7 76 2 Boy 80.4 78.0 81.8 80.5 80 3 Boy 83.3 82.0 85.4 83.3 83 4 Girl 96.0 94.9 97.1 98.6 96 5 Girl 87.7 90.0 89.6 90.3 89 6 Girl 85.7 86.9 87.9 87.0 86 A preferable layout is often the person-period layout (or the univariate format) where each individual has a record for each time for which they were observed. The person-period dataset has a number of advantages. First, it leads to more natural summaries of the data, e.g. getting an average by group, by time or by group and time is now straight forward. Second, the dataset will accommodate entry of unequal intervals in the time dimension, such as you have here. In addition, if you have them, you could add columns for any other demographic covariates and these could differ over time. Also, data in this format is prepared for modern analytical techniques such as multilevel modeling. Finally, the univariate data structure is consistent with good practice in database design and normalization, increasing efficiency and making it appropriate for the typical query structure. The univariate layout would look something like this... Univariate ID Age Gender Height 1 1 Boy 76.2 1 1.5 Boy 74.6 1 3 Boy 78.2 1 5 Boy 77.7 2 1 Girl 80.4 2 1.5 Girl 81.8 2 3 Girl 80.5 2 5 Girl 80 3 1 Boy 115.8 3 1.5 Boy 112.3 3 3 Boy 111.0 3 5 Boy 104.1
How do I setup up repeated measures data for analysis with nlme()?
NLME relies on a "univariate" as opposed to "multi-variate" data structure. See the description below, copied from my response to another question here: Data manipulation in R for functional data ana
How do I setup up repeated measures data for analysis with nlme()? NLME relies on a "univariate" as opposed to "multi-variate" data structure. See the description below, copied from my response to another question here: Data manipulation in R for functional data analysis As to how you would get the data into R and into one of these formats, we'd need to know more about what your input file looks like and the format that it is in. However, here are some general tips on formatting the type of data that you have for analysis in any system. Singer (Applied Longitudinal Data Analysis) suggests two generally useful layouts for the statistical analysis of longitudinal data: the person-level (mutlivariate) structure or the person-period (univariate) structure. The latter is generally preferrable for a number of reasons. The person-level data structure (or the multivariate format) contains one row of data for each observational unit (such as persons) and a variable for each measurement period. Age would not be included in the data set and would be implicit in the levels of your time factor (e.g., in a repeated measures ANOVA). This structure can lead naturally to summaries that aren't very meaningful, is less efficient than it could be, and cannot account for your unequally spaced observations (differing age intervals between observations) or time-varying covariates. That data setup might look something like this... Mutlivariate ID Gender height1 height2 height3 height4 height5 1 Boy 76.2 74.6 78.2 77.7 76 2 Boy 80.4 78.0 81.8 80.5 80 3 Boy 83.3 82.0 85.4 83.3 83 4 Girl 96.0 94.9 97.1 98.6 96 5 Girl 87.7 90.0 89.6 90.3 89 6 Girl 85.7 86.9 87.9 87.0 86 A preferable layout is often the person-period layout (or the univariate format) where each individual has a record for each time for which they were observed. The person-period dataset has a number of advantages. First, it leads to more natural summaries of the data, e.g. getting an average by group, by time or by group and time is now straight forward. Second, the dataset will accommodate entry of unequal intervals in the time dimension, such as you have here. In addition, if you have them, you could add columns for any other demographic covariates and these could differ over time. Also, data in this format is prepared for modern analytical techniques such as multilevel modeling. Finally, the univariate data structure is consistent with good practice in database design and normalization, increasing efficiency and making it appropriate for the typical query structure. The univariate layout would look something like this... Univariate ID Age Gender Height 1 1 Boy 76.2 1 1.5 Boy 74.6 1 3 Boy 78.2 1 5 Boy 77.7 2 1 Girl 80.4 2 1.5 Girl 81.8 2 3 Girl 80.5 2 5 Girl 80 3 1 Boy 115.8 3 1.5 Boy 112.3 3 3 Boy 111.0 3 5 Boy 104.1
How do I setup up repeated measures data for analysis with nlme()? NLME relies on a "univariate" as opposed to "multi-variate" data structure. See the description below, copied from my response to another question here: Data manipulation in R for functional data ana
40,902
Regression analysis and parameter estimates with populations
I like what chl has written. Despite that, I am moved to discuss whether this situation necessarily requires a complicated model. But first, let's begin with responses to some comments. (1) You don't lose any degrees of freedom due to spatial correlation of forest cover. This is an explanatory variable, not the one you're trying to model. You might lose "degrees of freedom" when the residuals of the dependent variable exhibit spatial autocorrelation. Such correlation is not necessarily a given even when a map of the dependent variable itself suggests strong spatial correlation. The reason is that the correlation in the map likely derives from the correlation in the forest cover (and other spatially distributed covariates). Remember, in such models you don't ask whether the "samples are independent"--it's usually obvious they are not--but whether any deviations in them from their modeled values are independent. (2) Therefore, a conditional autoregressive model might not be necessary. I think this modeling choice would be attractive only if you want to test a theory of contagion. Now to answer the original question: yes, first run an ordinary logistic (or Poisson) model, because as a general principle it's good to try simple (but reasonable) models first. Provided its residuals do not exhibit strong spatial correlation, you are then ok with the results. If there is evidence of correlation and evidence that it will appreciably affect your answers (coefficients, predictions, or whatever), consider using a generalized linear geostatistical model (GLM). These are described in Diggle & Riberio, Model-based Geostatistics (a relatively inexpensive and accessible text), which itself documents several R packages for making the estimates and some associated EDA tools (geoR and geoRglm). The GLM approach lets you simultaneously fit your model and assess the degree of spatial autocorrelation. The principal limitations I have found in these packages are (1) they don't handle anisotropy well--you can detect it but it's hard to incorporate it in a model--and (2) they don't have a provision for nested variograms, which somewhat limits your ability to model the spatial correlation. Both of these are no problem for smallish datasets, because you need (typically) hundreds to thousands of observations, or more, to model correlation at this level of detail. Finally, a word about the "population" question. I assume you are interested in more than a mere description of the data: you seek information about a possible association between disease and other observable factors. Even when you have a comprehensive description of the data for a spatial region, it still does not act like a census, because the outcomes could have turned out otherwise. Next year, with identical forest cover, there will be a slightly different pattern of disease. In other regions of the country or the world and at other times, exactly the same combinations of explanatory variable values are likely to produce varying rates of disease. Thus, you're modeling a process, not a population.
Regression analysis and parameter estimates with populations
I like what chl has written. Despite that, I am moved to discuss whether this situation necessarily requires a complicated model. But first, let's begin with responses to some comments. (1) You don'
Regression analysis and parameter estimates with populations I like what chl has written. Despite that, I am moved to discuss whether this situation necessarily requires a complicated model. But first, let's begin with responses to some comments. (1) You don't lose any degrees of freedom due to spatial correlation of forest cover. This is an explanatory variable, not the one you're trying to model. You might lose "degrees of freedom" when the residuals of the dependent variable exhibit spatial autocorrelation. Such correlation is not necessarily a given even when a map of the dependent variable itself suggests strong spatial correlation. The reason is that the correlation in the map likely derives from the correlation in the forest cover (and other spatially distributed covariates). Remember, in such models you don't ask whether the "samples are independent"--it's usually obvious they are not--but whether any deviations in them from their modeled values are independent. (2) Therefore, a conditional autoregressive model might not be necessary. I think this modeling choice would be attractive only if you want to test a theory of contagion. Now to answer the original question: yes, first run an ordinary logistic (or Poisson) model, because as a general principle it's good to try simple (but reasonable) models first. Provided its residuals do not exhibit strong spatial correlation, you are then ok with the results. If there is evidence of correlation and evidence that it will appreciably affect your answers (coefficients, predictions, or whatever), consider using a generalized linear geostatistical model (GLM). These are described in Diggle & Riberio, Model-based Geostatistics (a relatively inexpensive and accessible text), which itself documents several R packages for making the estimates and some associated EDA tools (geoR and geoRglm). The GLM approach lets you simultaneously fit your model and assess the degree of spatial autocorrelation. The principal limitations I have found in these packages are (1) they don't handle anisotropy well--you can detect it but it's hard to incorporate it in a model--and (2) they don't have a provision for nested variograms, which somewhat limits your ability to model the spatial correlation. Both of these are no problem for smallish datasets, because you need (typically) hundreds to thousands of observations, or more, to model correlation at this level of detail. Finally, a word about the "population" question. I assume you are interested in more than a mere description of the data: you seek information about a possible association between disease and other observable factors. Even when you have a comprehensive description of the data for a spatial region, it still does not act like a census, because the outcomes could have turned out otherwise. Next year, with identical forest cover, there will be a slightly different pattern of disease. In other regions of the country or the world and at other times, exactly the same combinations of explanatory variable values are likely to produce varying rates of disease. Thus, you're modeling a process, not a population.
Regression analysis and parameter estimates with populations I like what chl has written. Despite that, I am moved to discuss whether this situation necessarily requires a complicated model. But first, let's begin with responses to some comments. (1) You don'
40,903
Regression analysis and parameter estimates with populations
What you describe seems to refer to a particular case of multilevel modeling, where data are organized into a hierarchical structure; in your case, forests (1st level unit) nested in counties nested in states, but see Under what conditions should one use multilevel/hierarchical analysis?. Now, the "particular" case comes from the fact that you want to account for the spatial proximity which might be a vector for the propagation of Lyme disease (correct me if I am wrong), as is done in epidemiology where one is interested in studying the geography of infectious disease. In the usual case, we can use so-called spatial models like the multiple membership model or the conditional autoregressive model, among others. I enclose a couple of references about these approaches at the end, but I think you will find more references by looking at related studies in ecology or epidemiology. Now, I think that you may pay a particular attention at the following paper of Langford et al. which features multilevel modeling with spatially correlated data: Langford, IH, Leyland, AHL, Rasbash, and Goldstein, H (1999). Multilevel modelling of the geographical distributions of diseases. Journal of Royal Statistical Society C, 48, 253-268. Harvey Goldstein is the author of an excellent book on multilevel modeling, Multilevel Statistical Models (the 2nd edition is available for free). Finally, the book of Andrew Gelman, Data Analysis Using Regression and Multilevel/Hierarchical Models, may provide additional clues about hierarchical/multilevel modeling. About software, I know there is the R spdep package for modeling spatially correlated outcomes, but there are some examples of analysis of spatial hierachical data with WinBUGS on the BUGS Project. References Browne, W.J., Goldstein, H. and Rasbash, J. (2001) Multiple membership multiple classification (MMMC) models. Statistical Modelling, 1, 103-124. Lichstein, JW, Simons, TR, Shriner, SA, and Franzreb, KE (2002). Spatial autocorrelation and autoregressive models in ecology. Ecological Monographs, 72(3), 445-463. Feldkircher, M (2007). A Spatial CAR Model applied to a Cross-Country Growth Regression. Lawson, AB, Browne, WJ, and Vidal Rodeiro, CL (2003). Disease mapping with WinBUGS and MLwiN. John Wiley & Sons.
Regression analysis and parameter estimates with populations
What you describe seems to refer to a particular case of multilevel modeling, where data are organized into a hierarchical structure; in your case, forests (1st level unit) nested in counties nested i
Regression analysis and parameter estimates with populations What you describe seems to refer to a particular case of multilevel modeling, where data are organized into a hierarchical structure; in your case, forests (1st level unit) nested in counties nested in states, but see Under what conditions should one use multilevel/hierarchical analysis?. Now, the "particular" case comes from the fact that you want to account for the spatial proximity which might be a vector for the propagation of Lyme disease (correct me if I am wrong), as is done in epidemiology where one is interested in studying the geography of infectious disease. In the usual case, we can use so-called spatial models like the multiple membership model or the conditional autoregressive model, among others. I enclose a couple of references about these approaches at the end, but I think you will find more references by looking at related studies in ecology or epidemiology. Now, I think that you may pay a particular attention at the following paper of Langford et al. which features multilevel modeling with spatially correlated data: Langford, IH, Leyland, AHL, Rasbash, and Goldstein, H (1999). Multilevel modelling of the geographical distributions of diseases. Journal of Royal Statistical Society C, 48, 253-268. Harvey Goldstein is the author of an excellent book on multilevel modeling, Multilevel Statistical Models (the 2nd edition is available for free). Finally, the book of Andrew Gelman, Data Analysis Using Regression and Multilevel/Hierarchical Models, may provide additional clues about hierarchical/multilevel modeling. About software, I know there is the R spdep package for modeling spatially correlated outcomes, but there are some examples of analysis of spatial hierachical data with WinBUGS on the BUGS Project. References Browne, W.J., Goldstein, H. and Rasbash, J. (2001) Multiple membership multiple classification (MMMC) models. Statistical Modelling, 1, 103-124. Lichstein, JW, Simons, TR, Shriner, SA, and Franzreb, KE (2002). Spatial autocorrelation and autoregressive models in ecology. Ecological Monographs, 72(3), 445-463. Feldkircher, M (2007). A Spatial CAR Model applied to a Cross-Country Growth Regression. Lawson, AB, Browne, WJ, and Vidal Rodeiro, CL (2003). Disease mapping with WinBUGS and MLwiN. John Wiley & Sons.
Regression analysis and parameter estimates with populations What you describe seems to refer to a particular case of multilevel modeling, where data are organized into a hierarchical structure; in your case, forests (1st level unit) nested in counties nested i
40,904
Regression analysis and parameter estimates with populations
I work in a related area using what is called the Population Approach, in pharmacometrics. Basically you have a sample of individuals from the general population, and a moderate-size sample of observations of each individual, plus demographic covariates for these individuals. To model them, we want to make levels of model. We want to make an overall model that applies to the individuals that we hope will be representative of the entire population. The parameters of this overall model are called "fixed effects". Below that level, we have a model of each individual, because we expect individuals to differ from each other. So we have additional parameters that are different for each individual, and these are called "random effects". A key part to be estimated in the overall model is a measure of the variability of the random effects. I.e. we know the individuals will differ, but we want to model that variability. A further level of modeling is the variability of individual observations. Applying this to your field is not something I fully understand, but I would recommend WinBugs as a modeling tool, and a book "Markov Chain Monte Carlo in Practice" by Gilks, Richardson, and Spiegelhalter. There are example problems in there that look like they might be applicable to your problem.
Regression analysis and parameter estimates with populations
I work in a related area using what is called the Population Approach, in pharmacometrics. Basically you have a sample of individuals from the general population, and a moderate-size sample of observa
Regression analysis and parameter estimates with populations I work in a related area using what is called the Population Approach, in pharmacometrics. Basically you have a sample of individuals from the general population, and a moderate-size sample of observations of each individual, plus demographic covariates for these individuals. To model them, we want to make levels of model. We want to make an overall model that applies to the individuals that we hope will be representative of the entire population. The parameters of this overall model are called "fixed effects". Below that level, we have a model of each individual, because we expect individuals to differ from each other. So we have additional parameters that are different for each individual, and these are called "random effects". A key part to be estimated in the overall model is a measure of the variability of the random effects. I.e. we know the individuals will differ, but we want to model that variability. A further level of modeling is the variability of individual observations. Applying this to your field is not something I fully understand, but I would recommend WinBugs as a modeling tool, and a book "Markov Chain Monte Carlo in Practice" by Gilks, Richardson, and Spiegelhalter. There are example problems in there that look like they might be applicable to your problem.
Regression analysis and parameter estimates with populations I work in a related area using what is called the Population Approach, in pharmacometrics. Basically you have a sample of individuals from the general population, and a moderate-size sample of observa
40,905
Jaynes' Description of Maximum Entropy Distribution
Jaynes' reasoning here is essentially Bayesian, where the probability is a measure of uncertainty of our knowledge about something. This is opposed to frequentist reasoning, which is based on the assumption that one could potentially know the whole population, its parameters, and the underlying probability distribution (such knowledge is often impossible - e.g., the population can be infinite, or we might be dealing with a series events that may continue far into the future - like sunrise.) Thus, Jaynes bases his reasoning on the knowledge available to him (such as sample average $\bar{m}$), but does not make assumptions about what the "true" population average $\mu$ is or whether such a population average even exists.
Jaynes' Description of Maximum Entropy Distribution
Jaynes' reasoning here is essentially Bayesian, where the probability is a measure of uncertainty of our knowledge about something. This is opposed to frequentist reasoning, which is based on the assu
Jaynes' Description of Maximum Entropy Distribution Jaynes' reasoning here is essentially Bayesian, where the probability is a measure of uncertainty of our knowledge about something. This is opposed to frequentist reasoning, which is based on the assumption that one could potentially know the whole population, its parameters, and the underlying probability distribution (such knowledge is often impossible - e.g., the population can be infinite, or we might be dealing with a series events that may continue far into the future - like sunrise.) Thus, Jaynes bases his reasoning on the knowledge available to him (such as sample average $\bar{m}$), but does not make assumptions about what the "true" population average $\mu$ is or whether such a population average even exists.
Jaynes' Description of Maximum Entropy Distribution Jaynes' reasoning here is essentially Bayesian, where the probability is a measure of uncertainty of our knowledge about something. This is opposed to frequentist reasoning, which is based on the assu
40,906
Jaynes' Description of Maximum Entropy Distribution
Jaynes reasons that, given only this information, the most reasonable way to assign these probabilities is to choose the most uncertain probability distribution that satisfies all the requirements (i.e. observations, in this case the sample mean). Now, this is quite arbitrary, but I accept it as an intuitively compelling method. You say that you accept this method, but then you immediately reject it in the next paragraph. Of course it is true that the expected value of the probability distribution need not match the sample mean, but the whole content of the method just described (which you at first say you accept) is that he is matching the distribution moments to the sample moments in his constraints and then seeking the most uncertain distribution under those constraints. If you don't use this moment constraint, and just use a uniform distribution, then you are not using the method he just described. What is it about his method that you imagine you accept if not that?
Jaynes' Description of Maximum Entropy Distribution
Jaynes reasons that, given only this information, the most reasonable way to assign these probabilities is to choose the most uncertain probability distribution that satisfies all the requirements (i.
Jaynes' Description of Maximum Entropy Distribution Jaynes reasons that, given only this information, the most reasonable way to assign these probabilities is to choose the most uncertain probability distribution that satisfies all the requirements (i.e. observations, in this case the sample mean). Now, this is quite arbitrary, but I accept it as an intuitively compelling method. You say that you accept this method, but then you immediately reject it in the next paragraph. Of course it is true that the expected value of the probability distribution need not match the sample mean, but the whole content of the method just described (which you at first say you accept) is that he is matching the distribution moments to the sample moments in his constraints and then seeking the most uncertain distribution under those constraints. If you don't use this moment constraint, and just use a uniform distribution, then you are not using the method he just described. What is it about his method that you imagine you accept if not that?
Jaynes' Description of Maximum Entropy Distribution Jaynes reasons that, given only this information, the most reasonable way to assign these probabilities is to choose the most uncertain probability distribution that satisfies all the requirements (i.
40,907
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)?
The first issue you have here is that your likelihood function does not appear to match the description of your sampling mechanism. You say that you only observe events 1 and 2 happen, but if the sample size $n$ is known then this still fixes the number of times that event 3 happens (since $m_1 + m_2 + m_3 = n$). Taking an observation $\mathbf{m} \sim \text{Mu}(n, \mathbf{p})$ gives the likelihood function: $$L_\mathbf{m}(\theta) = \bigg( \frac{1}{2} \sin^2 (\theta) \bigg)^{m_1 + m_2} \bigg( \cos^2 (\theta) \bigg)^{n - m_1 - m_2},$$ which gives the log-likelihood: $$\ell_\mathbf{m}(\theta) = \text{const} + (m_1 + m_2) \log (\sin^2 (\theta)) + (n - m_1 - m_2) \log (\cos^2 (\theta)).$$ As you can see, the likelihood function has an extra term that you have not included in your question. We can see that $M_* = M_1+M_2 \sim \text{Bin}(n, \sin^2 (\theta))$ is a sufficient statistic in this problem so the problem is essentially one of binomial inference with a transformed probability parameter. With a bit of calculus it can be shown that the MLE solves: $$\sin^2 (\hat{\theta}) = \frac{m_1 + m_2}{n} \quad \quad \quad \implies \quad \quad \quad \hat{\theta} = \text{arcsin} \bigg( \sqrt{\frac{m_1 + m_2}{n}} \bigg).$$ This estimator for the parameter is generally biased (it is unbiased in the case where $\sin^2 (\theta) = \tfrac{1}{2}$) so the applicable version of the Cramér–Rao lower bound in this case is the generalisation for biased estimators: $$\mathbb{V}(\hat{\theta}) \geqslant \frac{|\psi'(\theta)|}{I(\theta)} \quad \quad \quad \quad \quad \psi(\theta) \equiv \mathbb{E}(\hat{\theta}).$$ The expectation function is: $$\begin{align} \psi(\theta) &= \sum_{m=0}^n \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \cdot \text{Bin} (m|n,\sin^2 (\theta)) \\[6pt] &= \sum_{m=0}^n {n \choose m} \cdot \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \cdot \sin^{2m} (\theta) \cdot \cos^{2(n-m)} (\theta). \\[6pt] &= \frac{\pi}{2} \cdot \sin^{2n} (\theta) - \frac{\pi}{2} \cdot \cos^{2n} (\theta) + \sum_{m=1}^{n-1} {n \choose m} \cdot \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \cdot \sin^{2m} (\theta) \cdot \cos^{2(n-m)} (\theta), \\[6pt] \end{align}$$ and its derivative (which appears in the bound) is: $$\begin{align} \psi'(\theta) &= \sum_{m=0}^n {n \choose m} \cdot \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \frac{d}{d\theta} \bigg[ \sin^{2m} (\theta) \cdot \cos^{2(n-m)} (\theta) \bigg] \\[6pt] &= n\pi \cdot \sin(\theta) \cos(\theta) [\sin^{2(n-1)} (\theta) + \cos^{2(n-1)} (\theta)] \\[6pt] &\quad + \sum_{m=1}^{n-1} {n \choose m} \cdot \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \sin^{2m-1} (\theta) \cos^{2(n-m)-1} (\theta) \\[6pt] &\quad \quad \quad \quad \quad \times \bigg[ 2m \cos^2 (\theta) - 2(n-m) \sin^2 (\theta) \bigg]. \\[6pt] &= n\pi \cdot \sin(\theta) \cos(\theta) [\sin^{2(n-1)} (\theta) + \cos^{2(n-1)} (\theta)] \\[6pt] &\quad + 2 \sum_{m=1}^{n-1} {n \choose m} \cdot \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \sin^{2m-1} (\theta) \cos^{2(n-m)-1} (\theta) (m - n \sin^2 (\theta)). \\[6pt] \end{align}$$ As you can see, this is a more complicated form for the Cramér–Rao lower bound. Nevertheless, it should hold in this problem.
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)
The first issue you have here is that your likelihood function does not appear to match the description of your sampling mechanism. You say that you only observe events 1 and 2 happen, but if the sam
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)? The first issue you have here is that your likelihood function does not appear to match the description of your sampling mechanism. You say that you only observe events 1 and 2 happen, but if the sample size $n$ is known then this still fixes the number of times that event 3 happens (since $m_1 + m_2 + m_3 = n$). Taking an observation $\mathbf{m} \sim \text{Mu}(n, \mathbf{p})$ gives the likelihood function: $$L_\mathbf{m}(\theta) = \bigg( \frac{1}{2} \sin^2 (\theta) \bigg)^{m_1 + m_2} \bigg( \cos^2 (\theta) \bigg)^{n - m_1 - m_2},$$ which gives the log-likelihood: $$\ell_\mathbf{m}(\theta) = \text{const} + (m_1 + m_2) \log (\sin^2 (\theta)) + (n - m_1 - m_2) \log (\cos^2 (\theta)).$$ As you can see, the likelihood function has an extra term that you have not included in your question. We can see that $M_* = M_1+M_2 \sim \text{Bin}(n, \sin^2 (\theta))$ is a sufficient statistic in this problem so the problem is essentially one of binomial inference with a transformed probability parameter. With a bit of calculus it can be shown that the MLE solves: $$\sin^2 (\hat{\theta}) = \frac{m_1 + m_2}{n} \quad \quad \quad \implies \quad \quad \quad \hat{\theta} = \text{arcsin} \bigg( \sqrt{\frac{m_1 + m_2}{n}} \bigg).$$ This estimator for the parameter is generally biased (it is unbiased in the case where $\sin^2 (\theta) = \tfrac{1}{2}$) so the applicable version of the Cramér–Rao lower bound in this case is the generalisation for biased estimators: $$\mathbb{V}(\hat{\theta}) \geqslant \frac{|\psi'(\theta)|}{I(\theta)} \quad \quad \quad \quad \quad \psi(\theta) \equiv \mathbb{E}(\hat{\theta}).$$ The expectation function is: $$\begin{align} \psi(\theta) &= \sum_{m=0}^n \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \cdot \text{Bin} (m|n,\sin^2 (\theta)) \\[6pt] &= \sum_{m=0}^n {n \choose m} \cdot \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \cdot \sin^{2m} (\theta) \cdot \cos^{2(n-m)} (\theta). \\[6pt] &= \frac{\pi}{2} \cdot \sin^{2n} (\theta) - \frac{\pi}{2} \cdot \cos^{2n} (\theta) + \sum_{m=1}^{n-1} {n \choose m} \cdot \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \cdot \sin^{2m} (\theta) \cdot \cos^{2(n-m)} (\theta), \\[6pt] \end{align}$$ and its derivative (which appears in the bound) is: $$\begin{align} \psi'(\theta) &= \sum_{m=0}^n {n \choose m} \cdot \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \frac{d}{d\theta} \bigg[ \sin^{2m} (\theta) \cdot \cos^{2(n-m)} (\theta) \bigg] \\[6pt] &= n\pi \cdot \sin(\theta) \cos(\theta) [\sin^{2(n-1)} (\theta) + \cos^{2(n-1)} (\theta)] \\[6pt] &\quad + \sum_{m=1}^{n-1} {n \choose m} \cdot \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \sin^{2m-1} (\theta) \cos^{2(n-m)-1} (\theta) \\[6pt] &\quad \quad \quad \quad \quad \times \bigg[ 2m \cos^2 (\theta) - 2(n-m) \sin^2 (\theta) \bigg]. \\[6pt] &= n\pi \cdot \sin(\theta) \cos(\theta) [\sin^{2(n-1)} (\theta) + \cos^{2(n-1)} (\theta)] \\[6pt] &\quad + 2 \sum_{m=1}^{n-1} {n \choose m} \cdot \text{arcsin} \bigg( \sqrt{\frac{m}{n}} \bigg) \sin^{2m-1} (\theta) \cos^{2(n-m)-1} (\theta) (m - n \sin^2 (\theta)). \\[6pt] \end{align}$$ As you can see, this is a more complicated form for the Cramér–Rao lower bound. Nevertheless, it should hold in this problem.
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB) The first issue you have here is that your likelihood function does not appear to match the description of your sampling mechanism. You say that you only observe events 1 and 2 happen, but if the sam
40,908
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)?
Variance of your MLE estimator should be computed while still considering the results to be random, i.e.: $$ \hat{\theta} = \mathrm{arg} \underset{\theta}{\max}\left[ \frac{1}{2}\sin ^2\theta \right] ^{m_1}\left[ \frac{1}{2}\sin ^2\theta \right] ^{m_2} \left[ \cos ^2\theta \right] ^{m_3} $$ $$ Var(\hat{\theta}) = Var \left( \mathrm{arg} \underset{\theta}{\max}\left[ \frac{1}{2}\sin ^2\theta \right] ^{m_1}\left[ \frac{1}{2}\sin ^2\theta \right] ^{m_2} \left[ \cos ^2\theta \right] ^{m_3} \right) = \dots $$ where $m_3$ is the number of observation of the event 3. You can't just rule out $\left[ \cos ^2\theta \right] ^{m_3}$ just because you didn't observe the event 3 after the experiment. If you don't know the value of $\theta$, you must consider the possibility of event 3 happening. Even if after doing $n$ experiments you would observe some events 3, i.e. $m_3 > 0$, the evaluation of the $\mathrm{arg}\max$ above would be a constant (if $m_1$, $m_2$, $m_3$ are some constant numbers). That would not mean the variance of the estimator is $0$ - we just evaluated the estimate accoring to results of experimenting, there is no randomness in it. What is the variance of the estimator $\hat{\theta}$ of the random variable $\theta$? To compute it, you'd need some assumption about $\theta$ (e.g. which distribution does it come from?). However, what you know by the Cramer-Rao theorem, is that the variance will be higher or equal than $1/4$.
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)
Variance of your MLE estimator should be computed while still considering the results to be random, i.e.: $$ \hat{\theta} = \mathrm{arg} \underset{\theta}{\max}\left[ \frac{1}{2}\sin ^2\theta \right]
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)? Variance of your MLE estimator should be computed while still considering the results to be random, i.e.: $$ \hat{\theta} = \mathrm{arg} \underset{\theta}{\max}\left[ \frac{1}{2}\sin ^2\theta \right] ^{m_1}\left[ \frac{1}{2}\sin ^2\theta \right] ^{m_2} \left[ \cos ^2\theta \right] ^{m_3} $$ $$ Var(\hat{\theta}) = Var \left( \mathrm{arg} \underset{\theta}{\max}\left[ \frac{1}{2}\sin ^2\theta \right] ^{m_1}\left[ \frac{1}{2}\sin ^2\theta \right] ^{m_2} \left[ \cos ^2\theta \right] ^{m_3} \right) = \dots $$ where $m_3$ is the number of observation of the event 3. You can't just rule out $\left[ \cos ^2\theta \right] ^{m_3}$ just because you didn't observe the event 3 after the experiment. If you don't know the value of $\theta$, you must consider the possibility of event 3 happening. Even if after doing $n$ experiments you would observe some events 3, i.e. $m_3 > 0$, the evaluation of the $\mathrm{arg}\max$ above would be a constant (if $m_1$, $m_2$, $m_3$ are some constant numbers). That would not mean the variance of the estimator is $0$ - we just evaluated the estimate accoring to results of experimenting, there is no randomness in it. What is the variance of the estimator $\hat{\theta}$ of the random variable $\theta$? To compute it, you'd need some assumption about $\theta$ (e.g. which distribution does it come from?). However, what you know by the Cramer-Rao theorem, is that the variance will be higher or equal than $1/4$.
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB) Variance of your MLE estimator should be computed while still considering the results to be random, i.e.: $$ \hat{\theta} = \mathrm{arg} \underset{\theta}{\max}\left[ \frac{1}{2}\sin ^2\theta \right]
40,909
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)?
Starting from the definition of the Cramer-Rao Lower bound from here. Suppose $\theta$ is an unknown deterministic parameter which is to be estimated from $n$ independent observations (measurements) of $x$, each from a distribution according to some probability density function $f(x;\theta )$. The variance of any unbiased estimator $\hat{\theta}$ of $\theta$ is then bounded by the reciprocal of the Fisher information $I(\theta )$: $$\operatorname{var}\left(\hat {\theta }\right)\geq {\frac {1}{I(\theta )}}.$$ Deriving the Maximum Likelihood Estimator proceeds as the original poster suggested taking derivative w.r.t. $\theta$ and set derivative to be zero we will get $$2\left( m_1+m_2 \right) \frac{\cos \hat{\theta}}{\sin \hat{\theta}}=2(n-m_1-m_2)\frac{\sin \hat{\theta}}{\cos \hat{\theta}}.$$ Re-arranging gives us $$\hat{\theta} = \tan^{-1} \sqrt{\frac{m_1+m_2}{n-m_1+m_2}}.$$ Although the proof is not straightforward, I have verified this with simulations, and it comes as no surprise based on the functional form of the estimator: $$\operatorname{E}\left(\hat{\theta}\right) \neq \theta.$$ The MLE for $\theta$ is biased. Therefore, the standard Cramer-Rao lower bound does not hold. There is a generalized lower bound for biased estimators, but I did not compute it. The full equation is: $$\operatorname{E}\left(\hat{\theta}\right) = \sum_{m_1 = 0}^{n-1} \sum_{m_2 = 0}^{n-m_1-1} \tan^{-1} \sqrt{\frac{m_1+m_2}{n-m_1+m_2}} {n\choose m_1}p_1^{m_1} (1-p_1)^{n-m_1} {n\choose m_2}p_2^{m_2} (1-p_2)^{n-m_2}$$ where $p_1 = p_2 = \frac{1}{2}\sin^2\theta$ and $m_1$ and $m_2$ are independent. $m_1 = \sum x_{1,i}$ and $m_2 = \sum x_{2,i}$ and $x_1, x_2, x_3 \sim Multinomial(\frac{1}{2}\sin^2\theta, \frac{1}{2}\sin^2\theta, cos^2\theta)$ The Variance can be calculated similarly: $$\operatorname{Var}\left(\hat{\theta}\right) = \operatorname{E}\left(\hat{\theta}^2\right) - \left[\operatorname{E}\left(\hat{\theta}\right)\right]^2.$$ MLE of $\theta$ is consistent As a side note, the MLE is consistent. As $n \rightarrow \infty,~~\operatorname{E}\left(\hat{\theta}\right) \rightarrow \theta.$ Although not a formal proof, you can guess that as $n \rightarrow \infty,$ $$m_1 \rightarrow np_1 = n\left(\frac{1}{2}\right)\sin^2\theta$$ $$m_2 \rightarrow n\left(\frac{1}{2}\right)\sin^2\theta$$ $$n-m_1-m_2 \rightarrow n\cos^2\theta$$ $$E\left(\hat{\theta}\right) \rightarrow \tan^{-1} \sqrt{\frac{\frac{n}{2}\sin^2\theta + \frac{n}{2}\sin^2\theta}{n\cos^2\theta}} = \theta.$$ A note on $\pi / 2$ As the original poster noted, if $\theta = \pi / 2$, then $m_3 = n - m_1 - m_2= 0$ because $\frac{1}{2} \sin^2 \theta = \frac{1}{2}$ and $\cos^2 \theta = 0.$ The estimator $\hat {\theta}$ is undefined for $\theta = \pi / 2.$ R Code Here is R code to show how to calculate $\operatorname{E}\left(\hat{\theta}\right)$ and $\operatorname{V}\left(\hat{\theta}\right)$ > theta <- pi / 4 > n <- 10 > e_theta_hat <- 0 > e_theta_hat_square <- 0 > for (m1 in 0:(n-1)) + { + for (m2 in 0:(n-m1-1)) + { + e_theta_hat <- e_theta_hat + atan(sqrt((m1+m2)/(n-m1-m2)))*dbinom(m1, n, 0.5*(sin(theta))^2)*dbinom(m2, n, 0.5*(sin(theta))^2) + e_theta_hat_square <- e_theta_hat_square + (atan(sqrt((m1+m2)/(n-m1-m2))))^2*dbinom(m1, n, 0.5*(sin(theta))^2)*dbinom(m2, n, 0.5*(sin(theta))^2) + } + } > e_theta_hat [1] 0.7662692 > theta [1] 0.7853982 > > e_theta_hat_square - (e_theta_hat)^2 [1] 0.04779768 > theta <- pi / 4 > n <- 1000 > e_theta_hat <- 0 > e_theta_hat_square <- 0 > for (m1 in 0:(n-1)) + { + for (m2 in 0:(n-m1-1)) + { + e_theta_hat <- e_theta_hat + atan(sqrt((m1+m2)/(n-m1-m2)))*dbinom(m1, n, 0.5*(sin(theta))^2)*dbinom(m2, n, 0.5*(sin(theta))^2) + e_theta_hat_square <- e_theta_hat_square + (atan(sqrt((m1+m2)/(n-m1-m2))))^2*dbinom(m1, n, 0.5*(sin(theta))^2)*dbinom(m2, n, 0.5*(sin(theta))^2) + } + } > e_theta_hat [1] 0.7853983 > theta [1] 0.7853982 > > e_theta_hat_square - (e_theta_hat)^2 [1] 0.0003755647 >
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)
Starting from the definition of the Cramer-Rao Lower bound from here. Suppose $\theta$ is an unknown deterministic parameter which is to be estimated from $n$ independent observations (measurements)
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)? Starting from the definition of the Cramer-Rao Lower bound from here. Suppose $\theta$ is an unknown deterministic parameter which is to be estimated from $n$ independent observations (measurements) of $x$, each from a distribution according to some probability density function $f(x;\theta )$. The variance of any unbiased estimator $\hat{\theta}$ of $\theta$ is then bounded by the reciprocal of the Fisher information $I(\theta )$: $$\operatorname{var}\left(\hat {\theta }\right)\geq {\frac {1}{I(\theta )}}.$$ Deriving the Maximum Likelihood Estimator proceeds as the original poster suggested taking derivative w.r.t. $\theta$ and set derivative to be zero we will get $$2\left( m_1+m_2 \right) \frac{\cos \hat{\theta}}{\sin \hat{\theta}}=2(n-m_1-m_2)\frac{\sin \hat{\theta}}{\cos \hat{\theta}}.$$ Re-arranging gives us $$\hat{\theta} = \tan^{-1} \sqrt{\frac{m_1+m_2}{n-m_1+m_2}}.$$ Although the proof is not straightforward, I have verified this with simulations, and it comes as no surprise based on the functional form of the estimator: $$\operatorname{E}\left(\hat{\theta}\right) \neq \theta.$$ The MLE for $\theta$ is biased. Therefore, the standard Cramer-Rao lower bound does not hold. There is a generalized lower bound for biased estimators, but I did not compute it. The full equation is: $$\operatorname{E}\left(\hat{\theta}\right) = \sum_{m_1 = 0}^{n-1} \sum_{m_2 = 0}^{n-m_1-1} \tan^{-1} \sqrt{\frac{m_1+m_2}{n-m_1+m_2}} {n\choose m_1}p_1^{m_1} (1-p_1)^{n-m_1} {n\choose m_2}p_2^{m_2} (1-p_2)^{n-m_2}$$ where $p_1 = p_2 = \frac{1}{2}\sin^2\theta$ and $m_1$ and $m_2$ are independent. $m_1 = \sum x_{1,i}$ and $m_2 = \sum x_{2,i}$ and $x_1, x_2, x_3 \sim Multinomial(\frac{1}{2}\sin^2\theta, \frac{1}{2}\sin^2\theta, cos^2\theta)$ The Variance can be calculated similarly: $$\operatorname{Var}\left(\hat{\theta}\right) = \operatorname{E}\left(\hat{\theta}^2\right) - \left[\operatorname{E}\left(\hat{\theta}\right)\right]^2.$$ MLE of $\theta$ is consistent As a side note, the MLE is consistent. As $n \rightarrow \infty,~~\operatorname{E}\left(\hat{\theta}\right) \rightarrow \theta.$ Although not a formal proof, you can guess that as $n \rightarrow \infty,$ $$m_1 \rightarrow np_1 = n\left(\frac{1}{2}\right)\sin^2\theta$$ $$m_2 \rightarrow n\left(\frac{1}{2}\right)\sin^2\theta$$ $$n-m_1-m_2 \rightarrow n\cos^2\theta$$ $$E\left(\hat{\theta}\right) \rightarrow \tan^{-1} \sqrt{\frac{\frac{n}{2}\sin^2\theta + \frac{n}{2}\sin^2\theta}{n\cos^2\theta}} = \theta.$$ A note on $\pi / 2$ As the original poster noted, if $\theta = \pi / 2$, then $m_3 = n - m_1 - m_2= 0$ because $\frac{1}{2} \sin^2 \theta = \frac{1}{2}$ and $\cos^2 \theta = 0.$ The estimator $\hat {\theta}$ is undefined for $\theta = \pi / 2.$ R Code Here is R code to show how to calculate $\operatorname{E}\left(\hat{\theta}\right)$ and $\operatorname{V}\left(\hat{\theta}\right)$ > theta <- pi / 4 > n <- 10 > e_theta_hat <- 0 > e_theta_hat_square <- 0 > for (m1 in 0:(n-1)) + { + for (m2 in 0:(n-m1-1)) + { + e_theta_hat <- e_theta_hat + atan(sqrt((m1+m2)/(n-m1-m2)))*dbinom(m1, n, 0.5*(sin(theta))^2)*dbinom(m2, n, 0.5*(sin(theta))^2) + e_theta_hat_square <- e_theta_hat_square + (atan(sqrt((m1+m2)/(n-m1-m2))))^2*dbinom(m1, n, 0.5*(sin(theta))^2)*dbinom(m2, n, 0.5*(sin(theta))^2) + } + } > e_theta_hat [1] 0.7662692 > theta [1] 0.7853982 > > e_theta_hat_square - (e_theta_hat)^2 [1] 0.04779768 > theta <- pi / 4 > n <- 1000 > e_theta_hat <- 0 > e_theta_hat_square <- 0 > for (m1 in 0:(n-1)) + { + for (m2 in 0:(n-m1-1)) + { + e_theta_hat <- e_theta_hat + atan(sqrt((m1+m2)/(n-m1-m2)))*dbinom(m1, n, 0.5*(sin(theta))^2)*dbinom(m2, n, 0.5*(sin(theta))^2) + e_theta_hat_square <- e_theta_hat_square + (atan(sqrt((m1+m2)/(n-m1-m2))))^2*dbinom(m1, n, 0.5*(sin(theta))^2)*dbinom(m2, n, 0.5*(sin(theta))^2) + } + } > e_theta_hat [1] 0.7853983 > theta [1] 0.7853982 > > e_theta_hat_square - (e_theta_hat)^2 [1] 0.0003755647 >
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB) Starting from the definition of the Cramer-Rao Lower bound from here. Suppose $\theta$ is an unknown deterministic parameter which is to be estimated from $n$ independent observations (measurements)
40,910
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)?
TLDR This factor 1/4 is a correct result. The asymptotic variance of the estimator $\sin^2 \theta$ is equal to the factor 1/4n. (and for smaller sample sizes you need to use the bound that is based on a non-zero bias) R-code demonstration set.seed(1) n = 200 p = rbinom(10^6,n,0.25)/n t = asin(sqrt(p)) var(t)*n ### 0.2518232 ~ 1/4 var(p)*n ### 0.1873885 ~ 3/8 The problem occurs when $\sin^2 \theta = 0$ or $\sin^2 \theta = 1$ as in your example case. The relationship with the Cramer-Rao bound breaks down because the information is infinite for $p=0$ or $p=1$ and it becomes undefined in the case of the parameterization $p = \sin(\theta)^2$, which has an infinite derivative and results in an undefined division of zero by zero. Derivation of information for simpler case To make the equations easier I am gonna use only two states instead of three. $p_1 = f(\theta)$ and $p_2 = 1-f(\theta)$ You apply the formula $$\mathcal{I}(\theta) = \sum_x{{ \overbrace{\left[ \frac{\frac{\partial}{\partial \theta} p\left( x;\theta \right) }{p\left( x;\theta \right) }\right] ^2}^{{logL^\prime}^2}}{p\left( x;\theta \right)}} \qquad \tag{1} $$ This derivative of the log likelihood is: $$logL^\prime = \frac{ m_1 f^\prime(\theta) - m_2 f^\prime(\theta)}{m_1 f(\theta) + m_2 (1-f(\theta))}$$ The probability is $$p(x;\theta) = f(\theta)^{m_1} (1-f(\theta))^{m_2}$$ And if we restrict to a single observation $m_1 = 1, m_2 = 0$ or $m_1 = 0, m_2 = 1$ then the sum in formula (1) becomes $$\mathcal{I}(\theta) = \frac{f^\prime (\theta)^2}{f(\theta)} + \frac{f^\prime (\theta)^2}{1-f(\theta)} = \frac{f^\prime (\theta)^2}{f(\theta) (1-f(\theta))} $$ then $$\mathcal{I}(\theta)^{-1} = \frac{f(\theta) (1-f(\theta))}{f^\prime (\theta)^2}$$ and with $f(\theta) = \sin^2\theta$ this becomes the same as your result $$\mathcal{I}(\theta)^{-1} = \frac{ \sin^2\theta \cos^2\theta}{(2 \cos\theta \sin\theta )^2} = \frac{1}{4}$$ But with $f(\theta) = \theta$ then you get $$\mathcal{I}(\theta)^{-1} = \theta(1-\theta)$$ like in this question https://math.stackexchange.com/questions/396982/fisher-information-of-a-binomial-distribution The two are related by the factor $$\left(\frac{\text{d} \theta}{\text{d} p}\right)^2 = \left(\frac{\text{d}\, \text{sin}^{-1}(p^{0.5})}{\text{d} p}\right)^2 = \frac{1}{4(1-p)p}$$.
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)
TLDR This factor 1/4 is a correct result. The asymptotic variance of the estimator $\sin^2 \theta$ is equal to the factor 1/4n. (and for smaller sample sizes you need to use the bound that is based on
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB)? TLDR This factor 1/4 is a correct result. The asymptotic variance of the estimator $\sin^2 \theta$ is equal to the factor 1/4n. (and for smaller sample sizes you need to use the bound that is based on a non-zero bias) R-code demonstration set.seed(1) n = 200 p = rbinom(10^6,n,0.25)/n t = asin(sqrt(p)) var(t)*n ### 0.2518232 ~ 1/4 var(p)*n ### 0.1873885 ~ 3/8 The problem occurs when $\sin^2 \theta = 0$ or $\sin^2 \theta = 1$ as in your example case. The relationship with the Cramer-Rao bound breaks down because the information is infinite for $p=0$ or $p=1$ and it becomes undefined in the case of the parameterization $p = \sin(\theta)^2$, which has an infinite derivative and results in an undefined division of zero by zero. Derivation of information for simpler case To make the equations easier I am gonna use only two states instead of three. $p_1 = f(\theta)$ and $p_2 = 1-f(\theta)$ You apply the formula $$\mathcal{I}(\theta) = \sum_x{{ \overbrace{\left[ \frac{\frac{\partial}{\partial \theta} p\left( x;\theta \right) }{p\left( x;\theta \right) }\right] ^2}^{{logL^\prime}^2}}{p\left( x;\theta \right)}} \qquad \tag{1} $$ This derivative of the log likelihood is: $$logL^\prime = \frac{ m_1 f^\prime(\theta) - m_2 f^\prime(\theta)}{m_1 f(\theta) + m_2 (1-f(\theta))}$$ The probability is $$p(x;\theta) = f(\theta)^{m_1} (1-f(\theta))^{m_2}$$ And if we restrict to a single observation $m_1 = 1, m_2 = 0$ or $m_1 = 0, m_2 = 1$ then the sum in formula (1) becomes $$\mathcal{I}(\theta) = \frac{f^\prime (\theta)^2}{f(\theta)} + \frac{f^\prime (\theta)^2}{1-f(\theta)} = \frac{f^\prime (\theta)^2}{f(\theta) (1-f(\theta))} $$ then $$\mathcal{I}(\theta)^{-1} = \frac{f(\theta) (1-f(\theta))}{f^\prime (\theta)^2}$$ and with $f(\theta) = \sin^2\theta$ this becomes the same as your result $$\mathcal{I}(\theta)^{-1} = \frac{ \sin^2\theta \cos^2\theta}{(2 \cos\theta \sin\theta )^2} = \frac{1}{4}$$ But with $f(\theta) = \theta$ then you get $$\mathcal{I}(\theta)^{-1} = \theta(1-\theta)$$ like in this question https://math.stackexchange.com/questions/396982/fisher-information-of-a-binomial-distribution The two are related by the factor $$\left(\frac{\text{d} \theta}{\text{d} p}\right)^2 = \left(\frac{\text{d}\, \text{sin}^{-1}(p^{0.5})}{\text{d} p}\right)^2 = \frac{1}{4(1-p)p}$$.
Why the variance of Maximum Likelihood Estimator(MLE) will be less than Cramer-Rao Lower Bound(CRLB) TLDR This factor 1/4 is a correct result. The asymptotic variance of the estimator $\sin^2 \theta$ is equal to the factor 1/4n. (and for smaller sample sizes you need to use the bound that is based on
40,911
General form of the distribution of distances to a fixed point in rectangle
Let the rectangle have dimensions $w \le h.$ Place two of its vertices at $(0,0)$ and $(w,h)$ in a Cartesian coordinate system and let the central point be at $(x,y)$ with $0\le x \le w$ and $0\le y \le h.$ The vertical line through $x$ and the horizontal line through $y$ divide this rectangle into subrectangles of areas $xy,$ $x(h-y),$ $(w-x)y,$ and $(w-x)(h-y).$ The mean distance to $(x,y)$ is the average mean distance within each of these subrectangles, weighted by their relative areas. Scale everything by a factor of $1/w$ to make the rectangle of unit width: the answer will be multiplied by $w$ to account for this scale. That reduces the problem to the case $(x,y)=(0,0)$ and $(w,h) = (1,h).$ The chance that the mean distance is less than any radius $r$ is proportional to the area of the rectangle within the circle of radius $r.$ Here are three typical configurations: If we let $s(x, r)$ be half the area of the segment of a semicircle of radius $r$ above a height of $x \ge 0,$ geometry tells us that when $x \ge r,$ $s(x,r)=0$ and otherwise $$s(x,r) = \frac{1}{2}\left( \theta r^2 - x \sqrt{r^2 - x^2}\right)$$ where $\theta = \arccos(x/r)$ is the angle subtended by the entire segment. There are generally two such half-segments in this figure (one or both of which might be empty), illustrated by the portions of the largest blue circle at the right and above the rectangle. They have areas $s(1,r)$ and $s(h,r),$ respectively. Subtracting them from the area of this quarter circle, $\pi r^2/4,$ yields the area remaining inside the rectangle. Dividing this by the rectangle's area $h$ gives the desired probability, as plotted here. The colors correspond to the regimes illustrated in the previous figure. Thus, the general solution is a mixture of four such distributions weighted by the subrectangle areas. The mean distance, to illustrate, is $$\begin{aligned} &\frac{1}{h}\int_0^h \int_0^1 \sqrt{u^2 + v^2}\,\mathrm d u \mathrm d v \\ &= \frac{d}{3} + \frac{\log(h+d)}{6h} + h^2\left(\frac{\log(h)}{12} - \frac{\log(d-1)}{8} + \frac{\log(d+1)}{24}\right) \end{aligned}$$ where $d = \sqrt{1 + h^2}$ is the diameter of the rectangle. Here is a tested R implementation of the distribution function to a vertex of a rectangle (of unit width and height h). # # Area of half a circular segment in a circle of radius `r` above a height of `h`. # segment <- function(h, r = 1) { ifelse(h >= r, 0, { a <- acos(pmin(1, h / r)) # The included angle (a * r^2 - h * sqrt(pmax(0, r^2 - h^2))) / 2 }) } # # Distance distribution function. # Vectorized over `r`. # ff <- function(r, h) { # Reduce to the case h >= 1. h <- abs(h) if (isTRUE(h < 1)) { r <- r / h^2 h <- 1 / h } # Clamp `r` to the support of the distribution. r <- pmax(0, pmin(sqrt(1 + h^2), r)) # Apply the formula. (pi * r^2 / 4 - segment(1, r) - segment(h, r)) / h } To illustrate the process of computing an area-weighted average, here is an implementation of the mean to any interior location in a rectangle. # # Works *only* for 0 <= x <= w and 0 <= y <= h. # Parallelized. # g <- function(x, y, w, h) { # # The basic formula for integrated distance to the origin. # f <- function(h) { u <- sqrt(1 + h^2) (log(h + u)/(6 * h) + u / 3 + h^2 * (log(h) / 12 - log(u - 1)/8 + log(u + 1)/24)) } # # Mean distance scaled by the rectangle's area. # f2 <- function(h, w = 1) ifelse(h * w > 0, f(h / w) * w^2 * h, 0) # # Area-weighted average of mean distances. # (f2(y, x) + f2(h-y, x) + f2(y, w-x) + f2(h-y, w-x)) / (w * h) } For testing, you may compare its output to a Monte-Carlo simulation: g.sim <- function(x, y, w, h, N = 1e3) { sqrt(colSums((matrix(runif(2 * N, 0, c(w, h)), 2) - c(x, y))^2)) } g.sim returns N distances, which you may use to estimate the entire distribution (compare that to ff) or any of its properties such as the mean distance (compare that to g). The simulation automatically handles the general case where $(x,y)$ is not necessarily in the interior of the rectangle. The formulas for the distribution and its mean can be extended to the general case by expressing the problem as a weighted average where some of the weights (for rectangles outside the original one) are negative. I leave that to the interested reader to devise -- no new ideas or formulas are needed.
General form of the distribution of distances to a fixed point in rectangle
Let the rectangle have dimensions $w \le h.$ Place two of its vertices at $(0,0)$ and $(w,h)$ in a Cartesian coordinate system and let the central point be at $(x,y)$ with $0\le x \le w$ and $0\le y
General form of the distribution of distances to a fixed point in rectangle Let the rectangle have dimensions $w \le h.$ Place two of its vertices at $(0,0)$ and $(w,h)$ in a Cartesian coordinate system and let the central point be at $(x,y)$ with $0\le x \le w$ and $0\le y \le h.$ The vertical line through $x$ and the horizontal line through $y$ divide this rectangle into subrectangles of areas $xy,$ $x(h-y),$ $(w-x)y,$ and $(w-x)(h-y).$ The mean distance to $(x,y)$ is the average mean distance within each of these subrectangles, weighted by their relative areas. Scale everything by a factor of $1/w$ to make the rectangle of unit width: the answer will be multiplied by $w$ to account for this scale. That reduces the problem to the case $(x,y)=(0,0)$ and $(w,h) = (1,h).$ The chance that the mean distance is less than any radius $r$ is proportional to the area of the rectangle within the circle of radius $r.$ Here are three typical configurations: If we let $s(x, r)$ be half the area of the segment of a semicircle of radius $r$ above a height of $x \ge 0,$ geometry tells us that when $x \ge r,$ $s(x,r)=0$ and otherwise $$s(x,r) = \frac{1}{2}\left( \theta r^2 - x \sqrt{r^2 - x^2}\right)$$ where $\theta = \arccos(x/r)$ is the angle subtended by the entire segment. There are generally two such half-segments in this figure (one or both of which might be empty), illustrated by the portions of the largest blue circle at the right and above the rectangle. They have areas $s(1,r)$ and $s(h,r),$ respectively. Subtracting them from the area of this quarter circle, $\pi r^2/4,$ yields the area remaining inside the rectangle. Dividing this by the rectangle's area $h$ gives the desired probability, as plotted here. The colors correspond to the regimes illustrated in the previous figure. Thus, the general solution is a mixture of four such distributions weighted by the subrectangle areas. The mean distance, to illustrate, is $$\begin{aligned} &\frac{1}{h}\int_0^h \int_0^1 \sqrt{u^2 + v^2}\,\mathrm d u \mathrm d v \\ &= \frac{d}{3} + \frac{\log(h+d)}{6h} + h^2\left(\frac{\log(h)}{12} - \frac{\log(d-1)}{8} + \frac{\log(d+1)}{24}\right) \end{aligned}$$ where $d = \sqrt{1 + h^2}$ is the diameter of the rectangle. Here is a tested R implementation of the distribution function to a vertex of a rectangle (of unit width and height h). # # Area of half a circular segment in a circle of radius `r` above a height of `h`. # segment <- function(h, r = 1) { ifelse(h >= r, 0, { a <- acos(pmin(1, h / r)) # The included angle (a * r^2 - h * sqrt(pmax(0, r^2 - h^2))) / 2 }) } # # Distance distribution function. # Vectorized over `r`. # ff <- function(r, h) { # Reduce to the case h >= 1. h <- abs(h) if (isTRUE(h < 1)) { r <- r / h^2 h <- 1 / h } # Clamp `r` to the support of the distribution. r <- pmax(0, pmin(sqrt(1 + h^2), r)) # Apply the formula. (pi * r^2 / 4 - segment(1, r) - segment(h, r)) / h } To illustrate the process of computing an area-weighted average, here is an implementation of the mean to any interior location in a rectangle. # # Works *only* for 0 <= x <= w and 0 <= y <= h. # Parallelized. # g <- function(x, y, w, h) { # # The basic formula for integrated distance to the origin. # f <- function(h) { u <- sqrt(1 + h^2) (log(h + u)/(6 * h) + u / 3 + h^2 * (log(h) / 12 - log(u - 1)/8 + log(u + 1)/24)) } # # Mean distance scaled by the rectangle's area. # f2 <- function(h, w = 1) ifelse(h * w > 0, f(h / w) * w^2 * h, 0) # # Area-weighted average of mean distances. # (f2(y, x) + f2(h-y, x) + f2(y, w-x) + f2(h-y, w-x)) / (w * h) } For testing, you may compare its output to a Monte-Carlo simulation: g.sim <- function(x, y, w, h, N = 1e3) { sqrt(colSums((matrix(runif(2 * N, 0, c(w, h)), 2) - c(x, y))^2)) } g.sim returns N distances, which you may use to estimate the entire distribution (compare that to ff) or any of its properties such as the mean distance (compare that to g). The simulation automatically handles the general case where $(x,y)$ is not necessarily in the interior of the rectangle. The formulas for the distribution and its mean can be extended to the general case by expressing the problem as a weighted average where some of the weights (for rectangles outside the original one) are negative. I leave that to the interested reader to devise -- no new ideas or formulas are needed.
General form of the distribution of distances to a fixed point in rectangle Let the rectangle have dimensions $w \le h.$ Place two of its vertices at $(0,0)$ and $(w,h)$ in a Cartesian coordinate system and let the central point be at $(x,y)$ with $0\le x \le w$ and $0\le y
40,912
What happens when DQN gradients become too big?
It's hard to say for sure, since the slide is so sparse, but I think the implication is that squaring a number with absolute value larger than 1 can become very large very quickly, and likewise the gradients can grow very fast. The author's suggestion of Huber loss makes sense as a remedy to this problem, because you can choose where the loss becomes MAE loss, which does not grow as quickly as a square error loss. Likewise, this suggests that you're correct that the problem isn't exploding gradients. Exploding gradients refers to multiple layers having gradients larger than 1, so the magnitude of the update compounds as the chain rule is applied. Even though the gradient is not exploding, it's still true that gradients can cause instability in training -- large steps in nearly-orthogonal directions can prevent the model from improving, or simply slow improvement.
What happens when DQN gradients become too big?
It's hard to say for sure, since the slide is so sparse, but I think the implication is that squaring a number with absolute value larger than 1 can become very large very quickly, and likewise the gr
What happens when DQN gradients become too big? It's hard to say for sure, since the slide is so sparse, but I think the implication is that squaring a number with absolute value larger than 1 can become very large very quickly, and likewise the gradients can grow very fast. The author's suggestion of Huber loss makes sense as a remedy to this problem, because you can choose where the loss becomes MAE loss, which does not grow as quickly as a square error loss. Likewise, this suggests that you're correct that the problem isn't exploding gradients. Exploding gradients refers to multiple layers having gradients larger than 1, so the magnitude of the update compounds as the chain rule is applied. Even though the gradient is not exploding, it's still true that gradients can cause instability in training -- large steps in nearly-orthogonal directions can prevent the model from improving, or simply slow improvement.
What happens when DQN gradients become too big? It's hard to say for sure, since the slide is so sparse, but I think the implication is that squaring a number with absolute value larger than 1 can become very large very quickly, and likewise the gr
40,913
Test the hypothesis that the performances of k machine learning models on the same test set is the same
Statistical tests, any of them, work on sets of data, not on a single data (for each of the $k$ ML models). Thus, if you compute any measure on the whole test set (let us call them aggregating measures) be it precision, recall, or IoU, you will get a single number for each of the ML algorithms, and there is no statistical test that can receive a single number (for each treatment) and compute a p-value. So, you cannot compute singe measure for each algorithm on the test set. The only set of data that you have is whether, for each data point in the data set, a particular algorithm got the prediction on that data right or wrong. Thus for each algorithm you have a set of binary data (0 or 1, correct or incorrect, and so on) on each of the data points in the test set. These measures are paired, or in the parlance of statistical tests, it is blocked - for the same data point in the test set you have the corresponding binary outcome (right or wrong) for each algorithm. Therefore, you want a test for binary variables (right or wrong), on multiple treatments, and blocked. The only one I know is the Cochran's Q test. The test is distribution free (but I am not sure if it is exact). If the p-value is high enough, you can conclude that all algorithm are equally correct, and thus (I believe) any summary measure, such as precision, recall, accuracy, will be "statistically equivalent" (there is no such a thing, but I think given that the Q test tells you that there is no statistical significant difference among the output of all algorithms I believe one can conclude that there is "no difference" for the aggregating measures). Answering the EDITs: EDIT1: if the output for each data point is a number (for example between 0 and 1 as you suggested but this works for any number) then you are in luck. What you have is a set of numbers and not of 0/1 and there are many more statistical tests for non-binary number data. The usual test in machine learning is the one proposed by Demsar (Statistical Comparisons of Classifiers over Multiple Data Sets) in https://www.jmlr.org/papers/volume7/demsar06a/demsar06a.pdf Remember that in your case the multiple datasets of the paper is the multiple datapoints in your test set. Demsar proposed a Friedman test followed by the Nemenyi test to determine which algorithm is significantly different than the others. Since you are hoping that all algorithms are equivalent, if you are lucky the Friedman test will result in the p-value high enough (be mindful of the caveats listed in the comments for my answer). There are implementations of these tests in both Python and R (at least). Garcia e Herrera ( An Extension on" Statistical Comparisons of Classifiers over Multiple Data Sets" for all Pairwise Comparisons.) https://www.jmlr.org/papers/volume9/garcia08a/garcia08a.pdf proposed other post-hoc tests (beyond the Nemenyi test). EDIT 2: The data used in the tests are i.i.d. The fact that the algorithms are trained on the same set is not a problem. The conclusion will take that into consideration - your conclusion is that the algorithms when trained on the that same training set, and tested on the that same test set are statistically significantly different or are not statistically significantly different. Your conclusions will be for that particular training and test sets. EDIT 3: I don't know about multiple aggregating metrics. But first, you are right that they are likely not i.i.d Second, there will be very few data for the statistical test. Say you will use 5 or 10 aggregating metrics, that will leave you with only 5 or 10 data for each algorithm. With so few data, the statistical tests will not likely find that the differences are significative!
Test the hypothesis that the performances of k machine learning models on the same test set is the s
Statistical tests, any of them, work on sets of data, not on a single data (for each of the $k$ ML models). Thus, if you compute any measure on the whole test set (let us call them aggregating measure
Test the hypothesis that the performances of k machine learning models on the same test set is the same Statistical tests, any of them, work on sets of data, not on a single data (for each of the $k$ ML models). Thus, if you compute any measure on the whole test set (let us call them aggregating measures) be it precision, recall, or IoU, you will get a single number for each of the ML algorithms, and there is no statistical test that can receive a single number (for each treatment) and compute a p-value. So, you cannot compute singe measure for each algorithm on the test set. The only set of data that you have is whether, for each data point in the data set, a particular algorithm got the prediction on that data right or wrong. Thus for each algorithm you have a set of binary data (0 or 1, correct or incorrect, and so on) on each of the data points in the test set. These measures are paired, or in the parlance of statistical tests, it is blocked - for the same data point in the test set you have the corresponding binary outcome (right or wrong) for each algorithm. Therefore, you want a test for binary variables (right or wrong), on multiple treatments, and blocked. The only one I know is the Cochran's Q test. The test is distribution free (but I am not sure if it is exact). If the p-value is high enough, you can conclude that all algorithm are equally correct, and thus (I believe) any summary measure, such as precision, recall, accuracy, will be "statistically equivalent" (there is no such a thing, but I think given that the Q test tells you that there is no statistical significant difference among the output of all algorithms I believe one can conclude that there is "no difference" for the aggregating measures). Answering the EDITs: EDIT1: if the output for each data point is a number (for example between 0 and 1 as you suggested but this works for any number) then you are in luck. What you have is a set of numbers and not of 0/1 and there are many more statistical tests for non-binary number data. The usual test in machine learning is the one proposed by Demsar (Statistical Comparisons of Classifiers over Multiple Data Sets) in https://www.jmlr.org/papers/volume7/demsar06a/demsar06a.pdf Remember that in your case the multiple datasets of the paper is the multiple datapoints in your test set. Demsar proposed a Friedman test followed by the Nemenyi test to determine which algorithm is significantly different than the others. Since you are hoping that all algorithms are equivalent, if you are lucky the Friedman test will result in the p-value high enough (be mindful of the caveats listed in the comments for my answer). There are implementations of these tests in both Python and R (at least). Garcia e Herrera ( An Extension on" Statistical Comparisons of Classifiers over Multiple Data Sets" for all Pairwise Comparisons.) https://www.jmlr.org/papers/volume9/garcia08a/garcia08a.pdf proposed other post-hoc tests (beyond the Nemenyi test). EDIT 2: The data used in the tests are i.i.d. The fact that the algorithms are trained on the same set is not a problem. The conclusion will take that into consideration - your conclusion is that the algorithms when trained on the that same training set, and tested on the that same test set are statistically significantly different or are not statistically significantly different. Your conclusions will be for that particular training and test sets. EDIT 3: I don't know about multiple aggregating metrics. But first, you are right that they are likely not i.i.d Second, there will be very few data for the statistical test. Say you will use 5 or 10 aggregating metrics, that will leave you with only 5 or 10 data for each algorithm. With so few data, the statistical tests will not likely find that the differences are significative!
Test the hypothesis that the performances of k machine learning models on the same test set is the s Statistical tests, any of them, work on sets of data, not on a single data (for each of the $k$ ML models). Thus, if you compute any measure on the whole test set (let us call them aggregating measure
40,914
Test the hypothesis that the performances of k machine learning models on the same test set is the same
Under the assumption that the $k$ ML algorithm performances are "the same", which I will interpret as "independent and identically distributed", on any given test, they are also exchangeable within the test. We can therefore construct a permutation test that preserves potential differences between the tests. Permutation tests are distribution-free, exact, and most powerful conditional upon the data, given the exchangeability of the elements being permuted. They have the additional advantage of allowing any test statistic to be used, as we do not need to be able to calculate the distribution of the statistic under a parametric null hypothesis. Let us assume an appropriate test statistic $T(X)$, where $X$ is the $k \times n$ matrix of the test results. Within each column (test), the observations are assumed exchangeable (across algorithms) under the null hypothesis; we can therefore in principle permute their row (algorithm) indices without changing the distribution of $T$. We should not permute across the columns, as we are not assuming that the test results are exchangeable given a particular algorithm - the test has an influence on the score. A permutation test would calculate all possible combinations of permutations for each test, and for each combination $k$ would calculate the test statistic $T_k$. We would then compare the test statistic $T_0$ as calculated on the observed data with the $T_k$ test statistics calculated on the permuted data, and find a p-value in an obvious way based upon what fraction of the $T_k$ test statistics exceeded $T_0$. As a simple example, we can construct a five-"algorithm" ten-"test" problem, where algorithms 1-4 have the same within-test distributional performances and algorithm 5 is mildly better (in this case, has a smaller result on the test.) The tests themselves are slightly different as well. We construct the matrix so that the test results are in $(0,1)$, close to your problem's results range: X <- matrix(0,5,10) for (test in 1:10) { X[1:4, test] <- rbeta(4, 5-0.2*test, 5+0.2*test) X[5, test] <- rbeta(1, 4-0.2*test, 6+0.2*test) } colnames(X) <- paste("Test", 1:10) rownames(X) <- paste("Algo", c("A","B","C","D","E")) round(X,4) Test 1 Test 2 Test 3 Test 4 Test 5 Test 6 Test 7 Test 8 Test 9 Test 10 Algo A 0.7210 0.3176 0.3773 0.2571 0.3365 0.4364 0.5966 0.2157 0.2142 0.2992 Algo B 0.4153 0.4240 0.4542 0.1841 0.6346 0.4591 0.3750 0.1338 0.5906 0.2124 Algo C 0.7269 0.3499 0.5192 0.6179 0.4444 0.4069 0.2565 0.1840 0.4877 0.2929 Algo D 0.2334 0.8319 0.2045 0.3491 0.2584 0.2575 0.5532 0.3079 0.3876 0.4806 Algo E 0.2510 0.3357 0.3252 0.3784 0.1769 0.1322 0.5008 0.2208 0.3242 0.2482 Now to construct a test statistic. A plausible statistic might involve normalizing each column (as the tests are known to be different,) taking the row means of the normalized observations, and seeing whether some function of the row means, e.g. the minimum, was larger or smaller (whichever is appropriate) than we expect. The construction of a suitable test statistic can be quite important to your overall results, so it is worth spending some time thinking about. The complexity of generating each possible permutation exactly once is too great (for me, in this case), so we will adopt a simpler approach; we will generate many, many permutations of the data instead: X_norm <- X for (test in 1:10) { X_norm[,test] <- X_norm[,test] / mean(X_norm[,test]) } test_statistic <- function(x) min(rowMeans(x)) observed_statistic <- test_statistic(X_norm) permutation_results <- rep(0, 10000) for (i in seq_along(permutation_results)) { for (test in 1:10) { X_norm[, test] <- sample(X_norm[, test]) } permutation_results[i] <- test_statistic(X_norm) } hist(permutation_results) abline(v = observed_statistic) mean(observed_statistic >= permutation_results) [1] 0.0745 We interpret the final number (0.0745) as the (approximate) permutation p-value of the test statistic. We have taken a few shortcuts in the code that do not affect the results, for example, as we are permuting each column's values, we don't need to re-normalize the data at each permutation step (which we would have to do were we, say, sampling from the column with replacement,) and we can just permute the previously-permuted columns without going back to the original data at each permutation step. Note that, in this example, the overall test procedure isn't that powerful in an absolute sense, as we only have a few tests and algorithms, and four of the five algorithms had the same expected performance. (As it happens, in 1,000 repeats of the experiment, we rejected the null hypothesis 35.4% of the time at the 95% level of confidence and 16.6% of the time at the 99% level of confidence.) Your mileage will vary! But the ability to choose a custom test statistic combined with the distribution-free, exact, and most powerful (conditional upon the data) properties of permutation tests make them an extremely useful tool in the applied statistician's toolbox. References for permutation tests aren't as common as one might hope; they are usually discussed as part of more general nonparametric statistics books. Permutation, Parametric, and Bootstrap Tests of Hypotheses by P. Good is my favorite among the more specialized books.
Test the hypothesis that the performances of k machine learning models on the same test set is the s
Under the assumption that the $k$ ML algorithm performances are "the same", which I will interpret as "independent and identically distributed", on any given test, they are also exchangeable within th
Test the hypothesis that the performances of k machine learning models on the same test set is the same Under the assumption that the $k$ ML algorithm performances are "the same", which I will interpret as "independent and identically distributed", on any given test, they are also exchangeable within the test. We can therefore construct a permutation test that preserves potential differences between the tests. Permutation tests are distribution-free, exact, and most powerful conditional upon the data, given the exchangeability of the elements being permuted. They have the additional advantage of allowing any test statistic to be used, as we do not need to be able to calculate the distribution of the statistic under a parametric null hypothesis. Let us assume an appropriate test statistic $T(X)$, where $X$ is the $k \times n$ matrix of the test results. Within each column (test), the observations are assumed exchangeable (across algorithms) under the null hypothesis; we can therefore in principle permute their row (algorithm) indices without changing the distribution of $T$. We should not permute across the columns, as we are not assuming that the test results are exchangeable given a particular algorithm - the test has an influence on the score. A permutation test would calculate all possible combinations of permutations for each test, and for each combination $k$ would calculate the test statistic $T_k$. We would then compare the test statistic $T_0$ as calculated on the observed data with the $T_k$ test statistics calculated on the permuted data, and find a p-value in an obvious way based upon what fraction of the $T_k$ test statistics exceeded $T_0$. As a simple example, we can construct a five-"algorithm" ten-"test" problem, where algorithms 1-4 have the same within-test distributional performances and algorithm 5 is mildly better (in this case, has a smaller result on the test.) The tests themselves are slightly different as well. We construct the matrix so that the test results are in $(0,1)$, close to your problem's results range: X <- matrix(0,5,10) for (test in 1:10) { X[1:4, test] <- rbeta(4, 5-0.2*test, 5+0.2*test) X[5, test] <- rbeta(1, 4-0.2*test, 6+0.2*test) } colnames(X) <- paste("Test", 1:10) rownames(X) <- paste("Algo", c("A","B","C","D","E")) round(X,4) Test 1 Test 2 Test 3 Test 4 Test 5 Test 6 Test 7 Test 8 Test 9 Test 10 Algo A 0.7210 0.3176 0.3773 0.2571 0.3365 0.4364 0.5966 0.2157 0.2142 0.2992 Algo B 0.4153 0.4240 0.4542 0.1841 0.6346 0.4591 0.3750 0.1338 0.5906 0.2124 Algo C 0.7269 0.3499 0.5192 0.6179 0.4444 0.4069 0.2565 0.1840 0.4877 0.2929 Algo D 0.2334 0.8319 0.2045 0.3491 0.2584 0.2575 0.5532 0.3079 0.3876 0.4806 Algo E 0.2510 0.3357 0.3252 0.3784 0.1769 0.1322 0.5008 0.2208 0.3242 0.2482 Now to construct a test statistic. A plausible statistic might involve normalizing each column (as the tests are known to be different,) taking the row means of the normalized observations, and seeing whether some function of the row means, e.g. the minimum, was larger or smaller (whichever is appropriate) than we expect. The construction of a suitable test statistic can be quite important to your overall results, so it is worth spending some time thinking about. The complexity of generating each possible permutation exactly once is too great (for me, in this case), so we will adopt a simpler approach; we will generate many, many permutations of the data instead: X_norm <- X for (test in 1:10) { X_norm[,test] <- X_norm[,test] / mean(X_norm[,test]) } test_statistic <- function(x) min(rowMeans(x)) observed_statistic <- test_statistic(X_norm) permutation_results <- rep(0, 10000) for (i in seq_along(permutation_results)) { for (test in 1:10) { X_norm[, test] <- sample(X_norm[, test]) } permutation_results[i] <- test_statistic(X_norm) } hist(permutation_results) abline(v = observed_statistic) mean(observed_statistic >= permutation_results) [1] 0.0745 We interpret the final number (0.0745) as the (approximate) permutation p-value of the test statistic. We have taken a few shortcuts in the code that do not affect the results, for example, as we are permuting each column's values, we don't need to re-normalize the data at each permutation step (which we would have to do were we, say, sampling from the column with replacement,) and we can just permute the previously-permuted columns without going back to the original data at each permutation step. Note that, in this example, the overall test procedure isn't that powerful in an absolute sense, as we only have a few tests and algorithms, and four of the five algorithms had the same expected performance. (As it happens, in 1,000 repeats of the experiment, we rejected the null hypothesis 35.4% of the time at the 95% level of confidence and 16.6% of the time at the 99% level of confidence.) Your mileage will vary! But the ability to choose a custom test statistic combined with the distribution-free, exact, and most powerful (conditional upon the data) properties of permutation tests make them an extremely useful tool in the applied statistician's toolbox. References for permutation tests aren't as common as one might hope; they are usually discussed as part of more general nonparametric statistics books. Permutation, Parametric, and Bootstrap Tests of Hypotheses by P. Good is my favorite among the more specialized books.
Test the hypothesis that the performances of k machine learning models on the same test set is the s Under the assumption that the $k$ ML algorithm performances are "the same", which I will interpret as "independent and identically distributed", on any given test, they are also exchangeable within th
40,915
Test the hypothesis that the performances of k machine learning models on the same test set is the same
Have a look at the Diebold-Mariano test (DM-Test): here, the forecast accuracy of 2 (arbitrary) models can be compared using their losses, e.g. MSE or RMSE. Let $L_{A,t}$ be the loss of model A at time t. If the difference between the losses $\Delta_{A,B,t}=L_{A,t}-L_{B,t}$ is significantly greater than zero then the forecast from B is better than A. Otherwise not. Let $\hat \varepsilon_A=[\hat \varepsilon_{A,T+1} \dots \hat \varepsilon_{A,T+N}]'$ be the vector of forecasting errors for model A for N-step-ahead forecasts. Define e.g. $L_{A,t}=|\hat \varepsilon_{A,t}|$ (MAE) or $L_{A,t}=|\hat \varepsilon_{A,t}|^2$ (MSE). Then $\bar \Delta_{A,B}=\frac{1}{N}\sum_{i=1}^N\Delta_{A,B,i}$ is the mean difference. The DM test statistic is $$ t_{DM} = \frac{\bar \Delta_{A,B}}{\sigma(\bar \Delta_{A,B})} \overset{a}{\sim} \mathcal{N}(0,1) $$ under the null that the difference is not significant (i.e. the 2 models are the same), where $\sigma(\bar \Delta_{A,B})$ is the standard deviation of $\bar \Delta_{A,B}$. Usually, the DM-Test is used to pairwise compare multiple models in a 2D matrix and can easily be extended to forecasting vectors (instead of point-forecasts). It is frequently used in electricity price forecasting. See Figure 3 of this paper (and the corresponding sections) for a very good example of how the test is employed. Also see the dm.test() R function.
Test the hypothesis that the performances of k machine learning models on the same test set is the s
Have a look at the Diebold-Mariano test (DM-Test): here, the forecast accuracy of 2 (arbitrary) models can be compared using their losses, e.g. MSE or RMSE. Let $L_{A,t}$ be the loss of model A at tim
Test the hypothesis that the performances of k machine learning models on the same test set is the same Have a look at the Diebold-Mariano test (DM-Test): here, the forecast accuracy of 2 (arbitrary) models can be compared using their losses, e.g. MSE or RMSE. Let $L_{A,t}$ be the loss of model A at time t. If the difference between the losses $\Delta_{A,B,t}=L_{A,t}-L_{B,t}$ is significantly greater than zero then the forecast from B is better than A. Otherwise not. Let $\hat \varepsilon_A=[\hat \varepsilon_{A,T+1} \dots \hat \varepsilon_{A,T+N}]'$ be the vector of forecasting errors for model A for N-step-ahead forecasts. Define e.g. $L_{A,t}=|\hat \varepsilon_{A,t}|$ (MAE) or $L_{A,t}=|\hat \varepsilon_{A,t}|^2$ (MSE). Then $\bar \Delta_{A,B}=\frac{1}{N}\sum_{i=1}^N\Delta_{A,B,i}$ is the mean difference. The DM test statistic is $$ t_{DM} = \frac{\bar \Delta_{A,B}}{\sigma(\bar \Delta_{A,B})} \overset{a}{\sim} \mathcal{N}(0,1) $$ under the null that the difference is not significant (i.e. the 2 models are the same), where $\sigma(\bar \Delta_{A,B})$ is the standard deviation of $\bar \Delta_{A,B}$. Usually, the DM-Test is used to pairwise compare multiple models in a 2D matrix and can easily be extended to forecasting vectors (instead of point-forecasts). It is frequently used in electricity price forecasting. See Figure 3 of this paper (and the corresponding sections) for a very good example of how the test is employed. Also see the dm.test() R function.
Test the hypothesis that the performances of k machine learning models on the same test set is the s Have a look at the Diebold-Mariano test (DM-Test): here, the forecast accuracy of 2 (arbitrary) models can be compared using their losses, e.g. MSE or RMSE. Let $L_{A,t}$ be the loss of model A at tim
40,916
Do the principal values of higher moments exist for the Cauchy distribution?
The odd integral moments have principal values of zero while the even integral moments have infinite principal values. By definition, the Cauchy Principal Value [w.r.t. infinity] of an integral over the real line is $$\operatorname{pv}\int_\mathbb{R} g(x)\,\mathrm{d}x = \lim_{R\to\infty} \int_{-R}^R g(x)\,\mathrm{dx}.$$ When $g$ is antisymmetric -- that is, $g(x) = -g(x)$ for all $x,$ obviously the right hand side is always zero, whence its limit is zero. The Cauchy density is proportional to $1/(1+x^2),$ which is symmetric about $0.$ Consequently, for any antisymmetric integrable function $h,$ $$g(x) = \frac{h(x)}{1+x^2}$$ is also integrable and antisymmetric, whence $$\operatorname{pv} \int_\mathbb R \frac{h(x)}{1+x^2}\,\mathrm{d}x = 0.$$ This is the case for $h(x) = x^{2k+1}$ when $k$ is a natural number. It is not the case when $h(x) = x^{2k}.$ With $k=0,$ the integral converges, but for $k\ge 1$ use the simple fact that when $|x|\ge 1,$ $$\frac{x^{2k}}{1+x^2} \ge \frac{x^{2k}}{x^2+x^2} = \frac{1}{2}x^{2k-2} \ge \frac{1}{2}$$ to estimate $$\begin{aligned} \lim_{R\to\infty}\int_{-R}^R \frac{x^{2k}}{1+x^2}\,\mathrm{d}x &\ge \lim_{R\to\infty}\left(\int_{-R}^{-1} + \int_1^R\right) \frac{x^{2k}}{1+x^2}\,\mathrm{d}x\\ &\ge \lim_{R\to\infty}\left(\int_{-R}^{-1} + \int_1^R\right) \frac{1}{2}\,\mathrm{d}x\\ &= \lim_{R\to\infty} R - 1 =\infty. \end{aligned}$$ A similar argument by symmetry handles the case of $negative$ integral $n,$ but now the principal value is computed by excising a small neighborhood $(-\epsilon,\epsilon)$ around zero and taking the limit (from above) as $\epsilon\to 0.$ Again there's cancellation for odd $n$ but divergence for even $n.$ Alternatively, change variables from $x$ to $1/x,$ which reduces the integral to the form explicitly considered here.
Do the principal values of higher moments exist for the Cauchy distribution?
The odd integral moments have principal values of zero while the even integral moments have infinite principal values. By definition, the Cauchy Principal Value [w.r.t. infinity] of an integral over
Do the principal values of higher moments exist for the Cauchy distribution? The odd integral moments have principal values of zero while the even integral moments have infinite principal values. By definition, the Cauchy Principal Value [w.r.t. infinity] of an integral over the real line is $$\operatorname{pv}\int_\mathbb{R} g(x)\,\mathrm{d}x = \lim_{R\to\infty} \int_{-R}^R g(x)\,\mathrm{dx}.$$ When $g$ is antisymmetric -- that is, $g(x) = -g(x)$ for all $x,$ obviously the right hand side is always zero, whence its limit is zero. The Cauchy density is proportional to $1/(1+x^2),$ which is symmetric about $0.$ Consequently, for any antisymmetric integrable function $h,$ $$g(x) = \frac{h(x)}{1+x^2}$$ is also integrable and antisymmetric, whence $$\operatorname{pv} \int_\mathbb R \frac{h(x)}{1+x^2}\,\mathrm{d}x = 0.$$ This is the case for $h(x) = x^{2k+1}$ when $k$ is a natural number. It is not the case when $h(x) = x^{2k}.$ With $k=0,$ the integral converges, but for $k\ge 1$ use the simple fact that when $|x|\ge 1,$ $$\frac{x^{2k}}{1+x^2} \ge \frac{x^{2k}}{x^2+x^2} = \frac{1}{2}x^{2k-2} \ge \frac{1}{2}$$ to estimate $$\begin{aligned} \lim_{R\to\infty}\int_{-R}^R \frac{x^{2k}}{1+x^2}\,\mathrm{d}x &\ge \lim_{R\to\infty}\left(\int_{-R}^{-1} + \int_1^R\right) \frac{x^{2k}}{1+x^2}\,\mathrm{d}x\\ &\ge \lim_{R\to\infty}\left(\int_{-R}^{-1} + \int_1^R\right) \frac{1}{2}\,\mathrm{d}x\\ &= \lim_{R\to\infty} R - 1 =\infty. \end{aligned}$$ A similar argument by symmetry handles the case of $negative$ integral $n,$ but now the principal value is computed by excising a small neighborhood $(-\epsilon,\epsilon)$ around zero and taking the limit (from above) as $\epsilon\to 0.$ Again there's cancellation for odd $n$ but divergence for even $n.$ Alternatively, change variables from $x$ to $1/x,$ which reduces the integral to the form explicitly considered here.
Do the principal values of higher moments exist for the Cauchy distribution? The odd integral moments have principal values of zero while the even integral moments have infinite principal values. By definition, the Cauchy Principal Value [w.r.t. infinity] of an integral over
40,917
Are all statistical models also causal models?
But is $Y = aX + cZ + e$ (as a regression model, not a math equation) also a causal model (albeit a "wrong" causal model)? If I manipulate $X$ it tells me what happens to $Y$. Doesn't it correspond to the causal graph $X \rightarrow Y, Z \rightarrow Y$ ? It may correspond to the causal graph $X \rightarrow Y, Z \rightarrow Y$... ... But it can just as well be $Y \rightarrow X, Y \rightarrow Z$. Statistical models are present wherever there are causal models, but those statistical models are not equivalent/identical to the causal models themselves. A statistical model only describes the correlation, and it does not (need to) describe the causation. You can describe and fit statistical models without a description of an underlying causal model. Or at least, certainly the statistical model alone does not tell you anything about the causation (except that there is some underlying causal mechanism, but we do not know which). In this sense it is not equivalent to a causal model. You could see a statistical model as the shadow of a causal model. Edit If I write a model $Y + aX + bZ + e$ in a programming language, I could do so as a function, e.g. in Python def model(a,X,c,Z): return a*X + b*Z + np.random.randn()``` In this case you are programming a causal model and not a statistical model. You are specifically defining the random noise as being added to the a*X+b*Z. But this does not need to be the case in order to get that there is a relation: $$ Y|X,Z \sim N(aX + bZ, \sigma^2)$$ Consider the data below The statistical model is that X and Y follow a bivariate distribution. But can you tell the causal model from it? Do we have $X = aY + \text{noise}$ or do we have $Y = aX +\text{noise}$ ? They can result in the same statistical distribution, but the causal models are different.
Are all statistical models also causal models?
But is $Y = aX + cZ + e$ (as a regression model, not a math equation) also a causal model (albeit a "wrong" causal model)? If I manipulate $X$ it tells me what happens to $Y$. Doesn't it correspond to
Are all statistical models also causal models? But is $Y = aX + cZ + e$ (as a regression model, not a math equation) also a causal model (albeit a "wrong" causal model)? If I manipulate $X$ it tells me what happens to $Y$. Doesn't it correspond to the causal graph $X \rightarrow Y, Z \rightarrow Y$ ? It may correspond to the causal graph $X \rightarrow Y, Z \rightarrow Y$... ... But it can just as well be $Y \rightarrow X, Y \rightarrow Z$. Statistical models are present wherever there are causal models, but those statistical models are not equivalent/identical to the causal models themselves. A statistical model only describes the correlation, and it does not (need to) describe the causation. You can describe and fit statistical models without a description of an underlying causal model. Or at least, certainly the statistical model alone does not tell you anything about the causation (except that there is some underlying causal mechanism, but we do not know which). In this sense it is not equivalent to a causal model. You could see a statistical model as the shadow of a causal model. Edit If I write a model $Y + aX + bZ + e$ in a programming language, I could do so as a function, e.g. in Python def model(a,X,c,Z): return a*X + b*Z + np.random.randn()``` In this case you are programming a causal model and not a statistical model. You are specifically defining the random noise as being added to the a*X+b*Z. But this does not need to be the case in order to get that there is a relation: $$ Y|X,Z \sim N(aX + bZ, \sigma^2)$$ Consider the data below The statistical model is that X and Y follow a bivariate distribution. But can you tell the causal model from it? Do we have $X = aY + \text{noise}$ or do we have $Y = aX +\text{noise}$ ? They can result in the same statistical distribution, but the causal models are different.
Are all statistical models also causal models? But is $Y = aX + cZ + e$ (as a regression model, not a math equation) also a causal model (albeit a "wrong" causal model)? If I manipulate $X$ it tells me what happens to $Y$. Doesn't it correspond to
40,918
Are all statistical models also causal models?
edit: I think my causal graph analysis in this simple example is wrong, but hopefully the broader point is still clear To the extent that you correctly identified that M is a mediator and Z is a confounder, your analysis is correct. If this is the right causal model (based either on background knowledge or causal discovery), there is only one thing you didn't mention explicitly: X is not a direct cause of Y. You can measure some total effect due to the effect mediated through M, but if you control M, you can make X and Y independent (Markov property).
Are all statistical models also causal models?
edit: I think my causal graph analysis in this simple example is wrong, but hopefully the broader point is still clear To the extent that you correctly identified that M is a mediator and Z is a conf
Are all statistical models also causal models? edit: I think my causal graph analysis in this simple example is wrong, but hopefully the broader point is still clear To the extent that you correctly identified that M is a mediator and Z is a confounder, your analysis is correct. If this is the right causal model (based either on background knowledge or causal discovery), there is only one thing you didn't mention explicitly: X is not a direct cause of Y. You can measure some total effect due to the effect mediated through M, but if you control M, you can make X and Y independent (Markov property).
Are all statistical models also causal models? edit: I think my causal graph analysis in this simple example is wrong, but hopefully the broader point is still clear To the extent that you correctly identified that M is a mediator and Z is a conf
40,919
Are all statistical models also causal models?
Are all statistical models also causal models? No, they aren't. So the point between Pearl's causal graphs and rules for manipulating causal graphs appears to be to turn a causal graph into a statistical model (e.g. a linear regression). This statement, at best, is confusing. The main point of Pearl works is to separate clearly: statistical concepts vs causal concepts. Your question itself reveal that you do not grasped this, not yet. In fact statements like the follow But is $Y=aX+cZ+e$ (as a regression model, not a math equation) also a causal model (albeit a "wrong" causal model)? If I manipulate $X$ it tells me what happens to $Y$. Doesn't it correspond to the causal graph $X→Y,Z→Y$ ? If so, then is the Pearl method just finding a transform of a causal graph into another causal graph that is easier to work with or represent as a regression? confirm my impression, definitely. Apart that a regression equation remain a respectable math equation (too much general concept) causal graph do not stay for represent some regression. Worse, the (causal) concept of manipulation cannot apply to regression. Indeed causal graphs represent structural equations and them must be clearly separated from regression equations. Indeed Pearl underscore repeatedly the opportunity to use different notations. If I write a model Y+aX+bZ+e in a programming language, I could do so as a function, e.g. in Python It looks like a causal model. It is so because the definitions demanded from programming language imply a kind of equal sign that is definitional ($:=$), it is different from the standard equal sign ($=$). The standard equal sign is logically symmetric, the other is not and precisely for this reason it is what a structural equation (causal concept) need. Said that, the main link between causal and statistical model is about identification (read here:Why do we need identification in causal inference?). For identification purpose Pearl suggest do-calculus (read here:What's the purpose of do-calculus?) For more details read here: Under which assumptions a regression can be interpreted causally? Criticism of Pearl's theory of causality
Are all statistical models also causal models?
Are all statistical models also causal models? No, they aren't. So the point between Pearl's causal graphs and rules for manipulating causal graphs appears to be to turn a causal graph into a statis
Are all statistical models also causal models? Are all statistical models also causal models? No, they aren't. So the point between Pearl's causal graphs and rules for manipulating causal graphs appears to be to turn a causal graph into a statistical model (e.g. a linear regression). This statement, at best, is confusing. The main point of Pearl works is to separate clearly: statistical concepts vs causal concepts. Your question itself reveal that you do not grasped this, not yet. In fact statements like the follow But is $Y=aX+cZ+e$ (as a regression model, not a math equation) also a causal model (albeit a "wrong" causal model)? If I manipulate $X$ it tells me what happens to $Y$. Doesn't it correspond to the causal graph $X→Y,Z→Y$ ? If so, then is the Pearl method just finding a transform of a causal graph into another causal graph that is easier to work with or represent as a regression? confirm my impression, definitely. Apart that a regression equation remain a respectable math equation (too much general concept) causal graph do not stay for represent some regression. Worse, the (causal) concept of manipulation cannot apply to regression. Indeed causal graphs represent structural equations and them must be clearly separated from regression equations. Indeed Pearl underscore repeatedly the opportunity to use different notations. If I write a model Y+aX+bZ+e in a programming language, I could do so as a function, e.g. in Python It looks like a causal model. It is so because the definitions demanded from programming language imply a kind of equal sign that is definitional ($:=$), it is different from the standard equal sign ($=$). The standard equal sign is logically symmetric, the other is not and precisely for this reason it is what a structural equation (causal concept) need. Said that, the main link between causal and statistical model is about identification (read here:Why do we need identification in causal inference?). For identification purpose Pearl suggest do-calculus (read here:What's the purpose of do-calculus?) For more details read here: Under which assumptions a regression can be interpreted causally? Criticism of Pearl's theory of causality
Are all statistical models also causal models? Are all statistical models also causal models? No, they aren't. So the point between Pearl's causal graphs and rules for manipulating causal graphs appears to be to turn a causal graph into a statis
40,920
Are thresholds for logistic regression models prevalence-specific?
Three intertwined issues need to be disentangled: (1) calibration of a probability model, (2) whether the model should be used to generate a hard probability threshold, and (3) if so, where the threshold should be. Let's take them in reverse order. (3) If you have a well-calibrated probability model and there is to be a probability threshold, then the choice should be based on the costs and benefits of true and false assignments to each class. This answer explains the choice for the two-class situation, with links to the complications with multi-class models. The threshold is not part of the logistic regression, although the title of this question seems to imply otherwise. The threshold is chosen based on the intended application's costs and benefits, after the probability model (however devised, it doesn't have to be logistic regression) is in place. (2) As Frank Harrell said in a comment, "Optimum decisions are independent of prevalence but are completely dependent on the probability of an outcome for an individual person." The probability of an outcome for an individual might depend on clinical considerations outside of what's captured in your probability model. Furthermore, the cost/benefit tradeoff discussed above might differ among individuals. An 85-year-old with prostate cancer might have less willingness to undergo surgery to search for potentially positive lymph nodes than a 60-year-old. All of that argues against setting firm probability thresholds for individuals based solely on a model. (1) The heart of this question is thus whether a probability model based on "a large dataset where the prevalence of lymph node metastasis was low (15%)" can be used in a "surgery consultation-hour (expected prevalence of Patients with lymph node metastasis = 30%)." That's a more complicated question about model calibration, in particular whether the logistic-regression intercept should be adjusted for that prevalence difference. A logistic regression model for probability $p$ of a condition ($D$) as a function of covariates $X$ $$\log \frac {p}{1-p} = \alpha + \beta^T X $$ has an intercept $\alpha$ representing the log-odds of $D$ in the sampled population at a baseline situation when covariate values are 0 (or at reference levels for categorical predictors). (The answer from @Eoin explores the situation when populations differ in baseline prevalence.) The probability of $D$ given $X$ in that same population is: $$ p(D|X) = \frac {\exp(\alpha + \beta^T X)}{1+\exp(\alpha + \beta^T X)}.$$ McCullagh and Nelder show (Section 4.3.3) a situation that might need adjustment of the intercept to take the sampled population into account. A retrospective study might evaluate all cases with $D$ but only a subset of those without the condition ($\bar D$). Then to estimate $p(D|X)$ with the above formula in the entire population, you need to adjust the intercept to $\alpha^*=\alpha + \log(\pi_0/\pi_1)$, where $\pi_0,\pi_1$ are the fractions of cases $D$ and non-cases $\bar D$ sampled, respectively. But they warn: It is essential here that the sampling proportions depend only on $D$ and not on $X$. That's probably not the case in your example of positive-node probability in prostate cancer patients evaluated in a "surgery consultation-hour." Those patients were chosen in part because their covariate values $X$ (probably including PSA and age) indicate that they already are at higher risk of nodal spread than the overall population of prostate cancer patients. If the original probability model was properly calibrated for the overall population of prostate cancer patients (15% node-positive), the question is whether that overall population is adequately representative of your overall prostate cancer population. In part: is the probability of node-positivity at baseline covariate conditions in the original study similar to yours? Patients discussed in the "surgery consultation-hour" presumably aren't at baseline covariate conditions. They were pre-selected based on suspected higher risk and thus should have higher expected node-positive probability. If the original model is well calibrated with respect to your overall prostate cancer population, there should be no problem applying it to this pre-selected higher-risk subset.
Are thresholds for logistic regression models prevalence-specific?
Three intertwined issues need to be disentangled: (1) calibration of a probability model, (2) whether the model should be used to generate a hard probability threshold, and (3) if so, where the thresh
Are thresholds for logistic regression models prevalence-specific? Three intertwined issues need to be disentangled: (1) calibration of a probability model, (2) whether the model should be used to generate a hard probability threshold, and (3) if so, where the threshold should be. Let's take them in reverse order. (3) If you have a well-calibrated probability model and there is to be a probability threshold, then the choice should be based on the costs and benefits of true and false assignments to each class. This answer explains the choice for the two-class situation, with links to the complications with multi-class models. The threshold is not part of the logistic regression, although the title of this question seems to imply otherwise. The threshold is chosen based on the intended application's costs and benefits, after the probability model (however devised, it doesn't have to be logistic regression) is in place. (2) As Frank Harrell said in a comment, "Optimum decisions are independent of prevalence but are completely dependent on the probability of an outcome for an individual person." The probability of an outcome for an individual might depend on clinical considerations outside of what's captured in your probability model. Furthermore, the cost/benefit tradeoff discussed above might differ among individuals. An 85-year-old with prostate cancer might have less willingness to undergo surgery to search for potentially positive lymph nodes than a 60-year-old. All of that argues against setting firm probability thresholds for individuals based solely on a model. (1) The heart of this question is thus whether a probability model based on "a large dataset where the prevalence of lymph node metastasis was low (15%)" can be used in a "surgery consultation-hour (expected prevalence of Patients with lymph node metastasis = 30%)." That's a more complicated question about model calibration, in particular whether the logistic-regression intercept should be adjusted for that prevalence difference. A logistic regression model for probability $p$ of a condition ($D$) as a function of covariates $X$ $$\log \frac {p}{1-p} = \alpha + \beta^T X $$ has an intercept $\alpha$ representing the log-odds of $D$ in the sampled population at a baseline situation when covariate values are 0 (or at reference levels for categorical predictors). (The answer from @Eoin explores the situation when populations differ in baseline prevalence.) The probability of $D$ given $X$ in that same population is: $$ p(D|X) = \frac {\exp(\alpha + \beta^T X)}{1+\exp(\alpha + \beta^T X)}.$$ McCullagh and Nelder show (Section 4.3.3) a situation that might need adjustment of the intercept to take the sampled population into account. A retrospective study might evaluate all cases with $D$ but only a subset of those without the condition ($\bar D$). Then to estimate $p(D|X)$ with the above formula in the entire population, you need to adjust the intercept to $\alpha^*=\alpha + \log(\pi_0/\pi_1)$, where $\pi_0,\pi_1$ are the fractions of cases $D$ and non-cases $\bar D$ sampled, respectively. But they warn: It is essential here that the sampling proportions depend only on $D$ and not on $X$. That's probably not the case in your example of positive-node probability in prostate cancer patients evaluated in a "surgery consultation-hour." Those patients were chosen in part because their covariate values $X$ (probably including PSA and age) indicate that they already are at higher risk of nodal spread than the overall population of prostate cancer patients. If the original probability model was properly calibrated for the overall population of prostate cancer patients (15% node-positive), the question is whether that overall population is adequately representative of your overall prostate cancer population. In part: is the probability of node-positivity at baseline covariate conditions in the original study similar to yours? Patients discussed in the "surgery consultation-hour" presumably aren't at baseline covariate conditions. They were pre-selected based on suspected higher risk and thus should have higher expected node-positive probability. If the original model is well calibrated with respect to your overall prostate cancer population, there should be no problem applying it to this pre-selected higher-risk subset.
Are thresholds for logistic regression models prevalence-specific? Three intertwined issues need to be disentangled: (1) calibration of a probability model, (2) whether the model should be used to generate a hard probability threshold, and (3) if so, where the thresh
40,921
Are thresholds for logistic regression models prevalence-specific?
Notwithstanding @Frank Harrels's comments, I think it's useful to think about this in terms of the intercept or bias terms in the logistic regression model, rather than in terms of thresholds. I'm not totally confident in this approach, but it should hopefully be useful! Let's imagine you only have one predictor, $x$. For convenience, let $x$ be centred to have a mean of $0$ in the training data. The model is then $P(y_i = 1) = \text{logit}^{-1}(\alpha + \beta x_i)$, the intercept $\alpha$ is the log odds of a positive outcome when $x = 0$ (the average value). Given a set of predictors values $x_1, x_2, \dots, x_N$, and the parameters $\alpha$ and $\beta$, the predicted prevalence is just the average of the predicted probabilities (I think), $\frac{\sum_{i=1}^N \text{logit}^{-1}(\alpha + \beta x_i)}{N}$. Now, if prevalence is 15% in your training context, and 30% in your test context, there are a few possible explanations. The first is that the distribution of the predictors - just $x$ here, but multiple things in reality - differ between the contexts, and this difference explains the difference in the total number of positive cases. If this is the case, your model can be used without modification in the test context. The second is that the distribution of the predictors hasn't changed, but some additional factors not captured by your model have. This could be handled heuristically by adjusting the value of $\alpha$ until the average predicted probability of a positive outcome matches the prevalence you expect for the test data (30%). The third, and most likely explanation is a mixture of the above: some things captured by your model have changed, and some things not not captured have changed as well. I think, but I can't say for certain, that this could handled in the same way, by adjusting the value of $\alpha$ until the mean predicted probability matches the expected prevalence. Now, none of this will help if the relationship between your predictors and the outcome differ between the training and test contexts, but there's not much we can do about that. Update For my own L&D, I had a go at simulating this, and it seems to work as described. Code is here: https://gist.github.com/EoinTravers/656ac7b77a5cfa966c706888185afcd5
Are thresholds for logistic regression models prevalence-specific?
Notwithstanding @Frank Harrels's comments, I think it's useful to think about this in terms of the intercept or bias terms in the logistic regression model, rather than in terms of thresholds. I'm not
Are thresholds for logistic regression models prevalence-specific? Notwithstanding @Frank Harrels's comments, I think it's useful to think about this in terms of the intercept or bias terms in the logistic regression model, rather than in terms of thresholds. I'm not totally confident in this approach, but it should hopefully be useful! Let's imagine you only have one predictor, $x$. For convenience, let $x$ be centred to have a mean of $0$ in the training data. The model is then $P(y_i = 1) = \text{logit}^{-1}(\alpha + \beta x_i)$, the intercept $\alpha$ is the log odds of a positive outcome when $x = 0$ (the average value). Given a set of predictors values $x_1, x_2, \dots, x_N$, and the parameters $\alpha$ and $\beta$, the predicted prevalence is just the average of the predicted probabilities (I think), $\frac{\sum_{i=1}^N \text{logit}^{-1}(\alpha + \beta x_i)}{N}$. Now, if prevalence is 15% in your training context, and 30% in your test context, there are a few possible explanations. The first is that the distribution of the predictors - just $x$ here, but multiple things in reality - differ between the contexts, and this difference explains the difference in the total number of positive cases. If this is the case, your model can be used without modification in the test context. The second is that the distribution of the predictors hasn't changed, but some additional factors not captured by your model have. This could be handled heuristically by adjusting the value of $\alpha$ until the average predicted probability of a positive outcome matches the prevalence you expect for the test data (30%). The third, and most likely explanation is a mixture of the above: some things captured by your model have changed, and some things not not captured have changed as well. I think, but I can't say for certain, that this could handled in the same way, by adjusting the value of $\alpha$ until the mean predicted probability matches the expected prevalence. Now, none of this will help if the relationship between your predictors and the outcome differ between the training and test contexts, but there's not much we can do about that. Update For my own L&D, I had a go at simulating this, and it seems to work as described. Code is here: https://gist.github.com/EoinTravers/656ac7b77a5cfa966c706888185afcd5
Are thresholds for logistic regression models prevalence-specific? Notwithstanding @Frank Harrels's comments, I think it's useful to think about this in terms of the intercept or bias terms in the logistic regression model, rather than in terms of thresholds. I'm not
40,922
Are thresholds for logistic regression models prevalence-specific?
In a sense, yes. This is the default with logistic regression. It is not treated as a "problem" to be remedied, but perhaps it should be. "Prevalence" here is taken to mean in-sample prevalence: specifically, if you calculate the fitted probabilities for each patient in a logistic regression sample, and perform an average, you will obtain the in-sample prevalence. An example in R: set.seed(123) x <- seq(-3, 3, 0.01) y <- rbinom(length(x), 1, plogis(-3 + 0.4 * x)) f <- glm(y ~ x, family=binomial) sum(f$fitted) sum(y) give > sum(f$fitted) [1] 42 > sum(y) [1] 42 i.e. 7% prevalence. Nevertheless, it's possible to build out complicated heirarchical models, or weighting to handle issues, such as oversampling of cases such as in a case-control study. Or to handle nested samples. Scott and Wild (1999) discuss weighting case-control case samples by the "known prevalence" of outcome, and conversely for the controls. This corrects the intercept term in the model so that the calibration is fitted to the referent prevalence. Of course, even the "known prevalence" may have uncertainty and there is not yet any optimum way to account for these layers of error. One relevant example is the COVID test. I'm not sure if a logistic model is involved in predicting presence of disease, but it was somewhat shocking to see how a test that was developed to diagnose presence of disease among symptomatic people at a particular time of the epidemic was basically unchanged for performing the same test in asymptomatic people later on. Only recently have the number of PCR cycles been adjusted which consequently reduced the number of false positive cases.
Are thresholds for logistic regression models prevalence-specific?
In a sense, yes. This is the default with logistic regression. It is not treated as a "problem" to be remedied, but perhaps it should be. "Prevalence" here is taken to mean in-sample prevalence: speci
Are thresholds for logistic regression models prevalence-specific? In a sense, yes. This is the default with logistic regression. It is not treated as a "problem" to be remedied, but perhaps it should be. "Prevalence" here is taken to mean in-sample prevalence: specifically, if you calculate the fitted probabilities for each patient in a logistic regression sample, and perform an average, you will obtain the in-sample prevalence. An example in R: set.seed(123) x <- seq(-3, 3, 0.01) y <- rbinom(length(x), 1, plogis(-3 + 0.4 * x)) f <- glm(y ~ x, family=binomial) sum(f$fitted) sum(y) give > sum(f$fitted) [1] 42 > sum(y) [1] 42 i.e. 7% prevalence. Nevertheless, it's possible to build out complicated heirarchical models, or weighting to handle issues, such as oversampling of cases such as in a case-control study. Or to handle nested samples. Scott and Wild (1999) discuss weighting case-control case samples by the "known prevalence" of outcome, and conversely for the controls. This corrects the intercept term in the model so that the calibration is fitted to the referent prevalence. Of course, even the "known prevalence" may have uncertainty and there is not yet any optimum way to account for these layers of error. One relevant example is the COVID test. I'm not sure if a logistic model is involved in predicting presence of disease, but it was somewhat shocking to see how a test that was developed to diagnose presence of disease among symptomatic people at a particular time of the epidemic was basically unchanged for performing the same test in asymptomatic people later on. Only recently have the number of PCR cycles been adjusted which consequently reduced the number of false positive cases.
Are thresholds for logistic regression models prevalence-specific? In a sense, yes. This is the default with logistic regression. It is not treated as a "problem" to be remedied, but perhaps it should be. "Prevalence" here is taken to mean in-sample prevalence: speci
40,923
What is the pdf of a normal distribution divided by the square root of a log-normal over n?
We can manipulate $Y$ to help us here. First note we can re-write $Y$ as $$Y = \frac{n^{1/2}Z}{X^{1/2}}$$ and because $Z\sim N(0,1)$ then $n^{1/2}Z \sim N(0, n)$. Now we know $X \sim \log N(a, b)$. By the definition of the log-normal we have $\log(X) \sim N(a, b)$. Using standard log laws we have $\log(X^{1/2}) = \frac{1}{2} \log(X)$ thus $\log(X^{1/2}) \sim N(\frac{a}{2}, \frac{b}{4})$. So by the definition of the log-Normal we have $\sqrt{X} \sim \log N(\frac{a}{2}, \frac{b}{4})$. So because $Y$ can actually be expressed as the ratio of a Normal RV and a log-Normal RV you can simply apply the result from the referenced question using the above representation of $Y$.
What is the pdf of a normal distribution divided by the square root of a log-normal over n?
We can manipulate $Y$ to help us here. First note we can re-write $Y$ as $$Y = \frac{n^{1/2}Z}{X^{1/2}}$$ and because $Z\sim N(0,1)$ then $n^{1/2}Z \sim N(0, n)$. Now we know $X \sim \log N(a, b)$. B
What is the pdf of a normal distribution divided by the square root of a log-normal over n? We can manipulate $Y$ to help us here. First note we can re-write $Y$ as $$Y = \frac{n^{1/2}Z}{X^{1/2}}$$ and because $Z\sim N(0,1)$ then $n^{1/2}Z \sim N(0, n)$. Now we know $X \sim \log N(a, b)$. By the definition of the log-normal we have $\log(X) \sim N(a, b)$. Using standard log laws we have $\log(X^{1/2}) = \frac{1}{2} \log(X)$ thus $\log(X^{1/2}) \sim N(\frac{a}{2}, \frac{b}{4})$. So by the definition of the log-Normal we have $\sqrt{X} \sim \log N(\frac{a}{2}, \frac{b}{4})$. So because $Y$ can actually be expressed as the ratio of a Normal RV and a log-Normal RV you can simply apply the result from the referenced question using the above representation of $Y$.
What is the pdf of a normal distribution divided by the square root of a log-normal over n? We can manipulate $Y$ to help us here. First note we can re-write $Y$ as $$Y = \frac{n^{1/2}Z}{X^{1/2}}$$ and because $Z\sim N(0,1)$ then $n^{1/2}Z \sim N(0, n)$. Now we know $X \sim \log N(a, b)$. B
40,924
Can a sample average be multimodal?
The answer is yes, it is possible for all the sample mean distributions to be multimodal. The idea is to exhibit a distribution of the $X_i$ that has rapidly increasing gaps in its support, so that no matter how many of the $X_i$ you might sum, there eventually will be a gap so large that the sum cannot fill it: that is, there will be places within the gap where the sum has zero probability. That would place some of the probability of the sum to the left of that point (on a number line) and some to the right; and thus the sum's distribution will have at least two modes. That makes the distribution of the mean at least bimodal. The rest of this post fleshes out this idea. If you read it, you should have no trouble finding sequences of weights $p_i$ and displacements $x_i$ for which the $X_i$ have finite variances (and therefore finite expectations, as required in the question): For instance, just pick $x_i$ and for the $p_i$ set $q_i = 2^{-i}/(x_i+1)^2,$ normalizing them to sum to unity. To illustrate, I set $q_i = 2^{-i}/(x_i+1)$ (so that the component weights don't taper off too quickly, but still ensuring a finite expectation) and graphed the density of $log(X)$ on a logarithmic axis (which is needed to depict the huge range of values in both dimensions). You can see how the gaps increase faster than exponentially. Separate components of the distribution are depicted in different colors. Although the graph eventually looks like a series of spikes, that is only because of the lack of resolution: each apparent spike has the shape of a Beta$(5,5)$ distribution and its width (therefore) is $1.$ Those who rely on the Central Limit Theorem or laws of large numbers to think about this problem might find this example paradoxical, but it isn't: those theorems concern properties of distributions in the large -- global properties -- whereas the number of modes of a distribution is a "hyperlocal" property, typically characterizing the distribution only in an infinitesimal part of its support. Intuitively, you can take any "nice" density function and put as many tiny bumps on it as you like without appreciably changing any of its moments, its tail behavior, or most other global properties of the distribution. Those theorems are also concerned about limiting properties, whereas the question is not about a limit at all. A counterexample must be a distribution (common to all the $X_i$) for which the distributions of infinitely many of the partial sums $$Y_n = \sum_{i=1}^n X_i$$ are multimodal. (The division by $n$ to form the means does not change the shape of the distribution and therefore does not change the number of modes.) To be a satisfactory example -- that is, not some kind of exceptional "pathology" uncharacteristic of the underlying ideas -- we ought to insist that this distribution be continuous with a continuous density so that modes (and therefore the modes of all the $Y_n$) are clearly defined. One counterexample is determined by three sequences with these properties: Random variables: Let $Z_i$ be a sequence of iid random variables supported on the interval $[0,1]$ with common distribution function $F$ having at least one mode. Any Beta$(a,b)$ distribution will serve. Displacements: Let $x_i$ be a sequence of numbers where $x_1=0$ and for every $i\gt 1,$ $x_i \ge i+i^{i+1}.$ Weights: Let $p_i,$ $i=1,2,\ldots,$ be a sequence of positive probabilities summing to $1$ (such as a geometric distribution $p_i = 2^{-i}$). We will shift each variable $Z_i$ to the location $x_i$ and weight it by $p_i$ to form a mixture with distribution function $$G(x) = \sum_{i=1}^\infty p_i F(x-x_i).$$ Because all the $p_i$ are positive, the support of this distribution is the union of the intervals $[x_i, x_i+1],$ which is non-negative and unbounded. The counterexample is a sequence of iid variables $X_i$ with common distribution $G.$ We need to investigate its modes. We can identify modes of $G$ by finding two nonempty intervals $(a_0,b_0)$ and $(a_1,b_1)$ with $a_0\lt b_0 \lt a_1\lt b_1$ for which $G$ has no probability, but $G$ has positive probability on the gap between them, $[b_0,a_1]:$ a mode of $G$ must lie in that gap. Let $F^{(n)}$ be the distribution of the sum of any $n$ distinct $Z_i.$ Note, because this is crucial to the argument, that the support of $F^{(n)}$ is contained in the interval $[0,n].$ As a matter of notation, when $\mathcal{I}$ is any multiset of indexes, let $$x_{\mathcal I} = \sum_{i\in\mathcal I} x_i$$ be the sum of the displacements indexed by $\mathcal I.$ Because each $X_i$ is a mixture of the $Z_j,$ $Y_n$ is itself a mixture of sums of collections of $n$ of the shifted versions of $Z_j.$ The mixture components of $Y_n$ are thereby determined by multisets of $n$ indexes $\mathcal I$ and each component's distribution function is $$F^{(n)}\left(x - x_{\mathcal I}\right),$$ whose support is contained in the shifted interval $[x_{\mathcal I}, x_{\mathcal I}+n].$ There are no more than $(n-1)^n$ such multisets corresponding to components with supports in $[0, x_n],$ because only choices from the set $\{x_1,x_2,\ldots, x_{n-1}\}$ yield sums less than $x_n.$ The support of $Y_n$ is contained within the union of supports of these component distributions. Let's examine the support of $Y_n$ within the interval $[n, x_n).$ Its size (Lebesgue measure) cannot exceed the sum of lengths of the component supports and therefore cannot be greater than $n(n-1)^n \lt n^{n+1}.$ Since we have required $x_n \gt n+n^{n+1}$ for all $n,$ there must be an interval of positive measure in $[n, x_n)$ where $Y_n$ has no probability. On the other hand, $Y_n$ has zero probability in $(-\infty, 0)$ and, since $x_1=0,$ positive probability in $[0,n]$ (where its weight is $p_1^n\gt 0$). Moreover, the support of $Y_n$ is unbounded because the (common) support of the $X_i$ is unbounded. We have thereby located at least one mode in $[0,x_n)$ and another in $[x_n,\infty).$ Consequently, For all $n$ there must be at least one mode of $Y_n$ in the interval $[0,x_n)$ and there must be at least one mode in the interval $[x_n,\infty):$ that is, $Y_n$ has a multimodal distribution, QED. Here is the graph corresponding to the initial illustration for sample sizes of $n=10^4:$ The first five components have merged into a density with no gaps (as apparent from the mixing of the colors in that part of the graph), but then--because each apparent spike has a width of only $10^4$--the gaps begin and continue ad infinitum. This makes it obvious that every one of these sampling distributions has infinitely many modes.
Can a sample average be multimodal?
The answer is yes, it is possible for all the sample mean distributions to be multimodal. The idea is to exhibit a distribution of the $X_i$ that has rapidly increasing gaps in its support, so that no
Can a sample average be multimodal? The answer is yes, it is possible for all the sample mean distributions to be multimodal. The idea is to exhibit a distribution of the $X_i$ that has rapidly increasing gaps in its support, so that no matter how many of the $X_i$ you might sum, there eventually will be a gap so large that the sum cannot fill it: that is, there will be places within the gap where the sum has zero probability. That would place some of the probability of the sum to the left of that point (on a number line) and some to the right; and thus the sum's distribution will have at least two modes. That makes the distribution of the mean at least bimodal. The rest of this post fleshes out this idea. If you read it, you should have no trouble finding sequences of weights $p_i$ and displacements $x_i$ for which the $X_i$ have finite variances (and therefore finite expectations, as required in the question): For instance, just pick $x_i$ and for the $p_i$ set $q_i = 2^{-i}/(x_i+1)^2,$ normalizing them to sum to unity. To illustrate, I set $q_i = 2^{-i}/(x_i+1)$ (so that the component weights don't taper off too quickly, but still ensuring a finite expectation) and graphed the density of $log(X)$ on a logarithmic axis (which is needed to depict the huge range of values in both dimensions). You can see how the gaps increase faster than exponentially. Separate components of the distribution are depicted in different colors. Although the graph eventually looks like a series of spikes, that is only because of the lack of resolution: each apparent spike has the shape of a Beta$(5,5)$ distribution and its width (therefore) is $1.$ Those who rely on the Central Limit Theorem or laws of large numbers to think about this problem might find this example paradoxical, but it isn't: those theorems concern properties of distributions in the large -- global properties -- whereas the number of modes of a distribution is a "hyperlocal" property, typically characterizing the distribution only in an infinitesimal part of its support. Intuitively, you can take any "nice" density function and put as many tiny bumps on it as you like without appreciably changing any of its moments, its tail behavior, or most other global properties of the distribution. Those theorems are also concerned about limiting properties, whereas the question is not about a limit at all. A counterexample must be a distribution (common to all the $X_i$) for which the distributions of infinitely many of the partial sums $$Y_n = \sum_{i=1}^n X_i$$ are multimodal. (The division by $n$ to form the means does not change the shape of the distribution and therefore does not change the number of modes.) To be a satisfactory example -- that is, not some kind of exceptional "pathology" uncharacteristic of the underlying ideas -- we ought to insist that this distribution be continuous with a continuous density so that modes (and therefore the modes of all the $Y_n$) are clearly defined. One counterexample is determined by three sequences with these properties: Random variables: Let $Z_i$ be a sequence of iid random variables supported on the interval $[0,1]$ with common distribution function $F$ having at least one mode. Any Beta$(a,b)$ distribution will serve. Displacements: Let $x_i$ be a sequence of numbers where $x_1=0$ and for every $i\gt 1,$ $x_i \ge i+i^{i+1}.$ Weights: Let $p_i,$ $i=1,2,\ldots,$ be a sequence of positive probabilities summing to $1$ (such as a geometric distribution $p_i = 2^{-i}$). We will shift each variable $Z_i$ to the location $x_i$ and weight it by $p_i$ to form a mixture with distribution function $$G(x) = \sum_{i=1}^\infty p_i F(x-x_i).$$ Because all the $p_i$ are positive, the support of this distribution is the union of the intervals $[x_i, x_i+1],$ which is non-negative and unbounded. The counterexample is a sequence of iid variables $X_i$ with common distribution $G.$ We need to investigate its modes. We can identify modes of $G$ by finding two nonempty intervals $(a_0,b_0)$ and $(a_1,b_1)$ with $a_0\lt b_0 \lt a_1\lt b_1$ for which $G$ has no probability, but $G$ has positive probability on the gap between them, $[b_0,a_1]:$ a mode of $G$ must lie in that gap. Let $F^{(n)}$ be the distribution of the sum of any $n$ distinct $Z_i.$ Note, because this is crucial to the argument, that the support of $F^{(n)}$ is contained in the interval $[0,n].$ As a matter of notation, when $\mathcal{I}$ is any multiset of indexes, let $$x_{\mathcal I} = \sum_{i\in\mathcal I} x_i$$ be the sum of the displacements indexed by $\mathcal I.$ Because each $X_i$ is a mixture of the $Z_j,$ $Y_n$ is itself a mixture of sums of collections of $n$ of the shifted versions of $Z_j.$ The mixture components of $Y_n$ are thereby determined by multisets of $n$ indexes $\mathcal I$ and each component's distribution function is $$F^{(n)}\left(x - x_{\mathcal I}\right),$$ whose support is contained in the shifted interval $[x_{\mathcal I}, x_{\mathcal I}+n].$ There are no more than $(n-1)^n$ such multisets corresponding to components with supports in $[0, x_n],$ because only choices from the set $\{x_1,x_2,\ldots, x_{n-1}\}$ yield sums less than $x_n.$ The support of $Y_n$ is contained within the union of supports of these component distributions. Let's examine the support of $Y_n$ within the interval $[n, x_n).$ Its size (Lebesgue measure) cannot exceed the sum of lengths of the component supports and therefore cannot be greater than $n(n-1)^n \lt n^{n+1}.$ Since we have required $x_n \gt n+n^{n+1}$ for all $n,$ there must be an interval of positive measure in $[n, x_n)$ where $Y_n$ has no probability. On the other hand, $Y_n$ has zero probability in $(-\infty, 0)$ and, since $x_1=0,$ positive probability in $[0,n]$ (where its weight is $p_1^n\gt 0$). Moreover, the support of $Y_n$ is unbounded because the (common) support of the $X_i$ is unbounded. We have thereby located at least one mode in $[0,x_n)$ and another in $[x_n,\infty).$ Consequently, For all $n$ there must be at least one mode of $Y_n$ in the interval $[0,x_n)$ and there must be at least one mode in the interval $[x_n,\infty):$ that is, $Y_n$ has a multimodal distribution, QED. Here is the graph corresponding to the initial illustration for sample sizes of $n=10^4:$ The first five components have merged into a density with no gaps (as apparent from the mixing of the colors in that part of the graph), but then--because each apparent spike has a width of only $10^4$--the gaps begin and continue ad infinitum. This makes it obvious that every one of these sampling distributions has infinitely many modes.
Can a sample average be multimodal? The answer is yes, it is possible for all the sample mean distributions to be multimodal. The idea is to exhibit a distribution of the $X_i$ that has rapidly increasing gaps in its support, so that no
40,925
When will $\text{Variance}=\text{Bias}^2$ hold for the optimal model?
The picture below suggests the optimal model (the one minimizing the expected squared prediction error) will have $\text{Variance}=\text{Bias}^2$. Sorry to rain on your parade, but this does not necessarily hold. The picture is misleading. No, that is not an answer to your question, but I would assume this reduces our interest in it altogether... As an example, assume model complexity $x$ can be parameterized in a single dimension with $0\leq x\leq 1$. Squared bias is given by $$ b(x) = 1-\sqrt{x}, $$ variance by $$v(x) = x^2, $$ and total error therefore by $$ e(x) = b(x)+v(x) = 1-\sqrt{x}+x^2. $$ Bias is decreasing, variance is increasing, both are convex, and the minimal error is achieved at $x=\frac{1}{4^\frac{2}{3}}$, far away from the point of intersection. The result about minimal error appearing at the intersection should indeed hold if we posit symmetry of bias and variance. But then they would need to be symmetric about some specific $x$ value, and that particular $x$ value would then turn out to be the minimum error complexity. I would not think such a symmetry to be very common, or therefore interesting.
When will $\text{Variance}=\text{Bias}^2$ hold for the optimal model?
The picture below suggests the optimal model (the one minimizing the expected squared prediction error) will have $\text{Variance}=\text{Bias}^2$. Sorry to rain on your parade, but this does not nece
When will $\text{Variance}=\text{Bias}^2$ hold for the optimal model? The picture below suggests the optimal model (the one minimizing the expected squared prediction error) will have $\text{Variance}=\text{Bias}^2$. Sorry to rain on your parade, but this does not necessarily hold. The picture is misleading. No, that is not an answer to your question, but I would assume this reduces our interest in it altogether... As an example, assume model complexity $x$ can be parameterized in a single dimension with $0\leq x\leq 1$. Squared bias is given by $$ b(x) = 1-\sqrt{x}, $$ variance by $$v(x) = x^2, $$ and total error therefore by $$ e(x) = b(x)+v(x) = 1-\sqrt{x}+x^2. $$ Bias is decreasing, variance is increasing, both are convex, and the minimal error is achieved at $x=\frac{1}{4^\frac{2}{3}}$, far away from the point of intersection. The result about minimal error appearing at the intersection should indeed hold if we posit symmetry of bias and variance. But then they would need to be symmetric about some specific $x$ value, and that particular $x$ value would then turn out to be the minimum error complexity. I would not think such a symmetry to be very common, or therefore interesting.
When will $\text{Variance}=\text{Bias}^2$ hold for the optimal model? The picture below suggests the optimal model (the one minimizing the expected squared prediction error) will have $\text{Variance}=\text{Bias}^2$. Sorry to rain on your parade, but this does not nece
40,926
When will $\text{Variance}=\text{Bias}^2$ hold for the optimal model?
When will $Variance=Bias^2$ hold for the optimal model? I think that some ad hoc example can be built but a general rule cannot exist. First of all is useful to say that the bias-variance tradeoffs (BVT) story matters in prediction only. Read here (What is the relationship between minimizing prediciton error versus parameter estimation error?). So, we have a true model in one side and several "proposed/estimated" models in another; among the last we looking for the best one. In general, the level of complexity in the proposed/estimated model that minimize the MSE, depends crucially on the true model. Then, It can seems that BVT story can suggest us that, under a true model with mid level of complexity, something like $Variance = Bias^2$ can hold for the best estimated model (min MSE). However this perspective do not take into account that the BVT must be analyzed under a precise amount of data. The best proposed/estimated model change if the number of available data change; indeed if we have an infinite amount of data only $Bias$ matters. Therefore, the relevance of the “symmetry” linked to $Variance = Bias^2$ decrease substantially. This topic is related Statistical Learning. Contradictions?
When will $\text{Variance}=\text{Bias}^2$ hold for the optimal model?
When will $Variance=Bias^2$ hold for the optimal model? I think that some ad hoc example can be built but a general rule cannot exist. First of all is useful to say that the bias-variance tradeoffs (
When will $\text{Variance}=\text{Bias}^2$ hold for the optimal model? When will $Variance=Bias^2$ hold for the optimal model? I think that some ad hoc example can be built but a general rule cannot exist. First of all is useful to say that the bias-variance tradeoffs (BVT) story matters in prediction only. Read here (What is the relationship between minimizing prediciton error versus parameter estimation error?). So, we have a true model in one side and several "proposed/estimated" models in another; among the last we looking for the best one. In general, the level of complexity in the proposed/estimated model that minimize the MSE, depends crucially on the true model. Then, It can seems that BVT story can suggest us that, under a true model with mid level of complexity, something like $Variance = Bias^2$ can hold for the best estimated model (min MSE). However this perspective do not take into account that the BVT must be analyzed under a precise amount of data. The best proposed/estimated model change if the number of available data change; indeed if we have an infinite amount of data only $Bias$ matters. Therefore, the relevance of the “symmetry” linked to $Variance = Bias^2$ decrease substantially. This topic is related Statistical Learning. Contradictions?
When will $\text{Variance}=\text{Bias}^2$ hold for the optimal model? When will $Variance=Bias^2$ hold for the optimal model? I think that some ad hoc example can be built but a general rule cannot exist. First of all is useful to say that the bias-variance tradeoffs (
40,927
How to find se.fit in R by hand?
You can’t just add up the standard errors. You need to work with the variances and covariances of the coefficient estimates, then take the square root to get back to the standard error scale. The formula for the variance of a weighted sum of correlated variables is the key, as the estimates of the intercept and slope are correlated random variables, not independent. Use vcov(roller.lm) to get the variance/covariance matrix (variances are the diagonal elements, covariances off-diagonal). Then apply the formula to get the estimated variance of the weighted sum (weight 1 for the intercept, weight for the slope the value of x for which you want the estimate). The square root gives the standard error. This answer works through the underlying code in detail, showing how you can then use the standard error to get confidence limits and prediction intervals.
How to find se.fit in R by hand?
You can’t just add up the standard errors. You need to work with the variances and covariances of the coefficient estimates, then take the square root to get back to the standard error scale. The form
How to find se.fit in R by hand? You can’t just add up the standard errors. You need to work with the variances and covariances of the coefficient estimates, then take the square root to get back to the standard error scale. The formula for the variance of a weighted sum of correlated variables is the key, as the estimates of the intercept and slope are correlated random variables, not independent. Use vcov(roller.lm) to get the variance/covariance matrix (variances are the diagonal elements, covariances off-diagonal). Then apply the formula to get the estimated variance of the weighted sum (weight 1 for the intercept, weight for the slope the value of x for which you want the estimate). The square root gives the standard error. This answer works through the underlying code in detail, showing how you can then use the standard error to get confidence limits and prediction intervals.
How to find se.fit in R by hand? You can’t just add up the standard errors. You need to work with the variances and covariances of the coefficient estimates, then take the square root to get back to the standard error scale. The form
40,928
Should a Hausman test be used to decide between fixed vs. random effects?
What the the Hausman test is doing is testing whether the results (i.e. the estimated coefficients) from a fixed effects and random effects model are significantly different. (I haven't ever seen people talk about it testing whether whether the fixed and "between" effects are different, although because the random effects model is estimated as a weighted average of the between and fixed effects models, you could look at it that way, I suppose.) However, the reason it's used to "decide between fixed vs random effects" is that if the results of the two models ARE different then that's a reason to prefer the fixed effects model. Here's why. A fixed effects (FE) model accounts for ALL omitted variable bias from variables at the higher "group" level, because a fixed effects model is basically just including a dummy indicator variable for each "group." This means that if you run a FE model you don't have to worry about omitted variable bias at the group level. A random effects (RE) model does NOT automatically account for all group level bias (that is, bias due to differences "between groups"), although it allows you to include group level predictors (that is, predictor variables that vary ONLY between groups, but not within groups) that do that. Now, if you were to include ALL significant group level covariates in your random effects model then you would get the same answers (in terms of lower level coefficients) as the FE model (or rather, the two answers will approach each other as sample sizes goes to infinity). But the standard errors of the RE model will be smaller. What all that means is that if the coefficients of a FE and RE model are basically the same, you should prefer the RE ones, because they have smaller standard errors, but if they are different you should prefer the FE ones because the fact that they are different suggests that there is omitted variable bias at the higher level that the RE model has not accounted for (but the FE model has). So that's why we use a Hausman test to see if the coefficients are different, and if the test says they are, we default to the FE model. Now, I'll note that in "real life" there are many other criteria by which we might choose between these two models. Sometimes the independent variables we care about are at the higher level in which case we CAN'T use a FE model, since in a FE model you can't include any group-level predictors (because they are colinear with the dummy variables). So a Hausman test is only appropriate when you have other substantive reason to prefer one model over the other. And I'll also note that in my experience the Hausman test is almost always significant: that is, it almost always tells you that the two models are significantly different even when that difference is so small as to be substantively meaningless. So, as is always the case in statistics: don't just blindly follow the results of the test.
Should a Hausman test be used to decide between fixed vs. random effects?
What the the Hausman test is doing is testing whether the results (i.e. the estimated coefficients) from a fixed effects and random effects model are significantly different. (I haven't ever seen peop
Should a Hausman test be used to decide between fixed vs. random effects? What the the Hausman test is doing is testing whether the results (i.e. the estimated coefficients) from a fixed effects and random effects model are significantly different. (I haven't ever seen people talk about it testing whether whether the fixed and "between" effects are different, although because the random effects model is estimated as a weighted average of the between and fixed effects models, you could look at it that way, I suppose.) However, the reason it's used to "decide between fixed vs random effects" is that if the results of the two models ARE different then that's a reason to prefer the fixed effects model. Here's why. A fixed effects (FE) model accounts for ALL omitted variable bias from variables at the higher "group" level, because a fixed effects model is basically just including a dummy indicator variable for each "group." This means that if you run a FE model you don't have to worry about omitted variable bias at the group level. A random effects (RE) model does NOT automatically account for all group level bias (that is, bias due to differences "between groups"), although it allows you to include group level predictors (that is, predictor variables that vary ONLY between groups, but not within groups) that do that. Now, if you were to include ALL significant group level covariates in your random effects model then you would get the same answers (in terms of lower level coefficients) as the FE model (or rather, the two answers will approach each other as sample sizes goes to infinity). But the standard errors of the RE model will be smaller. What all that means is that if the coefficients of a FE and RE model are basically the same, you should prefer the RE ones, because they have smaller standard errors, but if they are different you should prefer the FE ones because the fact that they are different suggests that there is omitted variable bias at the higher level that the RE model has not accounted for (but the FE model has). So that's why we use a Hausman test to see if the coefficients are different, and if the test says they are, we default to the FE model. Now, I'll note that in "real life" there are many other criteria by which we might choose between these two models. Sometimes the independent variables we care about are at the higher level in which case we CAN'T use a FE model, since in a FE model you can't include any group-level predictors (because they are colinear with the dummy variables). So a Hausman test is only appropriate when you have other substantive reason to prefer one model over the other. And I'll also note that in my experience the Hausman test is almost always significant: that is, it almost always tells you that the two models are significantly different even when that difference is so small as to be substantively meaningless. So, as is always the case in statistics: don't just blindly follow the results of the test.
Should a Hausman test be used to decide between fixed vs. random effects? What the the Hausman test is doing is testing whether the results (i.e. the estimated coefficients) from a fixed effects and random effects model are significantly different. (I haven't ever seen peop
40,929
Should a Hausman test be used to decide between fixed vs. random effects?
Let's say the Hausman test favors the fixed effect model. Why might you still be interested in using the random effects model? The random effects or multilevel model allows a degree of flexibility in modeling that is much messier and in some cases impossible to implement in the fixed effect model. Examples include: Random slopes for the association between lower level variables and the outcome, which allow you to investigate whether the within-group association varies across groups. A classic example is growth curve modeling whereby the linear (or quadratic) rate of change in the outcome, codified by a continuous time variable) is allowed to vary across individuals or groups. In the fixed effect model, you can get at this in a crude way by interacting the lower-level variable with the cluster dummy variables. If you have a lot of groups, you have a lot of interactions. Related to the above, random effect models allow for interactions between within- and between-level predictors, which are sometimes called cross-level interactions. To investigate these in a random effects models requires three parameters - a random slope for the lower-level predictor, the covariance between the random slope and random intercept, and the fixed effect term for the interaction. This is not possible to investigate in the fixed effects modeling framework because all cluster-level variables are thrown out. Investigation of different within- and between- associations for lower-level variables. Here the interest is investigating whether a within-cluster association is different than the between-cluster association. This is sometimes termed contextual effects modeling and also allows you to identify cases of Simpson's paradox. An example is the association between exercise and having a heart attack. While exercising, one is at higher risk for a heart attack, but on average, individuals who exercise a lot tend to have lower risk for a heart attack. Relatedly, adding in the cluster means of lower-level variables takes care of the endogeneity problem at level 1 often used as a reason to prefer fixed effects models. Prediction - random effects models employ empirical Bayes prediction of the random intercepts and slopes. This is great because the procedure corrects for the reliability of the group's prediction. Smaller groups get pulled toward the sample average prediction.
Should a Hausman test be used to decide between fixed vs. random effects?
Let's say the Hausman test favors the fixed effect model. Why might you still be interested in using the random effects model? The random effects or multilevel model allows a degree of flexibility in
Should a Hausman test be used to decide between fixed vs. random effects? Let's say the Hausman test favors the fixed effect model. Why might you still be interested in using the random effects model? The random effects or multilevel model allows a degree of flexibility in modeling that is much messier and in some cases impossible to implement in the fixed effect model. Examples include: Random slopes for the association between lower level variables and the outcome, which allow you to investigate whether the within-group association varies across groups. A classic example is growth curve modeling whereby the linear (or quadratic) rate of change in the outcome, codified by a continuous time variable) is allowed to vary across individuals or groups. In the fixed effect model, you can get at this in a crude way by interacting the lower-level variable with the cluster dummy variables. If you have a lot of groups, you have a lot of interactions. Related to the above, random effect models allow for interactions between within- and between-level predictors, which are sometimes called cross-level interactions. To investigate these in a random effects models requires three parameters - a random slope for the lower-level predictor, the covariance between the random slope and random intercept, and the fixed effect term for the interaction. This is not possible to investigate in the fixed effects modeling framework because all cluster-level variables are thrown out. Investigation of different within- and between- associations for lower-level variables. Here the interest is investigating whether a within-cluster association is different than the between-cluster association. This is sometimes termed contextual effects modeling and also allows you to identify cases of Simpson's paradox. An example is the association between exercise and having a heart attack. While exercising, one is at higher risk for a heart attack, but on average, individuals who exercise a lot tend to have lower risk for a heart attack. Relatedly, adding in the cluster means of lower-level variables takes care of the endogeneity problem at level 1 often used as a reason to prefer fixed effects models. Prediction - random effects models employ empirical Bayes prediction of the random intercepts and slopes. This is great because the procedure corrects for the reliability of the group's prediction. Smaller groups get pulled toward the sample average prediction.
Should a Hausman test be used to decide between fixed vs. random effects? Let's say the Hausman test favors the fixed effect model. Why might you still be interested in using the random effects model? The random effects or multilevel model allows a degree of flexibility in
40,930
MatchIt output using Coarsened Exact Matching
The effective sample size (ESS) is the size of an unweighted sample carrying approximately the same precision as the weighted sample in question. The formula for the ESS is $$ESS = \frac{(\sum w)^2}{\sum w^2}$$ When the weights are scaled to have an average of 1, the formula can be rewritten as $$ESS = \frac{n}{1+\text{Var}(w)}$$ where $n$ is the sample size and $\text{Var}(w)$ is the variance of the weights (computed using the population formula). The second formula makes it clear that when there is variability in the weights (i.e., the weights are not all the same), the ESS will be smaller than $n$. This is described in the documentation for summary.matchit(), which can be viewed here (7th paragraph in Details). In coarsened exact matching (CEM), a formula is used to compute the matching weights after the matching. The weights that arise from this formula are different for each unit and depend on how many units of each treatment group are in each matching stratum. This is explained in the matchit() documentation here (section "How Matching Weights Are Computed" in Details). The reason the ESS is not equal to the size of the treated sample is that CEM does not involve a 1:1 match of treated to control units. The ratio of treated to control units differs across strata. If you want 1:1 matching after CEM, set k2k = TRUE. Doing this drops units in each stratum so that the number of treated and control units is equal. With this option, all weights will be 1, the ESS will be equal to the sample size, and the ESS of the two groups will be the same. In your dataset, there would be no advantage to doing this. The match.data() output contains the data from the matched sample as well as columns related to the output of the matching. weights contains the matching weights. These must always be used in estimating the treatment effect; the point of matching is to create matching weights, which create covariate balance and reduce the bias in an effect estimate. subclass contains stratum membership, i.e., the ID of the stratum to which each unit is assigned. In 1:1 matching, each stratum will contain two units: one control and one treated. In CEM, varying numbers of treated and control units may appear within strata. The strata are used in the estimation of the standard error of the effect estimate. See the vignette on how to estimate effects after matching for how to use these columns. You'll want to refer to the section "After Stratum Matching" for estimating effects after CEM. Thank you for letting me know that it is unclear what those columns mean. I will update the documentation to be clearer. I encourage you to browse the MatchIt website as I have spent a considerable amount of time documenting every facet of MatchIt and providing instructions for how to use it validly.
MatchIt output using Coarsened Exact Matching
The effective sample size (ESS) is the size of an unweighted sample carrying approximately the same precision as the weighted sample in question. The formula for the ESS is $$ESS = \frac{(\sum w)^2}{\
MatchIt output using Coarsened Exact Matching The effective sample size (ESS) is the size of an unweighted sample carrying approximately the same precision as the weighted sample in question. The formula for the ESS is $$ESS = \frac{(\sum w)^2}{\sum w^2}$$ When the weights are scaled to have an average of 1, the formula can be rewritten as $$ESS = \frac{n}{1+\text{Var}(w)}$$ where $n$ is the sample size and $\text{Var}(w)$ is the variance of the weights (computed using the population formula). The second formula makes it clear that when there is variability in the weights (i.e., the weights are not all the same), the ESS will be smaller than $n$. This is described in the documentation for summary.matchit(), which can be viewed here (7th paragraph in Details). In coarsened exact matching (CEM), a formula is used to compute the matching weights after the matching. The weights that arise from this formula are different for each unit and depend on how many units of each treatment group are in each matching stratum. This is explained in the matchit() documentation here (section "How Matching Weights Are Computed" in Details). The reason the ESS is not equal to the size of the treated sample is that CEM does not involve a 1:1 match of treated to control units. The ratio of treated to control units differs across strata. If you want 1:1 matching after CEM, set k2k = TRUE. Doing this drops units in each stratum so that the number of treated and control units is equal. With this option, all weights will be 1, the ESS will be equal to the sample size, and the ESS of the two groups will be the same. In your dataset, there would be no advantage to doing this. The match.data() output contains the data from the matched sample as well as columns related to the output of the matching. weights contains the matching weights. These must always be used in estimating the treatment effect; the point of matching is to create matching weights, which create covariate balance and reduce the bias in an effect estimate. subclass contains stratum membership, i.e., the ID of the stratum to which each unit is assigned. In 1:1 matching, each stratum will contain two units: one control and one treated. In CEM, varying numbers of treated and control units may appear within strata. The strata are used in the estimation of the standard error of the effect estimate. See the vignette on how to estimate effects after matching for how to use these columns. You'll want to refer to the section "After Stratum Matching" for estimating effects after CEM. Thank you for letting me know that it is unclear what those columns mean. I will update the documentation to be clearer. I encourage you to browse the MatchIt website as I have spent a considerable amount of time documenting every facet of MatchIt and providing instructions for how to use it validly.
MatchIt output using Coarsened Exact Matching The effective sample size (ESS) is the size of an unweighted sample carrying approximately the same precision as the weighted sample in question. The formula for the ESS is $$ESS = \frac{(\sum w)^2}{\
40,931
MatchIt output using Coarsened Exact Matching
ESS is the Effective Sample Size: #Effective sample size ESS <- function(w) { weights <- weights * s.weights n <- matrix(0, ncol=2, nrow=6, dimnames = list(c("All (ESS)", "All", "Matched (ESS)","Matched", "Unmatched","Discarded"),... The treatment weight of 1 is why both the "unweighted" and ESS are 3127. If you had another question please clarify it. These resources may help: https://www.jstatsoft.org/article/view/v042i08 https://gking.harvard.edu/cem https://github.com/kosukeimai/MatchIt/
MatchIt output using Coarsened Exact Matching
ESS is the Effective Sample Size: #Effective sample size ESS <- function(w) { weights <- weights * s.weights n <- matrix(0, ncol=2, nrow=6, dimnames = list(c("All (ESS)", "All",
MatchIt output using Coarsened Exact Matching ESS is the Effective Sample Size: #Effective sample size ESS <- function(w) { weights <- weights * s.weights n <- matrix(0, ncol=2, nrow=6, dimnames = list(c("All (ESS)", "All", "Matched (ESS)","Matched", "Unmatched","Discarded"),... The treatment weight of 1 is why both the "unweighted" and ESS are 3127. If you had another question please clarify it. These resources may help: https://www.jstatsoft.org/article/view/v042i08 https://gking.harvard.edu/cem https://github.com/kosukeimai/MatchIt/
MatchIt output using Coarsened Exact Matching ESS is the Effective Sample Size: #Effective sample size ESS <- function(w) { weights <- weights * s.weights n <- matrix(0, ncol=2, nrow=6, dimnames = list(c("All (ESS)", "All",
40,932
Factor Levels in Interaction Terms for GLM
First, I would avoid any stepwise procedures. That said: if I include an interaction term between mpg and type, is it appropriate to have an interaction for only certain levels of type and mpg, but not include all levels of type for the interaction. Normally you would just specify the model as carVal ~ mpg * type or equivalently: carVal ~ mpg + type + mpg:type Then the software will create all the necessary dummy variables and interactions between them and mpg It looks from your question that you might be creating the dummy variables yourself, in which case there is no technical reason why you can't omit some of the interactions, if you have good reason to, but in my experience this can create all kinds of problems such as a rank-deficient model matrix, or an overfitted model which generalises extremely poorly to new data. So if you want to interaction, just use mpg * type - it will make your life much easier.
Factor Levels in Interaction Terms for GLM
First, I would avoid any stepwise procedures. That said: if I include an interaction term between mpg and type, is it appropriate to have an interaction for only certain levels of type and mpg, but n
Factor Levels in Interaction Terms for GLM First, I would avoid any stepwise procedures. That said: if I include an interaction term between mpg and type, is it appropriate to have an interaction for only certain levels of type and mpg, but not include all levels of type for the interaction. Normally you would just specify the model as carVal ~ mpg * type or equivalently: carVal ~ mpg + type + mpg:type Then the software will create all the necessary dummy variables and interactions between them and mpg It looks from your question that you might be creating the dummy variables yourself, in which case there is no technical reason why you can't omit some of the interactions, if you have good reason to, but in my experience this can create all kinds of problems such as a rank-deficient model matrix, or an overfitted model which generalises extremely poorly to new data. So if you want to interaction, just use mpg * type - it will make your life much easier.
Factor Levels in Interaction Terms for GLM First, I would avoid any stepwise procedures. That said: if I include an interaction term between mpg and type, is it appropriate to have an interaction for only certain levels of type and mpg, but n
40,933
Poisson distribution complications with proportions, GLMM
Normality and homoscedasticity were tested by Shapiro-Wilk and Levene test. Note that there is no requirement for the data to be normally distributed, nor homoscedastic. These tests are a waste of your time. If you want to model the raw counts as the outcome then a count model such as Poisson or negative binomial would be appropriate. If you want to model proportions as the outcome, then a count model will be inappropriate. A regular linear mixed model (LMM) might be sufficient. You can plot the residuals of the LMM and if they are approximately normally distributed, then all is good. If not then, you may consider a binomial GLMM or a beta GLMM.
Poisson distribution complications with proportions, GLMM
Normality and homoscedasticity were tested by Shapiro-Wilk and Levene test. Note that there is no requirement for the data to be normally distributed, nor homoscedastic. These tests are a waste of yo
Poisson distribution complications with proportions, GLMM Normality and homoscedasticity were tested by Shapiro-Wilk and Levene test. Note that there is no requirement for the data to be normally distributed, nor homoscedastic. These tests are a waste of your time. If you want to model the raw counts as the outcome then a count model such as Poisson or negative binomial would be appropriate. If you want to model proportions as the outcome, then a count model will be inappropriate. A regular linear mixed model (LMM) might be sufficient. You can plot the residuals of the LMM and if they are approximately normally distributed, then all is good. If not then, you may consider a binomial GLMM or a beta GLMM.
Poisson distribution complications with proportions, GLMM Normality and homoscedasticity were tested by Shapiro-Wilk and Levene test. Note that there is no requirement for the data to be normally distributed, nor homoscedastic. These tests are a waste of yo
40,934
Metropolis-Hastings for linear regression, prior on sigma?
There are a few minor issues with your sampler. First, you should always compute the PDF or PMF on a log scale, as for any non-trivial problem you will likely run into overflow/underflow issues (speaking from experience, this happens very quickly). I've switched these functions to a log scale but it's worth checking that I've done this correctly. The reason your sampler didn't work as you posted it is mainly because you didn't assign curr_s to mov_s (ie, you didn't update the current value if the Metropolis-Hastings ratio was above the uniform value). For a symmetric non-negative proposal, I've seen people use a log-normal distribution. However you could also adapt the acceptance ratio to be a Metropolis-Hastings ratio rather than a Metropolis ratio (ie, include the ratio of the densities of the proposal as well as the ratio of the posterior, see this for a quick guide). I don't think a truncated uniform distribution is symmetric so the behaviour of your sampler at values of sigma < 0.25 may be incorrect. You also didn't define your data (X, y) or import all the libraries you used, which is always nice as it makes it easier to load and debug your code. If I can be so bold as to suggest some simple next steps - it would be pretty straightforward to allow an arbitrary design matrix rather than simply slope and intercept. As for your question, What are the benefits of sampling different sigma values? For the model, $y_i \sim N(X_i\beta, \sigma^2)$, it is natural in most cases to assume that you do not know the magnitude of noise around the conditional mean. Learning this magnitude will enable you to make better predictions using the posterior estimates. This magnitude is controlled by $\sigma^2$. I struggle to think of a situation where the regression coefficients ($\beta$) are unknown, but the magnitude of the residuals $\epsilon_i = y_i - X_i\beta$ is known. Furthermore, to quantify uncertainty around predictions, it's necessary to have a good estimate of the variance around the conditional mean. import numpy as np import random import seaborn as sns def normalPDF(x,mu,sigma): num = np.exp(-1/2*((x-mu)/sigma)**2) den = np.sqrt(2*np.pi)*sigma return num/den def invGamma(x,a,b): non_zero = int(x>=0) func = x**(a-1)*np.exp(-x/b) return non_zero*func def lr_mcmc(X,Y,hops=10_000): samples = [] curr_a = random.gauss(1,1) curr_b = random.gauss(2,1) curr_s = random.uniform(3,1) prior_a_curr = normalPDF(x=curr_a,mu=1,sigma=1) prior_b_curr = normalPDF(x=curr_b,mu=2,sigma=1) prior_s_curr = invGamma(x=curr_s,a=3,b=1) log_lik_curr = sum([np.log(normalPDF(x=curr_b*x + curr_a,mu=y,sigma=curr_s)) for x,y in zip(X,Y)]) current_numerator = log_lik_curr + np.log(prior_a_curr) + np.log(prior_b_curr) + np.log(prior_s_curr) count = 0 for i in range(hops): samples.append((curr_b,curr_a,curr_s)) if count == 0: #propose movement to b mov_a = curr_a mov_b = curr_b + random.uniform(-0.25,0.25) mov_s = curr_s count += 1 elif count == 1: #propose movement to a mov_a = curr_a + random.uniform(-0.25,0.25) mov_b = curr_b mov_s = curr_s count += 1 else: #propose movement to s mov_a = curr_a mov_b = curr_b mov_s = curr_s + random.uniform(-0.25,0.25) count = 0 prior_b_mov = normalPDF(x=mov_b,mu=2,sigma=1) prior_a_mov = normalPDF(x=mov_a,mu=1,sigma=1) prior_s_mov = invGamma(x=mov_s,a=3,b=1) if prior_s_mov <=0: continue #automatically reject because variance cannot equal 0. log_lik_mov = sum([np.log(normalPDF(x=mov_b*x + mov_a,mu=y,sigma=mov_s)) for x,y in zip(X,Y)]) movement_numerator = log_lik_mov + np.log(prior_a_mov) + np.log(prior_b_mov) + np.log(prior_s_mov) ratio = np.exp(movement_numerator - current_numerator) event = random.uniform(0,1) if event <= ratio: curr_b = mov_b curr_a = mov_a curr_s = mov_s current_numerator = movement_numerator return samples beta = np.random.normal(0, 1, [1, ]) X = np.random.normal(0, 1, [20, 1]) y = np.matmul(X, beta) test2 = lr_mcmc(X=X, y=y, hops=25_000) sns.kdeplot([test2[i][0] for i in range(len(test2))],[test2[i][1] for i in range(len(test2))],cmap="inferno",shade=True) plt.show()
Metropolis-Hastings for linear regression, prior on sigma?
There are a few minor issues with your sampler. First, you should always compute the PDF or PMF on a log scale, as for any non-trivial problem you will likely run into overflow/underflow issues (speak
Metropolis-Hastings for linear regression, prior on sigma? There are a few minor issues with your sampler. First, you should always compute the PDF or PMF on a log scale, as for any non-trivial problem you will likely run into overflow/underflow issues (speaking from experience, this happens very quickly). I've switched these functions to a log scale but it's worth checking that I've done this correctly. The reason your sampler didn't work as you posted it is mainly because you didn't assign curr_s to mov_s (ie, you didn't update the current value if the Metropolis-Hastings ratio was above the uniform value). For a symmetric non-negative proposal, I've seen people use a log-normal distribution. However you could also adapt the acceptance ratio to be a Metropolis-Hastings ratio rather than a Metropolis ratio (ie, include the ratio of the densities of the proposal as well as the ratio of the posterior, see this for a quick guide). I don't think a truncated uniform distribution is symmetric so the behaviour of your sampler at values of sigma < 0.25 may be incorrect. You also didn't define your data (X, y) or import all the libraries you used, which is always nice as it makes it easier to load and debug your code. If I can be so bold as to suggest some simple next steps - it would be pretty straightforward to allow an arbitrary design matrix rather than simply slope and intercept. As for your question, What are the benefits of sampling different sigma values? For the model, $y_i \sim N(X_i\beta, \sigma^2)$, it is natural in most cases to assume that you do not know the magnitude of noise around the conditional mean. Learning this magnitude will enable you to make better predictions using the posterior estimates. This magnitude is controlled by $\sigma^2$. I struggle to think of a situation where the regression coefficients ($\beta$) are unknown, but the magnitude of the residuals $\epsilon_i = y_i - X_i\beta$ is known. Furthermore, to quantify uncertainty around predictions, it's necessary to have a good estimate of the variance around the conditional mean. import numpy as np import random import seaborn as sns def normalPDF(x,mu,sigma): num = np.exp(-1/2*((x-mu)/sigma)**2) den = np.sqrt(2*np.pi)*sigma return num/den def invGamma(x,a,b): non_zero = int(x>=0) func = x**(a-1)*np.exp(-x/b) return non_zero*func def lr_mcmc(X,Y,hops=10_000): samples = [] curr_a = random.gauss(1,1) curr_b = random.gauss(2,1) curr_s = random.uniform(3,1) prior_a_curr = normalPDF(x=curr_a,mu=1,sigma=1) prior_b_curr = normalPDF(x=curr_b,mu=2,sigma=1) prior_s_curr = invGamma(x=curr_s,a=3,b=1) log_lik_curr = sum([np.log(normalPDF(x=curr_b*x + curr_a,mu=y,sigma=curr_s)) for x,y in zip(X,Y)]) current_numerator = log_lik_curr + np.log(prior_a_curr) + np.log(prior_b_curr) + np.log(prior_s_curr) count = 0 for i in range(hops): samples.append((curr_b,curr_a,curr_s)) if count == 0: #propose movement to b mov_a = curr_a mov_b = curr_b + random.uniform(-0.25,0.25) mov_s = curr_s count += 1 elif count == 1: #propose movement to a mov_a = curr_a + random.uniform(-0.25,0.25) mov_b = curr_b mov_s = curr_s count += 1 else: #propose movement to s mov_a = curr_a mov_b = curr_b mov_s = curr_s + random.uniform(-0.25,0.25) count = 0 prior_b_mov = normalPDF(x=mov_b,mu=2,sigma=1) prior_a_mov = normalPDF(x=mov_a,mu=1,sigma=1) prior_s_mov = invGamma(x=mov_s,a=3,b=1) if prior_s_mov <=0: continue #automatically reject because variance cannot equal 0. log_lik_mov = sum([np.log(normalPDF(x=mov_b*x + mov_a,mu=y,sigma=mov_s)) for x,y in zip(X,Y)]) movement_numerator = log_lik_mov + np.log(prior_a_mov) + np.log(prior_b_mov) + np.log(prior_s_mov) ratio = np.exp(movement_numerator - current_numerator) event = random.uniform(0,1) if event <= ratio: curr_b = mov_b curr_a = mov_a curr_s = mov_s current_numerator = movement_numerator return samples beta = np.random.normal(0, 1, [1, ]) X = np.random.normal(0, 1, [20, 1]) y = np.matmul(X, beta) test2 = lr_mcmc(X=X, y=y, hops=25_000) sns.kdeplot([test2[i][0] for i in range(len(test2))],[test2[i][1] for i in range(len(test2))],cmap="inferno",shade=True) plt.show()
Metropolis-Hastings for linear regression, prior on sigma? There are a few minor issues with your sampler. First, you should always compute the PDF or PMF on a log scale, as for any non-trivial problem you will likely run into overflow/underflow issues (speak
40,935
How well does GAN (generative adversarial network) perform for small samples?
It's true that GANs generally produce good results when trained on a massive amount of data. However, CycleGAN has been around for a while and they produce realistic images when trained only on a few images (the open-sourced datasets used by the authors have about 1000 images on an average). That said, this (very recent) paper talks about differentiable augmentation as a novel technique for training data-efficient GANs. Their results include experiments with a fraction of data in CIFAR10 and CIFAR100 datasets. This paper from MIT considers evolutionary GAN training as a means to reduce the amount of data used for training. It would also help to look specifically into the papers that use GANs for medical image synthesis or translation problems because data is already scarce in the medical domain, hence people have found some interesting techniques to get around it. As for the non-image-generation applications of GANs, WaveGAN is a model for synthesizing audio, spaceGAN for geospatial modeling, etc. This Reddit discussion gives many more examples of GANs in non-image applications.
How well does GAN (generative adversarial network) perform for small samples?
It's true that GANs generally produce good results when trained on a massive amount of data. However, CycleGAN has been around for a while and they produce realistic images when trained only on a few
How well does GAN (generative adversarial network) perform for small samples? It's true that GANs generally produce good results when trained on a massive amount of data. However, CycleGAN has been around for a while and they produce realistic images when trained only on a few images (the open-sourced datasets used by the authors have about 1000 images on an average). That said, this (very recent) paper talks about differentiable augmentation as a novel technique for training data-efficient GANs. Their results include experiments with a fraction of data in CIFAR10 and CIFAR100 datasets. This paper from MIT considers evolutionary GAN training as a means to reduce the amount of data used for training. It would also help to look specifically into the papers that use GANs for medical image synthesis or translation problems because data is already scarce in the medical domain, hence people have found some interesting techniques to get around it. As for the non-image-generation applications of GANs, WaveGAN is a model for synthesizing audio, spaceGAN for geospatial modeling, etc. This Reddit discussion gives many more examples of GANs in non-image applications.
How well does GAN (generative adversarial network) perform for small samples? It's true that GANs generally produce good results when trained on a massive amount of data. However, CycleGAN has been around for a while and they produce realistic images when trained only on a few
40,936
Probability of having a disease - Bayes' Theorem problem
In order to find the posterior probability, you need two updates on the prior probability of any citizen having this disorder ($3\%$). In general, $P(T+| D) \cdot P(D) = P(D | T+) \cdot P(T+)$, where $D$ means "the citizen has the disorder" and $T+$ means "the citizen tests positive". In this case, $P(D)=3\%$ and $P(T+|D)=97\%$. $P(T+)$ can be calculated as a partition of a domain: $P(T+) = P(T+|D)\cdot P(D) + P(T+|\bar{D})\cdot P(\bar{D})$, where $\bar{D}$ means "the citizen does not have the disorder", and $P(\bar{D})=1-0.03=97\%$. $P(T+|\bar{D})$ is the false positive rate (the probability of testing positive given that one doesn't have the disorder). In this case, $P(T+|\bar{D})=2\%$. Then, $\begin{align} P(T+) &= 0.97\cdot 0.03 + 0.02\cdot0.97 \\ &= 0.0485 \end{align}$ The probability that a citizen has the disorder after testing positive, then, is $\begin{align} P(D|T+) &= \dfrac{0.97}{0.0485}\cdot 0.03 \\ &= 60\% \end{align}$ However, they test themselves again, and this time it comes back negative. You just have to apply this procedure again: $P(T-|D)\cdot P(D) = P(D|T-)\cdot P(T-)$, except you use $P(D)=60\%$, the updated probability that a citizen who tested positive has the disorder. In this case, $\begin{align} P(T-|D) &= 1-0.97 = 3\% \\ P(T-|\bar{D}) &= 1-0.02 = 98\% \end{align}$ In my calculations, it came out to $P(D|T-)=4.4\%$
Probability of having a disease - Bayes' Theorem problem
In order to find the posterior probability, you need two updates on the prior probability of any citizen having this disorder ($3\%$). In general, $P(T+| D) \cdot P(D) = P(D | T+) \cdot P(T+)$, where
Probability of having a disease - Bayes' Theorem problem In order to find the posterior probability, you need two updates on the prior probability of any citizen having this disorder ($3\%$). In general, $P(T+| D) \cdot P(D) = P(D | T+) \cdot P(T+)$, where $D$ means "the citizen has the disorder" and $T+$ means "the citizen tests positive". In this case, $P(D)=3\%$ and $P(T+|D)=97\%$. $P(T+)$ can be calculated as a partition of a domain: $P(T+) = P(T+|D)\cdot P(D) + P(T+|\bar{D})\cdot P(\bar{D})$, where $\bar{D}$ means "the citizen does not have the disorder", and $P(\bar{D})=1-0.03=97\%$. $P(T+|\bar{D})$ is the false positive rate (the probability of testing positive given that one doesn't have the disorder). In this case, $P(T+|\bar{D})=2\%$. Then, $\begin{align} P(T+) &= 0.97\cdot 0.03 + 0.02\cdot0.97 \\ &= 0.0485 \end{align}$ The probability that a citizen has the disorder after testing positive, then, is $\begin{align} P(D|T+) &= \dfrac{0.97}{0.0485}\cdot 0.03 \\ &= 60\% \end{align}$ However, they test themselves again, and this time it comes back negative. You just have to apply this procedure again: $P(T-|D)\cdot P(D) = P(D|T-)\cdot P(T-)$, except you use $P(D)=60\%$, the updated probability that a citizen who tested positive has the disorder. In this case, $\begin{align} P(T-|D) &= 1-0.97 = 3\% \\ P(T-|\bar{D}) &= 1-0.02 = 98\% \end{align}$ In my calculations, it came out to $P(D|T-)=4.4\%$
Probability of having a disease - Bayes' Theorem problem In order to find the posterior probability, you need two updates on the prior probability of any citizen having this disorder ($3\%$). In general, $P(T+| D) \cdot P(D) = P(D | T+) \cdot P(T+)$, where
40,937
Probability of having a disease - Bayes' Theorem problem
Assume the second test is independent of the first test (this means that the second test result is not affected by the first test). The probability that a person who has the disorder gets one + and one - testing results is 2 x 0.03 x 0.97 = 0.0582, while the probability a healthy person gets one + and one - testing results is 2 x 0.02 x 0.98 = 0.0392. Then applying Bayes theorem, we will get P = (0.03 x 0.0582)/(0.03 x 0.0582 + 0.97 x 0.0392) = 4.39 % This is the same as LmnICE's result, though the methods are somehow different.
Probability of having a disease - Bayes' Theorem problem
Assume the second test is independent of the first test (this means that the second test result is not affected by the first test). The probability that a person who has the disorder gets one + and on
Probability of having a disease - Bayes' Theorem problem Assume the second test is independent of the first test (this means that the second test result is not affected by the first test). The probability that a person who has the disorder gets one + and one - testing results is 2 x 0.03 x 0.97 = 0.0582, while the probability a healthy person gets one + and one - testing results is 2 x 0.02 x 0.98 = 0.0392. Then applying Bayes theorem, we will get P = (0.03 x 0.0582)/(0.03 x 0.0582 + 0.97 x 0.0392) = 4.39 % This is the same as LmnICE's result, though the methods are somehow different.
Probability of having a disease - Bayes' Theorem problem Assume the second test is independent of the first test (this means that the second test result is not affected by the first test). The probability that a person who has the disorder gets one + and on
40,938
What I should do if no distribution fits my dataset?
If you have 26K data, any test on a given distribution will fail. Because for that much data, the testing can detect tiny difference and report it is not coming from that distribution. I would strongly recommend you to read these posts Are large data sets inappropriate for hypothesis testing? Is normality testing 'essentially useless'? It is very common that data is not coming from any distribution in text book. But we still can do a lot with it. For example we can fit data with Mixture of Gaussian model. In addition, the distribution of your data seems too good (that coming from normal distribution) that may be coming from some simulation but not from the real world. I would suggest to do following thing: draw 26K sample from normal distribution and run the hypothesis test and all the plots to see the results. This is probability what was happening in your case.
What I should do if no distribution fits my dataset?
If you have 26K data, any test on a given distribution will fail. Because for that much data, the testing can detect tiny difference and report it is not coming from that distribution. I would strong
What I should do if no distribution fits my dataset? If you have 26K data, any test on a given distribution will fail. Because for that much data, the testing can detect tiny difference and report it is not coming from that distribution. I would strongly recommend you to read these posts Are large data sets inappropriate for hypothesis testing? Is normality testing 'essentially useless'? It is very common that data is not coming from any distribution in text book. But we still can do a lot with it. For example we can fit data with Mixture of Gaussian model. In addition, the distribution of your data seems too good (that coming from normal distribution) that may be coming from some simulation but not from the real world. I would suggest to do following thing: draw 26K sample from normal distribution and run the hypothesis test and all the plots to see the results. This is probability what was happening in your case.
What I should do if no distribution fits my dataset? If you have 26K data, any test on a given distribution will fail. Because for that much data, the testing can detect tiny difference and report it is not coming from that distribution. I would strong
40,939
What I should do if no distribution fits my dataset?
You could use Mathematica's FindDistribution command, but the person above who said that with so much data you are unlikely to see any test report that the data is Normal was absolutely correct. However, FindDistribution almost certainly will return one or more (mixture) distributions that fit fairly well. I had a similar problem and used Tukey's Fences (Wikipedia) to determine that about 18% of my very large data set was outliers. It took several months of on and off reflection and reading for me to figure out where the outliers were coming from. I suggest that you spend whatever time it takes to develop an accurate mental and/or pictorial model of what is going on in the process so that you can explain everything that is going on in your process, including outliers, with a theory.
What I should do if no distribution fits my dataset?
You could use Mathematica's FindDistribution command, but the person above who said that with so much data you are unlikely to see any test report that the data is Normal was absolutely correct. Howe
What I should do if no distribution fits my dataset? You could use Mathematica's FindDistribution command, but the person above who said that with so much data you are unlikely to see any test report that the data is Normal was absolutely correct. However, FindDistribution almost certainly will return one or more (mixture) distributions that fit fairly well. I had a similar problem and used Tukey's Fences (Wikipedia) to determine that about 18% of my very large data set was outliers. It took several months of on and off reflection and reading for me to figure out where the outliers were coming from. I suggest that you spend whatever time it takes to develop an accurate mental and/or pictorial model of what is going on in the process so that you can explain everything that is going on in your process, including outliers, with a theory.
What I should do if no distribution fits my dataset? You could use Mathematica's FindDistribution command, but the person above who said that with so much data you are unlikely to see any test report that the data is Normal was absolutely correct. Howe
40,940
What I should do if no distribution fits my dataset?
You got just Two options here: 1.Create a database which fits a distribution.! 2.divide your database (hope it will fit) and run them concurrently and merge later as per your requirement
What I should do if no distribution fits my dataset?
You got just Two options here: 1.Create a database which fits a distribution.! 2.divide your database (hope it will fit) and run them concurrently and merge later as per your requirement
What I should do if no distribution fits my dataset? You got just Two options here: 1.Create a database which fits a distribution.! 2.divide your database (hope it will fit) and run them concurrently and merge later as per your requirement
What I should do if no distribution fits my dataset? You got just Two options here: 1.Create a database which fits a distribution.! 2.divide your database (hope it will fit) and run them concurrently and merge later as per your requirement
40,941
Should I normalize all data prior feeding the neural network models?
Yes, normalisation/scaling is typically recommended and sometimes very important. Especially for neural networks, normalisation can be very crucial because when you input unnormalised inputs to activation functions, you can get stuck in a very flat region in the domain and may not learn at all. Or worse, you can end up with numerical issues. One very obvious reason is that you need to tune (but you don't) the weight initialisations in the network according to the input range corresponding to that weight, e.g. let $x_1,x_2$ be two distinct features and $w_1,w_2$ be the corresponding weights. Also let the range of the feature be as follows: $x_1\in[0,1000],x_2\in[0,1]$. When you initialise $w_i$ with numbers within $[-1,1]$ for example, it won't mean the same for $x_1$ and $x_2$. Probably, the sum $w_1x_1+w_2x_2$ will be dominated by $w_1x_1$ and you won't see the effect of $w_2x_2$ for some time unless you're very lucky, and learning will be hindered significantly until the network is finally able to learn what $w_1$ should have been in the first place. Doesn't normalization require that data conforms to the normal parametric distribution? No, normalisation has nothing to do with normal distribution. One form of normalisation, called standardising, which is subtracting the mean and dividing by the deviation is very common in the literature and typically used for converting a normal RV into standard normal RV. Although the idea may stem from normal distributions, the operation has nothing to do with normal distribution.
Should I normalize all data prior feeding the neural network models?
Yes, normalisation/scaling is typically recommended and sometimes very important. Especially for neural networks, normalisation can be very crucial because when you input unnormalised inputs to activa
Should I normalize all data prior feeding the neural network models? Yes, normalisation/scaling is typically recommended and sometimes very important. Especially for neural networks, normalisation can be very crucial because when you input unnormalised inputs to activation functions, you can get stuck in a very flat region in the domain and may not learn at all. Or worse, you can end up with numerical issues. One very obvious reason is that you need to tune (but you don't) the weight initialisations in the network according to the input range corresponding to that weight, e.g. let $x_1,x_2$ be two distinct features and $w_1,w_2$ be the corresponding weights. Also let the range of the feature be as follows: $x_1\in[0,1000],x_2\in[0,1]$. When you initialise $w_i$ with numbers within $[-1,1]$ for example, it won't mean the same for $x_1$ and $x_2$. Probably, the sum $w_1x_1+w_2x_2$ will be dominated by $w_1x_1$ and you won't see the effect of $w_2x_2$ for some time unless you're very lucky, and learning will be hindered significantly until the network is finally able to learn what $w_1$ should have been in the first place. Doesn't normalization require that data conforms to the normal parametric distribution? No, normalisation has nothing to do with normal distribution. One form of normalisation, called standardising, which is subtracting the mean and dividing by the deviation is very common in the literature and typically used for converting a normal RV into standard normal RV. Although the idea may stem from normal distributions, the operation has nothing to do with normal distribution.
Should I normalize all data prior feeding the neural network models? Yes, normalisation/scaling is typically recommended and sometimes very important. Especially for neural networks, normalisation can be very crucial because when you input unnormalised inputs to activa
40,942
Should I normalize all data prior feeding the neural network models?
The mention of Tensorflow in the question is a red herring -- the reasons that scaling is beneficial are not unique to Tensorflow, but instead are common to all methods that update model parameters using gradient descent. The reason we scale data is to improve gradient descent dynamics, and backpropagation using Tensorflow is just one application of gradient descent among many. Optimization via gradient descent proceeds more easily when the optimization surface is more "circular" and less "elliptical." The optimization proceeds more quickly in directions corresponding to the largest eigenvalue and more slowly in directions corresponding to the smallest eigenvalue. In other words, the optimization procedure is easier when the eigenvalues of the Hessian are on the same scale. None of this depends on the input data conforming to any particular parametric distribution; rescaling the inputs to have a common variance has the effect of preconditioning the Hessian matrix. More information: In Machine learning, how does normalization help in convergence of gradient descent? In general, real-valued inputs can be rescaled. There are some corner cases where rescaling inputs doesn't make any sense. For example, embeddings use a lookup table to transform integer-coded inputs to a specific vector. Rescaling this to have 0 mean and variance 1 (or vary between 0 and 1) is meaningless and not helpful, because it breaks the lookup table property.
Should I normalize all data prior feeding the neural network models?
The mention of Tensorflow in the question is a red herring -- the reasons that scaling is beneficial are not unique to Tensorflow, but instead are common to all methods that update model parameters us
Should I normalize all data prior feeding the neural network models? The mention of Tensorflow in the question is a red herring -- the reasons that scaling is beneficial are not unique to Tensorflow, but instead are common to all methods that update model parameters using gradient descent. The reason we scale data is to improve gradient descent dynamics, and backpropagation using Tensorflow is just one application of gradient descent among many. Optimization via gradient descent proceeds more easily when the optimization surface is more "circular" and less "elliptical." The optimization proceeds more quickly in directions corresponding to the largest eigenvalue and more slowly in directions corresponding to the smallest eigenvalue. In other words, the optimization procedure is easier when the eigenvalues of the Hessian are on the same scale. None of this depends on the input data conforming to any particular parametric distribution; rescaling the inputs to have a common variance has the effect of preconditioning the Hessian matrix. More information: In Machine learning, how does normalization help in convergence of gradient descent? In general, real-valued inputs can be rescaled. There are some corner cases where rescaling inputs doesn't make any sense. For example, embeddings use a lookup table to transform integer-coded inputs to a specific vector. Rescaling this to have 0 mean and variance 1 (or vary between 0 and 1) is meaningless and not helpful, because it breaks the lookup table property.
Should I normalize all data prior feeding the neural network models? The mention of Tensorflow in the question is a red herring -- the reasons that scaling is beneficial are not unique to Tensorflow, but instead are common to all methods that update model parameters us
40,943
Detailed description/scripts of mathematical models for Coronavirus
I know answers aren't supposed to be just links, but this is the best I can do. This page links to a number of public covid 19 studies done in R. https://refind.com/znmeb/r-tools-for-coronavirus This one Focuses in-depth on epidemiology models. https://timchurches.github.io/blog/posts/2020-02-18-analysing-covid-19-2019-ncov-outbreak-data-with-r-part-1/ Direct link to some of the cool stuff. https://www.statsandr.com/blog/top-r-resources-on-covid-19-coronavirus/
Detailed description/scripts of mathematical models for Coronavirus
I know answers aren't supposed to be just links, but this is the best I can do. This page links to a number of public covid 19 studies done in R. https://refind.com/znmeb/r-tools-for-coronavirus This
Detailed description/scripts of mathematical models for Coronavirus I know answers aren't supposed to be just links, but this is the best I can do. This page links to a number of public covid 19 studies done in R. https://refind.com/znmeb/r-tools-for-coronavirus This one Focuses in-depth on epidemiology models. https://timchurches.github.io/blog/posts/2020-02-18-analysing-covid-19-2019-ncov-outbreak-data-with-r-part-1/ Direct link to some of the cool stuff. https://www.statsandr.com/blog/top-r-resources-on-covid-19-coronavirus/
Detailed description/scripts of mathematical models for Coronavirus I know answers aren't supposed to be just links, but this is the best I can do. This page links to a number of public covid 19 studies done in R. https://refind.com/znmeb/r-tools-for-coronavirus This
40,944
Detailed description/scripts of mathematical models for Coronavirus
The lancet article The method from the article in the Lancet is very straightforward. They model the spread of the virus by simulating the transmission on the level of each single infected individual. For each infected person they compute (randomly) how many other people they will infect and how long it will take for those others to infect others (or how likely it is that the others get contained due to policy measures like quarantaine). They use this model to estimate the variation of the potential number of new cases after some given time, by computing the random model a thousand times for each particular set of model parameters. If the number is large then they consider the outbreak uncontrolled and then this stochastic model can be used to express the probability to control the outbreak for a given set of parameters. So the difference between a deterministic model and stochastic model is the following: deterministic The virus spreads with a constant number and and speed. For instance each person passes on the virus to two others in a given specific time interval and then the growth will be like 1,2,4,8,16,etc. stochastic The spread of the virus is random. By how many it increases is random and not every time the same factor. Some people spread a lot others only a little. For instance sometimes a person passes it on to three other people, and sometimes only one (but on average the same namely two). And then the growth will be random it may be high (when it triples a lot) it may be low (when only one person gets it). This randomness is expressed by repeating the model several times and then see how it ends up in all those cases. The serial interval distribution is explained in Figure 2 a . I haven't read the article in detail, but after a quick scan it seems to me that the serial time is the time between the moments that a person infects another person. The serial time distribution is the distribution of those times. It is not the name for a specific distribution. Note that the code of the Lancet article is available online. https://github.com/cmmid/ringbp/tree/master/R The imperial college article The infections will not continue exponentially. This is only in the very beginning. The reason why the infections rate decreases is because you can't infect a person that is already infected before. So the probability to spread the virus becomes less in time. (also, the infection rate depends on the weather/season as well, sometimes called respiratory season, that is I believe not incorporated in those models) A well known model that takes this decrease of infection rate into account is the SIR model (and this will already produce graphs like the ones you are looking for). However that model assumes homogeneous mixing which is not very realistic. So the model that they use at imperial college uses many smaller compartments which are schools, workplaces, households and probably some more. Then the spread occurs differently at different levels/distances. You can not infect your housemates when they are already sick, so often it is only one person that infects all the others members in the family (and that person has a relatively high transmission) and the others will spread relatively less (but they can pass on the virus in other places, like school work church etc. If these are not saturated yet. This is not easy to replicate. What you need to do is model the spatial structure realistically. Like age distribution in households and the networks of who is going to which work/school/church etc. A description of this work is given in one of the references. The model is normally used for influenza. https://www.pnas.org/content/suppl/2008/02/28/0706849105.DC1 I have made a toy model that sort of showcases these effects (but not with realistic distributions). What you get is not exponential growth but instead more something like a power law. The distribution grows in space and spreads at the edge of the infected population. It is a bit like the growth of area of a circle as function of it's circumference. $dA/dt = \text{constant} \times \text{circumference}$ but then for a fractal dimension structure. The result of the toy model is a curve that is in the beginning exponential (homogeneous mixing growth), but then changes into a power law relationship (growth at the edge of some geometric figure). In any case the growth is not exponential with a continuous rate, but instead the dynamics is changing (in this example the growth is only exponential for the first 5 generations). # create 500x500 people in matrix set.seed(1) L <- 5*10^2 people <- matrix(rep(0,(L)^2),L) # trackers for the locations of the people that got sick: # we start with index patient in the middle orderx <- c(round(L/2)) ordery <- c(round(L/2)) generation <- c(1) spread <- 0 R0 <- 3 R1 <- 0.25 # a probabiliy to spread the virus on long distance, e.g. due to travel. ##### run the virus ###### # compute probability density function # for probabilty of spreading out to nearby locations Lr <- 7 Lspread <- 1+Lr*2 # targets will be in a cube of LrxLr around the patient targets <- matrix(1:Lspread^2,Lspread) xt <- matrix(rep(c(1:Lspread)-(Lspread+1)/2,Lspread),Lspread) yt <- t(xt) # ps is some probability to get infected as function of distance ps <- c(exp(-c(Lr:1)*0.2),0,exp(-c(1:Lr)*0.2)) probs <- ps[xt+(Lspread+1)/2]*ps[yt+(Lspread+1)/2] ### plot for visualization of the spread plot(orderx,ordery,xlim=c(1,L),ylim=c(1,L), xlab = "", ylab= "", col=1,bg = 1,cex=0.2,pch=21) # itterate all the patients untill all have been dealt with # during this loop the number of patients increases while (spread < length(generation)) { spread <- spread + 1 x <- orderx[spread] y <- ordery[spread] g <- generation[spread] # selecting Rn people in the neighbourhood of the patient # Rn is sampled from a Poisson distribution with mean R0 Rn <- rpois(1,R0) if (Rn>0) { sel <- sample(targets,Rn, prob = probs) xt[sel] yt[sel] ## this loop picks out the R0 people ## these are gonna become new patients if they are susceptible for (i in 1:Rn) { #the modulo is to patch left with right and top with bottom xq <- (x+xt[sel[i]]-1)%%L+1 yq <- (y+yt[sel[i]]-1)%%L+1 # if the 'target' is not sick yet then add it as new patient if (people[xq,yq] == 0) { generation <- c(generation,g+1) orderx <- c(orderx,xq) ordery <- c(ordery,yq) people[xq,yq] <- g+1 colv <- (g+1)/30-floor((g+1)/30) points(xq,yq, col=hsv(colv,1,1),bg = hsv(colv,1,1),cex=0.1,pch=21) } } } ### additionally make R1 random people from far away sick nfar <- rpois(1,R1) ifar <- 0 while (ifar<nfar) { ifar = ifar +1 xq <- sample(1:L,1) yq <- sample(1:L,1) if ((people[xq,yq] == 0)*(rbinom(1,1,0.1)==1)) { generation <- c(generation,g+1) orderx <- c(orderx,xq) ordery <- c(ordery,yq) people[xq,yq] <- g+1 colv <- (g+1)/30-floor((g+1)/30) points(xq,yq, col=hsv(colv,1,1),bg = hsv(colv,1,1),cex=0.1,pch=21) } } } # ratio of people that got sick spread/L^2 # plot the spread in colours colv <- (generation+1)/40-floor((generation+1)/40) plot(orderx,ordery,xlim=c(1,L),ylim=c(1,L), xlab = "", ylab= "", col=hsv(colv,1,1),bg = hsv(colv,1,1),cex=0.1,pch=21) # plot the epidemiological curve I <- sapply(1:50, FUN = function(x) sum(generation == x)) plot(I, log = 'xy', xlab = "x, generation", ylab = "number of infectious people", type = "l", ylim = c(1,5*10^4), xlim = c(1,70)) gen <- 1:50 colv <- (gen+1)/40-floor((gen+1)/40) points(I,pch=21,col = 1, bg = hsv(colv,1,1)) lines((R0+R1)^c(0:50), lty=2) sm <- 4:50 lines(sm,0.5*sm^3.5, lty = 3) lines(sm,0.002*sm^6, lty = 4) legend(1,5*10^4, c(expression((R[0]+R[1])^x),expression(0.5*x^3.5), expression(0.002*x^6)), lty = c(2,3,4), xjust = 0, cex = 0.7)
Detailed description/scripts of mathematical models for Coronavirus
The lancet article The method from the article in the Lancet is very straightforward. They model the spread of the virus by simulating the transmission on the level of each single infected individual.
Detailed description/scripts of mathematical models for Coronavirus The lancet article The method from the article in the Lancet is very straightforward. They model the spread of the virus by simulating the transmission on the level of each single infected individual. For each infected person they compute (randomly) how many other people they will infect and how long it will take for those others to infect others (or how likely it is that the others get contained due to policy measures like quarantaine). They use this model to estimate the variation of the potential number of new cases after some given time, by computing the random model a thousand times for each particular set of model parameters. If the number is large then they consider the outbreak uncontrolled and then this stochastic model can be used to express the probability to control the outbreak for a given set of parameters. So the difference between a deterministic model and stochastic model is the following: deterministic The virus spreads with a constant number and and speed. For instance each person passes on the virus to two others in a given specific time interval and then the growth will be like 1,2,4,8,16,etc. stochastic The spread of the virus is random. By how many it increases is random and not every time the same factor. Some people spread a lot others only a little. For instance sometimes a person passes it on to three other people, and sometimes only one (but on average the same namely two). And then the growth will be random it may be high (when it triples a lot) it may be low (when only one person gets it). This randomness is expressed by repeating the model several times and then see how it ends up in all those cases. The serial interval distribution is explained in Figure 2 a . I haven't read the article in detail, but after a quick scan it seems to me that the serial time is the time between the moments that a person infects another person. The serial time distribution is the distribution of those times. It is not the name for a specific distribution. Note that the code of the Lancet article is available online. https://github.com/cmmid/ringbp/tree/master/R The imperial college article The infections will not continue exponentially. This is only in the very beginning. The reason why the infections rate decreases is because you can't infect a person that is already infected before. So the probability to spread the virus becomes less in time. (also, the infection rate depends on the weather/season as well, sometimes called respiratory season, that is I believe not incorporated in those models) A well known model that takes this decrease of infection rate into account is the SIR model (and this will already produce graphs like the ones you are looking for). However that model assumes homogeneous mixing which is not very realistic. So the model that they use at imperial college uses many smaller compartments which are schools, workplaces, households and probably some more. Then the spread occurs differently at different levels/distances. You can not infect your housemates when they are already sick, so often it is only one person that infects all the others members in the family (and that person has a relatively high transmission) and the others will spread relatively less (but they can pass on the virus in other places, like school work church etc. If these are not saturated yet. This is not easy to replicate. What you need to do is model the spatial structure realistically. Like age distribution in households and the networks of who is going to which work/school/church etc. A description of this work is given in one of the references. The model is normally used for influenza. https://www.pnas.org/content/suppl/2008/02/28/0706849105.DC1 I have made a toy model that sort of showcases these effects (but not with realistic distributions). What you get is not exponential growth but instead more something like a power law. The distribution grows in space and spreads at the edge of the infected population. It is a bit like the growth of area of a circle as function of it's circumference. $dA/dt = \text{constant} \times \text{circumference}$ but then for a fractal dimension structure. The result of the toy model is a curve that is in the beginning exponential (homogeneous mixing growth), but then changes into a power law relationship (growth at the edge of some geometric figure). In any case the growth is not exponential with a continuous rate, but instead the dynamics is changing (in this example the growth is only exponential for the first 5 generations). # create 500x500 people in matrix set.seed(1) L <- 5*10^2 people <- matrix(rep(0,(L)^2),L) # trackers for the locations of the people that got sick: # we start with index patient in the middle orderx <- c(round(L/2)) ordery <- c(round(L/2)) generation <- c(1) spread <- 0 R0 <- 3 R1 <- 0.25 # a probabiliy to spread the virus on long distance, e.g. due to travel. ##### run the virus ###### # compute probability density function # for probabilty of spreading out to nearby locations Lr <- 7 Lspread <- 1+Lr*2 # targets will be in a cube of LrxLr around the patient targets <- matrix(1:Lspread^2,Lspread) xt <- matrix(rep(c(1:Lspread)-(Lspread+1)/2,Lspread),Lspread) yt <- t(xt) # ps is some probability to get infected as function of distance ps <- c(exp(-c(Lr:1)*0.2),0,exp(-c(1:Lr)*0.2)) probs <- ps[xt+(Lspread+1)/2]*ps[yt+(Lspread+1)/2] ### plot for visualization of the spread plot(orderx,ordery,xlim=c(1,L),ylim=c(1,L), xlab = "", ylab= "", col=1,bg = 1,cex=0.2,pch=21) # itterate all the patients untill all have been dealt with # during this loop the number of patients increases while (spread < length(generation)) { spread <- spread + 1 x <- orderx[spread] y <- ordery[spread] g <- generation[spread] # selecting Rn people in the neighbourhood of the patient # Rn is sampled from a Poisson distribution with mean R0 Rn <- rpois(1,R0) if (Rn>0) { sel <- sample(targets,Rn, prob = probs) xt[sel] yt[sel] ## this loop picks out the R0 people ## these are gonna become new patients if they are susceptible for (i in 1:Rn) { #the modulo is to patch left with right and top with bottom xq <- (x+xt[sel[i]]-1)%%L+1 yq <- (y+yt[sel[i]]-1)%%L+1 # if the 'target' is not sick yet then add it as new patient if (people[xq,yq] == 0) { generation <- c(generation,g+1) orderx <- c(orderx,xq) ordery <- c(ordery,yq) people[xq,yq] <- g+1 colv <- (g+1)/30-floor((g+1)/30) points(xq,yq, col=hsv(colv,1,1),bg = hsv(colv,1,1),cex=0.1,pch=21) } } } ### additionally make R1 random people from far away sick nfar <- rpois(1,R1) ifar <- 0 while (ifar<nfar) { ifar = ifar +1 xq <- sample(1:L,1) yq <- sample(1:L,1) if ((people[xq,yq] == 0)*(rbinom(1,1,0.1)==1)) { generation <- c(generation,g+1) orderx <- c(orderx,xq) ordery <- c(ordery,yq) people[xq,yq] <- g+1 colv <- (g+1)/30-floor((g+1)/30) points(xq,yq, col=hsv(colv,1,1),bg = hsv(colv,1,1),cex=0.1,pch=21) } } } # ratio of people that got sick spread/L^2 # plot the spread in colours colv <- (generation+1)/40-floor((generation+1)/40) plot(orderx,ordery,xlim=c(1,L),ylim=c(1,L), xlab = "", ylab= "", col=hsv(colv,1,1),bg = hsv(colv,1,1),cex=0.1,pch=21) # plot the epidemiological curve I <- sapply(1:50, FUN = function(x) sum(generation == x)) plot(I, log = 'xy', xlab = "x, generation", ylab = "number of infectious people", type = "l", ylim = c(1,5*10^4), xlim = c(1,70)) gen <- 1:50 colv <- (gen+1)/40-floor((gen+1)/40) points(I,pch=21,col = 1, bg = hsv(colv,1,1)) lines((R0+R1)^c(0:50), lty=2) sm <- 4:50 lines(sm,0.5*sm^3.5, lty = 3) lines(sm,0.002*sm^6, lty = 4) legend(1,5*10^4, c(expression((R[0]+R[1])^x),expression(0.5*x^3.5), expression(0.002*x^6)), lty = c(2,3,4), xjust = 0, cex = 0.7)
Detailed description/scripts of mathematical models for Coronavirus The lancet article The method from the article in the Lancet is very straightforward. They model the spread of the virus by simulating the transmission on the level of each single infected individual.
40,945
Dickey-Fuller test significant => series stationary?
You are not misunderstanding anything as far as I can tell. You are presenting a solid story with logical supporting arguments. I could stop here and I think your question would be answered, but let me add some other comments that might be relevant. The (augmented) Dickey-Fuller test is based on an autoregressive model for the time series of interest. It is testing presence of a unit root against a specific alternative, a stationary process. The universe of cases explicitly considered is restricted to these two (both being autoregressive processes). They are used for deriving the distribution of the test statistic under $H_0$ and probably for examining the test's power against the specific alternative. (It has been a while since I read the original paper, so I do not remember the details; feel free to correct me.) In reality, not all time series are autoregressive with constant parameters and all the other nice features we tend to assume about them. You could very well argue none of the real-world time series follow any of the relatively simple models that we use. So the test should be understood as a simplification. Moreover, perfect stationarity is not necessary in practice. Approximate stationarity is good enough to get approximately correct results from models and tests that rely on the assumption of stationarity. Even though we know that all models are wrong, we still find some of them useful. I suggest using and interpreting the (A)DF test in this perspective. Responding to comments: arguably inferring any specific alternative from rejection of the $H_0$ is even worse than inferring the $H_0$ from non-rejection You can test the assumptions of the test. If there are no violations, a rejection of $H_0$ typically points to a specific alternative by construction of the test statistic. If so, inferring $H_1$ need not be so problematic, since the data contains something characteristic of $H_1$; otherwise the test statistic would not pick it up. at least the $H_0$ (in many tests) has a point shape, so something specific is tested, and we are entitled to say "data are compatible with the $H_0$". Can anything like this be stated for the stationary DF-alternative? $H_0$ as considered in the DF test contains the single undersirable parameter value (the root being equal to unity); $H_1$ contains all the desirable alternatives (the root being less than unity; keep in mind that values in the negative territory are usually irrelevant in practice). The possibility of an explosive process (the root above unity) is ruled out a priori. (Though there are versions of the test which have explosive process as the alternative, ruling out lower-than-unit roots a priori.) Thus it is quite satisfactory to have the test set up as is, targeting the single undersirable outcome and (hopefully) rejecting it with a high degree of confidence. In other words, the DF test targets a specific violation of stationarity, one that is probably more pernicious than others when it comes to messing up estimator's properties and inference. I think one incurs smallers losses by neglecting, say, a shift in variance than a unit root. The former only makes estimators inefficient, while the latter makes unconditional moments undefined/infinite etc. So a test that allows testing the $H_0$ of a unit root and (hopefully) rejecting it at a low significance level makes sense.
Dickey-Fuller test significant => series stationary?
You are not misunderstanding anything as far as I can tell. You are presenting a solid story with logical supporting arguments. I could stop here and I think your question would be answered, but let m
Dickey-Fuller test significant => series stationary? You are not misunderstanding anything as far as I can tell. You are presenting a solid story with logical supporting arguments. I could stop here and I think your question would be answered, but let me add some other comments that might be relevant. The (augmented) Dickey-Fuller test is based on an autoregressive model for the time series of interest. It is testing presence of a unit root against a specific alternative, a stationary process. The universe of cases explicitly considered is restricted to these two (both being autoregressive processes). They are used for deriving the distribution of the test statistic under $H_0$ and probably for examining the test's power against the specific alternative. (It has been a while since I read the original paper, so I do not remember the details; feel free to correct me.) In reality, not all time series are autoregressive with constant parameters and all the other nice features we tend to assume about them. You could very well argue none of the real-world time series follow any of the relatively simple models that we use. So the test should be understood as a simplification. Moreover, perfect stationarity is not necessary in practice. Approximate stationarity is good enough to get approximately correct results from models and tests that rely on the assumption of stationarity. Even though we know that all models are wrong, we still find some of them useful. I suggest using and interpreting the (A)DF test in this perspective. Responding to comments: arguably inferring any specific alternative from rejection of the $H_0$ is even worse than inferring the $H_0$ from non-rejection You can test the assumptions of the test. If there are no violations, a rejection of $H_0$ typically points to a specific alternative by construction of the test statistic. If so, inferring $H_1$ need not be so problematic, since the data contains something characteristic of $H_1$; otherwise the test statistic would not pick it up. at least the $H_0$ (in many tests) has a point shape, so something specific is tested, and we are entitled to say "data are compatible with the $H_0$". Can anything like this be stated for the stationary DF-alternative? $H_0$ as considered in the DF test contains the single undersirable parameter value (the root being equal to unity); $H_1$ contains all the desirable alternatives (the root being less than unity; keep in mind that values in the negative territory are usually irrelevant in practice). The possibility of an explosive process (the root above unity) is ruled out a priori. (Though there are versions of the test which have explosive process as the alternative, ruling out lower-than-unit roots a priori.) Thus it is quite satisfactory to have the test set up as is, targeting the single undersirable outcome and (hopefully) rejecting it with a high degree of confidence. In other words, the DF test targets a specific violation of stationarity, one that is probably more pernicious than others when it comes to messing up estimator's properties and inference. I think one incurs smallers losses by neglecting, say, a shift in variance than a unit root. The former only makes estimators inefficient, while the latter makes unconditional moments undefined/infinite etc. So a test that allows testing the $H_0$ of a unit root and (hopefully) rejecting it at a low significance level makes sense.
Dickey-Fuller test significant => series stationary? You are not misunderstanding anything as far as I can tell. You are presenting a solid story with logical supporting arguments. I could stop here and I think your question would be answered, but let m
40,946
Dickey-Fuller test significant => series stationary?
Another aspect that I recently became aware of (see particularly this thread Is the Dickey Fuller test one-sided or two-sided?) is that the DF-test can be interpreted as one-sided in the sense that it will only reject the unit root null hypothesis with even smaller probability than for a unit root, i.e., $\phi=1$, in case of an exploding series, i.e., $\phi>1$ for $X_{t}=\phi X_{t-1}+\epsilon_t$. One could therefore say that the effective null hypothesis is in fact $\phi\ge 1$ rather than $\phi=1$. As series with $\phi\ge 1$ are not stationary, the null hypothesis is not quite as specific as I thought when I originally wrote the question; as long as we exclude (for subject matter reasons; often this is unrealistic) $\phi\le -1$, the null hypothesis is not one very specific case of non-stationarity (the rejection of which would still leave most options for non-stationarity open), but rather a broader (though not all-encompassing) family of non-stationary distributions, which makes interpreting a rejection of it as "evidence against non-stationarity" somewhat more plausible. One thing that I'd be interested in is how the general class of non-stationary models (that do not necessarily obey the AR-model assumptions) looks like for which the DF-test has a low (say $\le\alpha$, the nominal test level) probability of rejection, as rejection will provide evidence against all of these.
Dickey-Fuller test significant => series stationary?
Another aspect that I recently became aware of (see particularly this thread Is the Dickey Fuller test one-sided or two-sided?) is that the DF-test can be interpreted as one-sided in the sense that it
Dickey-Fuller test significant => series stationary? Another aspect that I recently became aware of (see particularly this thread Is the Dickey Fuller test one-sided or two-sided?) is that the DF-test can be interpreted as one-sided in the sense that it will only reject the unit root null hypothesis with even smaller probability than for a unit root, i.e., $\phi=1$, in case of an exploding series, i.e., $\phi>1$ for $X_{t}=\phi X_{t-1}+\epsilon_t$. One could therefore say that the effective null hypothesis is in fact $\phi\ge 1$ rather than $\phi=1$. As series with $\phi\ge 1$ are not stationary, the null hypothesis is not quite as specific as I thought when I originally wrote the question; as long as we exclude (for subject matter reasons; often this is unrealistic) $\phi\le -1$, the null hypothesis is not one very specific case of non-stationarity (the rejection of which would still leave most options for non-stationarity open), but rather a broader (though not all-encompassing) family of non-stationary distributions, which makes interpreting a rejection of it as "evidence against non-stationarity" somewhat more plausible. One thing that I'd be interested in is how the general class of non-stationary models (that do not necessarily obey the AR-model assumptions) looks like for which the DF-test has a low (say $\le\alpha$, the nominal test level) probability of rejection, as rejection will provide evidence against all of these.
Dickey-Fuller test significant => series stationary? Another aspect that I recently became aware of (see particularly this thread Is the Dickey Fuller test one-sided or two-sided?) is that the DF-test can be interpreted as one-sided in the sense that it
40,947
AIC and its degrees of freedom for linear regression models
Some preliminaries: In LASSO models, the number of non-zero coefficients is an unbiased and consistent estimate for the degrees of freedom of the lasso (see, Zou et al. (2007) "On the "degrees of freedom" of the lasso" for more details). In ridge models, the degrees of freedom are directly related to the singular values of the centred input matrix $X$ (see, Hastie et al. (2009) "Elements of Statistical Learning" in Sect. 3.4.1 for more details). Assuming the matrix $X$ has the SVD $X = USV^T$, the degree of freedom as a function of $\lambda$ are $df(\lambda) = \sum_{j=1}^p \frac{s_j^2}{s_j^2 +\lambda}.$ We can see clearly that for $\lambda \rightarrow 0$ we get $p$ degrees for freedom and for $\lambda \rightarrow \infty$ we get $0$ degrees of freedom. Based on these and for your questions in particular: Yes, your observation is correct. M1 and M2 are not fitted on the same data. That said, the documentation mentions this because it aims to stop users from using different variants of the response variables and/or compare models that potentially have different rows of data or sample sizes. That is more obvious if we move from the "RSS"-derived calculation of AIC to the "Loglikehood"-derived one. Assuming a Gaussian log-likelihood as: $$ \log(L(\theta)) =-\frac{|D|}{2}\log(2\pi) -\frac{1}{2} \log(|K|) -\frac{1}{2}(x-\mu)^T K^{-1} (x-\mu), $$ with $K$ being the covariance structure of our model (and $|K|$ the determinant of it), $|D|$ the number of points in our datasets, $\mu$ the mean response and $x$ our dependent variable. There is nothing invalidating this to be used on different datasets assuming we have the same dependent variable. (Notice though that for BIC we do want nested models so the model covariance structure $K$ are hierarchical). Being quite permissive with ourselves, in M2 we have an "elastic-net-like" situation where certain explanatory variables coefficients are set manually to $0$. I hope it is clear that the original calculation for $k$ for M1 and M2 are a bit oversimplifying. They need to directly account for $\lambda$. That said, you are correct that for M3, we will use the number of $m$ non-zero coefficients.
AIC and its degrees of freedom for linear regression models
Some preliminaries: In LASSO models, the number of non-zero coefficients is an unbiased and consistent estimate for the degrees of freedom of the lasso (see, Zou et al. (2007) "On the "degrees of free
AIC and its degrees of freedom for linear regression models Some preliminaries: In LASSO models, the number of non-zero coefficients is an unbiased and consistent estimate for the degrees of freedom of the lasso (see, Zou et al. (2007) "On the "degrees of freedom" of the lasso" for more details). In ridge models, the degrees of freedom are directly related to the singular values of the centred input matrix $X$ (see, Hastie et al. (2009) "Elements of Statistical Learning" in Sect. 3.4.1 for more details). Assuming the matrix $X$ has the SVD $X = USV^T$, the degree of freedom as a function of $\lambda$ are $df(\lambda) = \sum_{j=1}^p \frac{s_j^2}{s_j^2 +\lambda}.$ We can see clearly that for $\lambda \rightarrow 0$ we get $p$ degrees for freedom and for $\lambda \rightarrow \infty$ we get $0$ degrees of freedom. Based on these and for your questions in particular: Yes, your observation is correct. M1 and M2 are not fitted on the same data. That said, the documentation mentions this because it aims to stop users from using different variants of the response variables and/or compare models that potentially have different rows of data or sample sizes. That is more obvious if we move from the "RSS"-derived calculation of AIC to the "Loglikehood"-derived one. Assuming a Gaussian log-likelihood as: $$ \log(L(\theta)) =-\frac{|D|}{2}\log(2\pi) -\frac{1}{2} \log(|K|) -\frac{1}{2}(x-\mu)^T K^{-1} (x-\mu), $$ with $K$ being the covariance structure of our model (and $|K|$ the determinant of it), $|D|$ the number of points in our datasets, $\mu$ the mean response and $x$ our dependent variable. There is nothing invalidating this to be used on different datasets assuming we have the same dependent variable. (Notice though that for BIC we do want nested models so the model covariance structure $K$ are hierarchical). Being quite permissive with ourselves, in M2 we have an "elastic-net-like" situation where certain explanatory variables coefficients are set manually to $0$. I hope it is clear that the original calculation for $k$ for M1 and M2 are a bit oversimplifying. They need to directly account for $\lambda$. That said, you are correct that for M3, we will use the number of $m$ non-zero coefficients.
AIC and its degrees of freedom for linear regression models Some preliminaries: In LASSO models, the number of non-zero coefficients is an unbiased and consistent estimate for the degrees of freedom of the lasso (see, Zou et al. (2007) "On the "degrees of free
40,948
What is better in Monte Carlo integration: product of means or mean of products?
Both approaches lead to unbiased estimators, hence comparing their variances amounts to comparing their second moments. Without loss of generality, since the distributions of $X$ and $Y$ are arbitrary, we can take both $\varphi_1$ and $\varphi_2$ to be the identity transform. Then $$\mathbb E[(\bar X\bar Y)^2]=\mathbb E[\bar X^2]\mathbb E[\bar Y^2]=\frac{n\mathbb E[X]+\sigma^2_X}{n}\frac{n\mathbb E[Y]+\sigma^2_Y}{n}$$ while $$\mathbb E[\overline {XY}^2]=\frac{n\mathbb E[X]\mathbb E[X]+\sigma^2_{XY}}{n}$$ Therefore if both $\mathbb E[X]$ and $\mathbb E[Y]$ are close to zero $$\mathbb E[(\bar X\bar Y)^2]=\text O(n^{-2})\quad\text{and}\quad\mathbb E[\overline {XY}^2]=\text O(n^{-1})$$ while otherwise mileage may vary $$\mathbb E[(\bar X\bar Y)^2]=\text O(n^{-1})\quad\text{and}\quad\mathbb E[\overline {XY}^2]=\text O(n^{-1})$$ Using the same example as in the earlier answer shows that the variability is slightly lower for the product of the averages (left) than for the average of the products (right), obtained over 10³ replications of 10⁴ simulations (the 10³ curves are the cumulated means): If we compare directly the variances estimated from the 10⁷ simulations in this example $$\text{var}(\bar X\bar Y)=\text{var}(\bar X)\mathbb E[\bar Y^2]+ \text{var}(\bar Y)\mathbb E[\bar X]^2\qquad\qquad\qquad\\=\frac{\text{var}(X)}{n}\frac{\mathbb E[Y^2]+(n-1)\mathbb E[Y]^2}{n}+\frac{\text{var}(Y)\mathbb E[X]^2}{n}$$ is estimated by [1] 8.990575e-07 while the variance of $\overline{XY}$ is estimated by [1] 1.097814e-06 If anything, I would favor the $\bar X\times\bar Y$ solution as it also writes as$$\frac{1}{n^2} \sum_{i=1}^n\sum_{j=1}^n X_iY_j$$giving the impression it exploits the independence between both samples in a more systematic manner.
What is better in Monte Carlo integration: product of means or mean of products?
Both approaches lead to unbiased estimators, hence comparing their variances amounts to comparing their second moments. Without loss of generality, since the distributions of $X$ and $Y$ are arbitr
What is better in Monte Carlo integration: product of means or mean of products? Both approaches lead to unbiased estimators, hence comparing their variances amounts to comparing their second moments. Without loss of generality, since the distributions of $X$ and $Y$ are arbitrary, we can take both $\varphi_1$ and $\varphi_2$ to be the identity transform. Then $$\mathbb E[(\bar X\bar Y)^2]=\mathbb E[\bar X^2]\mathbb E[\bar Y^2]=\frac{n\mathbb E[X]+\sigma^2_X}{n}\frac{n\mathbb E[Y]+\sigma^2_Y}{n}$$ while $$\mathbb E[\overline {XY}^2]=\frac{n\mathbb E[X]\mathbb E[X]+\sigma^2_{XY}}{n}$$ Therefore if both $\mathbb E[X]$ and $\mathbb E[Y]$ are close to zero $$\mathbb E[(\bar X\bar Y)^2]=\text O(n^{-2})\quad\text{and}\quad\mathbb E[\overline {XY}^2]=\text O(n^{-1})$$ while otherwise mileage may vary $$\mathbb E[(\bar X\bar Y)^2]=\text O(n^{-1})\quad\text{and}\quad\mathbb E[\overline {XY}^2]=\text O(n^{-1})$$ Using the same example as in the earlier answer shows that the variability is slightly lower for the product of the averages (left) than for the average of the products (right), obtained over 10³ replications of 10⁴ simulations (the 10³ curves are the cumulated means): If we compare directly the variances estimated from the 10⁷ simulations in this example $$\text{var}(\bar X\bar Y)=\text{var}(\bar X)\mathbb E[\bar Y^2]+ \text{var}(\bar Y)\mathbb E[\bar X]^2\qquad\qquad\qquad\\=\frac{\text{var}(X)}{n}\frac{\mathbb E[Y^2]+(n-1)\mathbb E[Y]^2}{n}+\frac{\text{var}(Y)\mathbb E[X]^2}{n}$$ is estimated by [1] 8.990575e-07 while the variance of $\overline{XY}$ is estimated by [1] 1.097814e-06 If anything, I would favor the $\bar X\times\bar Y$ solution as it also writes as$$\frac{1}{n^2} \sum_{i=1}^n\sum_{j=1}^n X_iY_j$$giving the impression it exploits the independence between both samples in a more systematic manner.
What is better in Monte Carlo integration: product of means or mean of products? Both approaches lead to unbiased estimators, hence comparing their variances amounts to comparing their second moments. Without loss of generality, since the distributions of $X$ and $Y$ are arbitr
40,949
What is better in Monte Carlo integration: product of means or mean of products?
Here is a trivial example in which both distributions are standard normal, the first function is $\phi_1(x) = x^\prime = x+2,$ and the second is $\phi_2(y) = y^\prime = y^2.$ So that $$E(X^\prime Y^\prime) = E(X^\prime)E(Y^\prime) = 2.$$ Letting $n = 10^7,$ simulations in R give essentially the same answer for both methods. set.seed(1234) x = rnorm(10^7); y = rnorm(10^7) x1 = x + 2; y1 = y^2 mean(x1*y1) [1] 1.998185 mean(x1); mean(y1); mean(x1)*mean(y1) [1] 2.000025 [1] 0.9993708 [1] 1.998766
What is better in Monte Carlo integration: product of means or mean of products?
Here is a trivial example in which both distributions are standard normal, the first function is $\phi_1(x) = x^\prime = x+2,$ and the second is $\phi_2(y) = y^\prime = y^2.$ So that $$E(X^\prime Y^\
What is better in Monte Carlo integration: product of means or mean of products? Here is a trivial example in which both distributions are standard normal, the first function is $\phi_1(x) = x^\prime = x+2,$ and the second is $\phi_2(y) = y^\prime = y^2.$ So that $$E(X^\prime Y^\prime) = E(X^\prime)E(Y^\prime) = 2.$$ Letting $n = 10^7,$ simulations in R give essentially the same answer for both methods. set.seed(1234) x = rnorm(10^7); y = rnorm(10^7) x1 = x + 2; y1 = y^2 mean(x1*y1) [1] 1.998185 mean(x1); mean(y1); mean(x1)*mean(y1) [1] 2.000025 [1] 0.9993708 [1] 1.998766
What is better in Monte Carlo integration: product of means or mean of products? Here is a trivial example in which both distributions are standard normal, the first function is $\phi_1(x) = x^\prime = x+2,$ and the second is $\phi_2(y) = y^\prime = y^2.$ So that $$E(X^\prime Y^\
40,950
Why do we log transform response ratios?
Imagine you have two treatments A and B, and two studies; the first shows A to be twice as effective and the second shows B to be twice as effective. If your metastudy combines the studies using the log approach you conclude that there is no basis for preferring one over the other because log(2)+log(1/2) = log(2)-log(2) = 0. Given that the situation is entirely symmetric this must be correct. However, if you do not take logs then your conclusion depends on which way up you form the response ratios. If you form A/B your meta-study would suggest A was 25% more effective than B... but if you analyse B/A then B becomes 25% more effective than A! If your analysis forms a ratio but does not take logs you introduce an artificial asymmetry into your analysis that is not present in the data. You can easily simulate the upward bias this imposes on the estimate of the effectiveness of the numerator treatment by sampling the effectiveness of A and B from the same distribution. By design there is no difference in effectiveness, but you will estimate the numerator treatment to be more effective by an amount that increases with the dispersion of your distribution. Labeling your two treatments not as A and B but as "treatment" and "control" obscures the symmetry of the situation a little but does not really change it, because "control" is just a treatment that involves doing nothing. Making it the denominator is a convenient convention for presentation, but the analysis should still be symmetric so exactly the same argument applies.
Why do we log transform response ratios?
Imagine you have two treatments A and B, and two studies; the first shows A to be twice as effective and the second shows B to be twice as effective. If your metastudy combines the studies using the
Why do we log transform response ratios? Imagine you have two treatments A and B, and two studies; the first shows A to be twice as effective and the second shows B to be twice as effective. If your metastudy combines the studies using the log approach you conclude that there is no basis for preferring one over the other because log(2)+log(1/2) = log(2)-log(2) = 0. Given that the situation is entirely symmetric this must be correct. However, if you do not take logs then your conclusion depends on which way up you form the response ratios. If you form A/B your meta-study would suggest A was 25% more effective than B... but if you analyse B/A then B becomes 25% more effective than A! If your analysis forms a ratio but does not take logs you introduce an artificial asymmetry into your analysis that is not present in the data. You can easily simulate the upward bias this imposes on the estimate of the effectiveness of the numerator treatment by sampling the effectiveness of A and B from the same distribution. By design there is no difference in effectiveness, but you will estimate the numerator treatment to be more effective by an amount that increases with the dispersion of your distribution. Labeling your two treatments not as A and B but as "treatment" and "control" obscures the symmetry of the situation a little but does not really change it, because "control" is just a treatment that involves doing nothing. Making it the denominator is a convenient convention for presentation, but the analysis should still be symmetric so exactly the same argument applies.
Why do we log transform response ratios? Imagine you have two treatments A and B, and two studies; the first shows A to be twice as effective and the second shows B to be twice as effective. If your metastudy combines the studies using the
40,951
PR AUC < 50% with ROC AUC > 90% - model good or bad?
You are correct to be suspicious of your results. While indeed it is relatively easy to somewhat simplistically dismiss an AUCROC as "bad" if it is close to $0.50$ (roughly speaking the probability that the model ranks a random positive example more highly than a random negative example), the same rationale is not relevant to the case of AUCPR. That is because the baseline of an AUCPR is not $0.50$ but rather it is dictated by the proportion of positives in our sample. That means that when dealing with an imbalanced sample our actual baseline might extremely low; one can read a more detailed exposition on this matter on the CV.SE thread here: What is "baseline" in precision recall curve. If we want a more informative interpretation of the P-R analysis, we can use what is knows as Precision-Recall Gain curves; these allow us to view the AUCPRG as the expected $F_1$ score. Details on the CV.SE thread here: Area Under the Precision Recall curve -similar interpretation to AUROC?. So to recap, a model with AUCROC ~ $90\%$ and AUCPR ~ $40\%$ is not bad or good for that matter. Without a reference point for performance, these numbers do not matter much and especially the AUCPR does not lend itself to simple direct interpretations either.
PR AUC < 50% with ROC AUC > 90% - model good or bad?
You are correct to be suspicious of your results. While indeed it is relatively easy to somewhat simplistically dismiss an AUCROC as "bad" if it is close to $0.50$ (roughly speaking the probability th
PR AUC < 50% with ROC AUC > 90% - model good or bad? You are correct to be suspicious of your results. While indeed it is relatively easy to somewhat simplistically dismiss an AUCROC as "bad" if it is close to $0.50$ (roughly speaking the probability that the model ranks a random positive example more highly than a random negative example), the same rationale is not relevant to the case of AUCPR. That is because the baseline of an AUCPR is not $0.50$ but rather it is dictated by the proportion of positives in our sample. That means that when dealing with an imbalanced sample our actual baseline might extremely low; one can read a more detailed exposition on this matter on the CV.SE thread here: What is "baseline" in precision recall curve. If we want a more informative interpretation of the P-R analysis, we can use what is knows as Precision-Recall Gain curves; these allow us to view the AUCPRG as the expected $F_1$ score. Details on the CV.SE thread here: Area Under the Precision Recall curve -similar interpretation to AUROC?. So to recap, a model with AUCROC ~ $90\%$ and AUCPR ~ $40\%$ is not bad or good for that matter. Without a reference point for performance, these numbers do not matter much and especially the AUCPR does not lend itself to simple direct interpretations either.
PR AUC < 50% with ROC AUC > 90% - model good or bad? You are correct to be suspicious of your results. While indeed it is relatively easy to somewhat simplistically dismiss an AUCROC as "bad" if it is close to $0.50$ (roughly speaking the probability th
40,952
Model for spatiotemporal and discrete variables
The typical approach to this problem is land-use regression (LUR). LUR hybridize methods for correlated data analysis and spatiotemporal dependence structures. Typically, at each site, there are one or more covariates which can be predicted at each geographic location, like proximity to highway, season, time of day, elevation, or other features. It's desirable to condition on these factors to increase predictive accuracy and consequently decrease spatiotemporal dependence. To handle the residual dependence structure, variograms are used to assess the extent of residual correlation over time and space, and these can estimate the variance-components of complex autoregressive covariance structures. There are quite a number of good review articles on LUR, one for instance is here: https://www.sciencedirect.com/science/article/pii/S1352231008005748 but pubmed will be your guide.
Model for spatiotemporal and discrete variables
The typical approach to this problem is land-use regression (LUR). LUR hybridize methods for correlated data analysis and spatiotemporal dependence structures. Typically, at each site, there are one o
Model for spatiotemporal and discrete variables The typical approach to this problem is land-use regression (LUR). LUR hybridize methods for correlated data analysis and spatiotemporal dependence structures. Typically, at each site, there are one or more covariates which can be predicted at each geographic location, like proximity to highway, season, time of day, elevation, or other features. It's desirable to condition on these factors to increase predictive accuracy and consequently decrease spatiotemporal dependence. To handle the residual dependence structure, variograms are used to assess the extent of residual correlation over time and space, and these can estimate the variance-components of complex autoregressive covariance structures. There are quite a number of good review articles on LUR, one for instance is here: https://www.sciencedirect.com/science/article/pii/S1352231008005748 but pubmed will be your guide.
Model for spatiotemporal and discrete variables The typical approach to this problem is land-use regression (LUR). LUR hybridize methods for correlated data analysis and spatiotemporal dependence structures. Typically, at each site, there are one o
40,953
Sums of normal random variables
Your example suggests that not only are the $n$ variables $X_1,X_2,\ldots,X_n$ independent, they also have the same Normal distribution. Let its parameters be $\mu$ (the mean) and $\sigma^2$ (the variance) and suppose the subset consists of $k$ of these variables. We might as well index the variables so that $X_1,\ldots, X_k$ are this subset. The question asks to compute the chance that the sum of the first $k$ variables equals or exceeds the sum of the rest: $$p_{n,k}(\mu,\sigma) = \Pr(X_1+\cdots+X_k \ge X_{k+1}+\cdots+X_n ) = \Pr(Y \le 0)$$ where $$Y = -(X_1+\cdots+X_k) + (X_{k+1}+\cdots+X_n).$$ $Y$ is a linear combination of independent Normal variables and therefore has a Normal distribution--but which one? The laws of expectation and variance immediately tell us $$E[Y] = -k\mu + (n-k)\mu = (n-2k)\mu$$ and $$\operatorname{Var}(Y) = k \sigma^2 + (n-k)\sigma^2 = n\sigma^2.$$ Therefore $$Z=\frac{Y - (n-2k)\mu}{\sigma\sqrt{n}}$$ has a standard Normal distribution with distribution function $\Phi,$ whence the answer is $$p_{n,k}(\mu,\sigma) = \Pr(Y \le 0) = \Pr\left(Z \le -\frac{(n-2k)\mu}{\sigma\sqrt{n}}\right) = \Phi\left(-\frac{(n-2k)\mu}{\sigma\sqrt{n}}\right).$$ In the question, $n=5,k=2,\mu=10,$ and $\sigma=3,$ whence $$p_{5,2}(10,3) = \Phi\left(-\frac{(5-2(2))10}{3\sqrt{10}}\right)\approx 0.0680186.$$ Generalization Little needs to change in this analysis even when the $X_i$ have different normal distributions or are even correlated: you only need to assume they have an $n$-variate Normal distribution to assure their linear combination still has a Normal distribution. The calculations are carried out in the same way and result in a similar formula. Check A commenter suggested solving this with simulation. Although that wouldn't be a solution, it's a decent way to check a solution quickly. Thus, in R we might establish the inputs of the simulation in some arbitrary way as n <- 5 k <- 2 mu <- 10 sigma <- 3 n.sim <- 1e6 # Simulation size set.seed(17) # For reproducible results and simulate such data and compare the sums with these two lines: x <- matrix(rnorm(n*n.sim, mu, sigma), ncol=n) p.hat <- mean(rowSums(x[, 1:k]) >= rowSums(x[, -(1:k)])) The post-processing consists of finding the fraction of simulated datasets in which one sum exceeds the other and comparing that to the theoretical solution: se <- sqrt(p.hat * (1-p.hat) / n.sim) p <- pnorm(-(n-2*k)*mu / (sigma * sqrt(n))) signif(c(Simulation=p.hat, Theory=p, `Z-score`=(p.hat-p)/se), 3) The output in this case is Simulation Theory Z-score 0.0677 0.0680 -1.1900 The agreement is close and the small absolute z-score allows us to attribute the discrepancy to random fluctuations rather than any error in the theoretical derivation.
Sums of normal random variables
Your example suggests that not only are the $n$ variables $X_1,X_2,\ldots,X_n$ independent, they also have the same Normal distribution. Let its parameters be $\mu$ (the mean) and $\sigma^2$ (the var
Sums of normal random variables Your example suggests that not only are the $n$ variables $X_1,X_2,\ldots,X_n$ independent, they also have the same Normal distribution. Let its parameters be $\mu$ (the mean) and $\sigma^2$ (the variance) and suppose the subset consists of $k$ of these variables. We might as well index the variables so that $X_1,\ldots, X_k$ are this subset. The question asks to compute the chance that the sum of the first $k$ variables equals or exceeds the sum of the rest: $$p_{n,k}(\mu,\sigma) = \Pr(X_1+\cdots+X_k \ge X_{k+1}+\cdots+X_n ) = \Pr(Y \le 0)$$ where $$Y = -(X_1+\cdots+X_k) + (X_{k+1}+\cdots+X_n).$$ $Y$ is a linear combination of independent Normal variables and therefore has a Normal distribution--but which one? The laws of expectation and variance immediately tell us $$E[Y] = -k\mu + (n-k)\mu = (n-2k)\mu$$ and $$\operatorname{Var}(Y) = k \sigma^2 + (n-k)\sigma^2 = n\sigma^2.$$ Therefore $$Z=\frac{Y - (n-2k)\mu}{\sigma\sqrt{n}}$$ has a standard Normal distribution with distribution function $\Phi,$ whence the answer is $$p_{n,k}(\mu,\sigma) = \Pr(Y \le 0) = \Pr\left(Z \le -\frac{(n-2k)\mu}{\sigma\sqrt{n}}\right) = \Phi\left(-\frac{(n-2k)\mu}{\sigma\sqrt{n}}\right).$$ In the question, $n=5,k=2,\mu=10,$ and $\sigma=3,$ whence $$p_{5,2}(10,3) = \Phi\left(-\frac{(5-2(2))10}{3\sqrt{10}}\right)\approx 0.0680186.$$ Generalization Little needs to change in this analysis even when the $X_i$ have different normal distributions or are even correlated: you only need to assume they have an $n$-variate Normal distribution to assure their linear combination still has a Normal distribution. The calculations are carried out in the same way and result in a similar formula. Check A commenter suggested solving this with simulation. Although that wouldn't be a solution, it's a decent way to check a solution quickly. Thus, in R we might establish the inputs of the simulation in some arbitrary way as n <- 5 k <- 2 mu <- 10 sigma <- 3 n.sim <- 1e6 # Simulation size set.seed(17) # For reproducible results and simulate such data and compare the sums with these two lines: x <- matrix(rnorm(n*n.sim, mu, sigma), ncol=n) p.hat <- mean(rowSums(x[, 1:k]) >= rowSums(x[, -(1:k)])) The post-processing consists of finding the fraction of simulated datasets in which one sum exceeds the other and comparing that to the theoretical solution: se <- sqrt(p.hat * (1-p.hat) / n.sim) p <- pnorm(-(n-2*k)*mu / (sigma * sqrt(n))) signif(c(Simulation=p.hat, Theory=p, `Z-score`=(p.hat-p)/se), 3) The output in this case is Simulation Theory Z-score 0.0677 0.0680 -1.1900 The agreement is close and the small absolute z-score allows us to attribute the discrepancy to random fluctuations rather than any error in the theoretical derivation.
Sums of normal random variables Your example suggests that not only are the $n$ variables $X_1,X_2,\ldots,X_n$ independent, they also have the same Normal distribution. Let its parameters be $\mu$ (the mean) and $\sigma^2$ (the var
40,954
Earth Movers Distance and Maximum Mean Discrepency
No, they are not the same. First, let's start with a more general framework to motivate the use of EMD or MMD. Suppose we want to fit a family $(\mu_{\theta})_{\theta}$ of parametric distributions to an empirical one $\nu$, which means we want to solve the following minimisation problem: $$\min_{\theta} \mathcal L(\mu_{\theta}, \nu)$$ where $\mathcal L$ measures the difference between two distributions. For example, if $\mathcal L$ is the Kullback-Leibler divergence, this is asymtotically equivalent to the usual maximum likelihood framework. Or when $\mathcal L$ is a $\phi$-divergence (I omit the detail of the function $\phi$), then we recover the infamous original GAN. Now, WGAN is nothing but picking $\mathcal L$ to be Wasserstein distance, or more precisely, $1$-Wasserstein distance, aka EMD (there are also $p$-Wasserstein distances, for $p \geq 1$, but they are all equivalent metrics, under some mild conditions). The maximisation in the minimax problem is just the dual form of EMD. (Bonus: if you pick $\mathcal L$ to be MMD, then you will find something called "Generative moment matching networks" but do NOT confuse with MMD-GAN, they are close but the latter is a generalisation of the former). Next, let see how MMD and EMD are different. They both belong to the family called Integral Probability Metrics, which means something of the form \begin{align*} d_{\mathcal F} (\mu, \nu) = \sup_{f \in \mathcal F} \Big( \int f d\mu - \int f d\nu \Big) \end{align*} For example, if $\mathcal F$ is a kernel function from the unit ball of the kernel-reproducing hilbert-space, then we recover MMD. Or if $\mathcal F$ is the set of $1$-Lipschitz functions, then we recover EMD in dual form. What special about this family is that under some mild conditions, it characterizes the convergence in law: $\mu_n \overset{\mathcal D}{\longrightarrow} \mu \Leftrightarrow d_{\mathcal F} (\mu_n, \mu) \to 0$. So MMD and EMD are equivalent in this sense. This is NOT true for Kullback-Leibler or total variation. Another way to see their difference (which I find more clear) is via the entropic regularisation defined as \begin{align*} L_{c, \epsilon}(\mu, \nu):= \min_{P \in \Pi(\mu, \nu)}\langle C, P \rangle + \epsilon H(P) \end{align*} For now, let's omit everything in the definition. What we care is when $\epsilon = 0$, we recover the definition of EMD (or more correctly optimal transport distance). When $\epsilon \to \infty$, we recover MMD.
Earth Movers Distance and Maximum Mean Discrepency
No, they are not the same. First, let's start with a more general framework to motivate the use of EMD or MMD. Suppose we want to fit a family $(\mu_{\theta})_{\theta}$ of parametric distributions to
Earth Movers Distance and Maximum Mean Discrepency No, they are not the same. First, let's start with a more general framework to motivate the use of EMD or MMD. Suppose we want to fit a family $(\mu_{\theta})_{\theta}$ of parametric distributions to an empirical one $\nu$, which means we want to solve the following minimisation problem: $$\min_{\theta} \mathcal L(\mu_{\theta}, \nu)$$ where $\mathcal L$ measures the difference between two distributions. For example, if $\mathcal L$ is the Kullback-Leibler divergence, this is asymtotically equivalent to the usual maximum likelihood framework. Or when $\mathcal L$ is a $\phi$-divergence (I omit the detail of the function $\phi$), then we recover the infamous original GAN. Now, WGAN is nothing but picking $\mathcal L$ to be Wasserstein distance, or more precisely, $1$-Wasserstein distance, aka EMD (there are also $p$-Wasserstein distances, for $p \geq 1$, but they are all equivalent metrics, under some mild conditions). The maximisation in the minimax problem is just the dual form of EMD. (Bonus: if you pick $\mathcal L$ to be MMD, then you will find something called "Generative moment matching networks" but do NOT confuse with MMD-GAN, they are close but the latter is a generalisation of the former). Next, let see how MMD and EMD are different. They both belong to the family called Integral Probability Metrics, which means something of the form \begin{align*} d_{\mathcal F} (\mu, \nu) = \sup_{f \in \mathcal F} \Big( \int f d\mu - \int f d\nu \Big) \end{align*} For example, if $\mathcal F$ is a kernel function from the unit ball of the kernel-reproducing hilbert-space, then we recover MMD. Or if $\mathcal F$ is the set of $1$-Lipschitz functions, then we recover EMD in dual form. What special about this family is that under some mild conditions, it characterizes the convergence in law: $\mu_n \overset{\mathcal D}{\longrightarrow} \mu \Leftrightarrow d_{\mathcal F} (\mu_n, \mu) \to 0$. So MMD and EMD are equivalent in this sense. This is NOT true for Kullback-Leibler or total variation. Another way to see their difference (which I find more clear) is via the entropic regularisation defined as \begin{align*} L_{c, \epsilon}(\mu, \nu):= \min_{P \in \Pi(\mu, \nu)}\langle C, P \rangle + \epsilon H(P) \end{align*} For now, let's omit everything in the definition. What we care is when $\epsilon = 0$, we recover the definition of EMD (or more correctly optimal transport distance). When $\epsilon \to \infty$, we recover MMD.
Earth Movers Distance and Maximum Mean Discrepency No, they are not the same. First, let's start with a more general framework to motivate the use of EMD or MMD. Suppose we want to fit a family $(\mu_{\theta})_{\theta}$ of parametric distributions to
40,955
Numerically/approximately integrating over independent gamma variables
Here is a sketch of a solution. The general strategy is to introduce the scalar sum $\theta_T=\sum\theta_i, $ then marginalize over it, then use it to turn the complicated multidimenional sum over the $\theta_{1..n}$ into a dynamic programming problem with aggressive cutoffs to prune solution space as the dynamic program runs. We know that $\theta_T$ is a sum of gamma RVs with heterogeneous parameters. Since $\beta_i>0$ for all $i$, the variances are finite, and if $n$ is large enough, this will succumb to the CLT, so $\theta_T \rightarrow_d ~~ N(\mu_T,\sigma^2_T)$ where $\mu_T =\sum \alpha_i/\beta_i$ and $\sigma^2_T=\sum \alpha_i/\beta_i^2.$ This gives us a credible subset of $\theta_T$ over which to focus our attention on $\theta \in [\theta_{T_0},\theta_{T_1}]$. Even if $n$ isn't particularly large, we are able to approximate $p(\theta_T)$ through numerical methods and other methods, which are contingent on the data. For each $\theta$ selected from this interval, we choose an integer $M$ so that $\theta/M$ is smallest quantity of $\theta$ to be allocated to $\theta_i$ in the partitioning of $\theta$ among the $\theta_{1..n}$. This turns the problem into a simple dynamic programming problem in which $\sum \theta_{1..n}=\theta_T$ is equivalent to $\sum m_i=M$ where $0\le m_i \le M, m_i \in \mathbb{N}. $ The number of solutions is $\binom{M+n-1}{n-1}$. For numbers like $M=20, n=10, \binom{29}{9} \sim 10^8$. Fortunately, we may implement the dynamic programming with an eye to selecting the solutions for which $P(\theta_i|\alpha_i,\beta_i)>\epsilon$ which will reduce the number tremendously. This is equivalent to $\sum m_i=M$ requiring that,e.g., $1 \le m_i \le M$, and now the number of solutions is $\binom{(M-n)+n-1}{n-1}$. For $M=20, n=10, \binom{19}{9}\sim 10^5,$ or 3 orders of magnitude smaller with a simple, obviously-correct requirement. The cleverness enters when you memo-ize the dynamic program in order to reuse the solutions, then use a rule for varying $\alpha_{1..n},\beta_{1..n}$ perhaps to maintain constant values for $\mu_T$ and $\sigma^2_T$, and which will also maximize reuse of the dynamic programming solution. This constancy of $\mu_T$ and $\sigma^2_T$ may well be a within the realm of your needs. Other tricks to making the problem manageable is what I would put in a more-than-just-a-sketch answer to this question. In summary, $$ \begin{align} P(X|\alpha_{1..n},\beta_{1..n}) &= \sum_{\theta_T} P(X|\theta_T,\alpha_{1..n},\beta_{1..n})P(\theta_T| \alpha_{1..n},\beta_{1..n} )\\ &= \sum_{\theta_T} \sum_{\{\theta_{1..n}|\sum \theta_i=\theta_T\}} P(X|\alpha_{1..n},\beta_{1..n})N(\theta_T|\mu_T,\sigma^2_T). \end{align} $$ Then, $P(X|\alpha_{1..n},\beta_{1..n})= \binom{X}{x_1,x_2..x_n}\theta_1^{x_1} \cdots \theta_n^{x_1}$ need only be evaluated only for those $\theta_{1..n}$ values that are high probability in the first place. Note that the $\theta_{1..n}$ are implicitly functions of $\alpha_{1..n},\beta_{1..n}$. Some observations Finding a dynamic programming problem in the wild is always a lot of fun. It would make for a fairly high profile research result, I should think. There are numbers $M$ and $n$ here where this approach becomes computationally very hard, even with dynamic programming. If $n$ has to be large, you may compensate by using smaller $M$ or larger $\epsilon.$ Ultimately, the problem may only be solvable if you are willing to a) use some restrictive priors, and/or b) accept a low resolution solution. The choice to marginalize over $\theta_T$ means that your use of log-likelihood will have to be term-by-term in the sum, rather than all at once, which is not so inconvenient in the grand scheme of things. Is this close to what you are looking for? Addendum A 20 line dynamic programming python script is able to enumerate $\binom{M+n-1}{n-1} M=100, ~n=20$ with a solution $4.910371215196107e+21$ in $0.18s$. This involves counting solutions by visiting them in the dynamic programming sort of way in which redundant solutions do not need to be revisited, just accounted for. In this enumeration, $\epsilon=0$. Visit-every-state enumeration is much slower, of course. For M=20 and n=10, the full enumeration that visits every one of the $10^8$ solutions currently takes 42s, which is where $\epsilon$ is valuable, and requirements that permit low resolution reporting of results. The python code is included here as requested. # -*- coding: utf-8 -*- """ Created on Fri Mar 8 21:38:57 2019 @author: Peter """ import numpy as np import scipy.special from datetime import datetime as dt Solutions=[] # is a list of lists of stars grouped by bars """ This is the recursive routine that uses optimal substructure -- the key design element of dynamic programming -- to *count* all of the distinct ways in which M identical stars can be located in n pidgeon holes. This is an exact enumeration of the solution to the stars-and-bars problem. This algorithm can be adapted to *visit* explicitly instead of leveraging dynamic programming and Memoization to merely *count* every solution, It is significantly slower if it visits the solutions. The advantage of visiting a solution is to eliminate solutions with a kpredictable low probability. """ """ countMe """ ########################################################## def countMe(m #The index of the pidgeon hole to start placing stars ,i #The number of stars that have to be placed ,V # ,visitEverySolution ): global Memo global Called; Called += 1 # this counts the number of times CountMe was called if i<0: return # base case solns =0 # this is a local count of solutions for # this instance, with M and i specified # in fxn signature for x in reversed(range(0,m+1)): #counting down from m to 0 VV=V # VV is mutable; V is not VV[i]=x for j in range(0,i): VV[j]=0 # clears the cubby holes to the left of i # needed for recursion if sum(VV)==M: # we have placed all of the stars global Solns; Solns += 1 solns += 1 # local solution global Solutions; Solutions.append(list(VV)) else: if visitEverySolution or Memo[m-x,i-1]==0: countMe(m-x,i-1,VV,visitEverySolution) solns += Memo[m-x,i-1] Memo[m,i]=solns return solns ############################################################## """ The beginning of execution is here. """ (M # number of stars ,n # number of bars+1 (or number of pidgeon holes) #)=(10,7) # 8008 solutions. use for testing )=(20,10) # 10015005 solutions # visitEverySolution=True takes 66 seconds # visitEverySolution=False takes 0.003 secodns """ Memo is a matrix containing the number of solutions with M stars up to and including the ith pidgeon hole. Memo is the hallmark of dynamic programming. """ Memo=np.zeros((M+1,n)) # V this the running occupancy of the pidgeon holes V=[0 for i in range(n)] #start with all pidgeon holes empty Solns=0 # global number of solutions Called=0 #global number of calls to countMe print("An exact solution can computed to be",scipy.special.binom(M+n-1,n-1)) visitEverySolution=False #count only, not visit t0=dt.now() countMe(M,n-1,V,visitEverySolution) # enter the counting routine here t1=dt.now() # We want to locate M stars in all pidgeon holes up to # and including n-1 (the last one) print("Elapsed time was",t1-t0) print("The number of solutions with M=",M,"stars and n=",n,"pidgeon holes is",Memo[M,n-1]) print("Solns=",Solns) print("CountMe was called",Called,"times.") #print(Solutions) ```
Numerically/approximately integrating over independent gamma variables
Here is a sketch of a solution. The general strategy is to introduce the scalar sum $\theta_T=\sum\theta_i, $ then marginalize over it, then use it to turn the complicated multidimenional sum over the
Numerically/approximately integrating over independent gamma variables Here is a sketch of a solution. The general strategy is to introduce the scalar sum $\theta_T=\sum\theta_i, $ then marginalize over it, then use it to turn the complicated multidimenional sum over the $\theta_{1..n}$ into a dynamic programming problem with aggressive cutoffs to prune solution space as the dynamic program runs. We know that $\theta_T$ is a sum of gamma RVs with heterogeneous parameters. Since $\beta_i>0$ for all $i$, the variances are finite, and if $n$ is large enough, this will succumb to the CLT, so $\theta_T \rightarrow_d ~~ N(\mu_T,\sigma^2_T)$ where $\mu_T =\sum \alpha_i/\beta_i$ and $\sigma^2_T=\sum \alpha_i/\beta_i^2.$ This gives us a credible subset of $\theta_T$ over which to focus our attention on $\theta \in [\theta_{T_0},\theta_{T_1}]$. Even if $n$ isn't particularly large, we are able to approximate $p(\theta_T)$ through numerical methods and other methods, which are contingent on the data. For each $\theta$ selected from this interval, we choose an integer $M$ so that $\theta/M$ is smallest quantity of $\theta$ to be allocated to $\theta_i$ in the partitioning of $\theta$ among the $\theta_{1..n}$. This turns the problem into a simple dynamic programming problem in which $\sum \theta_{1..n}=\theta_T$ is equivalent to $\sum m_i=M$ where $0\le m_i \le M, m_i \in \mathbb{N}. $ The number of solutions is $\binom{M+n-1}{n-1}$. For numbers like $M=20, n=10, \binom{29}{9} \sim 10^8$. Fortunately, we may implement the dynamic programming with an eye to selecting the solutions for which $P(\theta_i|\alpha_i,\beta_i)>\epsilon$ which will reduce the number tremendously. This is equivalent to $\sum m_i=M$ requiring that,e.g., $1 \le m_i \le M$, and now the number of solutions is $\binom{(M-n)+n-1}{n-1}$. For $M=20, n=10, \binom{19}{9}\sim 10^5,$ or 3 orders of magnitude smaller with a simple, obviously-correct requirement. The cleverness enters when you memo-ize the dynamic program in order to reuse the solutions, then use a rule for varying $\alpha_{1..n},\beta_{1..n}$ perhaps to maintain constant values for $\mu_T$ and $\sigma^2_T$, and which will also maximize reuse of the dynamic programming solution. This constancy of $\mu_T$ and $\sigma^2_T$ may well be a within the realm of your needs. Other tricks to making the problem manageable is what I would put in a more-than-just-a-sketch answer to this question. In summary, $$ \begin{align} P(X|\alpha_{1..n},\beta_{1..n}) &= \sum_{\theta_T} P(X|\theta_T,\alpha_{1..n},\beta_{1..n})P(\theta_T| \alpha_{1..n},\beta_{1..n} )\\ &= \sum_{\theta_T} \sum_{\{\theta_{1..n}|\sum \theta_i=\theta_T\}} P(X|\alpha_{1..n},\beta_{1..n})N(\theta_T|\mu_T,\sigma^2_T). \end{align} $$ Then, $P(X|\alpha_{1..n},\beta_{1..n})= \binom{X}{x_1,x_2..x_n}\theta_1^{x_1} \cdots \theta_n^{x_1}$ need only be evaluated only for those $\theta_{1..n}$ values that are high probability in the first place. Note that the $\theta_{1..n}$ are implicitly functions of $\alpha_{1..n},\beta_{1..n}$. Some observations Finding a dynamic programming problem in the wild is always a lot of fun. It would make for a fairly high profile research result, I should think. There are numbers $M$ and $n$ here where this approach becomes computationally very hard, even with dynamic programming. If $n$ has to be large, you may compensate by using smaller $M$ or larger $\epsilon.$ Ultimately, the problem may only be solvable if you are willing to a) use some restrictive priors, and/or b) accept a low resolution solution. The choice to marginalize over $\theta_T$ means that your use of log-likelihood will have to be term-by-term in the sum, rather than all at once, which is not so inconvenient in the grand scheme of things. Is this close to what you are looking for? Addendum A 20 line dynamic programming python script is able to enumerate $\binom{M+n-1}{n-1} M=100, ~n=20$ with a solution $4.910371215196107e+21$ in $0.18s$. This involves counting solutions by visiting them in the dynamic programming sort of way in which redundant solutions do not need to be revisited, just accounted for. In this enumeration, $\epsilon=0$. Visit-every-state enumeration is much slower, of course. For M=20 and n=10, the full enumeration that visits every one of the $10^8$ solutions currently takes 42s, which is where $\epsilon$ is valuable, and requirements that permit low resolution reporting of results. The python code is included here as requested. # -*- coding: utf-8 -*- """ Created on Fri Mar 8 21:38:57 2019 @author: Peter """ import numpy as np import scipy.special from datetime import datetime as dt Solutions=[] # is a list of lists of stars grouped by bars """ This is the recursive routine that uses optimal substructure -- the key design element of dynamic programming -- to *count* all of the distinct ways in which M identical stars can be located in n pidgeon holes. This is an exact enumeration of the solution to the stars-and-bars problem. This algorithm can be adapted to *visit* explicitly instead of leveraging dynamic programming and Memoization to merely *count* every solution, It is significantly slower if it visits the solutions. The advantage of visiting a solution is to eliminate solutions with a kpredictable low probability. """ """ countMe """ ########################################################## def countMe(m #The index of the pidgeon hole to start placing stars ,i #The number of stars that have to be placed ,V # ,visitEverySolution ): global Memo global Called; Called += 1 # this counts the number of times CountMe was called if i<0: return # base case solns =0 # this is a local count of solutions for # this instance, with M and i specified # in fxn signature for x in reversed(range(0,m+1)): #counting down from m to 0 VV=V # VV is mutable; V is not VV[i]=x for j in range(0,i): VV[j]=0 # clears the cubby holes to the left of i # needed for recursion if sum(VV)==M: # we have placed all of the stars global Solns; Solns += 1 solns += 1 # local solution global Solutions; Solutions.append(list(VV)) else: if visitEverySolution or Memo[m-x,i-1]==0: countMe(m-x,i-1,VV,visitEverySolution) solns += Memo[m-x,i-1] Memo[m,i]=solns return solns ############################################################## """ The beginning of execution is here. """ (M # number of stars ,n # number of bars+1 (or number of pidgeon holes) #)=(10,7) # 8008 solutions. use for testing )=(20,10) # 10015005 solutions # visitEverySolution=True takes 66 seconds # visitEverySolution=False takes 0.003 secodns """ Memo is a matrix containing the number of solutions with M stars up to and including the ith pidgeon hole. Memo is the hallmark of dynamic programming. """ Memo=np.zeros((M+1,n)) # V this the running occupancy of the pidgeon holes V=[0 for i in range(n)] #start with all pidgeon holes empty Solns=0 # global number of solutions Called=0 #global number of calls to countMe print("An exact solution can computed to be",scipy.special.binom(M+n-1,n-1)) visitEverySolution=False #count only, not visit t0=dt.now() countMe(M,n-1,V,visitEverySolution) # enter the counting routine here t1=dt.now() # We want to locate M stars in all pidgeon holes up to # and including n-1 (the last one) print("Elapsed time was",t1-t0) print("The number of solutions with M=",M,"stars and n=",n,"pidgeon holes is",Memo[M,n-1]) print("Solns=",Solns) print("CountMe was called",Called,"times.") #print(Solutions) ```
Numerically/approximately integrating over independent gamma variables Here is a sketch of a solution. The general strategy is to introduce the scalar sum $\theta_T=\sum\theta_i, $ then marginalize over it, then use it to turn the complicated multidimenional sum over the
40,956
Numerically/approximately integrating over independent gamma variables
Your question does not specify the trials parameter in the multinomial distribution, so I'm going to use the standard generic case where you have $n$ trial and $m$ categories. I will let $\tilde{\boldsymbol{\theta}} = (\tilde{\theta}_1,...,\tilde{\theta}_m)$ denote the normalised values $\tilde{\theta}_k = \theta_k / \sum_i \theta_i$, so the model of interest is: $$\mathbf{X} | \boldsymbol{\theta} \sim \text{Mu}(n,\tilde{\boldsymbol{\theta}}) \quad \quad \quad \theta_k \sim \text{Ga}(\alpha_k, \beta_k).$$ The required integral: The marginal mass function for $\mathbf{X}$ is given by: $$\begin{equation} \begin{aligned} p(\mathbf{x}|\boldsymbol{\alpha}, \boldsymbol{\beta}) &= \int \limits_\Theta \text{Mu}(\mathbf{x} | \tilde{\boldsymbol{\theta}}) \prod_{i=1}^m \text{Ga}(\theta_i | \alpha_i, \beta_i) \ d \boldsymbol{\theta} \\[6pt] &\overset{\mathbf{x}}{\propto} {n \choose \mathbf{x}} \int \limits_\Theta \frac{\prod_{i=1}^m \theta^{x_i + \alpha_i - 1} \exp( - \beta_i \theta_i )}{(\sum_{i=1}^m \theta_i)^n} \ d \boldsymbol{\theta}. \\[6pt] \end{aligned} \end{equation}$$ If $\beta_1 = ... = \beta_m = \beta$ then $\tilde{\boldsymbol{\theta}}$ has a Dirichlet distribution which means that $\mathbf{X}$ then has a multinomial-Dirichlet distribution. (In your question you incorrectly state that $\mathbf{X}$ has a Dirichlet distribution in this case. That can't be right because the Dirichlet distribution generates non-integer vectors of values.) There are various ways to approximate the above integral, and I will show you one of these methods below. (If time permits, I may come back to this answer and add other methods.) Approximation by direct sampling (useful if hyperparameters are fixed): Since the object of interest is a mass function obtained via a known conditional distribution, the simplest way to approximate the integral is simply to generate a large number of conditioning values and approximate the integral by an analogous sum. To do this, choose some large number of simulations $H \in \mathbb{N}$ and generate independent values: $$\theta_k^{(h)} \sim \text{Ga}(\alpha_k, \beta_k) \quad \quad \quad \text{for all } k=1,...,m \text{ and } h =1,...,H.$$ You can then use the approximation: $$\hat{p}_\text{DS}(\mathbf{x}|\boldsymbol{\alpha}, \boldsymbol{\beta}) = \frac{1}{H} \sum_{h=1}^H {n \choose \mathbf{x}} \frac{\prod_{k=1}^m \theta_k^{(h) \ x_k}}{(\sum_{k=1}^m \theta_k^{(h)})^n} .$$ This method requires you to generate $H \times m$ scalar parameter values and then evaluate the mass function as an average of $H$ multinomial mass functions. Note that this method evaluates the mass function for a fixed set of parameter values $\boldsymbol{\alpha}$ and $\boldsymbol{\beta}$, so it is not useful if you would like your approximation to serve as a function of those parameter values. Approximation by importance sampling (useful if hyperparameters are variables): The method of direct sampling builds the parameters $\boldsymbol{\alpha}$ and $\boldsymbol{\beta}$ into the simulation, so it is useful when these are fixed (i.e., when you don't need the function to vary over these values). If you would like your approximating function to also be able to vary over these parameters then you can use importance sampling instead. To do this, choose some mid-ranged hyperparameter values $\bar{\alpha}$ and $\bar{\beta}$, choose some large number of simulations $H \in \mathbb{N}$ and generate independent values: $$\theta_k^{(h)} \sim \text{Ga}(\bar{\alpha}, \bar{\beta}) \quad \quad \quad \text{for all } k=1,...,m \text{ and } h =1,...,H.$$ You can then use the approximation: $$\hat{p}_\text{IS}(\mathbf{x}|\boldsymbol{\alpha}, \boldsymbol{\beta}) = \frac{1}{H} \sum_{h=1}^H {n \choose \mathbf{x}} \frac{\prod_{k=1}^m \theta_k^{(h) \ x_k}}{(\sum_{k=1}^m \theta_k^{(h)})^n} \cdot \prod_{k=1}^m \frac{\text{Ga}(\theta_k^{(h)} | \alpha_k, \beta_k)}{\text{Ga}(\theta_k^{(h)} | \bar{\alpha}, \bar{\beta})}.$$ This method requires you to generate $H \times m$ scalar parameter values and then evaluate the mass function as an average of $H$ weighted multinomial mass functions, where the weighting is used to adjust for the hyperparameters. Note that this method treats the hyperparameters as variables that can be adjusted in the calculation of the approximating function (without generating new simulated values). Here is some R code to implement this latter method: #Load required libraries and set seed library(stats); library(matrixStats); set.seed(1); #Set parameter values for simulation m <- 3; A <- 2; B <- 3; H <- 10^4; #Simulate values of theta THETA <- array(rgamma(H*m, shape = A, rate = B), dim = c(H, m)); #Create function to generate approximation using importance sampling LOGMASS <- function(x, alpha, beta) { LOGWEIGHT <- array(0, dim = c(H, m)); for (h in 1:H) { for (k in 1:m) { T1 <- dgamma(THETA[h,k], shape = alpha[k], rate = beta[k], log = TRUE); T2 <- dgamma(THETA[h,k], shape = A, rate = B, log = TRUE); LOGWEIGHT[h,k] <- (T1 - T2); } } LOGW <- rowSums(LOGWEIGHT); LOGTERMS <- rep(0, H); for (h in 1:H) { LOGTERMS[h] <- (stats::dmultinom(x, size = sum(x), prob = THETA[h, ], log = TRUE) + LOGW[h]); } matrixStats::logSumExp(LOGTERMS) - log(H); } #Find approximate mass function at an example point x <- c(3,3,4); alpha <- c(4,3,2); beta <- c(2,1,2); LOGMASS(x, alpha, beta); [1] -4.132541 This code will allow you to generate the log-mass for your distribution at any input value for the observable vector and the hyperparameters. By setting H reasonably large you should get a good approximation to the true log-mass function. Some statistical theory and accuracy bounds for this kind of simulation can be found in O'Neill (2009).
Numerically/approximately integrating over independent gamma variables
Your question does not specify the trials parameter in the multinomial distribution, so I'm going to use the standard generic case where you have $n$ trial and $m$ categories. I will let $\tilde{\bol
Numerically/approximately integrating over independent gamma variables Your question does not specify the trials parameter in the multinomial distribution, so I'm going to use the standard generic case where you have $n$ trial and $m$ categories. I will let $\tilde{\boldsymbol{\theta}} = (\tilde{\theta}_1,...,\tilde{\theta}_m)$ denote the normalised values $\tilde{\theta}_k = \theta_k / \sum_i \theta_i$, so the model of interest is: $$\mathbf{X} | \boldsymbol{\theta} \sim \text{Mu}(n,\tilde{\boldsymbol{\theta}}) \quad \quad \quad \theta_k \sim \text{Ga}(\alpha_k, \beta_k).$$ The required integral: The marginal mass function for $\mathbf{X}$ is given by: $$\begin{equation} \begin{aligned} p(\mathbf{x}|\boldsymbol{\alpha}, \boldsymbol{\beta}) &= \int \limits_\Theta \text{Mu}(\mathbf{x} | \tilde{\boldsymbol{\theta}}) \prod_{i=1}^m \text{Ga}(\theta_i | \alpha_i, \beta_i) \ d \boldsymbol{\theta} \\[6pt] &\overset{\mathbf{x}}{\propto} {n \choose \mathbf{x}} \int \limits_\Theta \frac{\prod_{i=1}^m \theta^{x_i + \alpha_i - 1} \exp( - \beta_i \theta_i )}{(\sum_{i=1}^m \theta_i)^n} \ d \boldsymbol{\theta}. \\[6pt] \end{aligned} \end{equation}$$ If $\beta_1 = ... = \beta_m = \beta$ then $\tilde{\boldsymbol{\theta}}$ has a Dirichlet distribution which means that $\mathbf{X}$ then has a multinomial-Dirichlet distribution. (In your question you incorrectly state that $\mathbf{X}$ has a Dirichlet distribution in this case. That can't be right because the Dirichlet distribution generates non-integer vectors of values.) There are various ways to approximate the above integral, and I will show you one of these methods below. (If time permits, I may come back to this answer and add other methods.) Approximation by direct sampling (useful if hyperparameters are fixed): Since the object of interest is a mass function obtained via a known conditional distribution, the simplest way to approximate the integral is simply to generate a large number of conditioning values and approximate the integral by an analogous sum. To do this, choose some large number of simulations $H \in \mathbb{N}$ and generate independent values: $$\theta_k^{(h)} \sim \text{Ga}(\alpha_k, \beta_k) \quad \quad \quad \text{for all } k=1,...,m \text{ and } h =1,...,H.$$ You can then use the approximation: $$\hat{p}_\text{DS}(\mathbf{x}|\boldsymbol{\alpha}, \boldsymbol{\beta}) = \frac{1}{H} \sum_{h=1}^H {n \choose \mathbf{x}} \frac{\prod_{k=1}^m \theta_k^{(h) \ x_k}}{(\sum_{k=1}^m \theta_k^{(h)})^n} .$$ This method requires you to generate $H \times m$ scalar parameter values and then evaluate the mass function as an average of $H$ multinomial mass functions. Note that this method evaluates the mass function for a fixed set of parameter values $\boldsymbol{\alpha}$ and $\boldsymbol{\beta}$, so it is not useful if you would like your approximation to serve as a function of those parameter values. Approximation by importance sampling (useful if hyperparameters are variables): The method of direct sampling builds the parameters $\boldsymbol{\alpha}$ and $\boldsymbol{\beta}$ into the simulation, so it is useful when these are fixed (i.e., when you don't need the function to vary over these values). If you would like your approximating function to also be able to vary over these parameters then you can use importance sampling instead. To do this, choose some mid-ranged hyperparameter values $\bar{\alpha}$ and $\bar{\beta}$, choose some large number of simulations $H \in \mathbb{N}$ and generate independent values: $$\theta_k^{(h)} \sim \text{Ga}(\bar{\alpha}, \bar{\beta}) \quad \quad \quad \text{for all } k=1,...,m \text{ and } h =1,...,H.$$ You can then use the approximation: $$\hat{p}_\text{IS}(\mathbf{x}|\boldsymbol{\alpha}, \boldsymbol{\beta}) = \frac{1}{H} \sum_{h=1}^H {n \choose \mathbf{x}} \frac{\prod_{k=1}^m \theta_k^{(h) \ x_k}}{(\sum_{k=1}^m \theta_k^{(h)})^n} \cdot \prod_{k=1}^m \frac{\text{Ga}(\theta_k^{(h)} | \alpha_k, \beta_k)}{\text{Ga}(\theta_k^{(h)} | \bar{\alpha}, \bar{\beta})}.$$ This method requires you to generate $H \times m$ scalar parameter values and then evaluate the mass function as an average of $H$ weighted multinomial mass functions, where the weighting is used to adjust for the hyperparameters. Note that this method treats the hyperparameters as variables that can be adjusted in the calculation of the approximating function (without generating new simulated values). Here is some R code to implement this latter method: #Load required libraries and set seed library(stats); library(matrixStats); set.seed(1); #Set parameter values for simulation m <- 3; A <- 2; B <- 3; H <- 10^4; #Simulate values of theta THETA <- array(rgamma(H*m, shape = A, rate = B), dim = c(H, m)); #Create function to generate approximation using importance sampling LOGMASS <- function(x, alpha, beta) { LOGWEIGHT <- array(0, dim = c(H, m)); for (h in 1:H) { for (k in 1:m) { T1 <- dgamma(THETA[h,k], shape = alpha[k], rate = beta[k], log = TRUE); T2 <- dgamma(THETA[h,k], shape = A, rate = B, log = TRUE); LOGWEIGHT[h,k] <- (T1 - T2); } } LOGW <- rowSums(LOGWEIGHT); LOGTERMS <- rep(0, H); for (h in 1:H) { LOGTERMS[h] <- (stats::dmultinom(x, size = sum(x), prob = THETA[h, ], log = TRUE) + LOGW[h]); } matrixStats::logSumExp(LOGTERMS) - log(H); } #Find approximate mass function at an example point x <- c(3,3,4); alpha <- c(4,3,2); beta <- c(2,1,2); LOGMASS(x, alpha, beta); [1] -4.132541 This code will allow you to generate the log-mass for your distribution at any input value for the observable vector and the hyperparameters. By setting H reasonably large you should get a good approximation to the true log-mass function. Some statistical theory and accuracy bounds for this kind of simulation can be found in O'Neill (2009).
Numerically/approximately integrating over independent gamma variables Your question does not specify the trials parameter in the multinomial distribution, so I'm going to use the standard generic case where you have $n$ trial and $m$ categories. I will let $\tilde{\bol
40,957
Condition on the covariance matrix of a gaussian process needed to have the Markov property
Since the process is Gaussian and zero-mean, formulas for conditional means and variances for the multivariate normal distribution imply that you can write each $\mathbf{X}_t$ as a linear combinations of $\mathbf{X}_{t-1}$, $\mathbf{X}_{t-2}$, ... plus an independent Gaussian error term. But since the process is also Markovian, only the first term will have a non-zero matrix of coeffients $\boldsymbol{\phi}_1$. Thus, we can write $$ \mathbf{X}_t = \boldsymbol{\phi}_1\mathbf{X}_{t-1}+\mathbf{w}_t. \tag{1} $$ The Markov property also implies that the error terms $\mathbf{w}_1, \mathbf{w}_2, \dots$ must all be independent and covariance stationary implies that $\boldsymbol{\phi}_1$ and the variance matrix of $\mathbf{w}_t$ remains constant across time. Hence, the process you describe is a vector AR(1) process. Its autocovariance matrix function is $$ \boldsymbol\Gamma(k)=\mbox{Cov}(\mathbf{X}_{t-k},\mathbf{X}_{t})=\boldsymbol\Gamma(0) (\boldsymbol{\phi}_1')^k $$ for $k\ge 1$, see Wei, 2007, section 16.3.1. A further restriction is that $\boldsymbol\phi_1$ must have eigenvalues with modulus smaller than 1, otherwise the process is not stationary. Note also that $\boldsymbol\Gamma(-k)=\boldsymbol\Gamma(k)'$ by definition of the auto covariance matrix function (so the autocovariance matrix function can not depend only on $|i-j|$).
Condition on the covariance matrix of a gaussian process needed to have the Markov property
Since the process is Gaussian and zero-mean, formulas for conditional means and variances for the multivariate normal distribution imply that you can write each $\mathbf{X}_t$ as a linear combinations
Condition on the covariance matrix of a gaussian process needed to have the Markov property Since the process is Gaussian and zero-mean, formulas for conditional means and variances for the multivariate normal distribution imply that you can write each $\mathbf{X}_t$ as a linear combinations of $\mathbf{X}_{t-1}$, $\mathbf{X}_{t-2}$, ... plus an independent Gaussian error term. But since the process is also Markovian, only the first term will have a non-zero matrix of coeffients $\boldsymbol{\phi}_1$. Thus, we can write $$ \mathbf{X}_t = \boldsymbol{\phi}_1\mathbf{X}_{t-1}+\mathbf{w}_t. \tag{1} $$ The Markov property also implies that the error terms $\mathbf{w}_1, \mathbf{w}_2, \dots$ must all be independent and covariance stationary implies that $\boldsymbol{\phi}_1$ and the variance matrix of $\mathbf{w}_t$ remains constant across time. Hence, the process you describe is a vector AR(1) process. Its autocovariance matrix function is $$ \boldsymbol\Gamma(k)=\mbox{Cov}(\mathbf{X}_{t-k},\mathbf{X}_{t})=\boldsymbol\Gamma(0) (\boldsymbol{\phi}_1')^k $$ for $k\ge 1$, see Wei, 2007, section 16.3.1. A further restriction is that $\boldsymbol\phi_1$ must have eigenvalues with modulus smaller than 1, otherwise the process is not stationary. Note also that $\boldsymbol\Gamma(-k)=\boldsymbol\Gamma(k)'$ by definition of the auto covariance matrix function (so the autocovariance matrix function can not depend only on $|i-j|$).
Condition on the covariance matrix of a gaussian process needed to have the Markov property Since the process is Gaussian and zero-mean, formulas for conditional means and variances for the multivariate normal distribution imply that you can write each $\mathbf{X}_t$ as a linear combinations
40,958
Condition on the covariance matrix of a gaussian process needed to have the Markov property
A sufficient and necessary condition for a Gaussian process to be also Markovian is to have a triangular covariance function, i.e., $$ \mathrm{Cov}[X_{t_{1}}, X_{t_2}] = r_1(\min(t_1, t_2))r_2(\max(t_1, t_2)), $$ for unique (up to multiplicative constants) functions $r_1$ and $r_2$. The first full proof of this equivalence was provided in this paper by I. S. Borisov.
Condition on the covariance matrix of a gaussian process needed to have the Markov property
A sufficient and necessary condition for a Gaussian process to be also Markovian is to have a triangular covariance function, i.e., $$ \mathrm{Cov}[X_{t_{1}}, X_{t_2}] = r_1(\min(t_1, t_2))r_2(\max(t_
Condition on the covariance matrix of a gaussian process needed to have the Markov property A sufficient and necessary condition for a Gaussian process to be also Markovian is to have a triangular covariance function, i.e., $$ \mathrm{Cov}[X_{t_{1}}, X_{t_2}] = r_1(\min(t_1, t_2))r_2(\max(t_1, t_2)), $$ for unique (up to multiplicative constants) functions $r_1$ and $r_2$. The first full proof of this equivalence was provided in this paper by I. S. Borisov.
Condition on the covariance matrix of a gaussian process needed to have the Markov property A sufficient and necessary condition for a Gaussian process to be also Markovian is to have a triangular covariance function, i.e., $$ \mathrm{Cov}[X_{t_{1}}, X_{t_2}] = r_1(\min(t_1, t_2))r_2(\max(t_
40,959
Train/test split that resembles original dataset and each other
We can always stratify our sample so that the distribution of the underlying variables is similar between the two sets; stratified sampling is quite standard approach to ensure random subgroups have similar statistical properties. If we are using R they are multiple packages offering stratified sampling; e.g. the packages splitstackshape and stratification have a lot of readily available functionality. Most of stratified sampling methodology originates from survey statistics and ecology, so one might want to see a paper like Shao's (2003) "Impact of the Bootstrap on Sample Surveys", to get a better idea about potential implications of bootstrapping a (survey) sample. I have also found the UN's FAO (Food and Agriculture Organisation of the United Nations) Fisheries Technical Paper 434 on Sampling methods applied to fisheries science: a manual extremely readible and to the point (see in particular section 4 "Stratified random sampling") There are techniques that allows precise covariate balancing between control and treatment groups that could also be applicable but they are almost certainly an over-kill to use for picking a hold-out set. They might be useful as diagnostic tools nevertheless.
Train/test split that resembles original dataset and each other
We can always stratify our sample so that the distribution of the underlying variables is similar between the two sets; stratified sampling is quite standard approach to ensure random subgroups have s
Train/test split that resembles original dataset and each other We can always stratify our sample so that the distribution of the underlying variables is similar between the two sets; stratified sampling is quite standard approach to ensure random subgroups have similar statistical properties. If we are using R they are multiple packages offering stratified sampling; e.g. the packages splitstackshape and stratification have a lot of readily available functionality. Most of stratified sampling methodology originates from survey statistics and ecology, so one might want to see a paper like Shao's (2003) "Impact of the Bootstrap on Sample Surveys", to get a better idea about potential implications of bootstrapping a (survey) sample. I have also found the UN's FAO (Food and Agriculture Organisation of the United Nations) Fisheries Technical Paper 434 on Sampling methods applied to fisheries science: a manual extremely readible and to the point (see in particular section 4 "Stratified random sampling") There are techniques that allows precise covariate balancing between control and treatment groups that could also be applicable but they are almost certainly an over-kill to use for picking a hold-out set. They might be useful as diagnostic tools nevertheless.
Train/test split that resembles original dataset and each other We can always stratify our sample so that the distribution of the underlying variables is similar between the two sets; stratified sampling is quite standard approach to ensure random subgroups have s
40,960
Train/test split that resembles original dataset and each other
In addition to @usεr11852's answer: if you can do train/test splits that are random but have the desired distribution matching properties, you can repeat/iterate this: this is a resampling technique called set validation and in this is similar to cross validation and out-of-bootstrap validation. For a single continuous variable of interest, there are non-random cross validation schemes like venetian blinds splitting where you sort your samples according to the continuous variable and then assign groups with equal sample no. modulo $k$. That leaves a slight systematic difference between the groups. For multiple such covariates, clustering methods like k-means (using what is otherwise mostly considered a weakness: that k-means tends to produce similar-sized spherical clusters) or Kohonen maps have been used for the stratification. The Duplex algorithm (Snee: Validation of Regression Models: Methods and Examples, Technometrics 1977 (a variant of the Kennard-Stone algorithm) gives a single split into train and test sets. This algorithm is particularly interesting if you need to select a subset of a larger number of data points for training and testing (e.g. lots of measurements available, but reference values are expensive).
Train/test split that resembles original dataset and each other
In addition to @usεr11852's answer: if you can do train/test splits that are random but have the desired distribution matching properties, you can repeat/iterate this: this is a resampling technique
Train/test split that resembles original dataset and each other In addition to @usεr11852's answer: if you can do train/test splits that are random but have the desired distribution matching properties, you can repeat/iterate this: this is a resampling technique called set validation and in this is similar to cross validation and out-of-bootstrap validation. For a single continuous variable of interest, there are non-random cross validation schemes like venetian blinds splitting where you sort your samples according to the continuous variable and then assign groups with equal sample no. modulo $k$. That leaves a slight systematic difference between the groups. For multiple such covariates, clustering methods like k-means (using what is otherwise mostly considered a weakness: that k-means tends to produce similar-sized spherical clusters) or Kohonen maps have been used for the stratification. The Duplex algorithm (Snee: Validation of Regression Models: Methods and Examples, Technometrics 1977 (a variant of the Kennard-Stone algorithm) gives a single split into train and test sets. This algorithm is particularly interesting if you need to select a subset of a larger number of data points for training and testing (e.g. lots of measurements available, but reference values are expensive).
Train/test split that resembles original dataset and each other In addition to @usεr11852's answer: if you can do train/test splits that are random but have the desired distribution matching properties, you can repeat/iterate this: this is a resampling technique
40,961
Exclude observations with measurements below limit of detection?
OP asks about values below "limit of detection" in a quantitation (regression) context. Limit of detection, however is a method performance characteristic that refers to qualitative rather than quantitative tasks. This is why my original answer refers to the lower limit of qantitation (quantification) instead. See e.g. Currie, Pure&Appl. Chem., 67, 10, 1699-1723, 1995 on these terms. Turned out in the discussion, that the limit in question is actually the lower limit (end) of the calibration range. I.e. OP is asking how to deal with samples that turn out to be outside the range they calibrated and validated their method for. This makes my original answer somewhat off-topic. original answer: Don't exclude cases solely because they are below LLOQ! (lower limit of quantitation) The LLOQ is not a magic hard threshold below which nothing can be said. It is rather a convention to mark the concentration where the relative error of the analyses falls below 10 %. Note that LLOQ is often computed assuming homescedasticity, i.e. the absolute error being independent of the concentration. That is, you don't even assume different absolute error for cases below or above LLOQ. From that point of view, LLOQ is essentially just a way to express the absoute uncertainty of the analytical method in a concentration unit. (Like fuel economy in l/100 km vs. miles/gallon) Even if analytical error is concentration dependent, two cases with true concentration almost the same but slightly below and above LLOQ have almost the same uncertainty. (Left) censoring data (which is the technical term for excluding cases below LLOQ) leads to all kinds of complications in consecutive data analyses (and you'd need to use particular statistical methods that can deal with such data). Say thank you to your clinical lab that they provide you with full data: I've met many people who have the opposite difficulty: getting a report that just says below LLOQ, and no possibility to recover any further information. Bottomline: never censor your data unless you have really, really good reasons for doing so. update about replacing below LLOQ results by $\frac{LLOQ}{\sqrt 2}$ and in view of the comments below: From the comments below I think that we may be using terms in slightly different ways - possibly due to coming from different fields: linear range: concentration range where we get linear (can be relaxed to strictly monotonous) dependency of signal as function of concentration. calibration range: concentration range covered by calibration and validation samples. Outside this [precisely: the range covered by validation], we don't really know how our method behaves. => I totally agree that something$^{TM}$ needs to be done if 1/8 of the samples are outside calibration range and those samples moreover are important to reach correct conclusions in the study. LLOQ (aka LQ or LOQ) is a method performance characteristic. They can be inside or outside the calibration range. The most basic definition of LLOQ I'm aware of is specifying a relative error that must not be exceeded in the quantitation range. In my field, it is typically set to 10 % (but that can vary, and in fact should vary according to the requirements of the application. So the 10 % relative error to me is like the 5 % threshold for $p$ in significance testing, a default convention) I've encountered various replacement constants for $\leq$ LLOQ concentrations, ranging from 0 over $\frac{LLOQ}{2}$ to LLOQ and random values in the concentration range below LLOQ ( $\frac{LLOQ}{\sqrt 2}$ is new in that collection - what's the idea behind the $\frac{1}{\sqrt 2}$?). These are normally desperate attempts to impute values for censored data where not even (gu)estimates are available. With the above definition of LLOQ and validation data available for the whole concentration range encountered in your samples, replacing concentrations below LLOQ would amount to throwing away most of the little information you have for those samples, and that's typically not what you want. See my answer to this related question for illustrations. Also, this wouldn't avoid the necessity for using statistical methods that work with censored data, so there really isn't much difference to excluding. In your case, however, would it be possible to extend the validated concentration range somewhat further to the low side? Even if you don't extend the calibration range accordingly (which weuld IMHO be best). You say that excluding or not those 12 % of your samples has a large influence on your findings. So the idea here would be to rescue the study by establishing linearity and analytical error for a sufficiently large fraction of your samples to get stable estimates at the higher level (study question). While not being as good as having proper calibration from the beginning, the unexpected after all is something that has to be expected in research. With appropriate caution in the conclusions, this would IMHO be acceptable for early research (in contrast to later stages where better knowledge of expected concentration range would be available or work to establish this as analytical/clinical method). There are situations where your calibration function starts with a plateau for low concentrations before reaching a suitable sensitivity in the linear range (e.g. a particular absolute amount of analyte is masked/lost due to adsorption, ...). In contrast to low concentrations outside calibration/validation range but still inside linear range, you basically cannot say anything for concentrations in that plateau. I think of this as a "wet lab/chemical censoring". In that case => use statistical methods for censored data. The higher level question here is whether your analytical method is fit for purpose.
Exclude observations with measurements below limit of detection?
OP asks about values below "limit of detection" in a quantitation (regression) context. Limit of detection, however is a method performance characteristic that refers to qualitative rather than quant
Exclude observations with measurements below limit of detection? OP asks about values below "limit of detection" in a quantitation (regression) context. Limit of detection, however is a method performance characteristic that refers to qualitative rather than quantitative tasks. This is why my original answer refers to the lower limit of qantitation (quantification) instead. See e.g. Currie, Pure&Appl. Chem., 67, 10, 1699-1723, 1995 on these terms. Turned out in the discussion, that the limit in question is actually the lower limit (end) of the calibration range. I.e. OP is asking how to deal with samples that turn out to be outside the range they calibrated and validated their method for. This makes my original answer somewhat off-topic. original answer: Don't exclude cases solely because they are below LLOQ! (lower limit of quantitation) The LLOQ is not a magic hard threshold below which nothing can be said. It is rather a convention to mark the concentration where the relative error of the analyses falls below 10 %. Note that LLOQ is often computed assuming homescedasticity, i.e. the absolute error being independent of the concentration. That is, you don't even assume different absolute error for cases below or above LLOQ. From that point of view, LLOQ is essentially just a way to express the absoute uncertainty of the analytical method in a concentration unit. (Like fuel economy in l/100 km vs. miles/gallon) Even if analytical error is concentration dependent, two cases with true concentration almost the same but slightly below and above LLOQ have almost the same uncertainty. (Left) censoring data (which is the technical term for excluding cases below LLOQ) leads to all kinds of complications in consecutive data analyses (and you'd need to use particular statistical methods that can deal with such data). Say thank you to your clinical lab that they provide you with full data: I've met many people who have the opposite difficulty: getting a report that just says below LLOQ, and no possibility to recover any further information. Bottomline: never censor your data unless you have really, really good reasons for doing so. update about replacing below LLOQ results by $\frac{LLOQ}{\sqrt 2}$ and in view of the comments below: From the comments below I think that we may be using terms in slightly different ways - possibly due to coming from different fields: linear range: concentration range where we get linear (can be relaxed to strictly monotonous) dependency of signal as function of concentration. calibration range: concentration range covered by calibration and validation samples. Outside this [precisely: the range covered by validation], we don't really know how our method behaves. => I totally agree that something$^{TM}$ needs to be done if 1/8 of the samples are outside calibration range and those samples moreover are important to reach correct conclusions in the study. LLOQ (aka LQ or LOQ) is a method performance characteristic. They can be inside or outside the calibration range. The most basic definition of LLOQ I'm aware of is specifying a relative error that must not be exceeded in the quantitation range. In my field, it is typically set to 10 % (but that can vary, and in fact should vary according to the requirements of the application. So the 10 % relative error to me is like the 5 % threshold for $p$ in significance testing, a default convention) I've encountered various replacement constants for $\leq$ LLOQ concentrations, ranging from 0 over $\frac{LLOQ}{2}$ to LLOQ and random values in the concentration range below LLOQ ( $\frac{LLOQ}{\sqrt 2}$ is new in that collection - what's the idea behind the $\frac{1}{\sqrt 2}$?). These are normally desperate attempts to impute values for censored data where not even (gu)estimates are available. With the above definition of LLOQ and validation data available for the whole concentration range encountered in your samples, replacing concentrations below LLOQ would amount to throwing away most of the little information you have for those samples, and that's typically not what you want. See my answer to this related question for illustrations. Also, this wouldn't avoid the necessity for using statistical methods that work with censored data, so there really isn't much difference to excluding. In your case, however, would it be possible to extend the validated concentration range somewhat further to the low side? Even if you don't extend the calibration range accordingly (which weuld IMHO be best). You say that excluding or not those 12 % of your samples has a large influence on your findings. So the idea here would be to rescue the study by establishing linearity and analytical error for a sufficiently large fraction of your samples to get stable estimates at the higher level (study question). While not being as good as having proper calibration from the beginning, the unexpected after all is something that has to be expected in research. With appropriate caution in the conclusions, this would IMHO be acceptable for early research (in contrast to later stages where better knowledge of expected concentration range would be available or work to establish this as analytical/clinical method). There are situations where your calibration function starts with a plateau for low concentrations before reaching a suitable sensitivity in the linear range (e.g. a particular absolute amount of analyte is masked/lost due to adsorption, ...). In contrast to low concentrations outside calibration/validation range but still inside linear range, you basically cannot say anything for concentrations in that plateau. I think of this as a "wet lab/chemical censoring". In that case => use statistical methods for censored data. The higher level question here is whether your analytical method is fit for purpose.
Exclude observations with measurements below limit of detection? OP asks about values below "limit of detection" in a quantitation (regression) context. Limit of detection, however is a method performance characteristic that refers to qualitative rather than quant
40,962
Exclude observations with measurements below limit of detection?
Suppose you have an X with a measuring error with a standard deviation of 100. If X is measured to be 1000, then the expected value (assuming a well-calibrated measurement system) is around 1000. But suppose the measured amount is 110. It's possible that the actual value is 310; it's possible to be two standard deviations from the mean. But assuming that X is something that can't be negative, the actual value can't be two standard deviations below the measured value. Thus, there is likely a slight bias, and the expected value of the true value of X, given that the measured value is 110, is slightly more than 110. As your measured value gets smaller and smaller, this bias gets larger and larger. Whether this happens, and to what degree, depends on a lot of factors, such as what the distribution of actual values is and how the measurement error acts. But the bottom line is that including measured values below the LLOQ quite possibly can harm the validity of the regression. Unfortunately, removing them does not eliminate the problem, and can make it worse. You'll need to look at how the error is being modeled, what assumptions are being made about the actual distribution, and what methods there are to compensate. That removing them inverts the relationship certainly is a red flag that care needs to be taken in dealing with them.
Exclude observations with measurements below limit of detection?
Suppose you have an X with a measuring error with a standard deviation of 100. If X is measured to be 1000, then the expected value (assuming a well-calibrated measurement system) is around 1000. But
Exclude observations with measurements below limit of detection? Suppose you have an X with a measuring error with a standard deviation of 100. If X is measured to be 1000, then the expected value (assuming a well-calibrated measurement system) is around 1000. But suppose the measured amount is 110. It's possible that the actual value is 310; it's possible to be two standard deviations from the mean. But assuming that X is something that can't be negative, the actual value can't be two standard deviations below the measured value. Thus, there is likely a slight bias, and the expected value of the true value of X, given that the measured value is 110, is slightly more than 110. As your measured value gets smaller and smaller, this bias gets larger and larger. Whether this happens, and to what degree, depends on a lot of factors, such as what the distribution of actual values is and how the measurement error acts. But the bottom line is that including measured values below the LLOQ quite possibly can harm the validity of the regression. Unfortunately, removing them does not eliminate the problem, and can make it worse. You'll need to look at how the error is being modeled, what assumptions are being made about the actual distribution, and what methods there are to compensate. That removing them inverts the relationship certainly is a red flag that care needs to be taken in dealing with them.
Exclude observations with measurements below limit of detection? Suppose you have an X with a measuring error with a standard deviation of 100. If X is measured to be 1000, then the expected value (assuming a well-calibrated measurement system) is around 1000. But
40,963
Whether to use factors in R and when ordered factors?
Q1 - yes you are correct Q2 - you would usually choose to fit this as an ordered factor but you have the option of unordered if you wish to parameterise it in some unusual way. Q3 - if the variable is inherently continuous then categorising it loses information and leads to fitting a model which assumes the effect is identical for all values within each category with a jump to a new value at the boundary. This is usually thought to be scientifically implausible. Other people do it but there is no reason for you to do it. Q4 - this should make no difference, but why not try it and see what happens? You will not break R.
Whether to use factors in R and when ordered factors?
Q1 - yes you are correct Q2 - you would usually choose to fit this as an ordered factor but you have the option of unordered if you wish to parameterise it in some unusual way. Q3 - if the variable is
Whether to use factors in R and when ordered factors? Q1 - yes you are correct Q2 - you would usually choose to fit this as an ordered factor but you have the option of unordered if you wish to parameterise it in some unusual way. Q3 - if the variable is inherently continuous then categorising it loses information and leads to fitting a model which assumes the effect is identical for all values within each category with a jump to a new value at the boundary. This is usually thought to be scientifically implausible. Other people do it but there is no reason for you to do it. Q4 - this should make no difference, but why not try it and see what happens? You will not break R.
Whether to use factors in R and when ordered factors? Q1 - yes you are correct Q2 - you would usually choose to fit this as an ordered factor but you have the option of unordered if you wish to parameterise it in some unusual way. Q3 - if the variable is
40,964
Whether to use factors in R and when ordered factors?
Factor variables are used any time you have categorical data, where you wish to fit your model in a way that allows freedom for "effects" of those categories to vary arbitrarily. Ordered factors should be used when you have more than two categories that are ordinal in nature, and unordered factors should be used when you have only two categories, or any number of nominal categories. When you impose ordering of factors in a statistical model, this imposes a constraint that ensures that the magnitude and direction of the "effects" of those factors obey the proposed ordering. Thus, ordering of categories is equivalent to a constraint on the parameter space in the model. Full understanding the use of factors and numerical variables requires you to understand the underlying theory of measurement scales. The theory of measurement classifies variables according to whether they has meaningful relations according to various binary relations and arithmetic operators. A common typology separates variables into nominal, ordinal, interval, and ratio measurements. If you would like to know more about this subject then I would recommend reading some literature on measurement theory. A variable is characters like A\B\C of different kinds with no order, such as race(white/black etc) and gender (female/male). I know then I have to use factors, and not ordered factor. That is correct - race and gender would both be treated as nominal categories and so they should be treated as factors without a specification or ordering. (Technically there may be some rare applications where you would want to impose a parametric constraint that orders racial categories with respect to the magnitude and direction of "effects". In this case race would be treated an ordinal variable. This would only occur if there was a sound basis for imposing a parametric constraint on ordering, such as if race is associated with some other characteristic that justifies a constraint in the model.) When I meet some variable that records a series of stages, for example, tumor stage 1-4, acute kidney injury stage 1-4, should I use factors now? It seems that I should use ordered factors? Or is this simply a continuous numeric variable? These kind of classifications are generally discrete categorisations of some underlying variables that give more detail on the particular characteristics. For example, tumor stage is a simple categorisation determined by staging systems that take account of the size and spread of the tumor. These stages should not be treated as numerical variables, since that kind of treatment imposes implicit constraints that treat the "intervals" between the stages as being of equivalent magnitude in the model. Such variables should generally be treated as ordered factors. In this case the ordering constrains the magnitude of the "effects" in the model to the assigned order, but does not constrain the magnitude of the change in effects between different factor levels. When using these kinds of ordinal factor variables, it is also worth noting that they are commonly classified according to one or more underlying continuous variables. The categorical variable thus represents a loss of information compared to the underlying variables that determine the category. Hence, if the underlying continuous variables are part of the available data, you will usually get best results by using the underlying continuous variables in your model, and removing the factor variable entirely. Sometimes quantiles of a variable are calculated as a new variable, that is, values between 0~25% are categorized to 1, 25%~50% to 2, 50~75% to 3 and 75~100% to 4. The original variable is then removed from modeling, leaving only 1/2/3/4 representing Q1/Q2/Q3/Q4. This seems like the 2nd question above, so an ordered factor. Or, again, this is just a continuous numeric variable? That would be an ordered factor, and again, it involves a loss of information relative to the original variable. If the original variable is available it is usually best to model it directly. And finally, in a glm() logit regression model as an example, should I make the Y variable which is already 0/1 as integers a factor or not? Same question goes for X variables. I saw both glm(y ~ factor(x1) + ...) and glm(y ~ x1 + ...) on StackExchange, which is really getting me confused. When you use a factor variable in a statistical model, this variable is treated as a set of binary variables (with values 0 and 1) that indicate the different categories. One of the categories is treated as the baseline (represented by all indicators being 0) and the remaining categories are given an indicator variable. Thus, if you have a categorical variable with $k$ categories, that is treated as $k-1$ indicator variables in the model. One consequence of this is that a binary categorical variable is treated as a single indicator variable, and those two things are essentially equivalent in mathematical terms. Hence, when you are using a binary numerical variable with only two possible outcomes (e.g., 0 and 1), mathematically that is treated the same as any binary factor variable. In terms of actual syntax for putting variables into models in R, most of the modelling procedures will automatically deal with binary numeric variables and binary factor variables. For a logit regression the response variable y is binary, which is implicitly the same as a binary categorical variable. It is usually just treated as a numerical variable when fitting the model. If you put a binary factor variable into the glm function (either as the response or predictor) the function automatically assigns a corresponding binary indicator, so this does not cause any problem.
Whether to use factors in R and when ordered factors?
Factor variables are used any time you have categorical data, where you wish to fit your model in a way that allows freedom for "effects" of those categories to vary arbitrarily. Ordered factors shou
Whether to use factors in R and when ordered factors? Factor variables are used any time you have categorical data, where you wish to fit your model in a way that allows freedom for "effects" of those categories to vary arbitrarily. Ordered factors should be used when you have more than two categories that are ordinal in nature, and unordered factors should be used when you have only two categories, or any number of nominal categories. When you impose ordering of factors in a statistical model, this imposes a constraint that ensures that the magnitude and direction of the "effects" of those factors obey the proposed ordering. Thus, ordering of categories is equivalent to a constraint on the parameter space in the model. Full understanding the use of factors and numerical variables requires you to understand the underlying theory of measurement scales. The theory of measurement classifies variables according to whether they has meaningful relations according to various binary relations and arithmetic operators. A common typology separates variables into nominal, ordinal, interval, and ratio measurements. If you would like to know more about this subject then I would recommend reading some literature on measurement theory. A variable is characters like A\B\C of different kinds with no order, such as race(white/black etc) and gender (female/male). I know then I have to use factors, and not ordered factor. That is correct - race and gender would both be treated as nominal categories and so they should be treated as factors without a specification or ordering. (Technically there may be some rare applications where you would want to impose a parametric constraint that orders racial categories with respect to the magnitude and direction of "effects". In this case race would be treated an ordinal variable. This would only occur if there was a sound basis for imposing a parametric constraint on ordering, such as if race is associated with some other characteristic that justifies a constraint in the model.) When I meet some variable that records a series of stages, for example, tumor stage 1-4, acute kidney injury stage 1-4, should I use factors now? It seems that I should use ordered factors? Or is this simply a continuous numeric variable? These kind of classifications are generally discrete categorisations of some underlying variables that give more detail on the particular characteristics. For example, tumor stage is a simple categorisation determined by staging systems that take account of the size and spread of the tumor. These stages should not be treated as numerical variables, since that kind of treatment imposes implicit constraints that treat the "intervals" between the stages as being of equivalent magnitude in the model. Such variables should generally be treated as ordered factors. In this case the ordering constrains the magnitude of the "effects" in the model to the assigned order, but does not constrain the magnitude of the change in effects between different factor levels. When using these kinds of ordinal factor variables, it is also worth noting that they are commonly classified according to one or more underlying continuous variables. The categorical variable thus represents a loss of information compared to the underlying variables that determine the category. Hence, if the underlying continuous variables are part of the available data, you will usually get best results by using the underlying continuous variables in your model, and removing the factor variable entirely. Sometimes quantiles of a variable are calculated as a new variable, that is, values between 0~25% are categorized to 1, 25%~50% to 2, 50~75% to 3 and 75~100% to 4. The original variable is then removed from modeling, leaving only 1/2/3/4 representing Q1/Q2/Q3/Q4. This seems like the 2nd question above, so an ordered factor. Or, again, this is just a continuous numeric variable? That would be an ordered factor, and again, it involves a loss of information relative to the original variable. If the original variable is available it is usually best to model it directly. And finally, in a glm() logit regression model as an example, should I make the Y variable which is already 0/1 as integers a factor or not? Same question goes for X variables. I saw both glm(y ~ factor(x1) + ...) and glm(y ~ x1 + ...) on StackExchange, which is really getting me confused. When you use a factor variable in a statistical model, this variable is treated as a set of binary variables (with values 0 and 1) that indicate the different categories. One of the categories is treated as the baseline (represented by all indicators being 0) and the remaining categories are given an indicator variable. Thus, if you have a categorical variable with $k$ categories, that is treated as $k-1$ indicator variables in the model. One consequence of this is that a binary categorical variable is treated as a single indicator variable, and those two things are essentially equivalent in mathematical terms. Hence, when you are using a binary numerical variable with only two possible outcomes (e.g., 0 and 1), mathematically that is treated the same as any binary factor variable. In terms of actual syntax for putting variables into models in R, most of the modelling procedures will automatically deal with binary numeric variables and binary factor variables. For a logit regression the response variable y is binary, which is implicitly the same as a binary categorical variable. It is usually just treated as a numerical variable when fitting the model. If you put a binary factor variable into the glm function (either as the response or predictor) the function automatically assigns a corresponding binary indicator, so this does not cause any problem.
Whether to use factors in R and when ordered factors? Factor variables are used any time you have categorical data, where you wish to fit your model in a way that allows freedom for "effects" of those categories to vary arbitrarily. Ordered factors shou
40,965
Parameter tuning with vs without nested cross-validation
Part of the issue for #1 is terminology. We usually think of the training and test sets as the initial splitting that is done when you have assembled and cleaned your data. Resampling only happens on the training set; the test set is left for a final, unbiased evaluation of the model once you have singled one out as being the best. When resampling, I have been using different terminology for the data used in the model and for the data held-out for immediate prediction. I call those the analysis and assessment sets respectively. So for simple 10-fold CV, each analysis set is 90% of the training set and the assessment set is 10%. Your point about inefficient use of data with a training and test set is one complaint that I've heard over the years. However, it is good scientific practice to have a confirmatory data set that is only used to reaffirm the results that you obtained during the modeling process. There are ways to do resampling incorrectly and you would not know that this has occurred until you evaluate the next set of samples (that were not involved in the preceding analysis). Your point is valid but, unless your entire data set is pathologically small, the use of a test set far outweighs the inefficiency caused by the smaller training set. For #2, the only way to really know when you are overfitting is with a separate data set (such as the assessment set). Whether that comes from nested resampling or non-nested (please don't call it the caret method), using the model to predict other samples is the only way to tell. For #3, the process that I generally give to people is to do an initial training/test split, then resample the training set (using the same analysis/assessment splits across all testing). I generally use non-nested resampling (I'm the one who wrote caret) but nested sampling can be used too (more on that below). Executing the resampling process across different tuning parameters can be very effective at helping choose parameter values since overfitting is reflected in those statistics. Once you've settled on parameter values, the final model is refit on the entire training set. Think of the process like this: the model-related operations are a module and this module can be applied to any data set. Resampling is a methods of estimating the performance of that module and was invented to emulate what the results would be for the module fit on the entire training set. Even though resampling can sometimes used less data when the module is repeatedly evaluated, it is still a good estimator of the final model that uses all the training data. The documentation for the rsample package shows this at a more nuts-and-bolts level. For example, this page shows a neural network being tuned across epochs using simple 10-fold CV. In that example, you can see that the assessment sets (which would capture the effect of overfitting) are used to measure performance. About nesting versus non-nesting: the main worry in non-nested resampling is optimization bias. If we evaluate a large number of tuning parameter values, there is some bias that we get by just choosing the best value. We are likely to be optimistic in our performance estimate. That is a real pattern and it is shown nicely in the papers that discuss it. However... my experience is that, although real, this bias is very small in most cases (especially when compared to the experimental noise). I have yet to see a real data set when the non-nested resampling gave pathologically optimistic estimates. This vignette has a simulated case-study using rsample that is a good demonstration. If the cost of nested resampling were not so high, I would definitely be using it more often.
Parameter tuning with vs without nested cross-validation
Part of the issue for #1 is terminology. We usually think of the training and test sets as the initial splitting that is done when you have assembled and cleaned your data. Resampling only happens on
Parameter tuning with vs without nested cross-validation Part of the issue for #1 is terminology. We usually think of the training and test sets as the initial splitting that is done when you have assembled and cleaned your data. Resampling only happens on the training set; the test set is left for a final, unbiased evaluation of the model once you have singled one out as being the best. When resampling, I have been using different terminology for the data used in the model and for the data held-out for immediate prediction. I call those the analysis and assessment sets respectively. So for simple 10-fold CV, each analysis set is 90% of the training set and the assessment set is 10%. Your point about inefficient use of data with a training and test set is one complaint that I've heard over the years. However, it is good scientific practice to have a confirmatory data set that is only used to reaffirm the results that you obtained during the modeling process. There are ways to do resampling incorrectly and you would not know that this has occurred until you evaluate the next set of samples (that were not involved in the preceding analysis). Your point is valid but, unless your entire data set is pathologically small, the use of a test set far outweighs the inefficiency caused by the smaller training set. For #2, the only way to really know when you are overfitting is with a separate data set (such as the assessment set). Whether that comes from nested resampling or non-nested (please don't call it the caret method), using the model to predict other samples is the only way to tell. For #3, the process that I generally give to people is to do an initial training/test split, then resample the training set (using the same analysis/assessment splits across all testing). I generally use non-nested resampling (I'm the one who wrote caret) but nested sampling can be used too (more on that below). Executing the resampling process across different tuning parameters can be very effective at helping choose parameter values since overfitting is reflected in those statistics. Once you've settled on parameter values, the final model is refit on the entire training set. Think of the process like this: the model-related operations are a module and this module can be applied to any data set. Resampling is a methods of estimating the performance of that module and was invented to emulate what the results would be for the module fit on the entire training set. Even though resampling can sometimes used less data when the module is repeatedly evaluated, it is still a good estimator of the final model that uses all the training data. The documentation for the rsample package shows this at a more nuts-and-bolts level. For example, this page shows a neural network being tuned across epochs using simple 10-fold CV. In that example, you can see that the assessment sets (which would capture the effect of overfitting) are used to measure performance. About nesting versus non-nesting: the main worry in non-nested resampling is optimization bias. If we evaluate a large number of tuning parameter values, there is some bias that we get by just choosing the best value. We are likely to be optimistic in our performance estimate. That is a real pattern and it is shown nicely in the papers that discuss it. However... my experience is that, although real, this bias is very small in most cases (especially when compared to the experimental noise). I have yet to see a real data set when the non-nested resampling gave pathologically optimistic estimates. This vignette has a simulated case-study using rsample that is a good demonstration. If the cost of nested resampling were not so high, I would definitely be using it more often.
Parameter tuning with vs without nested cross-validation Part of the issue for #1 is terminology. We usually think of the training and test sets as the initial splitting that is done when you have assembled and cleaned your data. Resampling only happens on
40,966
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes
In short, yes, you can use decision trees for this problem. However there are many other ways to predict the result of multiclass problems. If you want to use decision trees one way of doing it could be to assign a unique integer to each of your classes. All examples of class one will be assigned the value y=1, all the examples of class two will be assigned to value y=2 etc. After this you could train a decision classification tree. Here is a quick implementation in Python which I got by modifying the example in this hackernoon post (https://hackernoon.com/a-brief-look-at-sklearn-tree-decisiontreeclassifier-c2ee262eab9a) You can see that we have classes 0,1,2 and 3 in the data and the algorithm trains to be able to predict these perfectly (note that there is over training here but that is a side note) from sklearn import tree from sklearn.model_selection import train_test_split import numpy as np features = np.array([ [29, 23, 72], [31, 25, 77], [31, 27, 82], [29, 29, 89], [31, 31, 72], [29, 33, 77], ]*10) labels = np.array([ [0], [1], [2], [3], [2], [0], ]*10) X_train, X_test, y_train, y_test = train_test_split( features, labels, test_size=0.3, random_state=42, ) clf = tree.DecisionTreeClassifier() clf.fit(X=X_train, y=y_train) clf.feature_importances_ # [ 1., 0., 0.] clf.score(X=X_test, y=y_test) # 1.0 clf.predict(X_test) # array([0, 0, 0, 3, 1, 0, 3, 0, 0, 3, 2, 2, 1, 3, 2, 0, 2, 0])
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes
In short, yes, you can use decision trees for this problem. However there are many other ways to predict the result of multiclass problems. If you want to use decision trees one way of doing it could
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes In short, yes, you can use decision trees for this problem. However there are many other ways to predict the result of multiclass problems. If you want to use decision trees one way of doing it could be to assign a unique integer to each of your classes. All examples of class one will be assigned the value y=1, all the examples of class two will be assigned to value y=2 etc. After this you could train a decision classification tree. Here is a quick implementation in Python which I got by modifying the example in this hackernoon post (https://hackernoon.com/a-brief-look-at-sklearn-tree-decisiontreeclassifier-c2ee262eab9a) You can see that we have classes 0,1,2 and 3 in the data and the algorithm trains to be able to predict these perfectly (note that there is over training here but that is a side note) from sklearn import tree from sklearn.model_selection import train_test_split import numpy as np features = np.array([ [29, 23, 72], [31, 25, 77], [31, 27, 82], [29, 29, 89], [31, 31, 72], [29, 33, 77], ]*10) labels = np.array([ [0], [1], [2], [3], [2], [0], ]*10) X_train, X_test, y_train, y_test = train_test_split( features, labels, test_size=0.3, random_state=42, ) clf = tree.DecisionTreeClassifier() clf.fit(X=X_train, y=y_train) clf.feature_importances_ # [ 1., 0., 0.] clf.score(X=X_test, y=y_test) # 1.0 clf.predict(X_test) # array([0, 0, 0, 3, 1, 0, 3, 0, 0, 3, 2, 2, 1, 3, 2, 0, 2, 0])
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes In short, yes, you can use decision trees for this problem. However there are many other ways to predict the result of multiclass problems. If you want to use decision trees one way of doing it could
40,967
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes
Of course it can. The binarity of the tree is only in the questions it asks. Each node of the tree represents a question with binary answer(unless it's a terminal node -> that one represents a "class") such as: Is the numeric variable $x_1 \geq \alpha_1$ ? Is the categorical variable $x_2 = male$ ? The tree then splits the observations according to the answer. There can be many terminal nodes leading to different "classes" or even many nodes leading to the same class. Note: I put the word "class" in "" so that I don't have to rephrase it for regression trees. Note2: Look up random forests for example to overcome some obstacles with trees.
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes
Of course it can. The binarity of the tree is only in the questions it asks. Each node of the tree represents a question with binary answer(unless it's a terminal node -> that one represents a "class"
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes Of course it can. The binarity of the tree is only in the questions it asks. Each node of the tree represents a question with binary answer(unless it's a terminal node -> that one represents a "class") such as: Is the numeric variable $x_1 \geq \alpha_1$ ? Is the categorical variable $x_2 = male$ ? The tree then splits the observations according to the answer. There can be many terminal nodes leading to different "classes" or even many nodes leading to the same class. Note: I put the word "class" in "" so that I don't have to rephrase it for regression trees. Note2: Look up random forests for example to overcome some obstacles with trees.
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes Of course it can. The binarity of the tree is only in the questions it asks. Each node of the tree represents a question with binary answer(unless it's a terminal node -> that one represents a "class"
40,968
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes
You can directly call the decision tree of sklearn to achieve the task. For each split node, you need to choose a best attribute and a best split point(for continuous attribute), then you need to compute the impurity of left and right child node respectively. The child impurity could be computed based gini index.
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes
You can directly call the decision tree of sklearn to achieve the task. For each split node, you need to choose a best attribute and a best split point(for continuous attribute), then you need to comp
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes You can directly call the decision tree of sklearn to achieve the task. For each split node, you need to choose a best attribute and a best split point(for continuous attribute), then you need to compute the impurity of left and right child node respectively. The child impurity could be computed based gini index.
How would you use decision trees to learn to predict a multiclass problem involving 6 unique classes You can directly call the decision tree of sklearn to achieve the task. For each split node, you need to choose a best attribute and a best split point(for continuous attribute), then you need to comp
40,969
Atoms of a sigma algebra
Since $A_i$ are disjoint and their union is the entire space $\mathcal{X}$, clearly you cannot construct a set $B$ such that $B$ is a strict subset of any $A_i$ using complimentation or union. Since no such set can be constructed, it immediately follows that the $\sigma$-algebra generated by them, defined as containing any set that can be expressed as a countable union or compliment of these $A_i$, can contain a strict subset of any $A_i$. If it was true, it would contradict the prior observation. Hence all $A_i$ are atoms. To see why no strict subset can be constructed, draw a diagram of a space and partition it into disjoint parts. It should be clear you cannot construct a strict subset of any the parts using the others (though you can construct any $A_i$ itself by complimenting the union of all other $A_j, j \neq i$. If such a strict subset could be constructed, it would imply that some $x \in A_i$ also belongs to another $A_j$, contradicting the disjoint property of $A_i$'s.
Atoms of a sigma algebra
Since $A_i$ are disjoint and their union is the entire space $\mathcal{X}$, clearly you cannot construct a set $B$ such that $B$ is a strict subset of any $A_i$ using complimentation or union. Since
Atoms of a sigma algebra Since $A_i$ are disjoint and their union is the entire space $\mathcal{X}$, clearly you cannot construct a set $B$ such that $B$ is a strict subset of any $A_i$ using complimentation or union. Since no such set can be constructed, it immediately follows that the $\sigma$-algebra generated by them, defined as containing any set that can be expressed as a countable union or compliment of these $A_i$, can contain a strict subset of any $A_i$. If it was true, it would contradict the prior observation. Hence all $A_i$ are atoms. To see why no strict subset can be constructed, draw a diagram of a space and partition it into disjoint parts. It should be clear you cannot construct a strict subset of any the parts using the others (though you can construct any $A_i$ itself by complimenting the union of all other $A_j, j \neq i$. If such a strict subset could be constructed, it would imply that some $x \in A_i$ also belongs to another $A_j$, contradicting the disjoint property of $A_i$'s.
Atoms of a sigma algebra Since $A_i$ are disjoint and their union is the entire space $\mathcal{X}$, clearly you cannot construct a set $B$ such that $B$ is a strict subset of any $A_i$ using complimentation or union. Since
40,970
Is there any paper which summarizes the mathematical foundation of deep learning? [closed]
To my knowledge, there is not a single paper that would summarize proven mathematical results. For general overview, I recommend going for textbooks instead, which are more likely to give you a broad background overview. Two prominent examples are: Bishop, Christopher M. Neural networks for pattern recognition. Oxford university press, 1995. Goodfellow, Ian, Yoshua Bengio, Aaron Courville, and Yoshua Bengio. Deep learning. Vol. 1. Cambridge: MIT press, 2016. These are rather introductory books, compared to the level of some papers you cited. If you want to go deeper into PAC learning theory (which you really should, if you plan on doing research on the learnability of NN models), read both of these: Mehryar Mohri, Afshin Rostamizadeh, and Ameet Talwalkar, Foundations of Machine Learning, MIT Press, 2012 (but wait for the 2018 edition, it's due on Christmas and it has a few considerable improvements) Shai Shalev-Shwartz , Shai Ben-David, Understanding Machine Learning: From Theory to Algorithms, Cambridge University Press, 2014 Also, if you are interested in historical stream of development of neural networks, read: Schmidhuber, J., 2015. Deep learning in neural networks: An overview. Neural networks, 61, pp.85-117. The tricky thing with mathematical theory and proofs in deep learning is that many important results don't have practical implications. For example, the super famous Universal approximation theorem says that a neural network with a single hidden layer can approximate any function to arbitrary precision. Why would you care for using more layers then if one is enough? Because it was empirically demonstrated that it works. Also, the Universal approximation theorem only tells us that such a network exists, but it doesn't tell anything about what we are really interested in, i.e., the learnability of such a network from training samples (an Information Theory problem, or a PAC learning problem, depending on how you cast it). the existence of an algorithm which can learn the correct network (its weight) in polynomial time (a theory of computation problem). For example, we have a universal approximation theorem for polynomials and a universal approximation theorem for Gaussian processes with the squared exponential kernel. But do we win ImageNet/Kaggle competitions with polynomials or GPs? Of course we don't. Another example is the convergence: Training neural networks using first order methods (gradient descent and the likes) is guaranteed1 to converge to a local minimum but nothing more. Since it is non-convex optimization problem, we simply cannot prove much more useful about it (although some research is being done about the local minima distance from a global minimum [1,2]). Naturally, much more attention is paid to empirical research studying what we can do even if we cannot prove it2. Finally, I am not aware of works proving much important about the network architecture or about their generalization ability (to be honest, I am not sure what kinds of proofs are you looking for here; maybe if you reply in comments or add details to your question, I can expand on it here.) [1]: Choromanska, A., Henaff, M., Mathieu, M., Arous, G.B. and LeCun, Y., 2015, February. The loss surfaces of multilayer networks. In Artificial Intelligence and Statistics (pp. 192-204). [2]: Soudry, D. and Carmon, Y., 2016. No bad local minima: Data independent training error guarantees for multilayer neural networks. arXiv preprint arXiv:1605.08361. 1 Guaranteed almost surely; see discussion around this answer for some pathological counterexamples. 2 This is not necessarily bad and it does not mean that deep learning is alchemy: Proofs and rigorous math theories often follow empirical evidence and engineering results.
Is there any paper which summarizes the mathematical foundation of deep learning? [closed]
To my knowledge, there is not a single paper that would summarize proven mathematical results. For general overview, I recommend going for textbooks instead, which are more likely to give you a broad
Is there any paper which summarizes the mathematical foundation of deep learning? [closed] To my knowledge, there is not a single paper that would summarize proven mathematical results. For general overview, I recommend going for textbooks instead, which are more likely to give you a broad background overview. Two prominent examples are: Bishop, Christopher M. Neural networks for pattern recognition. Oxford university press, 1995. Goodfellow, Ian, Yoshua Bengio, Aaron Courville, and Yoshua Bengio. Deep learning. Vol. 1. Cambridge: MIT press, 2016. These are rather introductory books, compared to the level of some papers you cited. If you want to go deeper into PAC learning theory (which you really should, if you plan on doing research on the learnability of NN models), read both of these: Mehryar Mohri, Afshin Rostamizadeh, and Ameet Talwalkar, Foundations of Machine Learning, MIT Press, 2012 (but wait for the 2018 edition, it's due on Christmas and it has a few considerable improvements) Shai Shalev-Shwartz , Shai Ben-David, Understanding Machine Learning: From Theory to Algorithms, Cambridge University Press, 2014 Also, if you are interested in historical stream of development of neural networks, read: Schmidhuber, J., 2015. Deep learning in neural networks: An overview. Neural networks, 61, pp.85-117. The tricky thing with mathematical theory and proofs in deep learning is that many important results don't have practical implications. For example, the super famous Universal approximation theorem says that a neural network with a single hidden layer can approximate any function to arbitrary precision. Why would you care for using more layers then if one is enough? Because it was empirically demonstrated that it works. Also, the Universal approximation theorem only tells us that such a network exists, but it doesn't tell anything about what we are really interested in, i.e., the learnability of such a network from training samples (an Information Theory problem, or a PAC learning problem, depending on how you cast it). the existence of an algorithm which can learn the correct network (its weight) in polynomial time (a theory of computation problem). For example, we have a universal approximation theorem for polynomials and a universal approximation theorem for Gaussian processes with the squared exponential kernel. But do we win ImageNet/Kaggle competitions with polynomials or GPs? Of course we don't. Another example is the convergence: Training neural networks using first order methods (gradient descent and the likes) is guaranteed1 to converge to a local minimum but nothing more. Since it is non-convex optimization problem, we simply cannot prove much more useful about it (although some research is being done about the local minima distance from a global minimum [1,2]). Naturally, much more attention is paid to empirical research studying what we can do even if we cannot prove it2. Finally, I am not aware of works proving much important about the network architecture or about their generalization ability (to be honest, I am not sure what kinds of proofs are you looking for here; maybe if you reply in comments or add details to your question, I can expand on it here.) [1]: Choromanska, A., Henaff, M., Mathieu, M., Arous, G.B. and LeCun, Y., 2015, February. The loss surfaces of multilayer networks. In Artificial Intelligence and Statistics (pp. 192-204). [2]: Soudry, D. and Carmon, Y., 2016. No bad local minima: Data independent training error guarantees for multilayer neural networks. arXiv preprint arXiv:1605.08361. 1 Guaranteed almost surely; see discussion around this answer for some pathological counterexamples. 2 This is not necessarily bad and it does not mean that deep learning is alchemy: Proofs and rigorous math theories often follow empirical evidence and engineering results.
Is there any paper which summarizes the mathematical foundation of deep learning? [closed] To my knowledge, there is not a single paper that would summarize proven mathematical results. For general overview, I recommend going for textbooks instead, which are more likely to give you a broad
40,971
Interpreting the standard error from emmeans - R
OK, let us dissect this model. First, the model itself: > getOption("contrasts") unordered ordered "contr.treatment" "contr.poly" > warp.lm <- lm(breaks ~ wool*tension, data = warpbreaks) > summary(warp.lm) ... (some output omitted) ... Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 44.556 3.647 12.218 2.43e-16 woolB -16.333 5.157 -3.167 0.002677 tensionM -20.556 5.157 -3.986 0.000228 tensionH -20.000 5.157 -3.878 0.000320 woolB:tensionM 21.111 7.294 2.895 0.005698 woolB:tensionH 10.556 7.294 1.447 0.154327 Residual standard error: 10.94 on 48 degrees of freedom Multiple R-squared: 0.3778, Adjusted R-squared: 0.3129 F-statistic: 5.828 on 5 and 48 DF, p-value: 0.0002772 This model has an underlying assumption that the error SD is homogeneous, and its estimated value is 10.94. With the default contrast coding ("contr.treatment"), The intercept is an estimate of the cell mean when each factor is at its first level The main-effect coefficients (for a model with interaction) are estimates of certain comparisons between cell means. In particular, they are comparisons of cell means where one factor is held constant while the other one changes. The interaction coefficients are estimates of certain interaction contrasts (namely, differences of differences) We can observe these results in the output from emmeans() and its relatives. For (1), note that the first result below matches the intercept, in both the estimate and the standard error: > emmeans(warp.lm, ~ wool * tension) wool tension emmean SE df lower.CL upper.CL A L 44.55556 3.646761 48 37.22325 51.88786 B L 28.22222 3.646761 48 20.88992 35.55453 A M 24.00000 3.646761 48 16.66769 31.33231 B M 28.77778 3.646761 48 21.44547 36.11008 A H 24.55556 3.646761 48 17.22325 31.88786 B H 18.77778 3.646761 48 11.44547 26.11008 For (2), the first, second, and fourth results below match the model summary in both estimate (with signs reversed) and standard error: > pairs(emmeans(warp.lm, ~ wool*tension)) contrast estimate SE df t.ratio p.value A,L - B,L 16.3333333 5.157299 48 3.167 0.0302 A,L - A,M 20.5555556 5.157299 48 3.986 0.0030 A,L - B,M 15.7777778 5.157299 48 3.059 0.0398 A,L - A,H 20.0000000 5.157299 48 3.878 0.0041 A,L - B,H 25.7777778 5.157299 48 4.998 0.0001 B,L - A,M 4.2222222 5.157299 48 0.819 0.9627 B,L - B,M -0.5555556 5.157299 48 -0.108 1.0000 B,L - A,H 3.6666667 5.157299 48 0.711 0.9797 B,L - B,H 9.4444444 5.157299 48 1.831 0.4561 A,M - B,M -4.7777778 5.157299 48 -0.926 0.9377 A,M - A,H -0.5555556 5.157299 48 -0.108 1.0000 A,M - B,H 5.2222222 5.157299 48 1.013 0.9115 B,M - A,H 4.2222222 5.157299 48 0.819 0.9627 B,M - B,H 10.0000000 5.157299 48 1.939 0.3919 A,H - B,H 5.7777778 5.157299 48 1.120 0.8706 For (3), the first two results below match the model summary in both estimate and standard error. > contrast(emmeans(warp.lm, ~ wool*tension), interaction = "pairwise") wool_pairwise tension_pairwise estimate SE df t.ratio p.value A - B L - M 21.11111 7.293523 48 2.895 0.0057 A - B L - H 10.55556 7.293523 48 1.447 0.1543 A - B M - H -10.55556 7.293523 48 -1.447 0.1543 Notice that within each set of results above, the standard errors stay constant within a table. That is a consequence of the fact that the design is balanced (equal numers of observations in each cell) and the model assumption of a constant error SD. If you fit a different model (using, say, nlme::gls() that allows for nonhomogeneous error variances, then you will get unequal SEs in both the model summary and the emmeans results.
Interpreting the standard error from emmeans - R
OK, let us dissect this model. First, the model itself: > getOption("contrasts") unordered ordered "contr.treatment" "contr.poly" > warp.lm <- lm(breaks ~ wool*tension, data
Interpreting the standard error from emmeans - R OK, let us dissect this model. First, the model itself: > getOption("contrasts") unordered ordered "contr.treatment" "contr.poly" > warp.lm <- lm(breaks ~ wool*tension, data = warpbreaks) > summary(warp.lm) ... (some output omitted) ... Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 44.556 3.647 12.218 2.43e-16 woolB -16.333 5.157 -3.167 0.002677 tensionM -20.556 5.157 -3.986 0.000228 tensionH -20.000 5.157 -3.878 0.000320 woolB:tensionM 21.111 7.294 2.895 0.005698 woolB:tensionH 10.556 7.294 1.447 0.154327 Residual standard error: 10.94 on 48 degrees of freedom Multiple R-squared: 0.3778, Adjusted R-squared: 0.3129 F-statistic: 5.828 on 5 and 48 DF, p-value: 0.0002772 This model has an underlying assumption that the error SD is homogeneous, and its estimated value is 10.94. With the default contrast coding ("contr.treatment"), The intercept is an estimate of the cell mean when each factor is at its first level The main-effect coefficients (for a model with interaction) are estimates of certain comparisons between cell means. In particular, they are comparisons of cell means where one factor is held constant while the other one changes. The interaction coefficients are estimates of certain interaction contrasts (namely, differences of differences) We can observe these results in the output from emmeans() and its relatives. For (1), note that the first result below matches the intercept, in both the estimate and the standard error: > emmeans(warp.lm, ~ wool * tension) wool tension emmean SE df lower.CL upper.CL A L 44.55556 3.646761 48 37.22325 51.88786 B L 28.22222 3.646761 48 20.88992 35.55453 A M 24.00000 3.646761 48 16.66769 31.33231 B M 28.77778 3.646761 48 21.44547 36.11008 A H 24.55556 3.646761 48 17.22325 31.88786 B H 18.77778 3.646761 48 11.44547 26.11008 For (2), the first, second, and fourth results below match the model summary in both estimate (with signs reversed) and standard error: > pairs(emmeans(warp.lm, ~ wool*tension)) contrast estimate SE df t.ratio p.value A,L - B,L 16.3333333 5.157299 48 3.167 0.0302 A,L - A,M 20.5555556 5.157299 48 3.986 0.0030 A,L - B,M 15.7777778 5.157299 48 3.059 0.0398 A,L - A,H 20.0000000 5.157299 48 3.878 0.0041 A,L - B,H 25.7777778 5.157299 48 4.998 0.0001 B,L - A,M 4.2222222 5.157299 48 0.819 0.9627 B,L - B,M -0.5555556 5.157299 48 -0.108 1.0000 B,L - A,H 3.6666667 5.157299 48 0.711 0.9797 B,L - B,H 9.4444444 5.157299 48 1.831 0.4561 A,M - B,M -4.7777778 5.157299 48 -0.926 0.9377 A,M - A,H -0.5555556 5.157299 48 -0.108 1.0000 A,M - B,H 5.2222222 5.157299 48 1.013 0.9115 B,M - A,H 4.2222222 5.157299 48 0.819 0.9627 B,M - B,H 10.0000000 5.157299 48 1.939 0.3919 A,H - B,H 5.7777778 5.157299 48 1.120 0.8706 For (3), the first two results below match the model summary in both estimate and standard error. > contrast(emmeans(warp.lm, ~ wool*tension), interaction = "pairwise") wool_pairwise tension_pairwise estimate SE df t.ratio p.value A - B L - M 21.11111 7.293523 48 2.895 0.0057 A - B L - H 10.55556 7.293523 48 1.447 0.1543 A - B M - H -10.55556 7.293523 48 -1.447 0.1543 Notice that within each set of results above, the standard errors stay constant within a table. That is a consequence of the fact that the design is balanced (equal numers of observations in each cell) and the model assumption of a constant error SD. If you fit a different model (using, say, nlme::gls() that allows for nonhomogeneous error variances, then you will get unequal SEs in both the model summary and the emmeans results.
Interpreting the standard error from emmeans - R OK, let us dissect this model. First, the model itself: > getOption("contrasts") unordered ordered "contr.treatment" "contr.poly" > warp.lm <- lm(breaks ~ wool*tension, data
40,972
Random Forest "out of bag" RMSE
I think I got the solution for the OOB RMSE, using keep.inbag=T from randomForest. First you can use predict in order to get the predictions from the model for your response, than simply evaluate using the RMSE formula: Rf_model <- randomForest(mpg ~., data = mtcars) rf_pred <- predict(Rf_model, mtcars) # predictions sqrt(sum(rf_pred - mtcars$mpg)^2) #RMSE #[1] 0.1781314 You can get fancy and make a custom rmse function to call: rmse_function <- function(pred, actual) { sqrt(sum(pred - actual)^2) } rmse_function(rf_pred, mtcars$mpg) #[1] 0.1781314 But this is the overall RMSE on train data. Not the OOB. We can probably calculate the OOB RMSE by keeping track of which observation is kept "outside" in each n_tree in the forest. Then we can use this to subset the data in order to make the prediction using only these rows. (The out of bag obs) Following this idea, we will have to make n_tree predictions, using only the subset of observations that for each tree is kept "out". We will have then n_tree RMSE, and we can average those to have an averate RMSE of the OOB observations. n_tree = 50 Rf_model <- randomForest(mpg ~., ntree = n_tree, data = mtcars, keep.inbag=T) # we use keep.inbag = T inbag <- lapply(1:n_tree, function(x) which(Rf_model[["inbag"]][ ,x] == 0)) # we get only the "zeros" # to look inside use View(Rf_model[["inbag"]]), I think that the zeros are the OOB rf_pred <- lapply(inbag, function(x) predict(Rf_model, mtcars[x, ])) # predictions (oob_err <- map2_dbl(rf_pred, inbag, function(x, y) rmse_function(x, mtcars[y, ]$mpg))) # [1] 1.03926667 0.01556667 2.98096667 1.27210000 1.86380000 2.25883333 3.49130000 0.18763333 1.59326667 0.11236667 # [11] 6.92163333 0.40183333 3.36586667 1.19960000 1.31833333 2.88373333 4.48326667 1.67406667 6.92566667 8.51793333 # [21] 3.32893333 0.65510000 3.87440000 1.89276667 3.51290000 3.13026667 4.81453333 0.59756667 1.56783333 6.12180000 # [31] 3.54490000 0.57406667 0.20236667 2.20220000 0.23226667 1.61360000 0.32690000 1.86300000 3.38393333 3.33723333 # [41] 1.43760000 6.63860000 0.13120000 1.48580000 1.32950000 2.85310000 2.01306667 2.16363333 4.80706667 1.74310000 mean(oob_err) # mean of the RMSEs #[1] 2.477725
Random Forest "out of bag" RMSE
I think I got the solution for the OOB RMSE, using keep.inbag=T from randomForest. First you can use predict in order to get the predictions from the model for your response, than simply evaluate usin
Random Forest "out of bag" RMSE I think I got the solution for the OOB RMSE, using keep.inbag=T from randomForest. First you can use predict in order to get the predictions from the model for your response, than simply evaluate using the RMSE formula: Rf_model <- randomForest(mpg ~., data = mtcars) rf_pred <- predict(Rf_model, mtcars) # predictions sqrt(sum(rf_pred - mtcars$mpg)^2) #RMSE #[1] 0.1781314 You can get fancy and make a custom rmse function to call: rmse_function <- function(pred, actual) { sqrt(sum(pred - actual)^2) } rmse_function(rf_pred, mtcars$mpg) #[1] 0.1781314 But this is the overall RMSE on train data. Not the OOB. We can probably calculate the OOB RMSE by keeping track of which observation is kept "outside" in each n_tree in the forest. Then we can use this to subset the data in order to make the prediction using only these rows. (The out of bag obs) Following this idea, we will have to make n_tree predictions, using only the subset of observations that for each tree is kept "out". We will have then n_tree RMSE, and we can average those to have an averate RMSE of the OOB observations. n_tree = 50 Rf_model <- randomForest(mpg ~., ntree = n_tree, data = mtcars, keep.inbag=T) # we use keep.inbag = T inbag <- lapply(1:n_tree, function(x) which(Rf_model[["inbag"]][ ,x] == 0)) # we get only the "zeros" # to look inside use View(Rf_model[["inbag"]]), I think that the zeros are the OOB rf_pred <- lapply(inbag, function(x) predict(Rf_model, mtcars[x, ])) # predictions (oob_err <- map2_dbl(rf_pred, inbag, function(x, y) rmse_function(x, mtcars[y, ]$mpg))) # [1] 1.03926667 0.01556667 2.98096667 1.27210000 1.86380000 2.25883333 3.49130000 0.18763333 1.59326667 0.11236667 # [11] 6.92163333 0.40183333 3.36586667 1.19960000 1.31833333 2.88373333 4.48326667 1.67406667 6.92566667 8.51793333 # [21] 3.32893333 0.65510000 3.87440000 1.89276667 3.51290000 3.13026667 4.81453333 0.59756667 1.56783333 6.12180000 # [31] 3.54490000 0.57406667 0.20236667 2.20220000 0.23226667 1.61360000 0.32690000 1.86300000 3.38393333 3.33723333 # [41] 1.43760000 6.63860000 0.13120000 1.48580000 1.32950000 2.85310000 2.01306667 2.16363333 4.80706667 1.74310000 mean(oob_err) # mean of the RMSEs #[1] 2.477725
Random Forest "out of bag" RMSE I think I got the solution for the OOB RMSE, using keep.inbag=T from randomForest. First you can use predict in order to get the predictions from the model for your response, than simply evaluate usin
40,973
Random Forest "out of bag" RMSE
The Mean of squared residuals: 0.05206834 in your output is the out-of-bag MSE estimate. Just take the square root: sqrt (tail (Rf_model$mse, 1)) (Apparently, $mse stores the oob MSE observed for bagging 1 : n trees, the last one is the one we need.) You can double check by manually calculating RMSE from the oob predictions: sqrt (mean ((Rf_model$predicted - whole_data$target)^2)
Random Forest "out of bag" RMSE
The Mean of squared residuals: 0.05206834 in your output is the out-of-bag MSE estimate. Just take the square root: sqrt (tail (Rf_model$mse, 1)) (Apparently, $mse stores the oob MSE observed for bag
Random Forest "out of bag" RMSE The Mean of squared residuals: 0.05206834 in your output is the out-of-bag MSE estimate. Just take the square root: sqrt (tail (Rf_model$mse, 1)) (Apparently, $mse stores the oob MSE observed for bagging 1 : n trees, the last one is the one we need.) You can double check by manually calculating RMSE from the oob predictions: sqrt (mean ((Rf_model$predicted - whole_data$target)^2)
Random Forest "out of bag" RMSE The Mean of squared residuals: 0.05206834 in your output is the out-of-bag MSE estimate. Just take the square root: sqrt (tail (Rf_model$mse, 1)) (Apparently, $mse stores the oob MSE observed for bag
40,974
Drop-out as a multiplicative noise in deep neural networks
The correct answer is actually the opposite of the answer by DuttaA. Dropout works so well exactly because it doesn't allow the ReLU to make the noise insignificant by just making its output larger. Let's see why. To make things simpler, I'll use the same toy architecture used in the book, which is a 2-2-1 fully connected NN (figure 7.7 of the book): and I'll follow the same notation, thus $h_i$ is the activation of unit $i$, and $\boldsymbol{\mu}=(\mu_1,\mu_2,\mu_3,\mu_4)$ is the vector of dropout masks, i.e., it's a vector of binary values $[0,1]$. It's a 4-element vector because dropout is only applied to input or hidden units, but not to output units. Now, how do we add noise to the neural vector using dropout? The noiseless output would be: $$ y = w_{21}h_1(w_{11}x_1+b_1)+w_{21}h_2(w_{12}x_2+b_2)+b_y $$ Let's consider additive noise: additive noise is usually added only to the input nodes. As a matter of fact, Ian explains in the paragraph just before the one you quoted that one of the advantages of dropout over traditional noise injection techniques is that the traditional methods only add noise at the input layer level, while dropout multiplies noise also at the hidden layers level. However, to simplify the treatment, I'll consider additive noise and dropout only at the hidden layer level (if you look around on GitHub, you'll find plenty of Keras models which don't use dropout for the input layer). Since the input layer is untouched, I'll make the following substitutions: $$\begin{align} w_{11}x_1+b_1 &= a_1 \\ w_{12}x_2+b_2 &= a_2 \end{align}$$ Thus we have: Additive noise $$ y = w_{21}(h_1(a_1)+\epsilon_1)+w_{21}(h_2(a_2)+\epsilon_2)+b_y = \mathbf{w}_2(\mathbf{h}+\boldsymbol{\epsilon})+b_y$$ If $\mathbf{h}$ is made of unbounded activation functions (e.g., ReLU), the neural network can get rid of $\boldsymbol{\epsilon}$ just by making $\mathbf{h}$ larger and larger. In this simple example, this could be achieved simply by making $\mathbf{w}_1$ and/or $\mathbf{b}$ huge. This is a pathological solution to the noise problem! We would like the hidden units to learn to perform well, whether other hidden units are in the model or not, i.e., not to rely too much on the presence of all the other hidden units (this is one of the possible interpretations of dropout). Instead, we only told the neural network to use both the hidden units, make their outputs huge and then of course reduce it so that loss is small (i.e., that the predicted $\hat{y}_j$ are close to the correct $y_j$ on the training set), by making $\mathbf{w}_2$ small. This is a classic "pathological solution" found by an optimizer - similar to when we use an optimizer for zero finding (i.e., we look for solutions which make the objective function, or loss, 0), and it finds it by making two additive terms huge, one going to $-\infty$ and the other going to $+\infty$. Let's see how this is different with multiplicative noise. Multiplicative noise (dropout) $$ y = w_{21}(h_1(a_1)\mu_1)+w_{21}(h_2(a_2)\mu_2)+b_y = \mathbf{w}_2(\mathbf{h}\odot \boldsymbol{\mu})+b_y$$ Now, since $\mu_1$ and $\mu_2$ are independent and identically distributed Bernoulli random variables (i.e., their value is either 0 or 1 with a certain probability $p_{drop}$), the NN can't just learn to make $\mathbf{h}$ huge in order to get rid of the noise. If $\mu_1$ is randomly 0, then whatever the (finite) value of $h_1$, its contribution to $y$ during those training steps is exactly 0. If the NN wants to find anyway a solution which yields a decent value of $y$, even in the presence of this pesky multiplicative noise, it will have to learn the fact that it cannot always rely on $h_1$ and $h_2$ both being in the network 1. PS this part of the book is great! I've never seen dropout explained so well, and the similarities with bagging (as well as the differences with boosting) so clearly underlined. 1of course, dropout would never be applied to such a small network, unless the function to be learned was extremely simple and the training set tiny. With just 2 hidden units, if we drop each units randomly and independently of the other, the neural network has very little capacity to learn anything. Just think that if $p_{drop}=0.5$ (a common choice for hidden units), then in 1 out of every 4 training steps both hidden units will be 0, and during that step the error won't backpropagate at all.
Drop-out as a multiplicative noise in deep neural networks
The correct answer is actually the opposite of the answer by DuttaA. Dropout works so well exactly because it doesn't allow the ReLU to make the noise insignificant by just making its output larger. L
Drop-out as a multiplicative noise in deep neural networks The correct answer is actually the opposite of the answer by DuttaA. Dropout works so well exactly because it doesn't allow the ReLU to make the noise insignificant by just making its output larger. Let's see why. To make things simpler, I'll use the same toy architecture used in the book, which is a 2-2-1 fully connected NN (figure 7.7 of the book): and I'll follow the same notation, thus $h_i$ is the activation of unit $i$, and $\boldsymbol{\mu}=(\mu_1,\mu_2,\mu_3,\mu_4)$ is the vector of dropout masks, i.e., it's a vector of binary values $[0,1]$. It's a 4-element vector because dropout is only applied to input or hidden units, but not to output units. Now, how do we add noise to the neural vector using dropout? The noiseless output would be: $$ y = w_{21}h_1(w_{11}x_1+b_1)+w_{21}h_2(w_{12}x_2+b_2)+b_y $$ Let's consider additive noise: additive noise is usually added only to the input nodes. As a matter of fact, Ian explains in the paragraph just before the one you quoted that one of the advantages of dropout over traditional noise injection techniques is that the traditional methods only add noise at the input layer level, while dropout multiplies noise also at the hidden layers level. However, to simplify the treatment, I'll consider additive noise and dropout only at the hidden layer level (if you look around on GitHub, you'll find plenty of Keras models which don't use dropout for the input layer). Since the input layer is untouched, I'll make the following substitutions: $$\begin{align} w_{11}x_1+b_1 &= a_1 \\ w_{12}x_2+b_2 &= a_2 \end{align}$$ Thus we have: Additive noise $$ y = w_{21}(h_1(a_1)+\epsilon_1)+w_{21}(h_2(a_2)+\epsilon_2)+b_y = \mathbf{w}_2(\mathbf{h}+\boldsymbol{\epsilon})+b_y$$ If $\mathbf{h}$ is made of unbounded activation functions (e.g., ReLU), the neural network can get rid of $\boldsymbol{\epsilon}$ just by making $\mathbf{h}$ larger and larger. In this simple example, this could be achieved simply by making $\mathbf{w}_1$ and/or $\mathbf{b}$ huge. This is a pathological solution to the noise problem! We would like the hidden units to learn to perform well, whether other hidden units are in the model or not, i.e., not to rely too much on the presence of all the other hidden units (this is one of the possible interpretations of dropout). Instead, we only told the neural network to use both the hidden units, make their outputs huge and then of course reduce it so that loss is small (i.e., that the predicted $\hat{y}_j$ are close to the correct $y_j$ on the training set), by making $\mathbf{w}_2$ small. This is a classic "pathological solution" found by an optimizer - similar to when we use an optimizer for zero finding (i.e., we look for solutions which make the objective function, or loss, 0), and it finds it by making two additive terms huge, one going to $-\infty$ and the other going to $+\infty$. Let's see how this is different with multiplicative noise. Multiplicative noise (dropout) $$ y = w_{21}(h_1(a_1)\mu_1)+w_{21}(h_2(a_2)\mu_2)+b_y = \mathbf{w}_2(\mathbf{h}\odot \boldsymbol{\mu})+b_y$$ Now, since $\mu_1$ and $\mu_2$ are independent and identically distributed Bernoulli random variables (i.e., their value is either 0 or 1 with a certain probability $p_{drop}$), the NN can't just learn to make $\mathbf{h}$ huge in order to get rid of the noise. If $\mu_1$ is randomly 0, then whatever the (finite) value of $h_1$, its contribution to $y$ during those training steps is exactly 0. If the NN wants to find anyway a solution which yields a decent value of $y$, even in the presence of this pesky multiplicative noise, it will have to learn the fact that it cannot always rely on $h_1$ and $h_2$ both being in the network 1. PS this part of the book is great! I've never seen dropout explained so well, and the similarities with bagging (as well as the differences with boosting) so clearly underlined. 1of course, dropout would never be applied to such a small network, unless the function to be learned was extremely simple and the training set tiny. With just 2 hidden units, if we drop each units randomly and independently of the other, the neural network has very little capacity to learn anything. Just think that if $p_{drop}=0.5$ (a common choice for hidden units), then in 1 out of every 4 training steps both hidden units will be 0, and during that step the error won't backpropagate at all.
Drop-out as a multiplicative noise in deep neural networks The correct answer is actually the opposite of the answer by DuttaA. Dropout works so well exactly because it doesn't allow the ReLU to make the noise insignificant by just making its output larger. L
40,975
Generate identically distributed dependent normal random numbers with prespecified sum
We will generate multivariate normals $X\sim MN(\mu, \Sigma)$ with $\mu\in\mathbb{R}^n$ and $\Sigma\in\mathbb{R}^{n\times n}$ such that their sum satisfies our condition. Let $Z=X_1 + \dots + X_n$. As a common mean, we choose $$ \mu_1 = \dots = \mu_n = \frac{a+b}{2n}. $$ In order that $Z\in[a,b]$ with probability $p$, its standard deviation should fulfill $$ \sigma_Z = \frac{b-a}{q_\alpha}, $$ where $q_\alpha$ is the standard normal quantile to the level $\alpha$, here $\alpha=1-\frac{1-p}{2}$. We now need to specify $\Sigma$. We have a lot of leeway here. Let us assume that we want each $X_i$'s variance to be $\sigma^2$ and the covariance be $\text{cov}(X_i,X_j)=\tau$ for $i\neq j$. The key to creating a "good" $\Sigma$ is this previous answer by probabilityislogic. It yields that the sum of our $X_i$s has variance $$ n\sigma^2 + n(n-1)\tau $$ so we need that $$ n\sigma^2 + n(n-1)\tau = \frac{b-a}{q_\alpha}.$$ We also need to ensure that $\Sigma$ is positive definite, but this is not overly hard. The easiest way to do this is to ensure that all entries in $\Sigma$ are positive, e.g., by setting $$ \sigma^2 := \frac{\sigma_Z^2}{2n}, \quad \tau := \frac{\sigma_Z^2}{2n(n-1)}, $$ but this gives very small values and very boring cumulative sums and trajectories: Less boring is to set $$ \sigma^2 := 1, \quad \tau := \frac{1}{n-1}\big(\frac{\sigma_Z^2}{n}-\sigma^2\big), $$ which yields much more interesting trajectories: Note that setting this does indeed yield a valid covariance matrix, because $\Sigma$ is then of the form $\Sigma_{ij} = m(i-j)$, namely $$ m(0) = \sigma^2, \quad m(j) = \tau\text{ for }j>0, $$ and we have that $$ \sum_{j>0} |m(j)| = (n-1)|\tau| = \big|\frac{\sigma_Z^2}{n}-\sigma^2\big| = \big|\frac{\sigma_Z^2}{n}-1\big| < 1 = \sigma^2 = m(0), $$ which is a sufficient condition for $\Sigma$ to be strictly positive definite by Wikipedia (Point 7 under "Further Properties"). R code below, but first, please go and upvote probabilityislogic's answer. n_steps <- 1000 target_min <- 1.99 target_max <- 2.01 target_prob <- 0.99 target_mean <- mean(c(target_min,target_max)) target_sd <- (target_max-target_mean)/qnorm(p=1-(1-target_prob)/2) mm <- rep(target_mean/n_steps,n_steps) # boring setting: # sigma_sq <- target_sd^2/(2*n_steps) # tau <- target_sd^2/(2*n_steps*(n_steps-1)) sigma_sq <- 1 tau <- (target_sd^2/n_steps-sigma_sq)/(n_steps-1) CC <- matrix(tau,nrow=n_steps,ncol=n_steps) diag(CC) <- sigma_sq library(MASS) foo <- mvrnorm(1,mu=mm,Sigma=CC) sum(foo) plot(cumsum(foo),type="l",xlab="",ylab="") abline(h=target_mean,lty=2)
Generate identically distributed dependent normal random numbers with prespecified sum
We will generate multivariate normals $X\sim MN(\mu, \Sigma)$ with $\mu\in\mathbb{R}^n$ and $\Sigma\in\mathbb{R}^{n\times n}$ such that their sum satisfies our condition. Let $Z=X_1 + \dots + X_n$. As
Generate identically distributed dependent normal random numbers with prespecified sum We will generate multivariate normals $X\sim MN(\mu, \Sigma)$ with $\mu\in\mathbb{R}^n$ and $\Sigma\in\mathbb{R}^{n\times n}$ such that their sum satisfies our condition. Let $Z=X_1 + \dots + X_n$. As a common mean, we choose $$ \mu_1 = \dots = \mu_n = \frac{a+b}{2n}. $$ In order that $Z\in[a,b]$ with probability $p$, its standard deviation should fulfill $$ \sigma_Z = \frac{b-a}{q_\alpha}, $$ where $q_\alpha$ is the standard normal quantile to the level $\alpha$, here $\alpha=1-\frac{1-p}{2}$. We now need to specify $\Sigma$. We have a lot of leeway here. Let us assume that we want each $X_i$'s variance to be $\sigma^2$ and the covariance be $\text{cov}(X_i,X_j)=\tau$ for $i\neq j$. The key to creating a "good" $\Sigma$ is this previous answer by probabilityislogic. It yields that the sum of our $X_i$s has variance $$ n\sigma^2 + n(n-1)\tau $$ so we need that $$ n\sigma^2 + n(n-1)\tau = \frac{b-a}{q_\alpha}.$$ We also need to ensure that $\Sigma$ is positive definite, but this is not overly hard. The easiest way to do this is to ensure that all entries in $\Sigma$ are positive, e.g., by setting $$ \sigma^2 := \frac{\sigma_Z^2}{2n}, \quad \tau := \frac{\sigma_Z^2}{2n(n-1)}, $$ but this gives very small values and very boring cumulative sums and trajectories: Less boring is to set $$ \sigma^2 := 1, \quad \tau := \frac{1}{n-1}\big(\frac{\sigma_Z^2}{n}-\sigma^2\big), $$ which yields much more interesting trajectories: Note that setting this does indeed yield a valid covariance matrix, because $\Sigma$ is then of the form $\Sigma_{ij} = m(i-j)$, namely $$ m(0) = \sigma^2, \quad m(j) = \tau\text{ for }j>0, $$ and we have that $$ \sum_{j>0} |m(j)| = (n-1)|\tau| = \big|\frac{\sigma_Z^2}{n}-\sigma^2\big| = \big|\frac{\sigma_Z^2}{n}-1\big| < 1 = \sigma^2 = m(0), $$ which is a sufficient condition for $\Sigma$ to be strictly positive definite by Wikipedia (Point 7 under "Further Properties"). R code below, but first, please go and upvote probabilityislogic's answer. n_steps <- 1000 target_min <- 1.99 target_max <- 2.01 target_prob <- 0.99 target_mean <- mean(c(target_min,target_max)) target_sd <- (target_max-target_mean)/qnorm(p=1-(1-target_prob)/2) mm <- rep(target_mean/n_steps,n_steps) # boring setting: # sigma_sq <- target_sd^2/(2*n_steps) # tau <- target_sd^2/(2*n_steps*(n_steps-1)) sigma_sq <- 1 tau <- (target_sd^2/n_steps-sigma_sq)/(n_steps-1) CC <- matrix(tau,nrow=n_steps,ncol=n_steps) diag(CC) <- sigma_sq library(MASS) foo <- mvrnorm(1,mu=mm,Sigma=CC) sum(foo) plot(cumsum(foo),type="l",xlab="",ylab="") abline(h=target_mean,lty=2)
Generate identically distributed dependent normal random numbers with prespecified sum We will generate multivariate normals $X\sim MN(\mu, \Sigma)$ with $\mu\in\mathbb{R}^n$ and $\Sigma\in\mathbb{R}^{n\times n}$ such that their sum satisfies our condition. Let $Z=X_1 + \dots + X_n$. As
40,976
Why does Bayesian optimization work?
Gaussian Process models have two nice properties in the Bayesian Optimization context: They can exactly fit the observed values of the black-box function $f$ (when there is no noise, at least) They smoothly interpolate between observed data points, with increasing statistical uncertainty the farther you move away from the observed data. The nature of this transition is predicable and known. These properties are essentially exactly what you'd want in a Bayesian optimization context: you know what the function values are (quality 1); but you're less certain about what happens between or far away from function evaluations (quality 2). (Deep) neural nets don't necessarily have either quality. Regarding (quality 1), it can be hard to get an NN to model a specific function without doing a lot of tedious work: attempting different model configurations and hyper-parameter tuning. Aside: Usually, the original problem that you're working on is, itself, a problem involving hyper-parameter tuning in its own right, such as selecting the optimal parameters for a SVM or perhaps even a NN. It would be more than a little circular to use yet another neural network to try and solve the original problem, since this new problem could be just as challenging to solve. I'd prefer to have hyperparameter tuning be a fully-automated procedure; the challenges of fitting yet another neural network seem to replace the original problem (optimization of a challenging, possibly expensive function) with another problem of similar complexity (designing a good neural network). Regarding quality 2, there is no guarantee that the NN has reasonable interpolation behavior between the observed data, or reasonable extrapolation beyond observed values. An NN that fits the data exactly can still have too many degrees of freedom, so the interpolations may be erratic. When a Gaussian Process with a constant mean function (a standard GP model used in BO) makes a prediction sufficiently far away from the observed data, the prediction reverts to the constant mean, and the variance reverts to the prior variance. By contrast, the NN can increase or decrease beyond the extrema of the training data, or oscillate in a complex pattern, or any number of other possibilities. Even if the final NN activation is bounded, these fluctuations can still flip the prediction from one extreme to the other between or beyond the training data; this doesn't seem reasonable. The Gaussian process behavior seems more plausible. It's worth noting that GPs aren't a perfect solution, either. The Gaussian process's behavior is governed, in a very specific and obvious way, by the parameters of the kernel. For example, the standard RBF kernel $$ k(x, y) = \exp(-\gamma ||x - y||_2^2) $$ is characterized by the "length-scale" parameter $\gamma > 0$. The choice of $\gamma$ strongly influences the predictions that you make: set it too large or too small and the predicted behavior will either have sharp swings or flat behavior between the observed data. A core challenge of building a good surrogate model is how to select the GP hyper-parameters. GPs give a cheap obvious way to query both the expectation (the GP's estimated value of the point) and variance (the GP's uncertainty around the estimated value) of any point. This is important because BO acquisition functions often incorporate estimates of variance as a component of evaluating which points to evaluate next with the expensive black-box function.
Why does Bayesian optimization work?
Gaussian Process models have two nice properties in the Bayesian Optimization context: They can exactly fit the observed values of the black-box function $f$ (when there is no noise, at least) They s
Why does Bayesian optimization work? Gaussian Process models have two nice properties in the Bayesian Optimization context: They can exactly fit the observed values of the black-box function $f$ (when there is no noise, at least) They smoothly interpolate between observed data points, with increasing statistical uncertainty the farther you move away from the observed data. The nature of this transition is predicable and known. These properties are essentially exactly what you'd want in a Bayesian optimization context: you know what the function values are (quality 1); but you're less certain about what happens between or far away from function evaluations (quality 2). (Deep) neural nets don't necessarily have either quality. Regarding (quality 1), it can be hard to get an NN to model a specific function without doing a lot of tedious work: attempting different model configurations and hyper-parameter tuning. Aside: Usually, the original problem that you're working on is, itself, a problem involving hyper-parameter tuning in its own right, such as selecting the optimal parameters for a SVM or perhaps even a NN. It would be more than a little circular to use yet another neural network to try and solve the original problem, since this new problem could be just as challenging to solve. I'd prefer to have hyperparameter tuning be a fully-automated procedure; the challenges of fitting yet another neural network seem to replace the original problem (optimization of a challenging, possibly expensive function) with another problem of similar complexity (designing a good neural network). Regarding quality 2, there is no guarantee that the NN has reasonable interpolation behavior between the observed data, or reasonable extrapolation beyond observed values. An NN that fits the data exactly can still have too many degrees of freedom, so the interpolations may be erratic. When a Gaussian Process with a constant mean function (a standard GP model used in BO) makes a prediction sufficiently far away from the observed data, the prediction reverts to the constant mean, and the variance reverts to the prior variance. By contrast, the NN can increase or decrease beyond the extrema of the training data, or oscillate in a complex pattern, or any number of other possibilities. Even if the final NN activation is bounded, these fluctuations can still flip the prediction from one extreme to the other between or beyond the training data; this doesn't seem reasonable. The Gaussian process behavior seems more plausible. It's worth noting that GPs aren't a perfect solution, either. The Gaussian process's behavior is governed, in a very specific and obvious way, by the parameters of the kernel. For example, the standard RBF kernel $$ k(x, y) = \exp(-\gamma ||x - y||_2^2) $$ is characterized by the "length-scale" parameter $\gamma > 0$. The choice of $\gamma$ strongly influences the predictions that you make: set it too large or too small and the predicted behavior will either have sharp swings or flat behavior between the observed data. A core challenge of building a good surrogate model is how to select the GP hyper-parameters. GPs give a cheap obvious way to query both the expectation (the GP's estimated value of the point) and variance (the GP's uncertainty around the estimated value) of any point. This is important because BO acquisition functions often incorporate estimates of variance as a component of evaluating which points to evaluate next with the expensive black-box function.
Why does Bayesian optimization work? Gaussian Process models have two nice properties in the Bayesian Optimization context: They can exactly fit the observed values of the black-box function $f$ (when there is no noise, at least) They s
40,977
What is the name of $E(XY)$? [duplicate]
Moments of the form $\mu'_{rs}=E(X^rY^s)$ are called "product moments" or more specifically "$r,s$ product moments"; you have the $1,1$ product moment, $\mu_{11}$. They may also be called raw product moments (to distinguish from central ones like covariance). Some people might call it a 'first order product moment', though 'first order' can be somewhat ambiguous (some people might interpret that to mean $\mu_{01}$ or $\mu_{10}$, perhaps). They are also sometimes called mixed moments (since they involve more than one variable) but the term can apply to moments in more than two variates; in this case we have mixed raw moments.
What is the name of $E(XY)$? [duplicate]
Moments of the form $\mu'_{rs}=E(X^rY^s)$ are called "product moments" or more specifically "$r,s$ product moments"; you have the $1,1$ product moment, $\mu_{11}$. They may also be called raw product
What is the name of $E(XY)$? [duplicate] Moments of the form $\mu'_{rs}=E(X^rY^s)$ are called "product moments" or more specifically "$r,s$ product moments"; you have the $1,1$ product moment, $\mu_{11}$. They may also be called raw product moments (to distinguish from central ones like covariance). Some people might call it a 'first order product moment', though 'first order' can be somewhat ambiguous (some people might interpret that to mean $\mu_{01}$ or $\mu_{10}$, perhaps). They are also sometimes called mixed moments (since they involve more than one variable) but the term can apply to moments in more than two variates; in this case we have mixed raw moments.
What is the name of $E(XY)$? [duplicate] Moments of the form $\mu'_{rs}=E(X^rY^s)$ are called "product moments" or more specifically "$r,s$ product moments"; you have the $1,1$ product moment, $\mu_{11}$. They may also be called raw product
40,978
Binomial distribution where the number of experiments is binomially distributed
Using the law of total covariance, \begin{align} \operatorname{Cov}(K,N) &=E\operatorname{Cov}(K,N|N)+\operatorname{Cov}(EK|N,EN|N) \\&=E 0+\operatorname{Cov}(pN,N) \\&=0+p\operatorname{Var}(N) \\&=pmq(1-q). \end{align}
Binomial distribution where the number of experiments is binomially distributed
Using the law of total covariance, \begin{align} \operatorname{Cov}(K,N) &=E\operatorname{Cov}(K,N|N)+\operatorname{Cov}(EK|N,EN|N) \\&=E 0+\operatorname{Cov}(pN,N) \\&=0+p\operatorname{Var}(N) \\&
Binomial distribution where the number of experiments is binomially distributed Using the law of total covariance, \begin{align} \operatorname{Cov}(K,N) &=E\operatorname{Cov}(K,N|N)+\operatorname{Cov}(EK|N,EN|N) \\&=E 0+\operatorname{Cov}(pN,N) \\&=0+p\operatorname{Var}(N) \\&=pmq(1-q). \end{align}
Binomial distribution where the number of experiments is binomially distributed Using the law of total covariance, \begin{align} \operatorname{Cov}(K,N) &=E\operatorname{Cov}(K,N|N)+\operatorname{Cov}(EK|N,EN|N) \\&=E 0+\operatorname{Cov}(pN,N) \\&=0+p\operatorname{Var}(N) \\&
40,979
hyperparameter tuning in neural networks
The link provided in @itdxer's comment is great. Based on this link, I am writing this answer. Hyperparameter optimization is neural networks is a tedious job as it contains many set of parameters. The possible approaches for finding the optimal parameters are: Hand tuning (Trial and Error) - @Sycorax's comment provides an example of hand tuning. Here, based on trial and error experiments and experience of the user, parameters are chosen. Grid Search - Here a grid is created based on parameter values. And then all possible parameter combinations is tried and and the best one is selected. Random Search - Here, instead of trying all possible combinations as in Grid Search, only randomly selected subset of the parameters is tried and the best is chosen. Bayesian Optimization (Gausian Proces) - Gaussian Process uses a set of previously evaluated parameters and resulting accuracy to make an assumption about unobserved parameters. Acquisition Function using this information suggest the next set of parameters. (Do not understand much, taken from this link) Tree-structured Parzen Estimators (TPE) - Each iteration TPE collects new observation and at the end of the iteration, the algorithm decides which set of parameters it should try next. (Do not understand much, taken from this link). Now as per this link The Bayesian Optimization and TPE algorithms show great improvement over the classic hyperparameter optimization methods. They allow to learn from the training history and give better and better estimations for the next set of parameters. Now the good thing is that there is a Python library called hyperopt for doing these. More details in the below pages: http://neupy.com/2016/12/17/hyperparameter_optimization_for_neural_networks.html https://jaberg.github.io/hyperopt/ . https://github.com/jaberg/hyperopt/wiki . https://github.com/wenyangfu/hyperparam-search-guides/blob/master/hyperopt-guide.md https://www.youtube.com/watch?v=Mp1xnPfE4PY
hyperparameter tuning in neural networks
The link provided in @itdxer's comment is great. Based on this link, I am writing this answer. Hyperparameter optimization is neural networks is a tedious job as it contains many set of parameters.
hyperparameter tuning in neural networks The link provided in @itdxer's comment is great. Based on this link, I am writing this answer. Hyperparameter optimization is neural networks is a tedious job as it contains many set of parameters. The possible approaches for finding the optimal parameters are: Hand tuning (Trial and Error) - @Sycorax's comment provides an example of hand tuning. Here, based on trial and error experiments and experience of the user, parameters are chosen. Grid Search - Here a grid is created based on parameter values. And then all possible parameter combinations is tried and and the best one is selected. Random Search - Here, instead of trying all possible combinations as in Grid Search, only randomly selected subset of the parameters is tried and the best is chosen. Bayesian Optimization (Gausian Proces) - Gaussian Process uses a set of previously evaluated parameters and resulting accuracy to make an assumption about unobserved parameters. Acquisition Function using this information suggest the next set of parameters. (Do not understand much, taken from this link) Tree-structured Parzen Estimators (TPE) - Each iteration TPE collects new observation and at the end of the iteration, the algorithm decides which set of parameters it should try next. (Do not understand much, taken from this link). Now as per this link The Bayesian Optimization and TPE algorithms show great improvement over the classic hyperparameter optimization methods. They allow to learn from the training history and give better and better estimations for the next set of parameters. Now the good thing is that there is a Python library called hyperopt for doing these. More details in the below pages: http://neupy.com/2016/12/17/hyperparameter_optimization_for_neural_networks.html https://jaberg.github.io/hyperopt/ . https://github.com/jaberg/hyperopt/wiki . https://github.com/wenyangfu/hyperparam-search-guides/blob/master/hyperopt-guide.md https://www.youtube.com/watch?v=Mp1xnPfE4PY
hyperparameter tuning in neural networks The link provided in @itdxer's comment is great. Based on this link, I am writing this answer. Hyperparameter optimization is neural networks is a tedious job as it contains many set of parameters.
40,980
hyperparameter tuning in neural networks
You need only replace your grid search with a different global search. Recommended steps: Google "optimizer elo ratings" to get a rough idea what works well From the well-performing algorithms, click through to the packages to see which already have integration with keras, tensorflow or similar.
hyperparameter tuning in neural networks
You need only replace your grid search with a different global search. Recommended steps: Google "optimizer elo ratings" to get a rough idea what works well From the well-performing algorithms, click
hyperparameter tuning in neural networks You need only replace your grid search with a different global search. Recommended steps: Google "optimizer elo ratings" to get a rough idea what works well From the well-performing algorithms, click through to the packages to see which already have integration with keras, tensorflow or similar.
hyperparameter tuning in neural networks You need only replace your grid search with a different global search. Recommended steps: Google "optimizer elo ratings" to get a rough idea what works well From the well-performing algorithms, click
40,981
Word2Vec : Difference between the two Weight matrices
They both capture the word semantics. Not only W, sometimes W' is also used as word vectors. Even in somecases (W+W')/2 has also been used and better results in that particular task have been obtained. Another thing to notice is that no activation function is used after the hidden layer, so the transformation from input to output is W[i]*W'^T for any activated word i in input. So for every word vector you are trying to learn the words that mostly occurs in its vicinity(context-window). You can think of the two linear transformation as, Semantics encoder from n-hot vector: Word-list to semantics Semantics decoder which outputs a probability vector: Semantics to probability distribution over words. Formally, vectors in W and W' are called input and output word vector representations, respectively.
Word2Vec : Difference between the two Weight matrices
They both capture the word semantics. Not only W, sometimes W' is also used as word vectors. Even in somecases (W+W')/2 has also been used and better results in that particular task have been obtained
Word2Vec : Difference between the two Weight matrices They both capture the word semantics. Not only W, sometimes W' is also used as word vectors. Even in somecases (W+W')/2 has also been used and better results in that particular task have been obtained. Another thing to notice is that no activation function is used after the hidden layer, so the transformation from input to output is W[i]*W'^T for any activated word i in input. So for every word vector you are trying to learn the words that mostly occurs in its vicinity(context-window). You can think of the two linear transformation as, Semantics encoder from n-hot vector: Word-list to semantics Semantics decoder which outputs a probability vector: Semantics to probability distribution over words. Formally, vectors in W and W' are called input and output word vector representations, respectively.
Word2Vec : Difference between the two Weight matrices They both capture the word semantics. Not only W, sometimes W' is also used as word vectors. Even in somecases (W+W')/2 has also been used and better results in that particular task have been obtained
40,982
CNN vs fully connected network for image recognition?
Fully connected neural networks are good enough classifiers, however they aren't good for feature extraction. Before the emergence on CNNs the state-of-the-art was to extract explicit features from images and then classify these features. CNNs are trained to identify and extract the best features from the images for the problem at hand. That is their main strength. The latter layers of a CNN are fully connected because of their strength as a classifier. So these two architectures aren't competing though as you may think as CNNs incorporate FC layers. If your question was how well a FC-based image recognition technique fairs compared to a CNN one, you should check the results of the ILSVRC for the past years. The last non-CNN architecture I think achieved a top 5 error rate of 30% (today with the state-of-the-art CNNs this is under 3%).
CNN vs fully connected network for image recognition?
Fully connected neural networks are good enough classifiers, however they aren't good for feature extraction. Before the emergence on CNNs the state-of-the-art was to extract explicit features from im
CNN vs fully connected network for image recognition? Fully connected neural networks are good enough classifiers, however they aren't good for feature extraction. Before the emergence on CNNs the state-of-the-art was to extract explicit features from images and then classify these features. CNNs are trained to identify and extract the best features from the images for the problem at hand. That is their main strength. The latter layers of a CNN are fully connected because of their strength as a classifier. So these two architectures aren't competing though as you may think as CNNs incorporate FC layers. If your question was how well a FC-based image recognition technique fairs compared to a CNN one, you should check the results of the ILSVRC for the past years. The last non-CNN architecture I think achieved a top 5 error rate of 30% (today with the state-of-the-art CNNs this is under 3%).
CNN vs fully connected network for image recognition? Fully connected neural networks are good enough classifiers, however they aren't good for feature extraction. Before the emergence on CNNs the state-of-the-art was to extract explicit features from im
40,983
CNN vs fully connected network for image recognition?
Does anyone know how the accuracy of CNNs compare with fully connected networks for image recognition? The sole fact that since AlexNet won ImageNet competition, every neural network that wins it uses CNN component, should be enough to convince you that CNNs are better for image data. You most likely won't be able to find any meaningful comparison, since CNNs are able to handle image data that is infeasible using only FC layers. Why? The number of weights in FC layer with 1000 neurons for 224x224x3 image is something like 150M. That's 150M for only one layer. If you're not convinced this is a huge number, then note that modern CNN architectures that have 50-100 layers while having overall couple dozen milion parameters (for example ResNet50 has 23M params, InceptionV3 has 21M parameters). Also are CNNs good at anything other than image recognition? Yes. They're good for any data that has spatial structure (for example 1D convolutions over time for music). Also they're used in NLP - see this paper on sentiment analysis or this one on translation.
CNN vs fully connected network for image recognition?
Does anyone know how the accuracy of CNNs compare with fully connected networks for image recognition? The sole fact that since AlexNet won ImageNet competition, every neural network that wins it u
CNN vs fully connected network for image recognition? Does anyone know how the accuracy of CNNs compare with fully connected networks for image recognition? The sole fact that since AlexNet won ImageNet competition, every neural network that wins it uses CNN component, should be enough to convince you that CNNs are better for image data. You most likely won't be able to find any meaningful comparison, since CNNs are able to handle image data that is infeasible using only FC layers. Why? The number of weights in FC layer with 1000 neurons for 224x224x3 image is something like 150M. That's 150M for only one layer. If you're not convinced this is a huge number, then note that modern CNN architectures that have 50-100 layers while having overall couple dozen milion parameters (for example ResNet50 has 23M params, InceptionV3 has 21M parameters). Also are CNNs good at anything other than image recognition? Yes. They're good for any data that has spatial structure (for example 1D convolutions over time for music). Also they're used in NLP - see this paper on sentiment analysis or this one on translation.
CNN vs fully connected network for image recognition? Does anyone know how the accuracy of CNNs compare with fully connected networks for image recognition? The sole fact that since AlexNet won ImageNet competition, every neural network that wins it u
40,984
CNN vs fully connected network for image recognition?
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. 1. Computational tractability. number of weights between CNN and FC such as input image of shape 500 x 500 x 3 will be in FC layer with 100 hidden unit (basis = 0) FC layer = Wx = 100 x ( 500 x 500 x 3 ) = 100 x 750000 = 75M on other hand: input image of shape 500 x 500 x 3 will be after convolving a 5 * 5 kernel with zero padding, the stride of 1. and 2 filters the new CNN layer = ((Hn + 2p - k )/s)+1,((Wn + 2p - k )/s)+1, Cn * filters num) = 496 x 496 x 6 the number of parameters in a CONV layer is : ((shape of width of the filter * shape of height of the filter * number of filters in the previous layer+1)*number of filters) 1 for bias number of parameters = (Fw * Fh * D + 1 ) * F = (5 * 5 * 3 + 1 )*2 = 152 2. Explicit hierarchical representation of features. the best thing in CNN architecture is no need for feature extraction. 3. Reduces overfitting. If the model is massively overfitting you can start adding dropout in small pieces. also, max-pooling reduce the overfitting too 4. Translation invariant. Invariance refers to the ability to remember an object as an object even though its object place changes. This is usually a positive thing because it maintains the object's identity, category, "Note that translation here has a specific meaning in vision, borrowed from geometry." The same object in different locations.
CNN vs fully connected network for image recognition?
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.
CNN vs fully connected network for image recognition? 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. 1. Computational tractability. number of weights between CNN and FC such as input image of shape 500 x 500 x 3 will be in FC layer with 100 hidden unit (basis = 0) FC layer = Wx = 100 x ( 500 x 500 x 3 ) = 100 x 750000 = 75M on other hand: input image of shape 500 x 500 x 3 will be after convolving a 5 * 5 kernel with zero padding, the stride of 1. and 2 filters the new CNN layer = ((Hn + 2p - k )/s)+1,((Wn + 2p - k )/s)+1, Cn * filters num) = 496 x 496 x 6 the number of parameters in a CONV layer is : ((shape of width of the filter * shape of height of the filter * number of filters in the previous layer+1)*number of filters) 1 for bias number of parameters = (Fw * Fh * D + 1 ) * F = (5 * 5 * 3 + 1 )*2 = 152 2. Explicit hierarchical representation of features. the best thing in CNN architecture is no need for feature extraction. 3. Reduces overfitting. If the model is massively overfitting you can start adding dropout in small pieces. also, max-pooling reduce the overfitting too 4. Translation invariant. Invariance refers to the ability to remember an object as an object even though its object place changes. This is usually a positive thing because it maintains the object's identity, category, "Note that translation here has a specific meaning in vision, borrowed from geometry." The same object in different locations.
CNN vs fully connected network for image recognition? 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.
40,985
Integral of a CDF
For cdfs $F$ of distributions with supports on $(0,a)$, $a$ being possibly $+\infty$, a useful representation of the expectation is $$\mathbb{E}_F[X]=\int_0^a x \text{d}F(x)=\int_0^a \{1-F(x)\}\text{d}x$$ by applying integration by parts, \begin{align*}\int_0^a x \text{d}F(x)&=-\int_0^a x \text{d}(1-F)(x)\\&=-\left[x(1-F(x))\right]_0^a+\int_0^a \{1-F(x)\}\text{d}x\\&=-\underbrace{a(1-F(a))}_{=0}+\underbrace{0(1-F(0))}_{=0}+\int_0^a \{1-F(x)\}\text{d}x\end{align*} In the special case when $a=+\infty$, $$\lim_{x\to\infty}x(1-F(x))=\lim_{x\to\infty}\frac{1-F(x)}{1/x} =\lim_{x\to\infty}\frac{-f(x)}{-1/x^2}=\lim_{x\to\infty}x^2f(x)=0$$ by L'Hospital's rule and the fact that $xf(x)$ is integrable at infinity (the expectation $\mathbb E_F[X]$ is assumed to exist). In the current case, one can turn the integral into an expectation as $$\int_0^y x\text{d}F(x)=F(y)\int_0^y x\frac{\text{d}F(x)}{F(y)}=\mathbb{E}_{\tilde{F}}[X]$$with $$\tilde{F}(x)=F(x)\big/F(y)\mathbb{I}_{(0,y)}(x)$$Thus $$\int_0^y x\text{d}F(x)=F(y)\int_0^y \{1-F(x)\big/F(y)\}\text{d}x$$ which is the representation that you found.
Integral of a CDF
For cdfs $F$ of distributions with supports on $(0,a)$, $a$ being possibly $+\infty$, a useful representation of the expectation is $$\mathbb{E}_F[X]=\int_0^a x \text{d}F(x)=\int_0^a \{1-F(x)\}\text{
Integral of a CDF For cdfs $F$ of distributions with supports on $(0,a)$, $a$ being possibly $+\infty$, a useful representation of the expectation is $$\mathbb{E}_F[X]=\int_0^a x \text{d}F(x)=\int_0^a \{1-F(x)\}\text{d}x$$ by applying integration by parts, \begin{align*}\int_0^a x \text{d}F(x)&=-\int_0^a x \text{d}(1-F)(x)\\&=-\left[x(1-F(x))\right]_0^a+\int_0^a \{1-F(x)\}\text{d}x\\&=-\underbrace{a(1-F(a))}_{=0}+\underbrace{0(1-F(0))}_{=0}+\int_0^a \{1-F(x)\}\text{d}x\end{align*} In the special case when $a=+\infty$, $$\lim_{x\to\infty}x(1-F(x))=\lim_{x\to\infty}\frac{1-F(x)}{1/x} =\lim_{x\to\infty}\frac{-f(x)}{-1/x^2}=\lim_{x\to\infty}x^2f(x)=0$$ by L'Hospital's rule and the fact that $xf(x)$ is integrable at infinity (the expectation $\mathbb E_F[X]$ is assumed to exist). In the current case, one can turn the integral into an expectation as $$\int_0^y x\text{d}F(x)=F(y)\int_0^y x\frac{\text{d}F(x)}{F(y)}=\mathbb{E}_{\tilde{F}}[X]$$with $$\tilde{F}(x)=F(x)\big/F(y)\mathbb{I}_{(0,y)}(x)$$Thus $$\int_0^y x\text{d}F(x)=F(y)\int_0^y \{1-F(x)\big/F(y)\}\text{d}x$$ which is the representation that you found.
Integral of a CDF For cdfs $F$ of distributions with supports on $(0,a)$, $a$ being possibly $+\infty$, a useful representation of the expectation is $$\mathbb{E}_F[X]=\int_0^a x \text{d}F(x)=\int_0^a \{1-F(x)\}\text{
40,986
Integral of a CDF
No. You'll have to take it, unfortunately. By the way, this integral shows up in expected shortfall (conditional value-at-risk) measure in risk management. It's used so much, that if there was a shortcut through CDF, people would have figured it out long ago.
Integral of a CDF
No. You'll have to take it, unfortunately. By the way, this integral shows up in expected shortfall (conditional value-at-risk) measure in risk management. It's used so much, that if there was a short
Integral of a CDF No. You'll have to take it, unfortunately. By the way, this integral shows up in expected shortfall (conditional value-at-risk) measure in risk management. It's used so much, that if there was a shortcut through CDF, people would have figured it out long ago.
Integral of a CDF No. You'll have to take it, unfortunately. By the way, this integral shows up in expected shortfall (conditional value-at-risk) measure in risk management. It's used so much, that if there was a short
40,987
Theory behind testing whether $\mu \in \mathbb{Q}$ for $X \sim \mathcal{N}(\mu, \sigma^2)$
Your intuition is correct: When you have a null set for the mean that is dense with respect to the total space, you won't be able differentiate the null and alternative sets with continuous data. This is because, for any mean value in the alternative hypothesis, we can always get one that is "arbitrarily close" in the null set. Hence, there should never be any evidence for the alternative hypothesis. To get a formal demonstration of this result, you need to go through the motions of constructing this as a composite hypothesis test. This is a bit tricky, since you have to make an argument for some test statistic, and there are some plausible objections here. Formal construction of classical hypothesis test: For this test the hypotheses are: $$\begin{equation} \begin{aligned} H_0 &: \mu \in \mathbb{Q}, \\[4pt] H_A &: \mu \notin \mathbb{Q}. \end{aligned} \end{equation}$$ The first problem you run into is constructing a test statistic. The likelihood ratio (LR) statistic for this problem is always equal to one, since the rationals are dense in the reals. We have: $$\sup_{\mu \in \mathbb{Q}} \sup_{\sigma >0} \prod_{i=1}^n \text{N}(x_i | \mu, \sigma^2) = \Big( \frac{n}{2 \pi \sum x_i^2} \Big)^{n/2} \exp \Big( - \frac{n}{2} \Big) = \sup_{\mu \notin \mathbb{Q}} \sup_{\sigma >0} \prod_{i=1}^n \text{N}(x_i | \mu, \sigma^2),$$ so that the ratio of these supremums is unity. This means that the standard LR statistic fails to serve as a measure of evidence for the hypotheses, and so we need a custom test statistic. Now, for these hypotheses, the ordinal ranking of evidence falls into only two categories: if the sample mean is rational (which occurs with probability zero), this is greater evidence for the null hypothesis; if the sample mean is irrational (which occurs with probability one), this is greater evidence for the alternative hypothesis. Hence, the appropriate test statistic for the test is $T \equiv T(X_1, ..., X_n) \equiv \mathbb{I}(\bar{X} \notin \mathbb{Q})$, with higher values of this (indicator) test statistic constituting greater evidence for the alternative. Since $\bar{X} \sim \text{N}(\mu, \sigma^2 /n)$ is continuous, we have $\mathbb{P}(T = 0 | \mu, \sigma) = \mathbb{P}(\bar{X} \in \mathbb{Q} | \mu, \sigma) = 0$ over all the parameter values (this follows from the fact that the rationals have Lebesgue measure zero). This means that the test statistic has the same distribution regardless of the parameter values. If we observe $\bar{x} \notin \mathbb{Q}$ (i.e., the sample mean is irrational) then the p-value for the test is: $$p \equiv \mathbb{P}(T(\bar{X}) \geqslant t(\bar{x}) | H_0) = \mathbb{P}(T \geqslant 1 | \mu \in \mathbb{Q}) = 1.$$ If we observe $\bar{x} \in \mathbb{Q}$ (i.e., the sample mean is rational) then the p-value for the test is: $$\begin{equation} \begin{aligned} p \equiv \mathbb{P}(T(\bar{X}) \geqslant t(\bar{x}) | H_0) &= \mathbb{P}(T \geqslant 0 | \mu \in \mathbb{Q}) = 1. \end{aligned} \end{equation}$$ So we see that even with a custom test statistic that tries to differentiate the hypotheses, we never get any evidence against the null. This is intuitively reasonable, since for any mean value in the alternative hypothesis, we can always get one that is "arbitrarily close" in the null set.
Theory behind testing whether $\mu \in \mathbb{Q}$ for $X \sim \mathcal{N}(\mu, \sigma^2)$
Your intuition is correct: When you have a null set for the mean that is dense with respect to the total space, you won't be able differentiate the null and alternative sets with continuous data. Thi
Theory behind testing whether $\mu \in \mathbb{Q}$ for $X \sim \mathcal{N}(\mu, \sigma^2)$ Your intuition is correct: When you have a null set for the mean that is dense with respect to the total space, you won't be able differentiate the null and alternative sets with continuous data. This is because, for any mean value in the alternative hypothesis, we can always get one that is "arbitrarily close" in the null set. Hence, there should never be any evidence for the alternative hypothesis. To get a formal demonstration of this result, you need to go through the motions of constructing this as a composite hypothesis test. This is a bit tricky, since you have to make an argument for some test statistic, and there are some plausible objections here. Formal construction of classical hypothesis test: For this test the hypotheses are: $$\begin{equation} \begin{aligned} H_0 &: \mu \in \mathbb{Q}, \\[4pt] H_A &: \mu \notin \mathbb{Q}. \end{aligned} \end{equation}$$ The first problem you run into is constructing a test statistic. The likelihood ratio (LR) statistic for this problem is always equal to one, since the rationals are dense in the reals. We have: $$\sup_{\mu \in \mathbb{Q}} \sup_{\sigma >0} \prod_{i=1}^n \text{N}(x_i | \mu, \sigma^2) = \Big( \frac{n}{2 \pi \sum x_i^2} \Big)^{n/2} \exp \Big( - \frac{n}{2} \Big) = \sup_{\mu \notin \mathbb{Q}} \sup_{\sigma >0} \prod_{i=1}^n \text{N}(x_i | \mu, \sigma^2),$$ so that the ratio of these supremums is unity. This means that the standard LR statistic fails to serve as a measure of evidence for the hypotheses, and so we need a custom test statistic. Now, for these hypotheses, the ordinal ranking of evidence falls into only two categories: if the sample mean is rational (which occurs with probability zero), this is greater evidence for the null hypothesis; if the sample mean is irrational (which occurs with probability one), this is greater evidence for the alternative hypothesis. Hence, the appropriate test statistic for the test is $T \equiv T(X_1, ..., X_n) \equiv \mathbb{I}(\bar{X} \notin \mathbb{Q})$, with higher values of this (indicator) test statistic constituting greater evidence for the alternative. Since $\bar{X} \sim \text{N}(\mu, \sigma^2 /n)$ is continuous, we have $\mathbb{P}(T = 0 | \mu, \sigma) = \mathbb{P}(\bar{X} \in \mathbb{Q} | \mu, \sigma) = 0$ over all the parameter values (this follows from the fact that the rationals have Lebesgue measure zero). This means that the test statistic has the same distribution regardless of the parameter values. If we observe $\bar{x} \notin \mathbb{Q}$ (i.e., the sample mean is irrational) then the p-value for the test is: $$p \equiv \mathbb{P}(T(\bar{X}) \geqslant t(\bar{x}) | H_0) = \mathbb{P}(T \geqslant 1 | \mu \in \mathbb{Q}) = 1.$$ If we observe $\bar{x} \in \mathbb{Q}$ (i.e., the sample mean is rational) then the p-value for the test is: $$\begin{equation} \begin{aligned} p \equiv \mathbb{P}(T(\bar{X}) \geqslant t(\bar{x}) | H_0) &= \mathbb{P}(T \geqslant 0 | \mu \in \mathbb{Q}) = 1. \end{aligned} \end{equation}$$ So we see that even with a custom test statistic that tries to differentiate the hypotheses, we never get any evidence against the null. This is intuitively reasonable, since for any mean value in the alternative hypothesis, we can always get one that is "arbitrarily close" in the null set.
Theory behind testing whether $\mu \in \mathbb{Q}$ for $X \sim \mathcal{N}(\mu, \sigma^2)$ Your intuition is correct: When you have a null set for the mean that is dense with respect to the total space, you won't be able differentiate the null and alternative sets with continuous data. Thi
40,988
validation/training accuracy and overfitting
In this case, should the validation accuracy always be roughly the same as the training accuracy if there is no overfitting? There are a few points here: "accuracy" and "loss/error/cost" are 2 separate concepts. "Accuracy" is often used in classification problems and computed as the percentage of correctly classified inputs. This makes it quite a noisy measure. The "loss/error/cost" is a better measure of performance, and can be analysed mathematically more easily. If I may, I'll reformulate your question as: "Is training error always less than validation error, even if there is no overfitting or bad representation of the data?" Not always, because these are random quantities. So for a particular combination of dataset + training-validation split + model, the validation error might be lower than the training error. But the expectation of the validation error (bold red line) will be higher than the expectation of the training error (bold blue line): (Image source: ESL Chapter 7). Even though training and validation data are drawn from the same distribution, we expect the model to perform better when training than when we test it in the validation set. Ignoring the irreducible error caused by noise in the data, every model will be associated with some bias and variance. There is no perfect model. And we expect the combination of bias and variance to be higher on the validation set than on the training set. This is because fitting the model minimises the training set error at the expense of validation set error.
validation/training accuracy and overfitting
In this case, should the validation accuracy always be roughly the same as the training accuracy if there is no overfitting? There are a few points here: "accuracy" and "loss/error/cost" are 2 sepa
validation/training accuracy and overfitting In this case, should the validation accuracy always be roughly the same as the training accuracy if there is no overfitting? There are a few points here: "accuracy" and "loss/error/cost" are 2 separate concepts. "Accuracy" is often used in classification problems and computed as the percentage of correctly classified inputs. This makes it quite a noisy measure. The "loss/error/cost" is a better measure of performance, and can be analysed mathematically more easily. If I may, I'll reformulate your question as: "Is training error always less than validation error, even if there is no overfitting or bad representation of the data?" Not always, because these are random quantities. So for a particular combination of dataset + training-validation split + model, the validation error might be lower than the training error. But the expectation of the validation error (bold red line) will be higher than the expectation of the training error (bold blue line): (Image source: ESL Chapter 7). Even though training and validation data are drawn from the same distribution, we expect the model to perform better when training than when we test it in the validation set. Ignoring the irreducible error caused by noise in the data, every model will be associated with some bias and variance. There is no perfect model. And we expect the combination of bias and variance to be higher on the validation set than on the training set. This is because fitting the model minimises the training set error at the expense of validation set error.
validation/training accuracy and overfitting In this case, should the validation accuracy always be roughly the same as the training accuracy if there is no overfitting? There are a few points here: "accuracy" and "loss/error/cost" are 2 sepa
40,989
validation/training accuracy and overfitting
Interesting question! The only situation I can think of is when the data come from a very high-dimensional space (e.g. real world images) where, even if your training and validation set roughly represent the real distribution, the distribution will be extremely sparse. Then it can easily happen that the samples from the validation set are unrepresented enough in the training set, even though the model is not overfitted. Cross validation should be able to reveal this phenomenon (possibly outliers in the distribution of accuracies for each fold).
validation/training accuracy and overfitting
Interesting question! The only situation I can think of is when the data come from a very high-dimensional space (e.g. real world images) where, even if your training and validation set roughly repres
validation/training accuracy and overfitting Interesting question! The only situation I can think of is when the data come from a very high-dimensional space (e.g. real world images) where, even if your training and validation set roughly represent the real distribution, the distribution will be extremely sparse. Then it can easily happen that the samples from the validation set are unrepresented enough in the training set, even though the model is not overfitted. Cross validation should be able to reveal this phenomenon (possibly outliers in the distribution of accuracies for each fold).
validation/training accuracy and overfitting Interesting question! The only situation I can think of is when the data come from a very high-dimensional space (e.g. real world images) where, even if your training and validation set roughly repres
40,990
Is it a creditable approach to use Random Forrest Variable importance for causal inference?
The analogous concept to parameter estimates in the context of tree based models are not the variable importances, they are the partial dependency plots. Recall the a parameter estimate in a regression can be interpreted as the effect of on the predictions of varying a feature, when all other features are held constant. In a regression (without basis expansions or interactions) the effect of this change is linear with respect to the change in the feature (or linear on the link scale for a glm), and so it can be summarized by a single number. In a more complex model, this effect is no longer linear, it is instead a curve. These curves can be plotted, and the result is called a partial dependence plot. So, for example, if you make partial dependence plots from a fit linear regression model (with no basis expansions or interactions) the resulting curves are lines whose slopes are the parameter estimates. Here's a quick overview of the idea, with some code to get started.
Is it a creditable approach to use Random Forrest Variable importance for causal inference?
The analogous concept to parameter estimates in the context of tree based models are not the variable importances, they are the partial dependency plots. Recall the a parameter estimate in a regressio
Is it a creditable approach to use Random Forrest Variable importance for causal inference? The analogous concept to parameter estimates in the context of tree based models are not the variable importances, they are the partial dependency plots. Recall the a parameter estimate in a regression can be interpreted as the effect of on the predictions of varying a feature, when all other features are held constant. In a regression (without basis expansions or interactions) the effect of this change is linear with respect to the change in the feature (or linear on the link scale for a glm), and so it can be summarized by a single number. In a more complex model, this effect is no longer linear, it is instead a curve. These curves can be plotted, and the result is called a partial dependence plot. So, for example, if you make partial dependence plots from a fit linear regression model (with no basis expansions or interactions) the resulting curves are lines whose slopes are the parameter estimates. Here's a quick overview of the idea, with some code to get started.
Is it a creditable approach to use Random Forrest Variable importance for causal inference? The analogous concept to parameter estimates in the context of tree based models are not the variable importances, they are the partial dependency plots. Recall the a parameter estimate in a regressio
40,991
Is it a creditable approach to use Random Forrest Variable importance for causal inference?
Yes, it is possible to extract causal interpretations from an RF model but certain requirements will need to be met by the model for the extraction to be valid. Similar requirements are also necessary before extracting causal inferences from a simple linear model. The issues around doing so are discussed in Zhao & Hastie (2017), "Causal Interpretations of Black Box Models". Beginning of paper's conclusion, "In contrast to the conventional view that machine learning algorithms are just blackbox predictive models, we have argued that it is possible to extract causal information from these models using the partial dependence plots (PDP) and the individual conditional expectation (ICE) plots. In summary, a successful attempt of causal interpretation requires: (1) A good predictive model, so the black-box function g is (hopefully) close to the law of nature f. (2) Some domain knowledge about the causal structure to assure the back-door condition is satisfied.(3) Visualization tools such as the PDP and its extension ICE."
Is it a creditable approach to use Random Forrest Variable importance for causal inference?
Yes, it is possible to extract causal interpretations from an RF model but certain requirements will need to be met by the model for the extraction to be valid. Similar requirements are also necessary
Is it a creditable approach to use Random Forrest Variable importance for causal inference? Yes, it is possible to extract causal interpretations from an RF model but certain requirements will need to be met by the model for the extraction to be valid. Similar requirements are also necessary before extracting causal inferences from a simple linear model. The issues around doing so are discussed in Zhao & Hastie (2017), "Causal Interpretations of Black Box Models". Beginning of paper's conclusion, "In contrast to the conventional view that machine learning algorithms are just blackbox predictive models, we have argued that it is possible to extract causal information from these models using the partial dependence plots (PDP) and the individual conditional expectation (ICE) plots. In summary, a successful attempt of causal interpretation requires: (1) A good predictive model, so the black-box function g is (hopefully) close to the law of nature f. (2) Some domain knowledge about the causal structure to assure the back-door condition is satisfied.(3) Visualization tools such as the PDP and its extension ICE."
Is it a creditable approach to use Random Forrest Variable importance for causal inference? Yes, it is possible to extract causal interpretations from an RF model but certain requirements will need to be met by the model for the extraction to be valid. Similar requirements are also necessary
40,992
Gradient Bandit Algorithm baseline
Your implementation is very close to being correct. The issue is in the definition of $\pi$ (which you have as $P$ in your code). From the notes: where here we have also introduced a useful new notation, $\pi_t(a)$, for the probability of taking action $a$ at time $t$. But in your code, you take an argmax: A = np.argmax(P) This should instead be a random integer with mass function defined by $P$.
Gradient Bandit Algorithm baseline
Your implementation is very close to being correct. The issue is in the definition of $\pi$ (which you have as $P$ in your code). From the notes: where here we have also introduced a useful new notat
Gradient Bandit Algorithm baseline Your implementation is very close to being correct. The issue is in the definition of $\pi$ (which you have as $P$ in your code). From the notes: where here we have also introduced a useful new notation, $\pi_t(a)$, for the probability of taking action $a$ at time $t$. But in your code, you take an argmax: A = np.argmax(P) This should instead be a random integer with mass function defined by $P$.
Gradient Bandit Algorithm baseline Your implementation is very close to being correct. The issue is in the definition of $\pi$ (which you have as $P$ in your code). From the notes: where here we have also introduced a useful new notat
40,993
Percentiles of $Z=\max(X,Y)$, where $X$ and $Y$ are correlated bivariate normal random variables
You can compute this numerically. As for theoretical results, I don't have a reference to the literature, but here's a calculation of how your problem is related to the standard normal CDF $\Phi$. The joint pdf is $$f(x_1,x_2)=\frac1{2\pi\sigma_1\sigma_2\sqrt{1-\rho^2}}\exp\left[-\frac{z}{2(1-\rho^2)}\right]$$ where $$z=\frac{(x_1-\mu_1)^2}{\sigma_1^2}-\frac{2\rho(x_1-\mu_1)(x_2-\mu_2)}{\sigma_1\sigma_2}+\frac{(x_2-\mu_2)^2}{\sigma_2^2}.$$ For simplicity I'll assume $\mu_1=\mu_2=0$, $\sigma_1=\sigma_2=1$: $$f(x_1,x_2)=\frac1{2\pi\sqrt{1-\rho^2}}\exp\left[-\frac{z}{2(1-\rho^2)}\right],\qquad z=x_1^2 - 2\rho x_1x_2 + x_2^2.$$ Now we have, using $x^2-2\rho xy = (x-\rho y)^2-\rho^2y^2$, that $$\Pr(\max(X,Y)\le a)=\int_{-\infty}^a\int_{-\infty}^a f(x,y)\,dx\,dy=$$ $$\frac1{2\pi\sqrt{1-\rho^2}}\int_{-\infty}^a\exp\left(-\frac{y^2}{2(1-\rho^2)}\right)\int_{-\infty}^a \exp\left(-\frac{x^2-2\rho xy}{2(1-\rho^2)}\right)\,dx\,dy$$ $$=\frac1{2\pi\sqrt{1-\rho^2}}\int_{-\infty}^a\exp\left(-\frac{y^2}{2}\right)\int_{-\infty}^a \exp\left(-\frac{(x-\rho y)^2}{2(1-\rho^2)}\right)\,dx\,dy$$ Let $W$ be normal with mean $\rho y$ and variance $1-\rho^2$. Then $$\Pr(W\le a)=\Pr\left((W-\rho y)/\sqrt{1-\rho^2}\le (a-\rho y)/\sqrt{1-\rho^2}\right)$$ $$=\Phi\left((a-\rho y)/\sqrt{1-\rho^2}\right).$$ So we get $$\Pr(\max(X,Y)\le a)=\frac1{\sqrt{2\pi}}\int_{-\infty}^a \exp\left(-y^2/2\right)\Phi\left(\frac{a-\rho y}{\sqrt{1-\rho^2}}\right)\,dy.$$ You can see that if $\rho=0$ then this is just $\Phi(a)^2$, as it should be.
Percentiles of $Z=\max(X,Y)$, where $X$ and $Y$ are correlated bivariate normal random variables
You can compute this numerically. As for theoretical results, I don't have a reference to the literature, but here's a calculation of how your problem is related to the standard normal CDF $\Phi$. The
Percentiles of $Z=\max(X,Y)$, where $X$ and $Y$ are correlated bivariate normal random variables You can compute this numerically. As for theoretical results, I don't have a reference to the literature, but here's a calculation of how your problem is related to the standard normal CDF $\Phi$. The joint pdf is $$f(x_1,x_2)=\frac1{2\pi\sigma_1\sigma_2\sqrt{1-\rho^2}}\exp\left[-\frac{z}{2(1-\rho^2)}\right]$$ where $$z=\frac{(x_1-\mu_1)^2}{\sigma_1^2}-\frac{2\rho(x_1-\mu_1)(x_2-\mu_2)}{\sigma_1\sigma_2}+\frac{(x_2-\mu_2)^2}{\sigma_2^2}.$$ For simplicity I'll assume $\mu_1=\mu_2=0$, $\sigma_1=\sigma_2=1$: $$f(x_1,x_2)=\frac1{2\pi\sqrt{1-\rho^2}}\exp\left[-\frac{z}{2(1-\rho^2)}\right],\qquad z=x_1^2 - 2\rho x_1x_2 + x_2^2.$$ Now we have, using $x^2-2\rho xy = (x-\rho y)^2-\rho^2y^2$, that $$\Pr(\max(X,Y)\le a)=\int_{-\infty}^a\int_{-\infty}^a f(x,y)\,dx\,dy=$$ $$\frac1{2\pi\sqrt{1-\rho^2}}\int_{-\infty}^a\exp\left(-\frac{y^2}{2(1-\rho^2)}\right)\int_{-\infty}^a \exp\left(-\frac{x^2-2\rho xy}{2(1-\rho^2)}\right)\,dx\,dy$$ $$=\frac1{2\pi\sqrt{1-\rho^2}}\int_{-\infty}^a\exp\left(-\frac{y^2}{2}\right)\int_{-\infty}^a \exp\left(-\frac{(x-\rho y)^2}{2(1-\rho^2)}\right)\,dx\,dy$$ Let $W$ be normal with mean $\rho y$ and variance $1-\rho^2$. Then $$\Pr(W\le a)=\Pr\left((W-\rho y)/\sqrt{1-\rho^2}\le (a-\rho y)/\sqrt{1-\rho^2}\right)$$ $$=\Phi\left((a-\rho y)/\sqrt{1-\rho^2}\right).$$ So we get $$\Pr(\max(X,Y)\le a)=\frac1{\sqrt{2\pi}}\int_{-\infty}^a \exp\left(-y^2/2\right)\Phi\left(\frac{a-\rho y}{\sqrt{1-\rho^2}}\right)\,dy.$$ You can see that if $\rho=0$ then this is just $\Phi(a)^2$, as it should be.
Percentiles of $Z=\max(X,Y)$, where $X$ and $Y$ are correlated bivariate normal random variables You can compute this numerically. As for theoretical results, I don't have a reference to the literature, but here's a calculation of how your problem is related to the standard normal CDF $\Phi$. The
40,994
How to simulate n Uniform[0,1] variables with a specified correlation?
Your method works. Take a standard bivariate normal random variable $(X_1,X_2)$ with correlation $\tau$. Let $\Phi$ be the standard Normal distribution function. The copula $(U_1,U_2)$ given by $U_i = \Phi(X_i)$ has some correlation $\rho=f(\tau)$. Although this function $f$ cannot be determined analytically (as far as I can tell), numerical integration with a full suite of values $\tau$ spanning the interval $[-1,1]$ suggests its inverse $f^{-1}$, which determines what $\tau$ needs to be to yield a correlation $\rho$, can be approximated to about $0.000001$ throughout the interval by the function $$\hat f^{-1}(\rho) = \frac{4118}{3163} \sin(\rho/3) + \frac{3183}{3149} \sin(2 \rho/3) - \frac{145}{2391} \sin(3 \rho/3).$$ Tests with the following R implementation support the claimed accuracy. (Actually, it would take a large simulation--greater than $10^{12}$ observations--to detect the error of approximation.) Edit Let $f_\tau$ be the standard bivariate Normal density, $$f_\tau(x_1,x_2) = \frac{1}{2\pi \sqrt{1-\tau^2}} \exp\left(-\frac{1}{2(1-\tau^2)}(x_1^2+x_2^2-2\tau x_1x_2)\right).$$ Then the correlation of the $U_i$ is a function of the moments $$m_\tau(i,j) = E[U_1^i U_2^j] = E[\Phi(X_1)^i\Phi(X_2)^j] = \iint f_\tau(x_1,x_2) \Phi(x_1)^i \Phi(x_2)^j dx_1 dx_2;$$ $$f(\tau)=\operatorname{Cor}(U_1,U_2) = \frac{m_\tau(1,1) - m_\tau(1,0)^2}{m_\tau(2,0)-m_\tau(1,0)^2}.$$ Most of these have easy analytical expressions based on univariate moments of the uniform distribution, because they do not depend on $\rho$: $m_\rho(1,0)=1/2,$ $m_\rho(2,0)=1/3.$ The one I integrated numerically is $m_\rho(1,1)$. I enforced the symmetry $f(-\tau)=-f(\tau)$ by numerically computing both $f(\pm \tau)$ and averaging their absolute values. unif.to.norm <- function(rho) { 4118/3163 * sin(rho/3) + 3183/3149 * sin(2 * rho/3) - 145/2391 * sin(rho) } # curve(unif.to.norm(rho)-rho, 0, 1, xname="rho") # Compare to a linear function library(MASS) # mvrnorm n <- 1e5 # observations to simulate d <- 5 # dimensions rho <- 0.6 # Must lie in [-1/(d-1), 1] # # Compute the correlation matrix for the multivariate Normal distribution. # rho.norm <- unif.to.norm(rho) Sigma <- matrix(rho.norm, d, d) + diag(rep(1-rho.norm, d)) # # Simulate data. # x <- pnorm(mvrnorm(n, rep(0, d), Sigma)) # # Display the data. # # pairs(x) # The scatterplots # par(mfrow=c(1, d)) # apply(x, 2, hist) # The histograms (will be uniform) # par(mfrow=c(1,1)) Sigma.hat <- cor(x) prec <- ceiling(log10(n)/2) signif(Sigma.hat, prec) # Should almost match `rho` in all off-diagonal entries signif(mean(Sigma.hat[lower.tri(Sigma.hat)]), prec+1)
How to simulate n Uniform[0,1] variables with a specified correlation?
Your method works. Take a standard bivariate normal random variable $(X_1,X_2)$ with correlation $\tau$. Let $\Phi$ be the standard Normal distribution function. The copula $(U_1,U_2)$ given by $U_i
How to simulate n Uniform[0,1] variables with a specified correlation? Your method works. Take a standard bivariate normal random variable $(X_1,X_2)$ with correlation $\tau$. Let $\Phi$ be the standard Normal distribution function. The copula $(U_1,U_2)$ given by $U_i = \Phi(X_i)$ has some correlation $\rho=f(\tau)$. Although this function $f$ cannot be determined analytically (as far as I can tell), numerical integration with a full suite of values $\tau$ spanning the interval $[-1,1]$ suggests its inverse $f^{-1}$, which determines what $\tau$ needs to be to yield a correlation $\rho$, can be approximated to about $0.000001$ throughout the interval by the function $$\hat f^{-1}(\rho) = \frac{4118}{3163} \sin(\rho/3) + \frac{3183}{3149} \sin(2 \rho/3) - \frac{145}{2391} \sin(3 \rho/3).$$ Tests with the following R implementation support the claimed accuracy. (Actually, it would take a large simulation--greater than $10^{12}$ observations--to detect the error of approximation.) Edit Let $f_\tau$ be the standard bivariate Normal density, $$f_\tau(x_1,x_2) = \frac{1}{2\pi \sqrt{1-\tau^2}} \exp\left(-\frac{1}{2(1-\tau^2)}(x_1^2+x_2^2-2\tau x_1x_2)\right).$$ Then the correlation of the $U_i$ is a function of the moments $$m_\tau(i,j) = E[U_1^i U_2^j] = E[\Phi(X_1)^i\Phi(X_2)^j] = \iint f_\tau(x_1,x_2) \Phi(x_1)^i \Phi(x_2)^j dx_1 dx_2;$$ $$f(\tau)=\operatorname{Cor}(U_1,U_2) = \frac{m_\tau(1,1) - m_\tau(1,0)^2}{m_\tau(2,0)-m_\tau(1,0)^2}.$$ Most of these have easy analytical expressions based on univariate moments of the uniform distribution, because they do not depend on $\rho$: $m_\rho(1,0)=1/2,$ $m_\rho(2,0)=1/3.$ The one I integrated numerically is $m_\rho(1,1)$. I enforced the symmetry $f(-\tau)=-f(\tau)$ by numerically computing both $f(\pm \tau)$ and averaging their absolute values. unif.to.norm <- function(rho) { 4118/3163 * sin(rho/3) + 3183/3149 * sin(2 * rho/3) - 145/2391 * sin(rho) } # curve(unif.to.norm(rho)-rho, 0, 1, xname="rho") # Compare to a linear function library(MASS) # mvrnorm n <- 1e5 # observations to simulate d <- 5 # dimensions rho <- 0.6 # Must lie in [-1/(d-1), 1] # # Compute the correlation matrix for the multivariate Normal distribution. # rho.norm <- unif.to.norm(rho) Sigma <- matrix(rho.norm, d, d) + diag(rep(1-rho.norm, d)) # # Simulate data. # x <- pnorm(mvrnorm(n, rep(0, d), Sigma)) # # Display the data. # # pairs(x) # The scatterplots # par(mfrow=c(1, d)) # apply(x, 2, hist) # The histograms (will be uniform) # par(mfrow=c(1,1)) Sigma.hat <- cor(x) prec <- ceiling(log10(n)/2) signif(Sigma.hat, prec) # Should almost match `rho` in all off-diagonal entries signif(mean(Sigma.hat[lower.tri(Sigma.hat)]), prec+1)
How to simulate n Uniform[0,1] variables with a specified correlation? Your method works. Take a standard bivariate normal random variable $(X_1,X_2)$ with correlation $\tau$. Let $\Phi$ be the standard Normal distribution function. The copula $(U_1,U_2)$ given by $U_i
40,995
How to simulate n Uniform[0,1] variables with a specified correlation?
@whuber: Great derivation, and highly useful for those creating copulas. I always wondered where some correlation gets lost when channeling the normal random deviates with desired correlation through the CDF: ## we arrive at rho = 1.91 set.seed(123) X <- mvrnorm(100000, mu = c(0, 0, 0), Sigma = matrix(c(1, 0.2, 0, 0.2, 1, 0, 0, 0, 1), nrow = 3), empirical = T) print(cor(X)) [,1] [,2] [,3] [1,] 1.000000e+00 2.000000e-01 -3.053512e-15 [2,] 2.000000e-01 1.000000e+00 2.217207e-15 [3,] -3.053512e-15 2.217207e-15 1.000000e+00 P <- pnorm(X) print(cor(P)) [,1] [,2] [,3] [1,] 1.0000000000 0.1915424223 0.0004832619 [2,] 0.1915424223 1.0000000000 0.0009725174 [3,] 0.0004832619 0.0009725174 1.0000000000 ## need to set rho a bit higher to obtain desired rho = 0.2 set.seed(123) X <- mvrnorm(100000, mu = c(0, 0, 0), Sigma = matrix(c(1, 0.209, 0, 0.209, 1, 0, 0, 0, 1), nrow = 3), empirical = T) print(cor(X)) [,1] [,2] [,3] [1,] 1.000000e+00 2.09000e-01 2.200462e-15 [2,] 2.090000e-01 1.00000e+00 -3.040320e-15 [3,] 2.200462e-15 -3.04032e-15 1.000000e+00 P <- pnorm(X) print(cor(P)) [,1] [,2] [,3] [1,] 1.0000000000 0.2001865963 0.0009690459 [2,] 0.2001865963 1.0000000000 0.0004781438 [3,] 0.0009690459 0.0004781438 1.0000000000
How to simulate n Uniform[0,1] variables with a specified correlation?
@whuber: Great derivation, and highly useful for those creating copulas. I always wondered where some correlation gets lost when channeling the normal random deviates with desired correlation through
How to simulate n Uniform[0,1] variables with a specified correlation? @whuber: Great derivation, and highly useful for those creating copulas. I always wondered where some correlation gets lost when channeling the normal random deviates with desired correlation through the CDF: ## we arrive at rho = 1.91 set.seed(123) X <- mvrnorm(100000, mu = c(0, 0, 0), Sigma = matrix(c(1, 0.2, 0, 0.2, 1, 0, 0, 0, 1), nrow = 3), empirical = T) print(cor(X)) [,1] [,2] [,3] [1,] 1.000000e+00 2.000000e-01 -3.053512e-15 [2,] 2.000000e-01 1.000000e+00 2.217207e-15 [3,] -3.053512e-15 2.217207e-15 1.000000e+00 P <- pnorm(X) print(cor(P)) [,1] [,2] [,3] [1,] 1.0000000000 0.1915424223 0.0004832619 [2,] 0.1915424223 1.0000000000 0.0009725174 [3,] 0.0004832619 0.0009725174 1.0000000000 ## need to set rho a bit higher to obtain desired rho = 0.2 set.seed(123) X <- mvrnorm(100000, mu = c(0, 0, 0), Sigma = matrix(c(1, 0.209, 0, 0.209, 1, 0, 0, 0, 1), nrow = 3), empirical = T) print(cor(X)) [,1] [,2] [,3] [1,] 1.000000e+00 2.09000e-01 2.200462e-15 [2,] 2.090000e-01 1.00000e+00 -3.040320e-15 [3,] 2.200462e-15 -3.04032e-15 1.000000e+00 P <- pnorm(X) print(cor(P)) [,1] [,2] [,3] [1,] 1.0000000000 0.2001865963 0.0009690459 [2,] 0.2001865963 1.0000000000 0.0004781438 [3,] 0.0009690459 0.0004781438 1.0000000000
How to simulate n Uniform[0,1] variables with a specified correlation? @whuber: Great derivation, and highly useful for those creating copulas. I always wondered where some correlation gets lost when channeling the normal random deviates with desired correlation through
40,996
non-linear regression: Residual Plots and RMSE on raw and log target variable
Although your question seems to be based on use of a boosted regression tree algorithm (XGBRegressor, with which I have no experience), your issues seem to be some that are also faced in standard linear regression, on which I base much of my answer. How to proceed depends on what you are trying to accomplish. To start, a few issues need to be clarified. First, a regression model is typically considered linear if it is linear in the parameters. In this terminology, non-linear transformations of predictor variables or outcome/target variables do not by themselves make a model non-linear. As you are evidently using boosted regression trees instead of a classical linear regression, it's not clear that the linear/non-linear distinction really applies, anyway. Second, there is no need for the target variable to have a symmetric distribution in standard linear regression, although that can help with regression trees. As your appropriate focus on the residual plots indicates, the distribution of residuals is important. Third, RMSE of your entire data set (which is what you seem to be showing) might not be the best measure of the quality of your model. Particularly if you intend to use the model for predictions on new cases, cross-validation or bootstrapping could provide much better estimates of such future performance. Now to your questions: The regressions for the linear and log-transformed prices attempt different things: the first tries to minimize the error in absolute terms (e.g., dollars), the second tries to minimize the error in relative/fractional terms (e.g., percentage error in predicted price). Which type of error do you care about for your application? If you care more about fractional errors, you should use the log transform and you shouldn't worry that the error in absolute terms appears bigger when you back-transform from the log scale. You should always, however, pay attention to residuals in whichever scale you choose. Skewness in the target variable is an issue in standard linear regression provided that some predictor variables are also appropriately skewed so that residuals are not skewed. Transformation of both predictor and target variables is often needed to meet the assumptions of a linear regression and to produce well-behaved residuals. With tree-based regression approaches that use mean values of target variables to choose cutoffs for trees, removing skewness in the target variable can be recommended; the authors of ISLR do a log transform for this purpose in their example of a regression tree (pp. 304 and following). Log transformation means that residuals will be in fractional rather than absolute terms, which seems to make sense for these types of data. You should always pay attention to residual plots. Comparing the RMSE of the regression for non-transformed prices against the exponentiated RMSE of the regression for log-transformed prices isn't always very useful. In your log-transformed analysis, the case with the largest absolute error in the log (fractional) scale is also the lowest in absolute predicted price. That case will make a large contribution to the RMSE error in the log-transformed scale (as will several other low-price cases), but perhaps a very small contribution to RMSE in absolute terms in the regression for non-transformed prices. That might account for your observation. In terms of how to proceed, it looks like the log-transformation of prices is useful but that your model doesn't deal too well with some of the most extremely low prices. You might need to incorporate your knowledge about the underlying subject matter, e.g. whether there is something special about such cases (other than that they don't fit well) that make them inappropriate to include in the model (for example, you might need to exclude all rents that are charged among family members, which might be lower than market rents, or rents in otherwise subsidized units if any), or whether transformations of some predictor variables might improve performance. Different choices of the tuning parameters for the boosting might help. And again, you should consider a different measure of model quality than RMSE on the entire data set. Finally, the classic linear regression approach can outperform tree-based approaches in many situations. You could try a standard linear regression with appropriate knowledge-based selection and transformations of predictors and target variable values, with cross-validation or bootstrapping to validate your modeling approach.
non-linear regression: Residual Plots and RMSE on raw and log target variable
Although your question seems to be based on use of a boosted regression tree algorithm (XGBRegressor, with which I have no experience), your issues seem to be some that are also faced in standard line
non-linear regression: Residual Plots and RMSE on raw and log target variable Although your question seems to be based on use of a boosted regression tree algorithm (XGBRegressor, with which I have no experience), your issues seem to be some that are also faced in standard linear regression, on which I base much of my answer. How to proceed depends on what you are trying to accomplish. To start, a few issues need to be clarified. First, a regression model is typically considered linear if it is linear in the parameters. In this terminology, non-linear transformations of predictor variables or outcome/target variables do not by themselves make a model non-linear. As you are evidently using boosted regression trees instead of a classical linear regression, it's not clear that the linear/non-linear distinction really applies, anyway. Second, there is no need for the target variable to have a symmetric distribution in standard linear regression, although that can help with regression trees. As your appropriate focus on the residual plots indicates, the distribution of residuals is important. Third, RMSE of your entire data set (which is what you seem to be showing) might not be the best measure of the quality of your model. Particularly if you intend to use the model for predictions on new cases, cross-validation or bootstrapping could provide much better estimates of such future performance. Now to your questions: The regressions for the linear and log-transformed prices attempt different things: the first tries to minimize the error in absolute terms (e.g., dollars), the second tries to minimize the error in relative/fractional terms (e.g., percentage error in predicted price). Which type of error do you care about for your application? If you care more about fractional errors, you should use the log transform and you shouldn't worry that the error in absolute terms appears bigger when you back-transform from the log scale. You should always, however, pay attention to residuals in whichever scale you choose. Skewness in the target variable is an issue in standard linear regression provided that some predictor variables are also appropriately skewed so that residuals are not skewed. Transformation of both predictor and target variables is often needed to meet the assumptions of a linear regression and to produce well-behaved residuals. With tree-based regression approaches that use mean values of target variables to choose cutoffs for trees, removing skewness in the target variable can be recommended; the authors of ISLR do a log transform for this purpose in their example of a regression tree (pp. 304 and following). Log transformation means that residuals will be in fractional rather than absolute terms, which seems to make sense for these types of data. You should always pay attention to residual plots. Comparing the RMSE of the regression for non-transformed prices against the exponentiated RMSE of the regression for log-transformed prices isn't always very useful. In your log-transformed analysis, the case with the largest absolute error in the log (fractional) scale is also the lowest in absolute predicted price. That case will make a large contribution to the RMSE error in the log-transformed scale (as will several other low-price cases), but perhaps a very small contribution to RMSE in absolute terms in the regression for non-transformed prices. That might account for your observation. In terms of how to proceed, it looks like the log-transformation of prices is useful but that your model doesn't deal too well with some of the most extremely low prices. You might need to incorporate your knowledge about the underlying subject matter, e.g. whether there is something special about such cases (other than that they don't fit well) that make them inappropriate to include in the model (for example, you might need to exclude all rents that are charged among family members, which might be lower than market rents, or rents in otherwise subsidized units if any), or whether transformations of some predictor variables might improve performance. Different choices of the tuning parameters for the boosting might help. And again, you should consider a different measure of model quality than RMSE on the entire data set. Finally, the classic linear regression approach can outperform tree-based approaches in many situations. You could try a standard linear regression with appropriate knowledge-based selection and transformations of predictors and target variable values, with cross-validation or bootstrapping to validate your modeling approach.
non-linear regression: Residual Plots and RMSE on raw and log target variable Although your question seems to be based on use of a boosted regression tree algorithm (XGBRegressor, with which I have no experience), your issues seem to be some that are also faced in standard line
40,997
Sum of forecasts
You can sum them, but as described by Hyndman et al in the Optimal combination forecasts for hierarchical time series paper (see also their hts package, the fpp2 chapter and those slides), you can do better by using hierarchical forecast that makes forecasts on all the levels (upper and higher) and then combines them.
Sum of forecasts
You can sum them, but as described by Hyndman et al in the Optimal combination forecasts for hierarchical time series paper (see also their hts package, the fpp2 chapter and those slides), you can do
Sum of forecasts You can sum them, but as described by Hyndman et al in the Optimal combination forecasts for hierarchical time series paper (see also their hts package, the fpp2 chapter and those slides), you can do better by using hierarchical forecast that makes forecasts on all the levels (upper and higher) and then combines them.
Sum of forecasts You can sum them, but as described by Hyndman et al in the Optimal combination forecasts for hierarchical time series paper (see also their hts package, the fpp2 chapter and those slides), you can do
40,998
Is there a bivariate $\beta$ distribution I can fit to my data?
There are many ways to define bivariate beta distributions, that is, bivariate distributions on the square $[0,1]\times [0,1]$ with beta marginals.One way is to start with the usual stochastic representation of the beta distribution using gamma variates, let $X\sim\mathcal{Gamma}(\alpha,\theta),~~ Y\sim\mathcal{Gamma}(\beta,\theta)$ (independent), then $$ \frac{X}{X+Y} \sim\mathcal{Beta}(\alpha,\beta) $$ If we can make a similar representation with three gamma variates, and use one of them in both ratios, we will get a correlated bivariate distribution with beta marginals. But note that such a construction cannot give negative correlations! A paper (arXiv) discussing this and many other constructions gives the following representation $$ X=\frac{G_1}{G_0+G_1},\quad Y=\frac{G_2}{G_0+G_2} $$ with shape parameters $\alpha_i$ and common scale parameter. The density function is: $$ f(x,y)=\frac{1}{B(\alpha_0,\alpha_1,\alpha_2)}\frac{x^{\alpha_1-1}(1-x)^{\alpha_0+\alpha_2-1}y^{\alpha_2-1}(1-y)^{\alpha_0+\alpha_1-1}}{(1-xy)^{\alpha_0+\alpha_1+\alpha_2}} $$ where $B$ is a generalized beta function $$ B(\alpha_1,\alpha_2,\alpha_3, \dots)=\frac{\prod_j \Gamma(\alpha_j)}{\Gamma(\prod_j \alpha_j)} $$ We can test this with your data, which has a low positive correlation, using maximum likelihood estimation. Some R code below: gbeta <- function(a, log=FALSE) { # Generalized beta function p <- length(a); if(p<2) stop("a must have length at least 2") if (min(a)<=0)stop("negative parameters is not allowed") lgbeta <- sum(lgamma(a)) - lgamma(sum(a)) if(log)lgbeta else exp(lgbeta) } dbibeta3 <- function(x, y, a0, a1, a2, log=FALSE) { logdens <- -gbeta(c(a0, a1, a2), log=TRUE) + (a1-1)*log(x) + (a0 + a2-1)*log(1-x) + (a2-1)*log(y) + (a0 + a1-1)*log(1-y) - (a0 + a1 + a2)*log(1-x*y) if(log) logdens else exp(logdens) } rbibeta3 <- function(n, a0, a1, a2) { if(min(c(a0, a1, a2))<= 0) stop("all parameters must be positive") G0 <- rgamma(n, a0, 1) G1 <- rgamma(n, a1, 1) G2 <- rgamma(n, a2, 1) cbind(G1/(G1 + G0), G2/(G2 + G0)) } betadata <- < data from your question > library(bbmle) # on CRAN minusloglik <- function(a0, a1, a2) { # we use log parameters x <- betadata[, 1]; y <- betadata[, 2] -sum(dbibeta3(x, y, exp(a0), exp(a1), exp(a2), log=TRUE)) } mod <- bbmle::mle2(minusloglik, start=list(a0=log(1), a1=log(3), a2=log(7))) > mod Call: bbmle::mle2(minuslogl = minusloglik, start = list(a0 = log(1), a1 = log(3), a2 = log(7))) Coefficients: a0 a1 a2 0.7116677 2.0963634 0.2249110 Log-likelihood: 27.22 > exp(coef(mod)) a0 a1 a2 2.037386 8.136527 1.252211 Let us simulate some data with these parameters, and plot them alongside your data: simdata <- rbibeta3(30, 2.037, 8.137, 1.252) The simulated data shows stronger correlation than the observed, so maybe this model is not a good one? We could try with some more flexible bivariate beta distributions!
Is there a bivariate $\beta$ distribution I can fit to my data?
There are many ways to define bivariate beta distributions, that is, bivariate distributions on the square $[0,1]\times [0,1]$ with beta marginals.One way is to start with the usual stochastic represe
Is there a bivariate $\beta$ distribution I can fit to my data? There are many ways to define bivariate beta distributions, that is, bivariate distributions on the square $[0,1]\times [0,1]$ with beta marginals.One way is to start with the usual stochastic representation of the beta distribution using gamma variates, let $X\sim\mathcal{Gamma}(\alpha,\theta),~~ Y\sim\mathcal{Gamma}(\beta,\theta)$ (independent), then $$ \frac{X}{X+Y} \sim\mathcal{Beta}(\alpha,\beta) $$ If we can make a similar representation with three gamma variates, and use one of them in both ratios, we will get a correlated bivariate distribution with beta marginals. But note that such a construction cannot give negative correlations! A paper (arXiv) discussing this and many other constructions gives the following representation $$ X=\frac{G_1}{G_0+G_1},\quad Y=\frac{G_2}{G_0+G_2} $$ with shape parameters $\alpha_i$ and common scale parameter. The density function is: $$ f(x,y)=\frac{1}{B(\alpha_0,\alpha_1,\alpha_2)}\frac{x^{\alpha_1-1}(1-x)^{\alpha_0+\alpha_2-1}y^{\alpha_2-1}(1-y)^{\alpha_0+\alpha_1-1}}{(1-xy)^{\alpha_0+\alpha_1+\alpha_2}} $$ where $B$ is a generalized beta function $$ B(\alpha_1,\alpha_2,\alpha_3, \dots)=\frac{\prod_j \Gamma(\alpha_j)}{\Gamma(\prod_j \alpha_j)} $$ We can test this with your data, which has a low positive correlation, using maximum likelihood estimation. Some R code below: gbeta <- function(a, log=FALSE) { # Generalized beta function p <- length(a); if(p<2) stop("a must have length at least 2") if (min(a)<=0)stop("negative parameters is not allowed") lgbeta <- sum(lgamma(a)) - lgamma(sum(a)) if(log)lgbeta else exp(lgbeta) } dbibeta3 <- function(x, y, a0, a1, a2, log=FALSE) { logdens <- -gbeta(c(a0, a1, a2), log=TRUE) + (a1-1)*log(x) + (a0 + a2-1)*log(1-x) + (a2-1)*log(y) + (a0 + a1-1)*log(1-y) - (a0 + a1 + a2)*log(1-x*y) if(log) logdens else exp(logdens) } rbibeta3 <- function(n, a0, a1, a2) { if(min(c(a0, a1, a2))<= 0) stop("all parameters must be positive") G0 <- rgamma(n, a0, 1) G1 <- rgamma(n, a1, 1) G2 <- rgamma(n, a2, 1) cbind(G1/(G1 + G0), G2/(G2 + G0)) } betadata <- < data from your question > library(bbmle) # on CRAN minusloglik <- function(a0, a1, a2) { # we use log parameters x <- betadata[, 1]; y <- betadata[, 2] -sum(dbibeta3(x, y, exp(a0), exp(a1), exp(a2), log=TRUE)) } mod <- bbmle::mle2(minusloglik, start=list(a0=log(1), a1=log(3), a2=log(7))) > mod Call: bbmle::mle2(minuslogl = minusloglik, start = list(a0 = log(1), a1 = log(3), a2 = log(7))) Coefficients: a0 a1 a2 0.7116677 2.0963634 0.2249110 Log-likelihood: 27.22 > exp(coef(mod)) a0 a1 a2 2.037386 8.136527 1.252211 Let us simulate some data with these parameters, and plot them alongside your data: simdata <- rbibeta3(30, 2.037, 8.137, 1.252) The simulated data shows stronger correlation than the observed, so maybe this model is not a good one? We could try with some more flexible bivariate beta distributions!
Is there a bivariate $\beta$ distribution I can fit to my data? There are many ways to define bivariate beta distributions, that is, bivariate distributions on the square $[0,1]\times [0,1]$ with beta marginals.One way is to start with the usual stochastic represe
40,999
Clustering weighted data with k clusters
You could simply make multiple copies of the points proportional to their weights and then run k-means. Here is an R implementation of that. ## Your data x = c(20, 21, 30, 31, 200, 201) w = c(100, 100, 100, 100, 1, 1) WeightedX = rep(x, w) kmeans(WeightedX, 2) Cluster means: [,1] 1 20.50000 2 32.18317
Clustering weighted data with k clusters
You could simply make multiple copies of the points proportional to their weights and then run k-means. Here is an R implementation of that. ## Your data x = c(20, 21, 30, 31, 200, 201) w = c(100, 10
Clustering weighted data with k clusters You could simply make multiple copies of the points proportional to their weights and then run k-means. Here is an R implementation of that. ## Your data x = c(20, 21, 30, 31, 200, 201) w = c(100, 100, 100, 100, 1, 1) WeightedX = rep(x, w) kmeans(WeightedX, 2) Cluster means: [,1] 1 20.50000 2 32.18317
Clustering weighted data with k clusters You could simply make multiple copies of the points proportional to their weights and then run k-means. Here is an R implementation of that. ## Your data x = c(20, 21, 30, 31, 200, 201) w = c(100, 10
41,000
Clustering weighted data with k clusters
You can trivially modify k-means to support weights. When computing the mean, just multiply every point with it's weight, and divide by the weight sum (the usual weighted mean). $$\mu = \frac{1}{\sum_{i\in C} w_i} \sum_{i\in C} w_i x_i$$ This needs to happen in k-means, at each iteration when it is recomputing the cluster means, to find the best weighted means. This is probably the easiest possible modification to k-means, fortunately. But you will need to edit the k-means function, so you need access to the source code of k-means. Don't use a blackbox tools like MATLAB!
Clustering weighted data with k clusters
You can trivially modify k-means to support weights. When computing the mean, just multiply every point with it's weight, and divide by the weight sum (the usual weighted mean). $$\mu = \frac{1}{\sum_
Clustering weighted data with k clusters You can trivially modify k-means to support weights. When computing the mean, just multiply every point with it's weight, and divide by the weight sum (the usual weighted mean). $$\mu = \frac{1}{\sum_{i\in C} w_i} \sum_{i\in C} w_i x_i$$ This needs to happen in k-means, at each iteration when it is recomputing the cluster means, to find the best weighted means. This is probably the easiest possible modification to k-means, fortunately. But you will need to edit the k-means function, so you need access to the source code of k-means. Don't use a blackbox tools like MATLAB!
Clustering weighted data with k clusters You can trivially modify k-means to support weights. When computing the mean, just multiply every point with it's weight, and divide by the weight sum (the usual weighted mean). $$\mu = \frac{1}{\sum_