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
48,401
How do I perform diagnostic checks on a beta regression?
I am afraid I have a relatively unsatisfying answer, but I have included a number of references you may explore. Beta regression models are relatively new, compared to the rest of the common generalized linear models. Ferrari & Cribari-Neto (2004) introduced the parameterization that is used by most statistical packages, so it's not even 15 years old yet. I say this because diagnostics for beta regression models are still an active area of research, with many different authors proposing different techniques for diagnosing issues with these models (Espinheira, Ferrari, & Cribari-Neto, 2008a, 2008b; Espinheira, Santos, & Cribari-Neto, 2017; Pereira, 2017). There does not seem yet to be an agreed-upon method for performing diagnostic checks on these models, but those papers should give you an idea. Comparing it to ordinary least squares regression (OLS), residuals should not necessarily be normally distributed (see papers above). Moreover, because you are estimating the $\phi$ parameter and because the variance is a function of the mean in the beta distribution, the model is naturally heteroskedastic. So you aren't doing the same type of diagnostic checks as you would in an OLS regression. You are also estimating random intercepts in your model. Using a Gaussian (e.g., identity) link function, you would expect these intercepts to be normally distributed, as well. I do not know what the expectation is in beta regression, and I would bet that the package might not give you satisfactory information on how they identify the models in the documentation (from my experience, beta regression models are included in packages that use a wide range of distributions, but far more rarely explained in much statistical detail). But hopefully they have a reference you can check somewhere; I am less familiar with mixed effects models in beta regression. References Espinheira, P. L., Ferrari, S. L., & Cribari-Neto, F. (2008a). Influence diagnostics in beta regression. Computational Statistics & Data Analysis, 52 (9), 4417–4431. Espinheira, P. L., Ferrari, S. L., & Cribari-Neto, F. (2008b). On beta regression residuals. Journal of Applied Statistics, 35(4), 407–419. Espinheira, P. L., Santos, E. G., & Cribari-Neto, F. (2017). On nonlinear beta regression residuals. Biometrical Journal, 59(3), 445–461. Ferrari, S. L., & Cribari-Neto, F. (2004). Beta regression for modelling rates and proportions. Journal of Applied Statistics, 31(7), 799–815. Pereira, G. H. (2017). On quantile residuals in beta regression. Communications in Statistics - Simulation and Computation, 1–15.
How do I perform diagnostic checks on a beta regression?
I am afraid I have a relatively unsatisfying answer, but I have included a number of references you may explore. Beta regression models are relatively new, compared to the rest of the common generaliz
How do I perform diagnostic checks on a beta regression? I am afraid I have a relatively unsatisfying answer, but I have included a number of references you may explore. Beta regression models are relatively new, compared to the rest of the common generalized linear models. Ferrari & Cribari-Neto (2004) introduced the parameterization that is used by most statistical packages, so it's not even 15 years old yet. I say this because diagnostics for beta regression models are still an active area of research, with many different authors proposing different techniques for diagnosing issues with these models (Espinheira, Ferrari, & Cribari-Neto, 2008a, 2008b; Espinheira, Santos, & Cribari-Neto, 2017; Pereira, 2017). There does not seem yet to be an agreed-upon method for performing diagnostic checks on these models, but those papers should give you an idea. Comparing it to ordinary least squares regression (OLS), residuals should not necessarily be normally distributed (see papers above). Moreover, because you are estimating the $\phi$ parameter and because the variance is a function of the mean in the beta distribution, the model is naturally heteroskedastic. So you aren't doing the same type of diagnostic checks as you would in an OLS regression. You are also estimating random intercepts in your model. Using a Gaussian (e.g., identity) link function, you would expect these intercepts to be normally distributed, as well. I do not know what the expectation is in beta regression, and I would bet that the package might not give you satisfactory information on how they identify the models in the documentation (from my experience, beta regression models are included in packages that use a wide range of distributions, but far more rarely explained in much statistical detail). But hopefully they have a reference you can check somewhere; I am less familiar with mixed effects models in beta regression. References Espinheira, P. L., Ferrari, S. L., & Cribari-Neto, F. (2008a). Influence diagnostics in beta regression. Computational Statistics & Data Analysis, 52 (9), 4417–4431. Espinheira, P. L., Ferrari, S. L., & Cribari-Neto, F. (2008b). On beta regression residuals. Journal of Applied Statistics, 35(4), 407–419. Espinheira, P. L., Santos, E. G., & Cribari-Neto, F. (2017). On nonlinear beta regression residuals. Biometrical Journal, 59(3), 445–461. Ferrari, S. L., & Cribari-Neto, F. (2004). Beta regression for modelling rates and proportions. Journal of Applied Statistics, 31(7), 799–815. Pereira, G. H. (2017). On quantile residuals in beta regression. Communications in Statistics - Simulation and Computation, 1–15.
How do I perform diagnostic checks on a beta regression? I am afraid I have a relatively unsatisfying answer, but I have included a number of references you may explore. Beta regression models are relatively new, compared to the rest of the common generaliz
48,402
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, ages 25 and up) (disparity, difference)
I'll weigh in with one point, but make it an answer so I can include some code and results. I think the way I would approach the question is to consider the effect size. If I have understood the question and data correctly, phi for the appropriate table comes out to 0.05. Cohen (1988) interprets this value as less than "small". Obviously, any interpretation of effect size is relative to the discipline and intention of the analysis. But the size of the effect does suggest that it may not large enough to get us too excited. The following is code in R. if(!require(psych)){install.packages("psych")} Men.no.bachelors = 74258000 - 27781000 Men.no.bachelors Women.no.bachelors = 64901000 - 27465000 Women.no.bachelors Input =(" Sex No.bachelors Bachelors Men 46477000 27781000 Women 37436000 27465000 ") Matrix = as.matrix(read.table(textConnection(Input), header=TRUE, row.names=1)) prop.table(Matrix, margin=1) ### c No.bachelors Bachelors ### Men 0.6258854 0.3741146 ### Women 0.5768170 0.4231830 library(psych) phi(Matrix, digits = 4) ### [1] 0.05 References Cohen, J. 1988. Statistical Power Analysis for the Behavioral Sciences, 2nd Edition. Routledge.
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, age
I'll weigh in with one point, but make it an answer so I can include some code and results. I think the way I would approach the question is to consider the effect size. If I have understood the quest
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, ages 25 and up) (disparity, difference) I'll weigh in with one point, but make it an answer so I can include some code and results. I think the way I would approach the question is to consider the effect size. If I have understood the question and data correctly, phi for the appropriate table comes out to 0.05. Cohen (1988) interprets this value as less than "small". Obviously, any interpretation of effect size is relative to the discipline and intention of the analysis. But the size of the effect does suggest that it may not large enough to get us too excited. The following is code in R. if(!require(psych)){install.packages("psych")} Men.no.bachelors = 74258000 - 27781000 Men.no.bachelors Women.no.bachelors = 64901000 - 27465000 Women.no.bachelors Input =(" Sex No.bachelors Bachelors Men 46477000 27781000 Women 37436000 27465000 ") Matrix = as.matrix(read.table(textConnection(Input), header=TRUE, row.names=1)) prop.table(Matrix, margin=1) ### c No.bachelors Bachelors ### Men 0.6258854 0.3741146 ### Women 0.5768170 0.4231830 library(psych) phi(Matrix, digits = 4) ### [1] 0.05 References Cohen, J. 1988. Statistical Power Analysis for the Behavioral Sciences, 2nd Edition. Routledge.
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, age I'll weigh in with one point, but make it an answer so I can include some code and results. I think the way I would approach the question is to consider the effect size. If I have understood the quest
48,403
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, ages 25 and up) (disparity, difference)
There are a few confusions at the base of this question that need to be addressed at the outset. As stated, your question asks about sex differences in the attainment of tertiary degrees; this question makes no mention of workforce participation, and hence, data on that metric is not relevant to your question as it is presently stated. However, your use of the data suggests that you are actually interested in sex differences in the attainment of tertiary degrees only among adults participating in the workforce. For the remainder of this post I am going to assume that your question is misstated, and your actual interest is in the latter issue. If you are interested in sex differences across the whole of the corresponding adult population (i.e., all U.S. civilians age 25 and over, including those not in the workforce) then you should be comparing numbers of tertiary degrees to the number of men and women in the population, and you would need to get estimates of those values. Having made an assumption about your interest here, the next step is to recognise that you are using outputs from census surveys. These outputs are not data - they are population estimates calculated from raw data held by the census bureau. The estimates should be accompanied by estimates of standard error, so you will need to obtain that information from the census material to get an idea of the accuracy of these estimates. Using the 95% CIs you have given, it is simple to reverse-engineer the standard errors of the estimates, which gives the following information: Civilian Labour Force With Tertiary Degrees Estimate | Std Err Estimate | Std Err Men 74,258,000 | 317814.0 27,781,000 | 310309.3 Women 64,901,000 | 313862.4 27,465,000 | 309710.3 As other commentators have pointed out in the comments to your post, these estimates come from complex survey techniques that generally use stratified sampling methods combined with complex inferential methods. Ideally you would approach this matter by obtaining the raw census data and using this to get a direct estimate of the proportion of tertiary degree holders of each sex, with appropriate standard errors. I am going to assume that this raw data is not available, or even if it is, that this kind of analysis is too onerous. The next best thing would be to use the above estimates as your "data" and perform your test using this information. This involves the analysis of a $2 \times 2$ contingency table with misclassification, with estimated standard errors for this misclassification being given in your census information. There is a substantial amount of literature on the analysis of contingency tables with misclassification, and this is a fairly complex area, owing to the variations on the problem and the difficulties of analysis. In your particular case you have estimated totals for the tertiary-degree holders of each sex and the row totals of all men and women in the labour force, and both are subject to misclassification error with estimated standard errors given. My suggestion: If you would like to conduct a formal test for sex differences in the proportion of tertiary degree-holders, I would suggest that your next job is to review the literature on the analysis of contingency tables with misclassification. Having a look at the numbers, I think it is obvious that you are going to see statistically significant evidence of a difference, but this is because you are comparing the sexes based only on people in the workforce. If you were to use population estimates that include people not in the workforce then I would imagine that this difference vanishes.
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, age
There are a few confusions at the base of this question that need to be addressed at the outset. As stated, your question asks about sex differences in the attainment of tertiary degrees; this questi
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, ages 25 and up) (disparity, difference) There are a few confusions at the base of this question that need to be addressed at the outset. As stated, your question asks about sex differences in the attainment of tertiary degrees; this question makes no mention of workforce participation, and hence, data on that metric is not relevant to your question as it is presently stated. However, your use of the data suggests that you are actually interested in sex differences in the attainment of tertiary degrees only among adults participating in the workforce. For the remainder of this post I am going to assume that your question is misstated, and your actual interest is in the latter issue. If you are interested in sex differences across the whole of the corresponding adult population (i.e., all U.S. civilians age 25 and over, including those not in the workforce) then you should be comparing numbers of tertiary degrees to the number of men and women in the population, and you would need to get estimates of those values. Having made an assumption about your interest here, the next step is to recognise that you are using outputs from census surveys. These outputs are not data - they are population estimates calculated from raw data held by the census bureau. The estimates should be accompanied by estimates of standard error, so you will need to obtain that information from the census material to get an idea of the accuracy of these estimates. Using the 95% CIs you have given, it is simple to reverse-engineer the standard errors of the estimates, which gives the following information: Civilian Labour Force With Tertiary Degrees Estimate | Std Err Estimate | Std Err Men 74,258,000 | 317814.0 27,781,000 | 310309.3 Women 64,901,000 | 313862.4 27,465,000 | 309710.3 As other commentators have pointed out in the comments to your post, these estimates come from complex survey techniques that generally use stratified sampling methods combined with complex inferential methods. Ideally you would approach this matter by obtaining the raw census data and using this to get a direct estimate of the proportion of tertiary degree holders of each sex, with appropriate standard errors. I am going to assume that this raw data is not available, or even if it is, that this kind of analysis is too onerous. The next best thing would be to use the above estimates as your "data" and perform your test using this information. This involves the analysis of a $2 \times 2$ contingency table with misclassification, with estimated standard errors for this misclassification being given in your census information. There is a substantial amount of literature on the analysis of contingency tables with misclassification, and this is a fairly complex area, owing to the variations on the problem and the difficulties of analysis. In your particular case you have estimated totals for the tertiary-degree holders of each sex and the row totals of all men and women in the labour force, and both are subject to misclassification error with estimated standard errors given. My suggestion: If you would like to conduct a formal test for sex differences in the proportion of tertiary degree-holders, I would suggest that your next job is to review the literature on the analysis of contingency tables with misclassification. Having a look at the numbers, I think it is obvious that you are going to see statistically significant evidence of a difference, but this is because you are comparing the sexes based only on people in the workforce. If you were to use population estimates that include people not in the workforce then I would imagine that this difference vanishes.
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, age There are a few confusions at the base of this question that need to be addressed at the outset. As stated, your question asks about sex differences in the attainment of tertiary degrees; this questi
48,404
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, ages 25 and up) (disparity, difference)
I will focus on the aspect of statistical significance and your calculations and tell why they are wrong. To give a more refined question that talks about 'practical' significance is a bit more difficult. Not only is this topic a bit more subjective (though you can already find several posts on this website about different interpretations of the term 'significance' that at least explains the aspects involved), it is also difficult because your goals are not so clear. Your title has a general question 'relationship between sex and bachelor's degree' but it becomes confusing due to the different ways that one can look at it (absolute numbers, relative, different intersections of ages, etcetera). It is questionable whether the (single) statistic that you use is good for your purpose, and it makes interpretation of 'practical significance' even more subjective/difficult. You should not use the chi-square test the way you do (on derived numbers and not original counts) (I am not sure whether you did this also in your second calculation which is a bit fuzzy, but it is true at least for your first calculation). The (Pearsons) chi-square test uses an estimate of binomial distributed data by approximating with a normal distribution that has the same variance/deviation. But your data is not binomial distributed. The numbers are not direct counts (the chi-square test needs to be applied to count data). Instead the values are obtained from a survey among 60 000 households. This will make your estimate of the relative standard error much smaller than reality. Example (an extreme example to make the point more clear). If you would survey only hundred women and find out that $36$ have a bsc or higher. Then this has an standard deviation of $\sqrt{36}=6$ or $17\%$. However if you recalculate it to the entire female population, say some $36 000 000$ have a bsc or higher, then you'd naively compute a standard deviation of $\sqrt{36 000 000} = 6000$ or $0.017\%$ . Based on the 60 000 households (america has roughly 126 million). You could say that the factor by which the survey-counts are inflated is 2100 (in reality it is a bit more complicated when corrections are added for the composition of households and a weighted sum is made instead of a simple multiplication by 2100). Then the observed counts are more something like (I use https://www.bls.gov/cps/cpsaat07.htm): - total women > 25 yrs: 112 872 000 -> 53 749 - total men > 25 yrs: 104 057 000 -> 49 551 - total working women > 25 yrs: 64 901 000 -> 30 905 - total working men > 25 yrs: 74 258 000 -> 35 361 - working women >25 >=bsc: 27 465 000 -> 13 079 - working men >25 >=bsc: 27 781 000 -> 13 229 The relative s.e. for the estimated fractions will be roughly $\sqrt{\frac{1-\hat{p}}{n\hat{p}}}$ or close to 0.5%. When you take a confidence interval roughly $\pm2SE$ then you have half the 4% which you see in your table (not bad for such simple approach, then there is more than just sampling errors, and also this calculation is just an estimate using the simple factor 2100 which in reality is more complicated). You should not combine the two variables like you do in your second correlation You take the worst case of the maximum and the minimum. But the observations in the sample are likely correlated. If you observe more/less people with a bsc (or higher) and a job then, conditioned on this, you would expect more/less people with a job. You could assume the observation as a contingency table (now you can use a chisquared test since they are original counts, or at least something that resembles it) with the margins fixed (this is not a correct assumption, but much more practical and does not generate too much of an error, if you'd like you could compute more complicated solutions, ie. exact tests): men women total >=bsc 13229 13079 26308 <bsc 22132 17826 39994 total 35361 30905 66302 Then $\chi^2(1) = 165.79$ and $p < 10^{-16}$ So it is still a big significant result. (Why do you think it should be different? Or at least you seem to desire a result that shows it is not significant)
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, age
I will focus on the aspect of statistical significance and your calculations and tell why they are wrong. To give a more refined question that talks about 'practical' significance is a bit more diffi
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, ages 25 and up) (disparity, difference) I will focus on the aspect of statistical significance and your calculations and tell why they are wrong. To give a more refined question that talks about 'practical' significance is a bit more difficult. Not only is this topic a bit more subjective (though you can already find several posts on this website about different interpretations of the term 'significance' that at least explains the aspects involved), it is also difficult because your goals are not so clear. Your title has a general question 'relationship between sex and bachelor's degree' but it becomes confusing due to the different ways that one can look at it (absolute numbers, relative, different intersections of ages, etcetera). It is questionable whether the (single) statistic that you use is good for your purpose, and it makes interpretation of 'practical significance' even more subjective/difficult. You should not use the chi-square test the way you do (on derived numbers and not original counts) (I am not sure whether you did this also in your second calculation which is a bit fuzzy, but it is true at least for your first calculation). The (Pearsons) chi-square test uses an estimate of binomial distributed data by approximating with a normal distribution that has the same variance/deviation. But your data is not binomial distributed. The numbers are not direct counts (the chi-square test needs to be applied to count data). Instead the values are obtained from a survey among 60 000 households. This will make your estimate of the relative standard error much smaller than reality. Example (an extreme example to make the point more clear). If you would survey only hundred women and find out that $36$ have a bsc or higher. Then this has an standard deviation of $\sqrt{36}=6$ or $17\%$. However if you recalculate it to the entire female population, say some $36 000 000$ have a bsc or higher, then you'd naively compute a standard deviation of $\sqrt{36 000 000} = 6000$ or $0.017\%$ . Based on the 60 000 households (america has roughly 126 million). You could say that the factor by which the survey-counts are inflated is 2100 (in reality it is a bit more complicated when corrections are added for the composition of households and a weighted sum is made instead of a simple multiplication by 2100). Then the observed counts are more something like (I use https://www.bls.gov/cps/cpsaat07.htm): - total women > 25 yrs: 112 872 000 -> 53 749 - total men > 25 yrs: 104 057 000 -> 49 551 - total working women > 25 yrs: 64 901 000 -> 30 905 - total working men > 25 yrs: 74 258 000 -> 35 361 - working women >25 >=bsc: 27 465 000 -> 13 079 - working men >25 >=bsc: 27 781 000 -> 13 229 The relative s.e. for the estimated fractions will be roughly $\sqrt{\frac{1-\hat{p}}{n\hat{p}}}$ or close to 0.5%. When you take a confidence interval roughly $\pm2SE$ then you have half the 4% which you see in your table (not bad for such simple approach, then there is more than just sampling errors, and also this calculation is just an estimate using the simple factor 2100 which in reality is more complicated). You should not combine the two variables like you do in your second correlation You take the worst case of the maximum and the minimum. But the observations in the sample are likely correlated. If you observe more/less people with a bsc (or higher) and a job then, conditioned on this, you would expect more/less people with a job. You could assume the observation as a contingency table (now you can use a chisquared test since they are original counts, or at least something that resembles it) with the margins fixed (this is not a correct assumption, but much more practical and does not generate too much of an error, if you'd like you could compute more complicated solutions, ie. exact tests): men women total >=bsc 13229 13079 26308 <bsc 22132 17826 39994 total 35361 30905 66302 Then $\chi^2(1) = 165.79$ and $p < 10^{-16}$ So it is still a big significant result. (Why do you think it should be different? Or at least you seem to desire a result that shows it is not significant)
Significance of relationship between sex and bachelor's degree or higher (2017 U.S. labor force, age I will focus on the aspect of statistical significance and your calculations and tell why they are wrong. To give a more refined question that talks about 'practical' significance is a bit more diffi
48,405
How to set up an intercept-only mixed logistic regression in order to test for difference from 50% chance level?
I think you are confused about the role of intercept in logistic regression. Logistic regression predicts the probability of some outcome, in your case e.g. the probability of the A choice. To do that, it forms a linear combination of predictors and passes it through a logistic function that "squeezes" real numbers from $-\infty$ to $+\infty$ into a $[0,1]$ interval. It looks like that (image from Wikipedia): $\quad\quad\quad\quad$ So if the linear combination has value 0 then the output of logistic function is $p=0.5$. This means that a logistic regression without any predictors whatsoever and with zero intercept predicts 50% chance. If you had 1 data point per subject, you could have used glm(choice ~ 1, family='binomial') and looked at the value and p-value for the intercept. In your case you have more than 1 data point per subject, so you can use glmer(choice ~ 1 + (1|subject), family='binomial')
How to set up an intercept-only mixed logistic regression in order to test for difference from 50% c
I think you are confused about the role of intercept in logistic regression. Logistic regression predicts the probability of some outcome, in your case e.g. the probability of the A choice. To do that
How to set up an intercept-only mixed logistic regression in order to test for difference from 50% chance level? I think you are confused about the role of intercept in logistic regression. Logistic regression predicts the probability of some outcome, in your case e.g. the probability of the A choice. To do that, it forms a linear combination of predictors and passes it through a logistic function that "squeezes" real numbers from $-\infty$ to $+\infty$ into a $[0,1]$ interval. It looks like that (image from Wikipedia): $\quad\quad\quad\quad$ So if the linear combination has value 0 then the output of logistic function is $p=0.5$. This means that a logistic regression without any predictors whatsoever and with zero intercept predicts 50% chance. If you had 1 data point per subject, you could have used glm(choice ~ 1, family='binomial') and looked at the value and p-value for the intercept. In your case you have more than 1 data point per subject, so you can use glmer(choice ~ 1 + (1|subject), family='binomial')
How to set up an intercept-only mixed logistic regression in order to test for difference from 50% c I think you are confused about the role of intercept in logistic regression. Logistic regression predicts the probability of some outcome, in your case e.g. the probability of the A choice. To do that
48,406
How to set up an intercept-only mixed logistic regression in order to test for difference from 50% chance level?
Suggest use of a Binomial test, with $p=0.5$. One common use of the binomial test is in the case where the null hypothesis is that two categories are equally likely to occur (such as a coin toss). Tables are widely available to give the significance observed numbers of observations in the categories for this case. However, the binomial test is not restricted to this case, and can be used for any probability. Edit: The above assumes that each subject is "cut from the same cloth." That is, that the probability, whatever that is, of choosing A or B is the same for each participant, and that each choice of A or B is performed only once. As a counterexample, suppose that subjects 1 and 2 would have perfect discordance in choices between the A and B objects. In that latter hypothetical case, our ability to detect even a perfect bias for each subject would be diminished, e.g., Subject 1 chooses only B 100 times while subject 2 chooses only A 100 times for a $P=0.5$. Clearly, from that hypothetical example, a lack of bias for overall choices is not equivalent to a lack of subject preference. There is not enough information provided about the experiment in the question above nor its participants to model this further. For example, the ability or inability to measure concordance is not presented and we have a perfect absence of context as to what is being adjudicated as A or B and how that occurs. For example, two judges pairwise adjudicating whether the A or B face of a dirty coin is showing is different than two judges adjudicating two separate piles of dirty coins with no overlapping opinions. We do not know if we are asking whether the judges are biased, if the "A vs B" coins are biased, and that neither collectively or separately. This problem is complicated enough, by itself, that it deserves separate treatment, so, I made it into a question of its own elsewhere.
How to set up an intercept-only mixed logistic regression in order to test for difference from 50% c
Suggest use of a Binomial test, with $p=0.5$. One common use of the binomial test is in the case where the null hypothesis is that two categories are equally likely to occur (such as a coin toss). Ta
How to set up an intercept-only mixed logistic regression in order to test for difference from 50% chance level? Suggest use of a Binomial test, with $p=0.5$. One common use of the binomial test is in the case where the null hypothesis is that two categories are equally likely to occur (such as a coin toss). Tables are widely available to give the significance observed numbers of observations in the categories for this case. However, the binomial test is not restricted to this case, and can be used for any probability. Edit: The above assumes that each subject is "cut from the same cloth." That is, that the probability, whatever that is, of choosing A or B is the same for each participant, and that each choice of A or B is performed only once. As a counterexample, suppose that subjects 1 and 2 would have perfect discordance in choices between the A and B objects. In that latter hypothetical case, our ability to detect even a perfect bias for each subject would be diminished, e.g., Subject 1 chooses only B 100 times while subject 2 chooses only A 100 times for a $P=0.5$. Clearly, from that hypothetical example, a lack of bias for overall choices is not equivalent to a lack of subject preference. There is not enough information provided about the experiment in the question above nor its participants to model this further. For example, the ability or inability to measure concordance is not presented and we have a perfect absence of context as to what is being adjudicated as A or B and how that occurs. For example, two judges pairwise adjudicating whether the A or B face of a dirty coin is showing is different than two judges adjudicating two separate piles of dirty coins with no overlapping opinions. We do not know if we are asking whether the judges are biased, if the "A vs B" coins are biased, and that neither collectively or separately. This problem is complicated enough, by itself, that it deserves separate treatment, so, I made it into a question of its own elsewhere.
How to set up an intercept-only mixed logistic regression in order to test for difference from 50% c Suggest use of a Binomial test, with $p=0.5$. One common use of the binomial test is in the case where the null hypothesis is that two categories are equally likely to occur (such as a coin toss). Ta
48,407
Investigate overdispersion in a plot for a poisson regression
One somewhat useful plot would be to plot absolute Pearson residuals against $\sqrt{\hat{y}}$ (or $\hat{y}$ or $\log(\hat{y})$...). It should look flat, and as long as the fitted mean isn't too small the mean value on the y-axis should be roughly about 0.8 (the mean of the squared Pearson residuals should be about 1). If it deviates considerably above 0.8 ($\sqrt{2/\pi}\approx 0.79788$ asymptotically) it's overdispersed, while if it isn't reasonably close to flat the variance-function is misspecified. Here's an example in R: x <- runif(200,3,14) m <- exp(0.3*x-1.5) y <- rpois(m,m) xyglmfit <- glm(y~x,family=poisson) xyfitted <- fitted(xyglmfit) pres <- residuals(xyglmfit,type="pearson") plot((xyfitted)^(1/2),abs(pres)) Note that the left end of the plot should have more skewness than the right end and will tend to have slightly larger values at the top. (That is, if you focus just on the maximum values rather than the middle, you'd expect to see a slight downslope.) It looks fairly flat and the mean looks somewhere in the region of 0.8. We could compute it: mean(abs(pres)) 0.7844303 This is about what we should see. However, if you're using R there's a standard plot there that does essentially the same job, the scale-location plot: plot(xyglmfit,which=3) This plot substitutes deviance residuals for Pearson residuals, which should work a little better at the smaller fitted values. However, the y-axis is now the square root of the scale above (square root of absolute deviance residuals), and the mean value under a correct specification would tend to be a little higher, at about 0.82 ($2^\frac14 \Gamma(\frac34)/\sqrt{\pi}\approx 0.82218$ asymptotically), at least for fitted values that are not too small. I added a blue horizontal line at 0.82 for reference there (via abline(h=0.82,col="blue")). It's also plotting against fitted values on the scale of the linear predictor (i.e. log-fitted), but the basic interpretation is the same -- if the trend is flat and roughly around 0.82, it's about what it should be, if it's higher than that you have overdispersion and if it's not flat you have a variance misspecification. Here we see that everything looks fine. The red curve is a local mean (a smoothed local fit) and the blue line is the asymptotic 0.82 value we should expect. As you see they're almost coincident. Here's a case with overdispersion done in R: y2 <- rpois(m,m)*10+rpois(m,m) xyglmfit2 <- glm(y2~x,family=poisson) xyfitted2 <- fitted(xyglmfit2) pres2 <- residuals(xyglmfit2,type="pearson") par(mfrow=c(1,2)) plot((xyfitted2)^(1/2),abs(pres2)) abline(h=0.8,col="blue") plot(xyglmfit2,which=3) abline(h=0.82,col="blue") The plot on the left is the first plot (with a 0.8 line marked in) and the second is the default scale-location plot in R with the 0.82 horizontal line marked in. We can see that the spread is wider (if we compute the mean square Pearson residual it comes out to about 9, rather than the "about 1" we should get). A caveat: these plots are only interpretable in this fashion if you get the mean specification essentially correct; otherwise you're confounding mean misspecification with variance issues in these plots.
Investigate overdispersion in a plot for a poisson regression
One somewhat useful plot would be to plot absolute Pearson residuals against $\sqrt{\hat{y}}$ (or $\hat{y}$ or $\log(\hat{y})$...). It should look flat, and as long as the fitted mean isn't too small
Investigate overdispersion in a plot for a poisson regression One somewhat useful plot would be to plot absolute Pearson residuals against $\sqrt{\hat{y}}$ (or $\hat{y}$ or $\log(\hat{y})$...). It should look flat, and as long as the fitted mean isn't too small the mean value on the y-axis should be roughly about 0.8 (the mean of the squared Pearson residuals should be about 1). If it deviates considerably above 0.8 ($\sqrt{2/\pi}\approx 0.79788$ asymptotically) it's overdispersed, while if it isn't reasonably close to flat the variance-function is misspecified. Here's an example in R: x <- runif(200,3,14) m <- exp(0.3*x-1.5) y <- rpois(m,m) xyglmfit <- glm(y~x,family=poisson) xyfitted <- fitted(xyglmfit) pres <- residuals(xyglmfit,type="pearson") plot((xyfitted)^(1/2),abs(pres)) Note that the left end of the plot should have more skewness than the right end and will tend to have slightly larger values at the top. (That is, if you focus just on the maximum values rather than the middle, you'd expect to see a slight downslope.) It looks fairly flat and the mean looks somewhere in the region of 0.8. We could compute it: mean(abs(pres)) 0.7844303 This is about what we should see. However, if you're using R there's a standard plot there that does essentially the same job, the scale-location plot: plot(xyglmfit,which=3) This plot substitutes deviance residuals for Pearson residuals, which should work a little better at the smaller fitted values. However, the y-axis is now the square root of the scale above (square root of absolute deviance residuals), and the mean value under a correct specification would tend to be a little higher, at about 0.82 ($2^\frac14 \Gamma(\frac34)/\sqrt{\pi}\approx 0.82218$ asymptotically), at least for fitted values that are not too small. I added a blue horizontal line at 0.82 for reference there (via abline(h=0.82,col="blue")). It's also plotting against fitted values on the scale of the linear predictor (i.e. log-fitted), but the basic interpretation is the same -- if the trend is flat and roughly around 0.82, it's about what it should be, if it's higher than that you have overdispersion and if it's not flat you have a variance misspecification. Here we see that everything looks fine. The red curve is a local mean (a smoothed local fit) and the blue line is the asymptotic 0.82 value we should expect. As you see they're almost coincident. Here's a case with overdispersion done in R: y2 <- rpois(m,m)*10+rpois(m,m) xyglmfit2 <- glm(y2~x,family=poisson) xyfitted2 <- fitted(xyglmfit2) pres2 <- residuals(xyglmfit2,type="pearson") par(mfrow=c(1,2)) plot((xyfitted2)^(1/2),abs(pres2)) abline(h=0.8,col="blue") plot(xyglmfit2,which=3) abline(h=0.82,col="blue") The plot on the left is the first plot (with a 0.8 line marked in) and the second is the default scale-location plot in R with the 0.82 horizontal line marked in. We can see that the spread is wider (if we compute the mean square Pearson residual it comes out to about 9, rather than the "about 1" we should get). A caveat: these plots are only interpretable in this fashion if you get the mean specification essentially correct; otherwise you're confounding mean misspecification with variance issues in these plots.
Investigate overdispersion in a plot for a poisson regression One somewhat useful plot would be to plot absolute Pearson residuals against $\sqrt{\hat{y}}$ (or $\hat{y}$ or $\log(\hat{y})$...). It should look flat, and as long as the fitted mean isn't too small
48,408
Principal Components of Random Walk
I actually recently wrote a paper on this subject which will appear at NIPS 2018: https://arxiv.org/abs/1806.08805 My collaborator and I proved that in the limit of an infinite number of dimensions the projection of a random walk onto any PCA component is a sinusoid. You are welcome to read the paper for the proof, but perhaps I can attempt a slightly more intuitive explanation. The random walk process is a translation invariant process. No matter how many steps you take and how far away you get from the origin, the process that determines the next step is exactly the same. (This is in contrast to an Ornstein-Uhlenbeck process, for example, which is a random walk in a quadratic well. In this case the process that determines what your next step will be depends on your distance from the origin.) Now, the eigenfunctions of any translation invariant operator are Fourier modes. Why is this? Well, in order to be translation invariant, the eigenfunctions need to be periodic, and in order to be an orthogonal basis, they need to be mutually orthogonal. The set of functions that satisfies these properties is the Fourier basis. As for your second question about two independent random walks seeming to be correlated, this is just an illusion. Although the projection of the trajectory of both random walks onto their first PCA component will be a cosine, the direction of the first PCA component will be completely random. An an analogy, if you do two random walks, each of 10^6 steps, you can be quite sure that both will end up at a distance of about 1000 from the origin. But the two walks had nothing to do with each other, and furthermore the direction that the walk happened to go will be different each time.
Principal Components of Random Walk
I actually recently wrote a paper on this subject which will appear at NIPS 2018: https://arxiv.org/abs/1806.08805 My collaborator and I proved that in the limit of an infinite number of dimensions th
Principal Components of Random Walk I actually recently wrote a paper on this subject which will appear at NIPS 2018: https://arxiv.org/abs/1806.08805 My collaborator and I proved that in the limit of an infinite number of dimensions the projection of a random walk onto any PCA component is a sinusoid. You are welcome to read the paper for the proof, but perhaps I can attempt a slightly more intuitive explanation. The random walk process is a translation invariant process. No matter how many steps you take and how far away you get from the origin, the process that determines the next step is exactly the same. (This is in contrast to an Ornstein-Uhlenbeck process, for example, which is a random walk in a quadratic well. In this case the process that determines what your next step will be depends on your distance from the origin.) Now, the eigenfunctions of any translation invariant operator are Fourier modes. Why is this? Well, in order to be translation invariant, the eigenfunctions need to be periodic, and in order to be an orthogonal basis, they need to be mutually orthogonal. The set of functions that satisfies these properties is the Fourier basis. As for your second question about two independent random walks seeming to be correlated, this is just an illusion. Although the projection of the trajectory of both random walks onto their first PCA component will be a cosine, the direction of the first PCA component will be completely random. An an analogy, if you do two random walks, each of 10^6 steps, you can be quite sure that both will end up at a distance of about 1000 from the origin. But the two walks had nothing to do with each other, and furthermore the direction that the walk happened to go will be different each time.
Principal Components of Random Walk I actually recently wrote a paper on this subject which will appear at NIPS 2018: https://arxiv.org/abs/1806.08805 My collaborator and I proved that in the limit of an infinite number of dimensions th
48,409
Estimate the variance of Gaussian distribution from noisy sample
I would answer this question through the use of bayesian estimation with a "non-informative" prior. notation and setup Data model... $(y_i|\mu,\sigma^2)\sim N(\mu,\sigma^2+\sigma_e^2) $ for $i=1,\dots,n $ Prior... $p (\mu,\sigma^2)\propto(\sigma^2+\sigma_e^2)^{-2} $ The prior is not favouring one source. We have $\frac {\sigma^2}{\sigma^2+\sigma_e^2}\sim U (0,1) $ - the variance proportion is uniformly distributed in the prior. Now all this leads to a marginal posterior for $\sigma^2$ of $$p (\sigma^2|DI)\propto(\sigma^2+\sigma_e^2)^{-(n+1)/2-1}\exp\left(-\frac {(n-1)s^2}{2(\sigma^2+\sigma_e^2)}\right)$$ This is a "truncated" inverse gamma distribution for $(\sigma^2+\sigma_e^2)$ with shape parameter $\frac {n+1}{2} $ and scale parameter $\frac {(n-1)s^2}{2} $ where $s^2=\frac {1}{n-1}\sum_{i=1}^n (y_i-\overline {y})^2$ and $\overline {y}=\frac {1}{n}\sum_{i=1}^n y_i $. The truncation is that $(\sigma^2+\sigma_e^2)>\sigma_e^2$ how to make use of this First I would check if the truncation matters by calculating the probability that $(\sigma^2+\sigma_e^2)\leq \sigma_e^2$ using the inverse gamma cdf. A quick "eyeball" check can also be that $s^2>>\sigma_e^2$ (i.e. most of the variation in the data does not comes from measurement error). If the truncation is not important, we can just use the normal inverse gamma. The expected value of the above posterior is $E(\sigma^2|DI)\approx s^2-\sigma_e^2$ and the variance is given as $$var(\sigma^2|DI)=var(\sigma^2+\sigma_e^2|DI)\approx\frac {2}{n-3}\left [E(\sigma^2+\sigma_e^2|DI)\right]^2\approx\frac {2}{n-3}s^4$$. You need to have $n>3$ to apply these formulae. This is pretty much your expression but with $\sigma^2$ replaced by $s^2$. If the truncation matters, the you'll need to work in terms of the incomplete gamma function. If you define the function $f (k)=\gamma \left (\frac {n+1}{2}+k, \frac {(n-1)s^2}{2\sigma_e^2}\right)$ then you have....for the expected value... $$E (\sigma^2|DI)=s^2\frac{n-1}{2}\frac {f(-1)}{f (0)}-\sigma_e^2$$ And the variance is given by $$var (\sigma^2|DI)=\left [E(\sigma^2+\sigma_e^2|DI)\right]^2\left [\frac{f (-2)f (0)}{f (-1)^2} - 1\right]$$
Estimate the variance of Gaussian distribution from noisy sample
I would answer this question through the use of bayesian estimation with a "non-informative" prior. notation and setup Data model... $(y_i|\mu,\sigma^2)\sim N(\mu,\sigma^2+\sigma_e^2) $ for $i=1,\dots
Estimate the variance of Gaussian distribution from noisy sample I would answer this question through the use of bayesian estimation with a "non-informative" prior. notation and setup Data model... $(y_i|\mu,\sigma^2)\sim N(\mu,\sigma^2+\sigma_e^2) $ for $i=1,\dots,n $ Prior... $p (\mu,\sigma^2)\propto(\sigma^2+\sigma_e^2)^{-2} $ The prior is not favouring one source. We have $\frac {\sigma^2}{\sigma^2+\sigma_e^2}\sim U (0,1) $ - the variance proportion is uniformly distributed in the prior. Now all this leads to a marginal posterior for $\sigma^2$ of $$p (\sigma^2|DI)\propto(\sigma^2+\sigma_e^2)^{-(n+1)/2-1}\exp\left(-\frac {(n-1)s^2}{2(\sigma^2+\sigma_e^2)}\right)$$ This is a "truncated" inverse gamma distribution for $(\sigma^2+\sigma_e^2)$ with shape parameter $\frac {n+1}{2} $ and scale parameter $\frac {(n-1)s^2}{2} $ where $s^2=\frac {1}{n-1}\sum_{i=1}^n (y_i-\overline {y})^2$ and $\overline {y}=\frac {1}{n}\sum_{i=1}^n y_i $. The truncation is that $(\sigma^2+\sigma_e^2)>\sigma_e^2$ how to make use of this First I would check if the truncation matters by calculating the probability that $(\sigma^2+\sigma_e^2)\leq \sigma_e^2$ using the inverse gamma cdf. A quick "eyeball" check can also be that $s^2>>\sigma_e^2$ (i.e. most of the variation in the data does not comes from measurement error). If the truncation is not important, we can just use the normal inverse gamma. The expected value of the above posterior is $E(\sigma^2|DI)\approx s^2-\sigma_e^2$ and the variance is given as $$var(\sigma^2|DI)=var(\sigma^2+\sigma_e^2|DI)\approx\frac {2}{n-3}\left [E(\sigma^2+\sigma_e^2|DI)\right]^2\approx\frac {2}{n-3}s^4$$. You need to have $n>3$ to apply these formulae. This is pretty much your expression but with $\sigma^2$ replaced by $s^2$. If the truncation matters, the you'll need to work in terms of the incomplete gamma function. If you define the function $f (k)=\gamma \left (\frac {n+1}{2}+k, \frac {(n-1)s^2}{2\sigma_e^2}\right)$ then you have....for the expected value... $$E (\sigma^2|DI)=s^2\frac{n-1}{2}\frac {f(-1)}{f (0)}-\sigma_e^2$$ And the variance is given by $$var (\sigma^2|DI)=\left [E(\sigma^2+\sigma_e^2|DI)\right]^2\left [\frac{f (-2)f (0)}{f (-1)^2} - 1\right]$$
Estimate the variance of Gaussian distribution from noisy sample I would answer this question through the use of bayesian estimation with a "non-informative" prior. notation and setup Data model... $(y_i|\mu,\sigma^2)\sim N(\mu,\sigma^2+\sigma_e^2) $ for $i=1,\dots
48,410
Estimate the variance of Gaussian distribution from noisy sample
If (using the notation of the answer from @probabilityislogic) $\sigma_e^2$ is known, then the maximum likelihood estimator of $\sigma^2$ is $$\hat{\sigma}^2={{n-1}\over{n}}s^2-\sigma_e^2$$ (or rather the maximum of this and zero). The estimate of the asymptotic variance of $\hat{\sigma}^2$ is given by $$\frac{2 (n-1)^2 s^4}{n^3}$$ which for large $n$ is very close to $$\frac{2s^4}{n}$$ And this is very similar to your result although by $\sigma^2$ you must mean $\sigma^2+\sigma_e^2$. So your formula is consistent with the asymptotic theory. Maybe you could expand on what you mean by "seems to be too small" and why you think that.
Estimate the variance of Gaussian distribution from noisy sample
If (using the notation of the answer from @probabilityislogic) $\sigma_e^2$ is known, then the maximum likelihood estimator of $\sigma^2$ is $$\hat{\sigma}^2={{n-1}\over{n}}s^2-\sigma_e^2$$ (or rather
Estimate the variance of Gaussian distribution from noisy sample If (using the notation of the answer from @probabilityislogic) $\sigma_e^2$ is known, then the maximum likelihood estimator of $\sigma^2$ is $$\hat{\sigma}^2={{n-1}\over{n}}s^2-\sigma_e^2$$ (or rather the maximum of this and zero). The estimate of the asymptotic variance of $\hat{\sigma}^2$ is given by $$\frac{2 (n-1)^2 s^4}{n^3}$$ which for large $n$ is very close to $$\frac{2s^4}{n}$$ And this is very similar to your result although by $\sigma^2$ you must mean $\sigma^2+\sigma_e^2$. So your formula is consistent with the asymptotic theory. Maybe you could expand on what you mean by "seems to be too small" and why you think that.
Estimate the variance of Gaussian distribution from noisy sample If (using the notation of the answer from @probabilityislogic) $\sigma_e^2$ is known, then the maximum likelihood estimator of $\sigma^2$ is $$\hat{\sigma}^2={{n-1}\over{n}}s^2-\sigma_e^2$$ (or rather
48,411
About specifying independent priors for each parameter in bayesian modeling
They are specified as independent when you do not want to assume that they are a priori informative about each other. That is, knowing the value of one would not change your mind about any of the others, before seeing any data. If, on the other hand, you thought that e.g. larger means tended to correspond to smaller standard deviation you would specify $p(\mu, \sigma)$ such that $\mu$ and $\sigma$ were negatively correlated. In that case it would only make sense to talk about $p(\mu, \sigma)$ as the prior over $\mu$ and $\sigma$. Although the marginals $p(\mu)$ and $p(\sigma)$ certainly exist -- just integrate out $\sigma$ from $p(\mu, \sigma)$ to get $p(\mu)$ for example -- the product $p(\mu)p(\sigma)$ isn't the prior. When the two quantities have independent priors, of course, it is, because $p(\mu)p(\sigma) = p(\mu, \sigma)$ by definition. Hence it is always possible to describe the prior of each parameter separately, but those are only marginals of the actual prior, which you can't recover from them unless it just happens to be a product. To get your intuition going to begin with, it's helpful to follow the book in thinking of the the prior as a big multivariate thing, which all gets updated in the light of data, rather than the end result of a lot of little priors. In some happy circumstances we might model some of the big thing's component parts as informationally uncoupled, and in still happier circumstances we can think of it decomposing into a product of univariate distributions, but these are special cases.
About specifying independent priors for each parameter in bayesian modeling
They are specified as independent when you do not want to assume that they are a priori informative about each other. That is, knowing the value of one would not change your mind about any of the oth
About specifying independent priors for each parameter in bayesian modeling They are specified as independent when you do not want to assume that they are a priori informative about each other. That is, knowing the value of one would not change your mind about any of the others, before seeing any data. If, on the other hand, you thought that e.g. larger means tended to correspond to smaller standard deviation you would specify $p(\mu, \sigma)$ such that $\mu$ and $\sigma$ were negatively correlated. In that case it would only make sense to talk about $p(\mu, \sigma)$ as the prior over $\mu$ and $\sigma$. Although the marginals $p(\mu)$ and $p(\sigma)$ certainly exist -- just integrate out $\sigma$ from $p(\mu, \sigma)$ to get $p(\mu)$ for example -- the product $p(\mu)p(\sigma)$ isn't the prior. When the two quantities have independent priors, of course, it is, because $p(\mu)p(\sigma) = p(\mu, \sigma)$ by definition. Hence it is always possible to describe the prior of each parameter separately, but those are only marginals of the actual prior, which you can't recover from them unless it just happens to be a product. To get your intuition going to begin with, it's helpful to follow the book in thinking of the the prior as a big multivariate thing, which all gets updated in the light of data, rather than the end result of a lot of little priors. In some happy circumstances we might model some of the big thing's component parts as informationally uncoupled, and in still happier circumstances we can think of it decomposing into a product of univariate distributions, but these are special cases.
About specifying independent priors for each parameter in bayesian modeling They are specified as independent when you do not want to assume that they are a priori informative about each other. That is, knowing the value of one would not change your mind about any of the oth
48,412
Which regression analysis should I use for ranked data?
It sounds like you have the potential for two different models here, one that predicts rank and one that predicts premium. For the rank model, something like an ordinal logistic regression may be appropriate. For the premium model, a linear regression may work. Both models can accommodate continuous and categorical predictors and can be implemented in a number of software packages. Something to consider in your dataset is the concept of nesting. By that I mean that some observations may violate the assumption of independence required by both of these models. Specifically, you can certainly imagine a scenario in which, for a variety of reasons, individual cases from the same state or an even smaller geographic region share certain characteristics that increase their similarity to each each other and their dissimilarity with the remaining cases in the set. Technically, this becomes an issue of correlated error terms in your model (i.e., the model tends to incorrectly predict values for sets of cases in the same way), which is a violation of one of the key assumptions of models I mentioned above. Should you find that your data are nested or there is reason to believe that something like the scenario I describe above applies, you can use a multilevel extension of the models I mentioned. Again numerous software packages exist that offer implementation of this slightly more complex family of models.
Which regression analysis should I use for ranked data?
It sounds like you have the potential for two different models here, one that predicts rank and one that predicts premium. For the rank model, something like an ordinal logistic regression may be app
Which regression analysis should I use for ranked data? It sounds like you have the potential for two different models here, one that predicts rank and one that predicts premium. For the rank model, something like an ordinal logistic regression may be appropriate. For the premium model, a linear regression may work. Both models can accommodate continuous and categorical predictors and can be implemented in a number of software packages. Something to consider in your dataset is the concept of nesting. By that I mean that some observations may violate the assumption of independence required by both of these models. Specifically, you can certainly imagine a scenario in which, for a variety of reasons, individual cases from the same state or an even smaller geographic region share certain characteristics that increase their similarity to each each other and their dissimilarity with the remaining cases in the set. Technically, this becomes an issue of correlated error terms in your model (i.e., the model tends to incorrectly predict values for sets of cases in the same way), which is a violation of one of the key assumptions of models I mentioned above. Should you find that your data are nested or there is reason to believe that something like the scenario I describe above applies, you can use a multilevel extension of the models I mentioned. Again numerous software packages exist that offer implementation of this slightly more complex family of models.
Which regression analysis should I use for ranked data? It sounds like you have the potential for two different models here, one that predicts rank and one that predicts premium. For the rank model, something like an ordinal logistic regression may be app
48,413
Naïve Bayes Theorem for multiple features
Naive Bayes algorithm assumes that your features are independent (hence we call it "naive", since it makes the naive assumption about independence, so we don't have to care about dependencies between them). What follows, we model $$ \begin{align} p(C_k, x_1, x_2, ..., x_n) &\propto p(x_1 | C_k) \, p(x_2 | C_k) \dots p(x_n | C_k) \, p(C_k) \\ &= \prod_{i=1}^n p(x_i|C_k) \, p(C_k) \end{align} $$ This follow from the Bayes theorem and independence. So in your example today = (sunny, cool, high, strong), you look at $p($day = sunny $|$ play = yes $)$, and $p($outlook = cool $|$ play = yes $)$, etc. For more details see the great Wikipedia article on naive Bayes algorithm, the Understanding Naive Bayes thread on our site and the A simple explanation of Naive Bayes Classification thread on StackOverflow.com.
Naïve Bayes Theorem for multiple features
Naive Bayes algorithm assumes that your features are independent (hence we call it "naive", since it makes the naive assumption about independence, so we don't have to care about dependencies between
Naïve Bayes Theorem for multiple features Naive Bayes algorithm assumes that your features are independent (hence we call it "naive", since it makes the naive assumption about independence, so we don't have to care about dependencies between them). What follows, we model $$ \begin{align} p(C_k, x_1, x_2, ..., x_n) &\propto p(x_1 | C_k) \, p(x_2 | C_k) \dots p(x_n | C_k) \, p(C_k) \\ &= \prod_{i=1}^n p(x_i|C_k) \, p(C_k) \end{align} $$ This follow from the Bayes theorem and independence. So in your example today = (sunny, cool, high, strong), you look at $p($day = sunny $|$ play = yes $)$, and $p($outlook = cool $|$ play = yes $)$, etc. For more details see the great Wikipedia article on naive Bayes algorithm, the Understanding Naive Bayes thread on our site and the A simple explanation of Naive Bayes Classification thread on StackOverflow.com.
Naïve Bayes Theorem for multiple features Naive Bayes algorithm assumes that your features are independent (hence we call it "naive", since it makes the naive assumption about independence, so we don't have to care about dependencies between
48,414
Why do we need density in estimation and cumulative distribution in transformation?
I guess that what you mean is maximum likelihood estimation scenario, where we consider some value $\hat \theta$ as the best guess for $\theta$ if it maximizes the likelihood function: $$ L(\theta) = \prod_{i=1}^n f(x_i|\theta) $$ Imagine a simple model, where we want to estimate the mean of normal distribution with known standard deviation $\sigma$, say that instead probability density function you used cumulative density function and tried to maximize $\prod_{i=1}^n F(x_i|\mu)$, then no matter of what your data is the perfect choice for $\mu$ is $-\infty$ since $\Pr(X -\infty \le x) = 1$ for any $x$, so the function reaches it's maximum at such value. Same said visually, look at the following plot, it shows standard normal density function (black) and standard normal cumulative distribution function (gray). The most probable value is $X=\mu=0$, where the density distribution peaks. On another hand, the density at $X=\infty$ is zero, while $\Pr(X=\infty)=1$. Cumulative distribution function does not let you to find the peak by looking at its maximum.
Why do we need density in estimation and cumulative distribution in transformation?
I guess that what you mean is maximum likelihood estimation scenario, where we consider some value $\hat \theta$ as the best guess for $\theta$ if it maximizes the likelihood function: $$ L(\theta) =
Why do we need density in estimation and cumulative distribution in transformation? I guess that what you mean is maximum likelihood estimation scenario, where we consider some value $\hat \theta$ as the best guess for $\theta$ if it maximizes the likelihood function: $$ L(\theta) = \prod_{i=1}^n f(x_i|\theta) $$ Imagine a simple model, where we want to estimate the mean of normal distribution with known standard deviation $\sigma$, say that instead probability density function you used cumulative density function and tried to maximize $\prod_{i=1}^n F(x_i|\mu)$, then no matter of what your data is the perfect choice for $\mu$ is $-\infty$ since $\Pr(X -\infty \le x) = 1$ for any $x$, so the function reaches it's maximum at such value. Same said visually, look at the following plot, it shows standard normal density function (black) and standard normal cumulative distribution function (gray). The most probable value is $X=\mu=0$, where the density distribution peaks. On another hand, the density at $X=\infty$ is zero, while $\Pr(X=\infty)=1$. Cumulative distribution function does not let you to find the peak by looking at its maximum.
Why do we need density in estimation and cumulative distribution in transformation? I guess that what you mean is maximum likelihood estimation scenario, where we consider some value $\hat \theta$ as the best guess for $\theta$ if it maximizes the likelihood function: $$ L(\theta) =
48,415
Find the MSE of a true response and its predicted value using OLS estimation
Here are two facts that we can utilize: if $A$ is a constant matrix, then $$\operatorname{E}[AX]=A\operatorname{E}[X],\qquad\operatorname{Var}(AX)=A\operatorname{Var}(X)A'.$$ For convenience let's denote $\hat{y}=f(\mathbf{x};\mathcal{D})$. Notice that $\operatorname{E}_{\mathcal{D}}\left[\left(\hat{y}-\operatorname{E}[\hat{y}]\right)^2\right]$ is just a fancy way of writing $\operatorname{Var}_{\mathcal{D}}(\hat{y})=\operatorname{Var}_{\mathcal{D}}(x'(X'X)^{-1}X'y)$. Thus, $$\operatorname{E}_{\mathcal{D}}\left[\left(\hat{y}-\operatorname{E}[\hat{y}]\right)^2\right]=x'(X'X)^{-1}X'\operatorname{Var}_{\mathcal{D}}(y)X(X'X)^{-1}x=x'(X'X)^{-1}x.$$ On the other hand, you already know that $\operatorname{E}_{\mathcal{D}}[\hat{y}]=x'\theta$, since $\operatorname{E}[\eta]=0$, the bias part $$\operatorname{E}_{\mathcal{D}}[\hat{y}]-\operatorname{E}[y\mid x]=0$$ as well. Therefore, the MSE over one test point $x$ is $$\operatorname{MSE}(x)=1+x'(X'X)^{-1}x.$$ To average over the test set, note that $$x'(X'X)^{-1}x=\operatorname{tr}(x'(X'X)^{-1}x)=\operatorname{tr}((X'X)^{-1}xx').$$ So $$\operatorname{E}_x[x'(X'X)^{-1}x]=\operatorname{tr}((X'X)^{-1}\operatorname{E}_x(xx')).$$
Find the MSE of a true response and its predicted value using OLS estimation
Here are two facts that we can utilize: if $A$ is a constant matrix, then $$\operatorname{E}[AX]=A\operatorname{E}[X],\qquad\operatorname{Var}(AX)=A\operatorname{Var}(X)A'.$$ For convenience let's den
Find the MSE of a true response and its predicted value using OLS estimation Here are two facts that we can utilize: if $A$ is a constant matrix, then $$\operatorname{E}[AX]=A\operatorname{E}[X],\qquad\operatorname{Var}(AX)=A\operatorname{Var}(X)A'.$$ For convenience let's denote $\hat{y}=f(\mathbf{x};\mathcal{D})$. Notice that $\operatorname{E}_{\mathcal{D}}\left[\left(\hat{y}-\operatorname{E}[\hat{y}]\right)^2\right]$ is just a fancy way of writing $\operatorname{Var}_{\mathcal{D}}(\hat{y})=\operatorname{Var}_{\mathcal{D}}(x'(X'X)^{-1}X'y)$. Thus, $$\operatorname{E}_{\mathcal{D}}\left[\left(\hat{y}-\operatorname{E}[\hat{y}]\right)^2\right]=x'(X'X)^{-1}X'\operatorname{Var}_{\mathcal{D}}(y)X(X'X)^{-1}x=x'(X'X)^{-1}x.$$ On the other hand, you already know that $\operatorname{E}_{\mathcal{D}}[\hat{y}]=x'\theta$, since $\operatorname{E}[\eta]=0$, the bias part $$\operatorname{E}_{\mathcal{D}}[\hat{y}]-\operatorname{E}[y\mid x]=0$$ as well. Therefore, the MSE over one test point $x$ is $$\operatorname{MSE}(x)=1+x'(X'X)^{-1}x.$$ To average over the test set, note that $$x'(X'X)^{-1}x=\operatorname{tr}(x'(X'X)^{-1}x)=\operatorname{tr}((X'X)^{-1}xx').$$ So $$\operatorname{E}_x[x'(X'X)^{-1}x]=\operatorname{tr}((X'X)^{-1}\operatorname{E}_x(xx')).$$
Find the MSE of a true response and its predicted value using OLS estimation Here are two facts that we can utilize: if $A$ is a constant matrix, then $$\operatorname{E}[AX]=A\operatorname{E}[X],\qquad\operatorname{Var}(AX)=A\operatorname{Var}(X)A'.$$ For convenience let's den
48,416
Quantile regression - "check function"
The check function stems from applying an optimization view of expressing the $\tau$-th sample quantile of a sample $\{Y_1, \ldots, Y_n\}$. Conventionally, given an observed sample $Y_1, \ldots, Y_n$, the $\tau$-th sample quantile $\hat{Q}_Y(\tau)$ is defined by ranking, i.e., $\hat{Q}_Y(\tau)$ is the $\lfloor n\tau \rfloor$-th order statistic of $(Y_1, \ldots, Y_n)$. In a completely different point of view, it can be shown that it is also the solution of the following optimization problem: $$\hat{Q}_Y(\tau) = \text{argmin}_{\xi} \sum_{i = 1}^n \rho_\tau(Y_i - \xi). \tag{1}$$ An intuitive proof of this fact can be found in Qunantile Regression (2005), Section 1.3, by Roger Koenker. In view of $(1)$, the $\tau$-th sample quantile receives a new interpretation as the minimizer of some loss function which is determined by the check function $\rho_\tau(\cdot)$. This is in agreement with more standardized results for the least-squares estimate and the least-absolute-deviation estimate, as the following chart shows: The extension from the one-sample problem above to the regression setting is straightforward, which simply replaces the $\xi$ in $(1)$ by the regression function $x'b$ (yes, the aim here is to minimize the total "loss" of residuals, where "loss" is clearly defined by the $\rho_\tau(\cdot)$: $$\hat{\beta}(\tau) = \text{argmin}_{b \in \mathbb{R}^p} \sum_{i = 1}^n \rho_\tau(Y_i - x_i'b).$$ $\hat{\beta}(\tau)$ is referred to as $\tau$-th regression quantile, which, by virtue of the property of $\rho_\tau(\cdot)$, also bears some interesting ordering interpretation relative to the fitted regression quantile surface $y = x'\hat{\beta}(\tau)$, for details, see remark on page 40 of Regression Quantiles (1978) by Koenker and Bassett. In summary, the check function is a loss function that retrieves the $\tau$-th sample quantile, and more importantly, that makes the generalization from the one-sample problem (where ordering is possible) to the regression problem (where ordering is rather awkward) practical.
Quantile regression - "check function"
The check function stems from applying an optimization view of expressing the $\tau$-th sample quantile of a sample $\{Y_1, \ldots, Y_n\}$. Conventionally, given an observed sample $Y_1, \ldots, Y_n$
Quantile regression - "check function" The check function stems from applying an optimization view of expressing the $\tau$-th sample quantile of a sample $\{Y_1, \ldots, Y_n\}$. Conventionally, given an observed sample $Y_1, \ldots, Y_n$, the $\tau$-th sample quantile $\hat{Q}_Y(\tau)$ is defined by ranking, i.e., $\hat{Q}_Y(\tau)$ is the $\lfloor n\tau \rfloor$-th order statistic of $(Y_1, \ldots, Y_n)$. In a completely different point of view, it can be shown that it is also the solution of the following optimization problem: $$\hat{Q}_Y(\tau) = \text{argmin}_{\xi} \sum_{i = 1}^n \rho_\tau(Y_i - \xi). \tag{1}$$ An intuitive proof of this fact can be found in Qunantile Regression (2005), Section 1.3, by Roger Koenker. In view of $(1)$, the $\tau$-th sample quantile receives a new interpretation as the minimizer of some loss function which is determined by the check function $\rho_\tau(\cdot)$. This is in agreement with more standardized results for the least-squares estimate and the least-absolute-deviation estimate, as the following chart shows: The extension from the one-sample problem above to the regression setting is straightforward, which simply replaces the $\xi$ in $(1)$ by the regression function $x'b$ (yes, the aim here is to minimize the total "loss" of residuals, where "loss" is clearly defined by the $\rho_\tau(\cdot)$: $$\hat{\beta}(\tau) = \text{argmin}_{b \in \mathbb{R}^p} \sum_{i = 1}^n \rho_\tau(Y_i - x_i'b).$$ $\hat{\beta}(\tau)$ is referred to as $\tau$-th regression quantile, which, by virtue of the property of $\rho_\tau(\cdot)$, also bears some interesting ordering interpretation relative to the fitted regression quantile surface $y = x'\hat{\beta}(\tau)$, for details, see remark on page 40 of Regression Quantiles (1978) by Koenker and Bassett. In summary, the check function is a loss function that retrieves the $\tau$-th sample quantile, and more importantly, that makes the generalization from the one-sample problem (where ordering is possible) to the regression problem (where ordering is rather awkward) practical.
Quantile regression - "check function" The check function stems from applying an optimization view of expressing the $\tau$-th sample quantile of a sample $\{Y_1, \ldots, Y_n\}$. Conventionally, given an observed sample $Y_1, \ldots, Y_n$
48,417
Statistics in the context of Search Engine Optimization (SEO)?
First, I would like to explain the history of SEOs and consequently why many SEO books do not provide the exact implementation details for a general audience. From my understanding, there are very few people who know exactly how search engines work. If someone knows how Google's search works in great detail, he/she can make a lot of money by discerning how to cheat the search, and (for a profit) ranking someone's website into the top search results. This is why Google/Bing's searches are proprietary rather than open access. In addition, the search engine is necessarily a very complex system. You can expect any decent search tool to make use of nested algorithms, thousands of hand written rules, AI-assisted human filtering on content, and so on. In summary, while components of the system may make use of well known learning procedures, the overall system cannot be described simply by math. Even if that were possible, the system is sure to reflect newer and more sophisticated features by the time any one person came to grips with its current state. We do not know how often Google update their algorithm, and what exactly those updates entail. Since no one person knows exactly how things work, some observers conduct experiments to see or modify results. Some tricks are really hacks. For example, some site designers include "dirty / hot / unrelated" key words in the page, but make the text transparent so browsers clicking-through do not see the text although that text essentially swayed the search that originally sought such content. These types of tricks are falling out of favor, and are examples of how Google's dynamic algorithm development quickly matches and overcomes the site designers' biasing efforts. These are examples of SEO tricks, and illustrates why search implementation quickly deviates from a purely mathematical or statistical treatment. Above are real world examples of SEO, and why there are not too many math in the SEO books. But if you want to study recommendation system in general, there are many places to start with. Such as Learn to rank Non-negative matrix factorization Eigendecomposition (Markov process, stationary distribution / original page rank algorithm) And many more.
Statistics in the context of Search Engine Optimization (SEO)?
First, I would like to explain the history of SEOs and consequently why many SEO books do not provide the exact implementation details for a general audience. From my understanding, there are very fe
Statistics in the context of Search Engine Optimization (SEO)? First, I would like to explain the history of SEOs and consequently why many SEO books do not provide the exact implementation details for a general audience. From my understanding, there are very few people who know exactly how search engines work. If someone knows how Google's search works in great detail, he/she can make a lot of money by discerning how to cheat the search, and (for a profit) ranking someone's website into the top search results. This is why Google/Bing's searches are proprietary rather than open access. In addition, the search engine is necessarily a very complex system. You can expect any decent search tool to make use of nested algorithms, thousands of hand written rules, AI-assisted human filtering on content, and so on. In summary, while components of the system may make use of well known learning procedures, the overall system cannot be described simply by math. Even if that were possible, the system is sure to reflect newer and more sophisticated features by the time any one person came to grips with its current state. We do not know how often Google update their algorithm, and what exactly those updates entail. Since no one person knows exactly how things work, some observers conduct experiments to see or modify results. Some tricks are really hacks. For example, some site designers include "dirty / hot / unrelated" key words in the page, but make the text transparent so browsers clicking-through do not see the text although that text essentially swayed the search that originally sought such content. These types of tricks are falling out of favor, and are examples of how Google's dynamic algorithm development quickly matches and overcomes the site designers' biasing efforts. These are examples of SEO tricks, and illustrates why search implementation quickly deviates from a purely mathematical or statistical treatment. Above are real world examples of SEO, and why there are not too many math in the SEO books. But if you want to study recommendation system in general, there are many places to start with. Such as Learn to rank Non-negative matrix factorization Eigendecomposition (Markov process, stationary distribution / original page rank algorithm) And many more.
Statistics in the context of Search Engine Optimization (SEO)? First, I would like to explain the history of SEOs and consequently why many SEO books do not provide the exact implementation details for a general audience. From my understanding, there are very fe
48,418
How to conduct sample size calculation for >2 groups in R?
If you do a three group comparison: Trt1 vs Ctl and Trt2 vs control, then a sample size calculation can be done in the following way: Obtain sample sizes for Trt1 and Ctl in a two group comparison. Obtain sample sizes for Trt2 and Ctl in a second two group comparison. Assign Trt1 and Trt2 according to their respective sample size calculations. Assign control according to the maximum of either sample size calculation. It will simply be a slightly more precise/powerful comparison in the smaller, larger effect treatment group. If the effects of Trt1 and Trt2 are equal, their sample sizes are equal, and you simply assign another 50% of the participants to the other treatment.
How to conduct sample size calculation for >2 groups in R?
If you do a three group comparison: Trt1 vs Ctl and Trt2 vs control, then a sample size calculation can be done in the following way: Obtain sample sizes for Trt1 and Ctl in a two group comparison. Ob
How to conduct sample size calculation for >2 groups in R? If you do a three group comparison: Trt1 vs Ctl and Trt2 vs control, then a sample size calculation can be done in the following way: Obtain sample sizes for Trt1 and Ctl in a two group comparison. Obtain sample sizes for Trt2 and Ctl in a second two group comparison. Assign Trt1 and Trt2 according to their respective sample size calculations. Assign control according to the maximum of either sample size calculation. It will simply be a slightly more precise/powerful comparison in the smaller, larger effect treatment group. If the effects of Trt1 and Trt2 are equal, their sample sizes are equal, and you simply assign another 50% of the participants to the other treatment.
How to conduct sample size calculation for >2 groups in R? If you do a three group comparison: Trt1 vs Ctl and Trt2 vs control, then a sample size calculation can be done in the following way: Obtain sample sizes for Trt1 and Ctl in a two group comparison. Ob
48,419
Where can I find more materials on 'binning' after PCA?
Let's draw a picture with two variables. It will illustrate the general idea. To achieve this, I generated a set of 500 data with expected correlation of $0.25$, computed the first principal component (PC), cut it into five equinumerous bins, and computed the first PC for each of the bins. The first PC (not shown directly) points along the major axis of the cloud of all points. The boundaries between bins are lines perpendicular to that direction. These are shown in white. They carve the plane into five regions, to which the points are assigned and colored by region. The first PC of the points within each bin is indicated with an arrow originating at the centroid of the bin's points. (The centroids are marked with black dots.) The sense in which this "decorrelates" anything is unclear, because--as is apparent in the plot--the points within each bin may, if anything, be more correlated than the original points. This procedure does stratify the data according to their positions along the major axis of the point cloud, thereby removing most of the effect of variation along the major axis: perhaps that accomplishes something useful in the application. The R code is written to enable variation of the simulation parameters: number of points, correlation coefficient, and number of bins. I offer it for use in further exploring this situation. library(MASS) # Generates multivariate Normal data library(ggplot2) # Plots nicely library(data.table) # Computes on data frames well # # Specify the multivariate data distribution. # n <- 5e2 # Sample size mu <- c(0,0) # Mean rho <- 0.25 # Correlation coefficient n.bins <- 5 # Number of bins # # Generate correlated variables. # X <- as.data.table(mvrnorm(n, mu, matrix(c(1,rho,rho,1), 2))) # Observations # # Compute the first PC. # P <- prcomp(X, rank.=1) X$PC1 <- t(t(X) - P$center) %*% P$rotation # # Bin the first principal component. # n.bins <- min(n.bins, n) q <- quantile(X$PC1, seq(0, 1, length.out=n.bins+1)) q[1] <- -Inf; q[n.bins+1] <- Inf X$Bin <- cut(X$PC1, q) # # Create a data frame for plotting the bin boundaries. # beta <- P$rotation Q <- data.table(intercept=q[-c(1,n.bins+1)]/beta[2], slope=-beta[1]/beta[2]) # # Do PCA by bin. # f <- function(x, y, length=1.5) { s <- sign(cor(x,y)) slope <- s * sd(y) / sd(x) intercept <- mean(y) - mean(x) * slope list(x=mean(x), y=mean(y), xend=mean(x)+length*s*sd(x), yend=mean(y)+length*sd(y)) } # # Create a data frame for plotting the bin PCs. # P <- X[, c(f(V1, V2)), by=Bin] # # Plot the data and the results. # g <- ggplot(X, aes(V1, V2, group=Bin, color=Bin)) + geom_abline(aes(intercept=intercept, slope=slope), data=Q, size=1, color="White", alpha=0.9) + geom_segment(aes(x=x, y=y, xend=xend, yend=yend), data=P, size=1.25, arrow = arrow(length = unit(0.02, "npc"))) + geom_point(aes(x, y), data=P, shape=19, size=1.5, color="Black") + geom_point(alpha=0.4) + coord_fixed() + ggtitle("Bins of the First PC", "First PC of Each Bin Shown With Arrows") + theme(panel.grid=element_blank()) print(g)
Where can I find more materials on 'binning' after PCA?
Let's draw a picture with two variables. It will illustrate the general idea. To achieve this, I generated a set of 500 data with expected correlation of $0.25$, computed the first principal componen
Where can I find more materials on 'binning' after PCA? Let's draw a picture with two variables. It will illustrate the general idea. To achieve this, I generated a set of 500 data with expected correlation of $0.25$, computed the first principal component (PC), cut it into five equinumerous bins, and computed the first PC for each of the bins. The first PC (not shown directly) points along the major axis of the cloud of all points. The boundaries between bins are lines perpendicular to that direction. These are shown in white. They carve the plane into five regions, to which the points are assigned and colored by region. The first PC of the points within each bin is indicated with an arrow originating at the centroid of the bin's points. (The centroids are marked with black dots.) The sense in which this "decorrelates" anything is unclear, because--as is apparent in the plot--the points within each bin may, if anything, be more correlated than the original points. This procedure does stratify the data according to their positions along the major axis of the point cloud, thereby removing most of the effect of variation along the major axis: perhaps that accomplishes something useful in the application. The R code is written to enable variation of the simulation parameters: number of points, correlation coefficient, and number of bins. I offer it for use in further exploring this situation. library(MASS) # Generates multivariate Normal data library(ggplot2) # Plots nicely library(data.table) # Computes on data frames well # # Specify the multivariate data distribution. # n <- 5e2 # Sample size mu <- c(0,0) # Mean rho <- 0.25 # Correlation coefficient n.bins <- 5 # Number of bins # # Generate correlated variables. # X <- as.data.table(mvrnorm(n, mu, matrix(c(1,rho,rho,1), 2))) # Observations # # Compute the first PC. # P <- prcomp(X, rank.=1) X$PC1 <- t(t(X) - P$center) %*% P$rotation # # Bin the first principal component. # n.bins <- min(n.bins, n) q <- quantile(X$PC1, seq(0, 1, length.out=n.bins+1)) q[1] <- -Inf; q[n.bins+1] <- Inf X$Bin <- cut(X$PC1, q) # # Create a data frame for plotting the bin boundaries. # beta <- P$rotation Q <- data.table(intercept=q[-c(1,n.bins+1)]/beta[2], slope=-beta[1]/beta[2]) # # Do PCA by bin. # f <- function(x, y, length=1.5) { s <- sign(cor(x,y)) slope <- s * sd(y) / sd(x) intercept <- mean(y) - mean(x) * slope list(x=mean(x), y=mean(y), xend=mean(x)+length*s*sd(x), yend=mean(y)+length*sd(y)) } # # Create a data frame for plotting the bin PCs. # P <- X[, c(f(V1, V2)), by=Bin] # # Plot the data and the results. # g <- ggplot(X, aes(V1, V2, group=Bin, color=Bin)) + geom_abline(aes(intercept=intercept, slope=slope), data=Q, size=1, color="White", alpha=0.9) + geom_segment(aes(x=x, y=y, xend=xend, yend=yend), data=P, size=1.25, arrow = arrow(length = unit(0.02, "npc"))) + geom_point(aes(x, y), data=P, shape=19, size=1.5, color="Black") + geom_point(alpha=0.4) + coord_fixed() + ggtitle("Bins of the First PC", "First PC of Each Bin Shown With Arrows") + theme(panel.grid=element_blank()) print(g)
Where can I find more materials on 'binning' after PCA? Let's draw a picture with two variables. It will illustrate the general idea. To achieve this, I generated a set of 500 data with expected correlation of $0.25$, computed the first principal componen
48,420
Second directional derivate and Hessian matrix
Think carefully about what you mean when you describe the directional derivative as the "slope" of a function $f$ in a certain direction. The concept of a "slope" only really makes sense in the context of a function whose domain is one-dimensional. It helps to think of it this way. Let $f({\bf x})$ be a scalar valued function whose domain is $\mathbb{R}^D$, and let ${\bf X}(t)$ be a continuous vector valued function parameterised in $\mathbb{R}^1.$ ${\bf X}(t)$ can be thought of as a path taken by a point particle in $D$-dimensional space. Then we can define $g(t) = f({\bf X}(t))$ as the value of the field $f$ experienced by the particle as it moves along the path. $g(t)$ is $\mathbb{R} \rightarrow \mathbb{R}.$ It's with this function that we can talk about ordinary one-dimensional concepts like slopes, second derivatives, etc. For example, if ${\bf X}(t_0) = {\bf u}$ is some direction, the way to think of the directional derivative of $f$ in direction $\bf u$ is $g'(t_0)$, i.e. the slope of $g$ at $t_0.$ The second directional derivative of $f$ in direction $\bf u$ is $g''(t_0).$ Any time we talk about an $n$'th "directional derivative" of some function $f$ in $\mathbb{R}^D$ at point ${\bf x}_0$ in the direction $\bf u$, we're implicitly talking about the $n$'th derivative of a function in $\mathbb{R}^1$ described by the value of $f$ parameterized by a one-dimensional path in $\mathbb{R}^D$ whose direction at ${\bf x}_0$ is $\bf u$. Another (perhaps simpler) way of thinking about it is as follows. If $f({\bf x})$ is a scalar valued function whose domain is $\mathbb{R}^D$ then the directional derivative $D_{\bf u} f ({\bf x})$ is also a scalar valued function whose domain is $\mathbb{R}^D.$ The second directional derivative of $f$ in $\bf u$ is simply the directional derivative of $D_{\bf u} f ({\bf x}),$ i.e. it is $D_{\bf u} D_{\bf u} f ({\bf x}).$ Remember, $d$ is assumed in the text to be a unit vector. If $d$ is a linear combination of unit vectors in an orthonormal basis given by $d = \sum_i c_i x_i$ then you can easily show that $d^T d = \sum_i c_i^2.$ Because $d$ is assumed to be a unit vector it follows that $\sum_i c_i^2 = 1.$ If $d$ is not specifically an eigenvector then none of the $c_i$'s are $1,$ which means that $c_i \in [0,1)$ $\forall i.$ Here I'm assuming that the basis is normalized (i.e. $||x_i||^2 = 1$). However, you don't need to assume this. In general, the weight of each eigenvalue is simply $(c_i ||x_i||)^2$. If $d$ is a unit vector, given the orthogonality of the basis you can show that $\sum_i (c_i ||x_i||)^2 = 1.$ This is a claim that the direction for which a function $f$ has the highest second derivative is the direction of the eigenvector of the Hessian of $f$ that has the highest eigenvalue. This claim follows from what was claimed above. If the directional second derivative of $f,$ for any directional vector $d,$ is the weighted average of all eigenvalues of the Hessian with weights given by $d$'s projection in each eigenvector, then obviously the direction that maximizes the directional derivative is the one for which the weight of the highest eigenvalue is $1,$ and all other weights is $0.$ (Recall the constraint that $\sum_i c_i^2 = 1.$) This direction is just the eigenvector that corresponds to the highest eigenvalue.
Second directional derivate and Hessian matrix
Think carefully about what you mean when you describe the directional derivative as the "slope" of a function $f$ in a certain direction. The concept of a "slope" only really makes sense in the contex
Second directional derivate and Hessian matrix Think carefully about what you mean when you describe the directional derivative as the "slope" of a function $f$ in a certain direction. The concept of a "slope" only really makes sense in the context of a function whose domain is one-dimensional. It helps to think of it this way. Let $f({\bf x})$ be a scalar valued function whose domain is $\mathbb{R}^D$, and let ${\bf X}(t)$ be a continuous vector valued function parameterised in $\mathbb{R}^1.$ ${\bf X}(t)$ can be thought of as a path taken by a point particle in $D$-dimensional space. Then we can define $g(t) = f({\bf X}(t))$ as the value of the field $f$ experienced by the particle as it moves along the path. $g(t)$ is $\mathbb{R} \rightarrow \mathbb{R}.$ It's with this function that we can talk about ordinary one-dimensional concepts like slopes, second derivatives, etc. For example, if ${\bf X}(t_0) = {\bf u}$ is some direction, the way to think of the directional derivative of $f$ in direction $\bf u$ is $g'(t_0)$, i.e. the slope of $g$ at $t_0.$ The second directional derivative of $f$ in direction $\bf u$ is $g''(t_0).$ Any time we talk about an $n$'th "directional derivative" of some function $f$ in $\mathbb{R}^D$ at point ${\bf x}_0$ in the direction $\bf u$, we're implicitly talking about the $n$'th derivative of a function in $\mathbb{R}^1$ described by the value of $f$ parameterized by a one-dimensional path in $\mathbb{R}^D$ whose direction at ${\bf x}_0$ is $\bf u$. Another (perhaps simpler) way of thinking about it is as follows. If $f({\bf x})$ is a scalar valued function whose domain is $\mathbb{R}^D$ then the directional derivative $D_{\bf u} f ({\bf x})$ is also a scalar valued function whose domain is $\mathbb{R}^D.$ The second directional derivative of $f$ in $\bf u$ is simply the directional derivative of $D_{\bf u} f ({\bf x}),$ i.e. it is $D_{\bf u} D_{\bf u} f ({\bf x}).$ Remember, $d$ is assumed in the text to be a unit vector. If $d$ is a linear combination of unit vectors in an orthonormal basis given by $d = \sum_i c_i x_i$ then you can easily show that $d^T d = \sum_i c_i^2.$ Because $d$ is assumed to be a unit vector it follows that $\sum_i c_i^2 = 1.$ If $d$ is not specifically an eigenvector then none of the $c_i$'s are $1,$ which means that $c_i \in [0,1)$ $\forall i.$ Here I'm assuming that the basis is normalized (i.e. $||x_i||^2 = 1$). However, you don't need to assume this. In general, the weight of each eigenvalue is simply $(c_i ||x_i||)^2$. If $d$ is a unit vector, given the orthogonality of the basis you can show that $\sum_i (c_i ||x_i||)^2 = 1.$ This is a claim that the direction for which a function $f$ has the highest second derivative is the direction of the eigenvector of the Hessian of $f$ that has the highest eigenvalue. This claim follows from what was claimed above. If the directional second derivative of $f,$ for any directional vector $d,$ is the weighted average of all eigenvalues of the Hessian with weights given by $d$'s projection in each eigenvector, then obviously the direction that maximizes the directional derivative is the one for which the weight of the highest eigenvalue is $1,$ and all other weights is $0.$ (Recall the constraint that $\sum_i c_i^2 = 1.$) This direction is just the eigenvector that corresponds to the highest eigenvalue.
Second directional derivate and Hessian matrix Think carefully about what you mean when you describe the directional derivative as the "slope" of a function $f$ in a certain direction. The concept of a "slope" only really makes sense in the contex
48,421
Why do the leading eigenvectors of $A$ maximize $\text{Tr}(D^TAD)$?
Let us denote $X^\top X$ by $A$. By construction, it is a $n\times n$ square symmetric positive semi-definite matrix, i.e. it has an eigenvalue decomposition $A=V\Lambda V^\top$, where $V$ is the matrix of eigenvectors (each column is an eigenvector) and $\Lambda$ is a diagonal matrix of non-negative eigenvalues $\lambda_i$ sorted in the descending order. You want to maximize $$\operatorname{Tr}(D^\top A D),$$ where $D$ has $l$ orthonormal columns. Let us write it as $$\operatorname{Tr}(D^\top V\Lambda V^\top D)=\operatorname{Tr}(\tilde D^\top\Lambda \tilde D)=\operatorname{Tr}\big(\tilde D^\top \operatorname{diag}\{\lambda_i\}\, \tilde D\big)=\sum_{i=1}^n\lambda_i\sum_{j=1}^l\tilde D_{ij}^2.$$ This algebraic manipulation corresponds to rotating the coordinate frame such that $A$ becomes diagonal. The matrix $D$ gets transformed as $\tilde D=V^\top D$ which also has $l$ orthonormal columns. And the whole trace is reduced to a linear combination of eigenvalues $\lambda_i$. What can we say about the coefficients $a_i=\sum_{j=1}^l\tilde D_{ij}^2$ in this linear combination? They are row sums of squares in $\tilde D$, and hence (i) they are all $\le 1$ and (ii) they sum to $l$. If so, then it is rather obvious that to maximize the sum, one should take these coefficients to be $(1,\ldots, 1, 0, \ldots, 0)$, simply selecting the top $l$ eigenvalues. Indeed, if e.g. $a_1<1$ then the sum will increase if we set $a_1=1$ and reduce the size of the last non-zero $a_i$ term accordingly. This means that the maximum will be achieved if $\tilde D$ is the first $l$ columns of the identity matrix. And accordingly if $D$ is the first $l$ columns of $V$, i.e. the first $l$ eigenvectors. QED. (Of course this is a not a unique solution. $D$ can be rotated/reflected with any $l\times l$ orthogonal matrix without changing the value of the trace.) This is very close to my answer in Why does PCA maximize total variance of the projection? This reasoning follows @whuber's comment in that thread: [I]s it not intuitively obvious that given a collection of wallets of various amounts of cash (modeling the non-negative eigenvalues), and a fixed number $k$ that you can pick, that selecting the $k$ richest wallets will maximize your total cash? The proof that this intuition is correct is almost trivial: if you haven't taken the $k$ largest, then you can improve your sum by exchanging the smallest one you took for a larger amount.
Why do the leading eigenvectors of $A$ maximize $\text{Tr}(D^TAD)$?
Let us denote $X^\top X$ by $A$. By construction, it is a $n\times n$ square symmetric positive semi-definite matrix, i.e. it has an eigenvalue decomposition $A=V\Lambda V^\top$, where $V$ is the matr
Why do the leading eigenvectors of $A$ maximize $\text{Tr}(D^TAD)$? Let us denote $X^\top X$ by $A$. By construction, it is a $n\times n$ square symmetric positive semi-definite matrix, i.e. it has an eigenvalue decomposition $A=V\Lambda V^\top$, where $V$ is the matrix of eigenvectors (each column is an eigenvector) and $\Lambda$ is a diagonal matrix of non-negative eigenvalues $\lambda_i$ sorted in the descending order. You want to maximize $$\operatorname{Tr}(D^\top A D),$$ where $D$ has $l$ orthonormal columns. Let us write it as $$\operatorname{Tr}(D^\top V\Lambda V^\top D)=\operatorname{Tr}(\tilde D^\top\Lambda \tilde D)=\operatorname{Tr}\big(\tilde D^\top \operatorname{diag}\{\lambda_i\}\, \tilde D\big)=\sum_{i=1}^n\lambda_i\sum_{j=1}^l\tilde D_{ij}^2.$$ This algebraic manipulation corresponds to rotating the coordinate frame such that $A$ becomes diagonal. The matrix $D$ gets transformed as $\tilde D=V^\top D$ which also has $l$ orthonormal columns. And the whole trace is reduced to a linear combination of eigenvalues $\lambda_i$. What can we say about the coefficients $a_i=\sum_{j=1}^l\tilde D_{ij}^2$ in this linear combination? They are row sums of squares in $\tilde D$, and hence (i) they are all $\le 1$ and (ii) they sum to $l$. If so, then it is rather obvious that to maximize the sum, one should take these coefficients to be $(1,\ldots, 1, 0, \ldots, 0)$, simply selecting the top $l$ eigenvalues. Indeed, if e.g. $a_1<1$ then the sum will increase if we set $a_1=1$ and reduce the size of the last non-zero $a_i$ term accordingly. This means that the maximum will be achieved if $\tilde D$ is the first $l$ columns of the identity matrix. And accordingly if $D$ is the first $l$ columns of $V$, i.e. the first $l$ eigenvectors. QED. (Of course this is a not a unique solution. $D$ can be rotated/reflected with any $l\times l$ orthogonal matrix without changing the value of the trace.) This is very close to my answer in Why does PCA maximize total variance of the projection? This reasoning follows @whuber's comment in that thread: [I]s it not intuitively obvious that given a collection of wallets of various amounts of cash (modeling the non-negative eigenvalues), and a fixed number $k$ that you can pick, that selecting the $k$ richest wallets will maximize your total cash? The proof that this intuition is correct is almost trivial: if you haven't taken the $k$ largest, then you can improve your sum by exchanging the smallest one you took for a larger amount.
Why do the leading eigenvectors of $A$ maximize $\text{Tr}(D^TAD)$? Let us denote $X^\top X$ by $A$. By construction, it is a $n\times n$ square symmetric positive semi-definite matrix, i.e. it has an eigenvalue decomposition $A=V\Lambda V^\top$, where $V$ is the matr
48,422
Why do the leading eigenvectors of $A$ maximize $\text{Tr}(D^TAD)$?
Define $W=X^TX$, and denote by $v_i$ a unit-norm eigenvector corresponding to its $i$-th largest eigenvalue. By the variational characterization of eigenvalues, $$ v_1 = \underset{x,\|x\|_2=1}{\arg\max} ~ ~ x^T W x $$ Since you are looking for an orthogonal matrix, your next vector should be in a space orthogonal to $v_2$. Define $W^{(2)}=W-v_1v_1^TW$. It just so happens that $$ v_2 = \underset{x,\|x\|_2=1}{\arg\max} ~ ~ x^T W^{(2)} x $$ And so on. Why are we sure that it is indeed the eigenvectors that maximize the sum? Can't we start with a different pair of vectors and then make up for it afterwards, as whuber pointed out? If $X=U\Sigma V^T$ is the singular value decomposition of $X$, then $X^TX=W=V\Sigma^2 V^T$ is the eigendecomposition of $W$. Define $X_l=U_l\Sigma_l V_l^T$, where $U_l, V_l$ are $U,V$ truncated to the first $l$ columns and $\Sigma_l$ to the leading $l\times l$ block. By the Eckart-Young-Mirsky theorem we know that $$ \|X-X_l\|_F^2=\min_{A,rank(A)\leq l} \|X-A\|_F^2 $$ And it is easy to see that $\underset{A}{\arg\min} \|X-A\|_F^2=\underset{A}{\arg\max} \|A\|_F^2$ whenever $A$ is the result of projecting a matrix onto the span of $X$, so $$ \|X_l\|_F^2=\max_{A,rank(A)\leq l} \|A\|_F^2 $$ Now, observe that $X_l^TX_l=V_l\Sigma_l^2V_l^T$, that is, $V_l^TX_l^TX_lV_l=\Sigma_l^2$ $\|X_l\|_F^2=\sum_{i=1}^l\sigma_i^2$ Therefore, $\mbox{tr}(V_l^TX_l^TX_lV_l)=\mbox{tr}(\Sigma_l^2)=\sum_{i=1}^l\sigma_i^2$ is optimal. Finally, note that $V_l^TX_l^TX_lV_l=V_l^TX^TXV_l$
Why do the leading eigenvectors of $A$ maximize $\text{Tr}(D^TAD)$?
Define $W=X^TX$, and denote by $v_i$ a unit-norm eigenvector corresponding to its $i$-th largest eigenvalue. By the variational characterization of eigenvalues, $$ v_1 = \underset{x,\|x\|_2=1}{\arg\ma
Why do the leading eigenvectors of $A$ maximize $\text{Tr}(D^TAD)$? Define $W=X^TX$, and denote by $v_i$ a unit-norm eigenvector corresponding to its $i$-th largest eigenvalue. By the variational characterization of eigenvalues, $$ v_1 = \underset{x,\|x\|_2=1}{\arg\max} ~ ~ x^T W x $$ Since you are looking for an orthogonal matrix, your next vector should be in a space orthogonal to $v_2$. Define $W^{(2)}=W-v_1v_1^TW$. It just so happens that $$ v_2 = \underset{x,\|x\|_2=1}{\arg\max} ~ ~ x^T W^{(2)} x $$ And so on. Why are we sure that it is indeed the eigenvectors that maximize the sum? Can't we start with a different pair of vectors and then make up for it afterwards, as whuber pointed out? If $X=U\Sigma V^T$ is the singular value decomposition of $X$, then $X^TX=W=V\Sigma^2 V^T$ is the eigendecomposition of $W$. Define $X_l=U_l\Sigma_l V_l^T$, where $U_l, V_l$ are $U,V$ truncated to the first $l$ columns and $\Sigma_l$ to the leading $l\times l$ block. By the Eckart-Young-Mirsky theorem we know that $$ \|X-X_l\|_F^2=\min_{A,rank(A)\leq l} \|X-A\|_F^2 $$ And it is easy to see that $\underset{A}{\arg\min} \|X-A\|_F^2=\underset{A}{\arg\max} \|A\|_F^2$ whenever $A$ is the result of projecting a matrix onto the span of $X$, so $$ \|X_l\|_F^2=\max_{A,rank(A)\leq l} \|A\|_F^2 $$ Now, observe that $X_l^TX_l=V_l\Sigma_l^2V_l^T$, that is, $V_l^TX_l^TX_lV_l=\Sigma_l^2$ $\|X_l\|_F^2=\sum_{i=1}^l\sigma_i^2$ Therefore, $\mbox{tr}(V_l^TX_l^TX_lV_l)=\mbox{tr}(\Sigma_l^2)=\sum_{i=1}^l\sigma_i^2$ is optimal. Finally, note that $V_l^TX_l^TX_lV_l=V_l^TX^TXV_l$
Why do the leading eigenvectors of $A$ maximize $\text{Tr}(D^TAD)$? Define $W=X^TX$, and denote by $v_i$ a unit-norm eigenvector corresponding to its $i$-th largest eigenvalue. By the variational characterization of eigenvalues, $$ v_1 = \underset{x,\|x\|_2=1}{\arg\ma
48,423
Interpretation of standard error of ARIMA parameters
The standard errors of estimated AR parameters have the same interpretation as the standard error of any other estimate: they are (an estimate of) the standard deviation of its sampling distribution. The idea is that there is some unknown but fixed underlying data generating process (DGP), governed by an unknown but fixed ARIMA process. The specific time series you observe is a single realization of this process. If you now went and sampled many time series arising from this DGP, then they would all look somewhat different, because of different innovations. However, you could fit an ARIMA model to all of them. Then you would of course get different AR parameter estimates for each time series. The standard error of the AR estimates is an estimate of the standard deviation of these AR estimates. A simulation might be helpful. Below, I'll use an AR(2) model with parameters $(1.0,-0.2)$. I'll generate a time series of length 100 using this model, then fit an AR(2) model, store the AR parameter estimates - and repeat this 10,000 times. Finally, I plot histograms of the parameter estimates, plus the actual values as red vertical lines - and then compare the standard deviations of the AR parameter estimates against the (average of the) estimated standard errors. And the two match up. nn <- 100 n.sims <- 10000 true.model <- list(ar=c(1.0,-0.2)) params <- ses <- matrix(NA,nrow=n.sims,ncol=length(true.model$ar)) for ( ii in 1:n.sims ) { set.seed(ii) series <- arima.sim(model=true.model,n=nn) model <- arima(series,order=c(2,0,0),include.mean=FALSE) params[ii,] <- coefficients(model) ses[ii,] <- sqrt(diag(model$var.coef)) } opar <- par(mfrow=c(1,2)) for ( jj in seq_along(true.model$ar) ) { hist(params[,jj],col="grey",xlab="",main=paste0("AR(",jj,") parameter")) abline(v=true.model$ar[jj],lwd=2,col="red") } par(opar) apply(params,2,sd) # [1] 0.09844388 0.09795008 apply(ses,2,mean) # [1] 0.09754488 0.09833490 Note that I simulate with a zero mean and explicitly tell arima() to not use a mean. And that the entire exercise crucially depends on the assumption that we know the ARIMA orders with certainty! If we first need to select the correct order, then everything will be biased, and the standard errors lose their interpretation. (Yes, this kind of makes all this a somewhat theoretical and academic exercise.) If you want to dive more deeply into the maths, any mathematical time series textbook should do well. (Anything with "business" in the title will likely gloss over these details.) I recently skimmed Time Series: Theory and Methods by Brockwell and Davies (2006), which looked pretty good, but I can't recall offhand whether this topic was treated at any depth there.
Interpretation of standard error of ARIMA parameters
The standard errors of estimated AR parameters have the same interpretation as the standard error of any other estimate: they are (an estimate of) the standard deviation of its sampling distribution.
Interpretation of standard error of ARIMA parameters The standard errors of estimated AR parameters have the same interpretation as the standard error of any other estimate: they are (an estimate of) the standard deviation of its sampling distribution. The idea is that there is some unknown but fixed underlying data generating process (DGP), governed by an unknown but fixed ARIMA process. The specific time series you observe is a single realization of this process. If you now went and sampled many time series arising from this DGP, then they would all look somewhat different, because of different innovations. However, you could fit an ARIMA model to all of them. Then you would of course get different AR parameter estimates for each time series. The standard error of the AR estimates is an estimate of the standard deviation of these AR estimates. A simulation might be helpful. Below, I'll use an AR(2) model with parameters $(1.0,-0.2)$. I'll generate a time series of length 100 using this model, then fit an AR(2) model, store the AR parameter estimates - and repeat this 10,000 times. Finally, I plot histograms of the parameter estimates, plus the actual values as red vertical lines - and then compare the standard deviations of the AR parameter estimates against the (average of the) estimated standard errors. And the two match up. nn <- 100 n.sims <- 10000 true.model <- list(ar=c(1.0,-0.2)) params <- ses <- matrix(NA,nrow=n.sims,ncol=length(true.model$ar)) for ( ii in 1:n.sims ) { set.seed(ii) series <- arima.sim(model=true.model,n=nn) model <- arima(series,order=c(2,0,0),include.mean=FALSE) params[ii,] <- coefficients(model) ses[ii,] <- sqrt(diag(model$var.coef)) } opar <- par(mfrow=c(1,2)) for ( jj in seq_along(true.model$ar) ) { hist(params[,jj],col="grey",xlab="",main=paste0("AR(",jj,") parameter")) abline(v=true.model$ar[jj],lwd=2,col="red") } par(opar) apply(params,2,sd) # [1] 0.09844388 0.09795008 apply(ses,2,mean) # [1] 0.09754488 0.09833490 Note that I simulate with a zero mean and explicitly tell arima() to not use a mean. And that the entire exercise crucially depends on the assumption that we know the ARIMA orders with certainty! If we first need to select the correct order, then everything will be biased, and the standard errors lose their interpretation. (Yes, this kind of makes all this a somewhat theoretical and academic exercise.) If you want to dive more deeply into the maths, any mathematical time series textbook should do well. (Anything with "business" in the title will likely gloss over these details.) I recently skimmed Time Series: Theory and Methods by Brockwell and Davies (2006), which looked pretty good, but I can't recall offhand whether this topic was treated at any depth there.
Interpretation of standard error of ARIMA parameters The standard errors of estimated AR parameters have the same interpretation as the standard error of any other estimate: they are (an estimate of) the standard deviation of its sampling distribution.
48,424
Multilabel Classification with scikit-learn and Probabilities instead of Simple Labels
Let me try to answer this, I will edit the answer as I have more information. In general scikit-learn does not provide classifiers that handle the multi-label classification problem very well. That's why I started the scikit-multilearn's extension of scikit-learn and together with a lovely team of multi-label classification people around the world we are implementing more state of the art methods for MLC. First of all, the question is do you need probabilities or just an estimate of how sure a classifier is. Not always the exact probabilities are what you can get very cheaply. I understand that you want to get probabilities P(A|X), P(B|X) etc. for a given instance X. A. The simplest case: labels are indpendent i.e. P(A and B|X)=P(A|X)P(B|X). If such case occurs you can use scikit-multilearns Binary Relevance classifier's predict_proba: here's a simple example with SVC as the per label probability estimator: from skmultilearn.problem_transform import BinaryRelevance from sklearn.svm import SVC classifier = BinaryRelevance(classifier = SVC(probability=True), require_dense = [False, True]) classifier.fit(X_train, y_train) probabilities = classifier.predict_proba(X_test) This will estimate per label probabilities and then renormalize them. Unfortunately Binary Relevance may fail to detect a rise/fall of probabilities in case when a combination of labels is mutually or even totally dependent, it just happens. B. If your labels are not independent you need to explore the data set and ask yourself what is the level of co-dependence in your data. There are several ways to handle dependencies. If you really expect a total dependence, a Label Powerset approach may be better, where each combination is treated as a separate class and probability will be estimated per that class. Note that this transformation is a hard one to perform, due to label imbalances and the underfitting nature of Label Powerset transformation, I've created a solution for this to divide the label space into interconnected subspaces - a data-driven approach to detect dependencies and split the problem into interally more dependent subproblems - see the data-driven approach to multi-label classification paper. An example how to use it is here: http://scikit.ml/api/classify.html#ensemble-approaches - just use predict_proba instead of predict. Also you might want to change the clusterer to: clusterer = IGraphLabelCooccurenceClusterer('fastgreedy', weighted=True, include_self_edges=False) so that the label partition is more granular. It detects clusters of co-occurring labels and then calculates joint distributions P(A1,...,An|X) for labels A1...An per cluster, i.e. it expects the clusters of labels to independent. If you like it and use this method please cite both the data-driven paper and the arxiv paper of scikit-multilearn, we can get funding to develop the library that way :) Also I'd love to know how the method worked for you so I can maybe improve it. I find it easiest to just start with something, so if I were you, I'd go ahead and check the approach from point A and see what level of result you're getting. Then I'd try the label space partition approach. I need to write a tutorial on how to use it to explore the relations, will add this to my documentation todo list.
Multilabel Classification with scikit-learn and Probabilities instead of Simple Labels
Let me try to answer this, I will edit the answer as I have more information. In general scikit-learn does not provide classifiers that handle the multi-label classification problem very well. That's
Multilabel Classification with scikit-learn and Probabilities instead of Simple Labels Let me try to answer this, I will edit the answer as I have more information. In general scikit-learn does not provide classifiers that handle the multi-label classification problem very well. That's why I started the scikit-multilearn's extension of scikit-learn and together with a lovely team of multi-label classification people around the world we are implementing more state of the art methods for MLC. First of all, the question is do you need probabilities or just an estimate of how sure a classifier is. Not always the exact probabilities are what you can get very cheaply. I understand that you want to get probabilities P(A|X), P(B|X) etc. for a given instance X. A. The simplest case: labels are indpendent i.e. P(A and B|X)=P(A|X)P(B|X). If such case occurs you can use scikit-multilearns Binary Relevance classifier's predict_proba: here's a simple example with SVC as the per label probability estimator: from skmultilearn.problem_transform import BinaryRelevance from sklearn.svm import SVC classifier = BinaryRelevance(classifier = SVC(probability=True), require_dense = [False, True]) classifier.fit(X_train, y_train) probabilities = classifier.predict_proba(X_test) This will estimate per label probabilities and then renormalize them. Unfortunately Binary Relevance may fail to detect a rise/fall of probabilities in case when a combination of labels is mutually or even totally dependent, it just happens. B. If your labels are not independent you need to explore the data set and ask yourself what is the level of co-dependence in your data. There are several ways to handle dependencies. If you really expect a total dependence, a Label Powerset approach may be better, where each combination is treated as a separate class and probability will be estimated per that class. Note that this transformation is a hard one to perform, due to label imbalances and the underfitting nature of Label Powerset transformation, I've created a solution for this to divide the label space into interconnected subspaces - a data-driven approach to detect dependencies and split the problem into interally more dependent subproblems - see the data-driven approach to multi-label classification paper. An example how to use it is here: http://scikit.ml/api/classify.html#ensemble-approaches - just use predict_proba instead of predict. Also you might want to change the clusterer to: clusterer = IGraphLabelCooccurenceClusterer('fastgreedy', weighted=True, include_self_edges=False) so that the label partition is more granular. It detects clusters of co-occurring labels and then calculates joint distributions P(A1,...,An|X) for labels A1...An per cluster, i.e. it expects the clusters of labels to independent. If you like it and use this method please cite both the data-driven paper and the arxiv paper of scikit-multilearn, we can get funding to develop the library that way :) Also I'd love to know how the method worked for you so I can maybe improve it. I find it easiest to just start with something, so if I were you, I'd go ahead and check the approach from point A and see what level of result you're getting. Then I'd try the label space partition approach. I need to write a tutorial on how to use it to explore the relations, will add this to my documentation todo list.
Multilabel Classification with scikit-learn and Probabilities instead of Simple Labels Let me try to answer this, I will edit the answer as I have more information. In general scikit-learn does not provide classifiers that handle the multi-label classification problem very well. That's
48,425
Inference for Dynamic Bayesian Networks
I personally think the question is too broad to be answered well, But I still want to give some suggestions. I feel Murphy's introduction to graphical models is very useful and it covers Bayesian Network with discrete time very well. If you have not checked this, I would recommend to read this first. A Brief Introduction to Graphical Models and Bayesian Networks To build a Bayesian network (with discrete time or dynamic bayesian network), there are two parts, specify or learn the structure and specify or learn parameter. To my experience, it is not common to learn both structure and parameter from data. People often use the domain knowledge plus assumptions to make the structure And learn the parameters from data. A useful R library can be found in BNLearn, it supports both structure and parameter learning. Finally I may suggest you to check some Recurrent Neural Network literatures. The deep learning book chapter 10 gives very nice explanation on the relationship between dynamic bayesian network and recurrent neural network. Deep learning is a really hot area recently, and there are more resources there.
Inference for Dynamic Bayesian Networks
I personally think the question is too broad to be answered well, But I still want to give some suggestions. I feel Murphy's introduction to graphical models is very useful and it covers Bayesian Netw
Inference for Dynamic Bayesian Networks I personally think the question is too broad to be answered well, But I still want to give some suggestions. I feel Murphy's introduction to graphical models is very useful and it covers Bayesian Network with discrete time very well. If you have not checked this, I would recommend to read this first. A Brief Introduction to Graphical Models and Bayesian Networks To build a Bayesian network (with discrete time or dynamic bayesian network), there are two parts, specify or learn the structure and specify or learn parameter. To my experience, it is not common to learn both structure and parameter from data. People often use the domain knowledge plus assumptions to make the structure And learn the parameters from data. A useful R library can be found in BNLearn, it supports both structure and parameter learning. Finally I may suggest you to check some Recurrent Neural Network literatures. The deep learning book chapter 10 gives very nice explanation on the relationship between dynamic bayesian network and recurrent neural network. Deep learning is a really hot area recently, and there are more resources there.
Inference for Dynamic Bayesian Networks I personally think the question is too broad to be answered well, But I still want to give some suggestions. I feel Murphy's introduction to graphical models is very useful and it covers Bayesian Netw
48,426
Tuning adaboost
Number of weak learners Train many, many weak learners. Then look at a test-error vs. number of estimators curve to find the optimal number. Learning rate Smaller is better, but you will have to fit more weak learners the smaller the learning rate. During initial modeling and EDA, set the learning rate rather large (0.01 for example). Then when fitting your final model, set it very small (0.0001 for example), fit many, many weak learners, and run the model over night. Maximum number of splits There is no a-priori best answer. You need to grid search this one.
Tuning adaboost
Number of weak learners Train many, many weak learners. Then look at a test-error vs. number of estimators curve to find the optimal number. Learning rate Smaller is better, but you will have to f
Tuning adaboost Number of weak learners Train many, many weak learners. Then look at a test-error vs. number of estimators curve to find the optimal number. Learning rate Smaller is better, but you will have to fit more weak learners the smaller the learning rate. During initial modeling and EDA, set the learning rate rather large (0.01 for example). Then when fitting your final model, set it very small (0.0001 for example), fit many, many weak learners, and run the model over night. Maximum number of splits There is no a-priori best answer. You need to grid search this one.
Tuning adaboost Number of weak learners Train many, many weak learners. Then look at a test-error vs. number of estimators curve to find the optimal number. Learning rate Smaller is better, but you will have to f
48,427
Diagnostics for General Linear Models
Pearson residuals in general do not follow a normal distribution. Deviance residuals don't follow normal distribution, right? They don't, but they will typically be much closer to being normally distributed than Pearson residuals. Here's an example with a Poisson model applied to actually Poisson data Clearly the working residuals are the least normal-looking. The Pearson residuals are better but still show a clear curvature. The straightest Q-Q plots are for the deviance and Anscombe residuals. This is fairly typical across a number of GLM models. None of them are actually normal, but the Pearson residuals are clearly skewed, while the deviance residuals are much more nearly symmetric.
Diagnostics for General Linear Models
Pearson residuals in general do not follow a normal distribution. Deviance residuals don't follow normal distribution, right? They don't, but they will typically be much closer to being normally di
Diagnostics for General Linear Models Pearson residuals in general do not follow a normal distribution. Deviance residuals don't follow normal distribution, right? They don't, but they will typically be much closer to being normally distributed than Pearson residuals. Here's an example with a Poisson model applied to actually Poisson data Clearly the working residuals are the least normal-looking. The Pearson residuals are better but still show a clear curvature. The straightest Q-Q plots are for the deviance and Anscombe residuals. This is fairly typical across a number of GLM models. None of them are actually normal, but the Pearson residuals are clearly skewed, while the deviance residuals are much more nearly symmetric.
Diagnostics for General Linear Models Pearson residuals in general do not follow a normal distribution. Deviance residuals don't follow normal distribution, right? They don't, but they will typically be much closer to being normally di
48,428
Diagnostics for General Linear Models
In a number of texts both Pearson and deviance residuals (or their standardized versions, for example, Sheather (2009)) are used to plot against predicted values. When it comes to the comparison between these two types residuals, deviance residuals is preferred over Pearson residuals. As an explanation of why this is the case, Simonoff argues that The Pearson residuals are probably the most commonly used residuals, but the deviance residuals (or standardized deviance residuals) are actually preferred, since their distribution is closer to that of least squares residuals (Simonoff, 2003: 133). In an earlier and widely cited article, Pierce & Schafer (1986) argued about the superior performance of deviance residuals, concluding that: The deviance-based residuals are remarkably appropriate, and if continuity corrections are made the discreteness presents no real problem for their use in individual data point diagnostics (Pierce & Schafer, 1986: 985). They made reference to McCullagh & Nelder's classic text on GLM (1983), where the latter compared adjusted deviance residuals and Pearson residuals in the case of binary data and reached a similar conclusion (p.87). In both of these texts, the similarity between Anscombe and (adjusted) deviance residuals and their performance in terms of approximating normality is emphasized. They are considered successful in "producing residual structures that are: centered at zero, have standard error of one, and are approximately normal" (Gill, 2001: 59). As far as I understand, this is not the case for Pearson residuals which are more skewed compared to deviance residuals. However, @Scortchi's answer to this question highlights an important point: "the deviance (or Pearson) residuals are not expected to have a normal distribution except for a Gaussian model." Gill, J., 2001. Generalized Linear Models: A Unified Approach. Sage Publications. McCullagh, P., Nelder, J.A., 1983. Generalized Linear Models. Chapman and Hall. Pierce, D.A., Schafer, D.W., 1986. Residuals in Generalized Linear Models. J. Am. Stat. Assoc. 81, 977–986. Sheather, S.J., 2009. A Modern Approach to Regression with R. Springer. Simonoff, J.S., 2003. Analyzing Categorical Data. Springer.
Diagnostics for General Linear Models
In a number of texts both Pearson and deviance residuals (or their standardized versions, for example, Sheather (2009)) are used to plot against predicted values. When it comes to the comparison betwe
Diagnostics for General Linear Models In a number of texts both Pearson and deviance residuals (or their standardized versions, for example, Sheather (2009)) are used to plot against predicted values. When it comes to the comparison between these two types residuals, deviance residuals is preferred over Pearson residuals. As an explanation of why this is the case, Simonoff argues that The Pearson residuals are probably the most commonly used residuals, but the deviance residuals (or standardized deviance residuals) are actually preferred, since their distribution is closer to that of least squares residuals (Simonoff, 2003: 133). In an earlier and widely cited article, Pierce & Schafer (1986) argued about the superior performance of deviance residuals, concluding that: The deviance-based residuals are remarkably appropriate, and if continuity corrections are made the discreteness presents no real problem for their use in individual data point diagnostics (Pierce & Schafer, 1986: 985). They made reference to McCullagh & Nelder's classic text on GLM (1983), where the latter compared adjusted deviance residuals and Pearson residuals in the case of binary data and reached a similar conclusion (p.87). In both of these texts, the similarity between Anscombe and (adjusted) deviance residuals and their performance in terms of approximating normality is emphasized. They are considered successful in "producing residual structures that are: centered at zero, have standard error of one, and are approximately normal" (Gill, 2001: 59). As far as I understand, this is not the case for Pearson residuals which are more skewed compared to deviance residuals. However, @Scortchi's answer to this question highlights an important point: "the deviance (or Pearson) residuals are not expected to have a normal distribution except for a Gaussian model." Gill, J., 2001. Generalized Linear Models: A Unified Approach. Sage Publications. McCullagh, P., Nelder, J.A., 1983. Generalized Linear Models. Chapman and Hall. Pierce, D.A., Schafer, D.W., 1986. Residuals in Generalized Linear Models. J. Am. Stat. Assoc. 81, 977–986. Sheather, S.J., 2009. A Modern Approach to Regression with R. Springer. Simonoff, J.S., 2003. Analyzing Categorical Data. Springer.
Diagnostics for General Linear Models In a number of texts both Pearson and deviance residuals (or their standardized versions, for example, Sheather (2009)) are used to plot against predicted values. When it comes to the comparison betwe
48,429
Bias-corrected percentile confidence intervals
You almost had it. Change your Step 2 code as shown below. You want the value of Z associated with the proportion you computed in Step 1 and that is what qnorm will give you. rsq.bc <- quantile(mtcar.boot.rsq$boot.rsq, c(pnorm((2*pnorm(mean(mtcar.boot.rsq$boot.high))) - 1.96), pnorm((2*pnorm(mean(mtcar.boot.rsq$boot.high))) + 1.96))) becomes rsq.bc <- quantile(mtcar.boot.rsq$boot.rsq, c(pnorm((2*qnorm(mean(mtcar.boot.rsq$boot.high))) - 1.96), pnorm((2*qnorm(mean(mtcar.boot.rsq$boot.high))) + 1.96))) You might find this page helpful: http://influentialpoints.com/Training/bootstrap_confidence_intervals.htm#bias
Bias-corrected percentile confidence intervals
You almost had it. Change your Step 2 code as shown below. You want the value of Z associated with the proportion you computed in Step 1 and that is what qnorm will give you. rsq.bc <- quantile(mtcar
Bias-corrected percentile confidence intervals You almost had it. Change your Step 2 code as shown below. You want the value of Z associated with the proportion you computed in Step 1 and that is what qnorm will give you. rsq.bc <- quantile(mtcar.boot.rsq$boot.rsq, c(pnorm((2*pnorm(mean(mtcar.boot.rsq$boot.high))) - 1.96), pnorm((2*pnorm(mean(mtcar.boot.rsq$boot.high))) + 1.96))) becomes rsq.bc <- quantile(mtcar.boot.rsq$boot.rsq, c(pnorm((2*qnorm(mean(mtcar.boot.rsq$boot.high))) - 1.96), pnorm((2*qnorm(mean(mtcar.boot.rsq$boot.high))) + 1.96))) You might find this page helpful: http://influentialpoints.com/Training/bootstrap_confidence_intervals.htm#bias
Bias-corrected percentile confidence intervals You almost had it. Change your Step 2 code as shown below. You want the value of Z associated with the proportion you computed in Step 1 and that is what qnorm will give you. rsq.bc <- quantile(mtcar
48,430
Reasons as to why standard multiple regression would not be appropriate?
The really interesting aspect of this question is that the doses are recorded as intervals and those intervals span sizable portions of the total range. This means we should be concerned that standard procedures, like logistic regression, that represent the doses as individual numbers might be misleading. By means of visualizations, I will take you step-by-step through a simple (and no means thorough) analysis until we arrive at the final complex but highly illuminating graphic. Your time might best be used by skimming down the plots, then backing up to study anything that captures your interest. Let's look at this more closely. Suppose that any given dose $x$ (not a range--an actual dose) is associated with a chance of $p(x, s)$ that any cockroach of species $s$ will die in these experimental conditions. Further suppose that cockroach deaths are (statistically) independent. (This assumption can in principle be tested; for now, it is needed because relevant information for testing it is unavailable.) This is a Binomial Generalized Linear Model (albeit without a specified link function--yet). These assumptions can (and should) be written mathematically so that we can determine an appropriate procedure to estimate $p(x,s)$. Consider a cockroach of species $s$ that was administered a dose $x$ between $a$ and $b$ units. The indicator of its death is a random variable taking the value $1$ with probability $p(x,s)$. The total number of deaths of $20$ such individuals is the sum of $20$ such variables, where $x$ ranges between $a$ and $b$ as determined in the experiment. If $x$ were fixed, that total would therefore have a Binomial$(20, p(x,s))$ distribution. But if $p(x,s)$ varies over that interval $(a,b]$, then the total has a different distribution. To make further progress, we have to specify how $p$ might vary with $x$. A standard, simple way is with a "logistic link function" where the log odds of death are assumed to be a linear function of dose. Equivalently, let's suppose $$p(x,s) = 1 - \frac{1}{1 + \exp{\left(\alpha(s) + \beta(s)x\right)}}$$ for numbers $\alpha(s)$ and $\beta(s)$ that could differ between the two species. (This gives two competing models: when $\alpha$ or $\beta$ differ between the species the model has an "interaction.") In the next plot, $x$ values were randomly assigned (independently) within each interval (limiting the "20+" interval to the range 20-25) and the model without interaction was fit. The curves plot $p(x,s)$ for $s=1,2$. The uncertainty arising from recording each dose only with its interval can be assessed by repeating this random selection of possible doses within the intervals. For the next figure, 100 models were fit. The doses within each interval were chosen according to various scaled Beta distributions with randomly-selected parameters; some of those parameter choices could cause most of the doses to be near one end of an interval or another. For each iteration the same Beta distribution, appropriately scaled, was used in each interval: thus, doses might be consistently chosen near the low ends or near the high ends of the intervals. To combine the two assessments of uncertainty--prediction error as estimated within the model and variation due to uncertain location of the doses within each interval--the last figure superimposes all 100 "error polygons" (as shown in the second figure above). Most of the data fit nicely within these visual envelopes. The only exception is the observation of no deaths for Species 1 (red) at a dose of 0-1 units: its interval, plotted in the bottom left corner, appears to be a little low. I will end by saying a little more about the "interaction." For all 100 datasets, both models were fit (with and without interaction). Just as an analyst might do in practice, the no-interaction model was chosen unless the model with interaction was determined to be "more significant" than the one without interaction. The decision was made by comparing the AICs of the models, referring the difference to a $\chi^2(1)$ distribution, and setting the significance level at $95\%$. What actually happened is that in every case, the no-interaction model was chosen. Visually, no interaction means that the fitted curves are horizontal translates of each other: that is, there will be some constant $\mu$ for which $p(x,1)=p(x-\mu,2)$ for all $x$. You can see this in the second figure above: the fit (black curve) for Species 1 is about $\mu=9$ dose units to the right of the fit for Species 2. One might interpret this as follows: The susceptibility of Species 2 to the dose is about the same as giving nine more units of the dose to an individual of Species 1. As an example of what effect this dynamic model selection might have, let's alter the data a tiny bit. Suppose that $12$ instead of $20$ deaths were observed in Species 1 at a dose of "20+". Now, fairly frequently, the data appear to have different "shapes" for the two species. The models with interaction fit steeper dose-response curves to Species 2 than to Species 1. What is especially interesting is how these overlapping fits and error envelopes collectively account for (a) uncertainty computed within each model, (b) uncertainty due to how doses were recorded, and now (c) uncertainty due to the analyst's choice of model.
Reasons as to why standard multiple regression would not be appropriate?
The really interesting aspect of this question is that the doses are recorded as intervals and those intervals span sizable portions of the total range. This means we should be concerned that standard
Reasons as to why standard multiple regression would not be appropriate? The really interesting aspect of this question is that the doses are recorded as intervals and those intervals span sizable portions of the total range. This means we should be concerned that standard procedures, like logistic regression, that represent the doses as individual numbers might be misleading. By means of visualizations, I will take you step-by-step through a simple (and no means thorough) analysis until we arrive at the final complex but highly illuminating graphic. Your time might best be used by skimming down the plots, then backing up to study anything that captures your interest. Let's look at this more closely. Suppose that any given dose $x$ (not a range--an actual dose) is associated with a chance of $p(x, s)$ that any cockroach of species $s$ will die in these experimental conditions. Further suppose that cockroach deaths are (statistically) independent. (This assumption can in principle be tested; for now, it is needed because relevant information for testing it is unavailable.) This is a Binomial Generalized Linear Model (albeit without a specified link function--yet). These assumptions can (and should) be written mathematically so that we can determine an appropriate procedure to estimate $p(x,s)$. Consider a cockroach of species $s$ that was administered a dose $x$ between $a$ and $b$ units. The indicator of its death is a random variable taking the value $1$ with probability $p(x,s)$. The total number of deaths of $20$ such individuals is the sum of $20$ such variables, where $x$ ranges between $a$ and $b$ as determined in the experiment. If $x$ were fixed, that total would therefore have a Binomial$(20, p(x,s))$ distribution. But if $p(x,s)$ varies over that interval $(a,b]$, then the total has a different distribution. To make further progress, we have to specify how $p$ might vary with $x$. A standard, simple way is with a "logistic link function" where the log odds of death are assumed to be a linear function of dose. Equivalently, let's suppose $$p(x,s) = 1 - \frac{1}{1 + \exp{\left(\alpha(s) + \beta(s)x\right)}}$$ for numbers $\alpha(s)$ and $\beta(s)$ that could differ between the two species. (This gives two competing models: when $\alpha$ or $\beta$ differ between the species the model has an "interaction.") In the next plot, $x$ values were randomly assigned (independently) within each interval (limiting the "20+" interval to the range 20-25) and the model without interaction was fit. The curves plot $p(x,s)$ for $s=1,2$. The uncertainty arising from recording each dose only with its interval can be assessed by repeating this random selection of possible doses within the intervals. For the next figure, 100 models were fit. The doses within each interval were chosen according to various scaled Beta distributions with randomly-selected parameters; some of those parameter choices could cause most of the doses to be near one end of an interval or another. For each iteration the same Beta distribution, appropriately scaled, was used in each interval: thus, doses might be consistently chosen near the low ends or near the high ends of the intervals. To combine the two assessments of uncertainty--prediction error as estimated within the model and variation due to uncertain location of the doses within each interval--the last figure superimposes all 100 "error polygons" (as shown in the second figure above). Most of the data fit nicely within these visual envelopes. The only exception is the observation of no deaths for Species 1 (red) at a dose of 0-1 units: its interval, plotted in the bottom left corner, appears to be a little low. I will end by saying a little more about the "interaction." For all 100 datasets, both models were fit (with and without interaction). Just as an analyst might do in practice, the no-interaction model was chosen unless the model with interaction was determined to be "more significant" than the one without interaction. The decision was made by comparing the AICs of the models, referring the difference to a $\chi^2(1)$ distribution, and setting the significance level at $95\%$. What actually happened is that in every case, the no-interaction model was chosen. Visually, no interaction means that the fitted curves are horizontal translates of each other: that is, there will be some constant $\mu$ for which $p(x,1)=p(x-\mu,2)$ for all $x$. You can see this in the second figure above: the fit (black curve) for Species 1 is about $\mu=9$ dose units to the right of the fit for Species 2. One might interpret this as follows: The susceptibility of Species 2 to the dose is about the same as giving nine more units of the dose to an individual of Species 1. As an example of what effect this dynamic model selection might have, let's alter the data a tiny bit. Suppose that $12$ instead of $20$ deaths were observed in Species 1 at a dose of "20+". Now, fairly frequently, the data appear to have different "shapes" for the two species. The models with interaction fit steeper dose-response curves to Species 2 than to Species 1. What is especially interesting is how these overlapping fits and error envelopes collectively account for (a) uncertainty computed within each model, (b) uncertainty due to how doses were recorded, and now (c) uncertainty due to the analyst's choice of model.
Reasons as to why standard multiple regression would not be appropriate? The really interesting aspect of this question is that the doses are recorded as intervals and those intervals span sizable portions of the total range. This means we should be concerned that standard
48,431
Differences between a sequence of simple linear regressions vs a single multiple linear regression
The second strategy is the same linear model, but with a different/inferior estimation procedure. Let's look at the sequential approach more closely, with two covariates $X_1$ and $X_2$. After regressing $Y$ on $X_1$, we have: $$\hat Y = b_0 + b_1X_1$$ Now, you want to regress the residuals on $X_2$. Thus, the model we are assuming is, $$Y - \hat Y = \alpha_0 + \alpha_1 X_2 + \epsilon$$ Or equivalently, \begin{align*} Y &= \hat Y + \alpha_0 + \alpha_1 X_2 + \epsilon \\ &= (b_0 + \alpha_0) + b_1 X_1 + \alpha_1 X_2 + \epsilon \end{align*} It seems to me, that the sequential approach is more or less a roundabout way, to getting the same linear model, with a different estimation procedure. Strategy 1 $$Y = \beta_0 + \beta_1X_1 + \beta_2X_2 + \epsilon$$ Strategy 2 $$Y = (b_0 + \alpha_0) + b_1 X_1 + \alpha_1 X_2 + \epsilon$$ Since the OLS estimators are the Best Linear Unbiased Estimators for normally distributed $\epsilon$, it's hard to imagine that the second approach could offer any improvement. Simulations I simulated $n=100$ data points from the model $Y = 1 + 2X_1 - X_2 + \epsilon$, where $\epsilon \sim N(0, 1)$. Repeating the simulation $10,000$ times, we can consider sampling distributions for the OLS and sequential procedures. The estimation of $\beta_3$ is comparable for both cases, but the OLS estimation procedure leads to more precise estimation of $\beta_0$ and $\beta_1$.
Differences between a sequence of simple linear regressions vs a single multiple linear regression
The second strategy is the same linear model, but with a different/inferior estimation procedure. Let's look at the sequential approach more closely, with two covariates $X_1$ and $X_2$. After regres
Differences between a sequence of simple linear regressions vs a single multiple linear regression The second strategy is the same linear model, but with a different/inferior estimation procedure. Let's look at the sequential approach more closely, with two covariates $X_1$ and $X_2$. After regressing $Y$ on $X_1$, we have: $$\hat Y = b_0 + b_1X_1$$ Now, you want to regress the residuals on $X_2$. Thus, the model we are assuming is, $$Y - \hat Y = \alpha_0 + \alpha_1 X_2 + \epsilon$$ Or equivalently, \begin{align*} Y &= \hat Y + \alpha_0 + \alpha_1 X_2 + \epsilon \\ &= (b_0 + \alpha_0) + b_1 X_1 + \alpha_1 X_2 + \epsilon \end{align*} It seems to me, that the sequential approach is more or less a roundabout way, to getting the same linear model, with a different estimation procedure. Strategy 1 $$Y = \beta_0 + \beta_1X_1 + \beta_2X_2 + \epsilon$$ Strategy 2 $$Y = (b_0 + \alpha_0) + b_1 X_1 + \alpha_1 X_2 + \epsilon$$ Since the OLS estimators are the Best Linear Unbiased Estimators for normally distributed $\epsilon$, it's hard to imagine that the second approach could offer any improvement. Simulations I simulated $n=100$ data points from the model $Y = 1 + 2X_1 - X_2 + \epsilon$, where $\epsilon \sim N(0, 1)$. Repeating the simulation $10,000$ times, we can consider sampling distributions for the OLS and sequential procedures. The estimation of $\beta_3$ is comparable for both cases, but the OLS estimation procedure leads to more precise estimation of $\beta_0$ and $\beta_1$.
Differences between a sequence of simple linear regressions vs a single multiple linear regression The second strategy is the same linear model, but with a different/inferior estimation procedure. Let's look at the sequential approach more closely, with two covariates $X_1$ and $X_2$. After regres
48,432
With H2O AutoML is it okay to use my test set as the leaderboard?
According to the docs: leaderboard_frame: This argument allows the user to specify a particular data frame to rank the models on the leaderboard. This frame will not be used for anything besides creating the leaderboard. If this option is not specified, then a leaderboard_frame will be created from the training_frame. This means that the validation_frame is used to tune the hyperparameters on the individual models, and then leaderboard_frame is used to choose the winning tuned model. This choice makes the winning models score on the leaderboard_frame optimistically biased, for the same reason the validation set performance of the tuned model is always optimistically biased (you cannot use the same data set to make modeling choices and estimate the hold out error). So, if you would like an unbiased estimate of the final, tuned model, then you still need a test set held out from the whole process.
With H2O AutoML is it okay to use my test set as the leaderboard?
According to the docs: leaderboard_frame: This argument allows the user to specify a particular data frame to rank the models on the leaderboard. This frame will not be used for anything besides crea
With H2O AutoML is it okay to use my test set as the leaderboard? According to the docs: leaderboard_frame: This argument allows the user to specify a particular data frame to rank the models on the leaderboard. This frame will not be used for anything besides creating the leaderboard. If this option is not specified, then a leaderboard_frame will be created from the training_frame. This means that the validation_frame is used to tune the hyperparameters on the individual models, and then leaderboard_frame is used to choose the winning tuned model. This choice makes the winning models score on the leaderboard_frame optimistically biased, for the same reason the validation set performance of the tuned model is always optimistically biased (you cannot use the same data set to make modeling choices and estimate the hold out error). So, if you would like an unbiased estimate of the final, tuned model, then you still need a test set held out from the whole process.
With H2O AutoML is it okay to use my test set as the leaderboard? According to the docs: leaderboard_frame: This argument allows the user to specify a particular data frame to rank the models on the leaderboard. This frame will not be used for anything besides crea
48,433
Recurrent networks mimicking previous / current input
This is a very common problem. Here is an article with a good explanation. People have been trying to do this for a very long time, and it is safe to say there is no such thing as model that can tell you what the price of a financial instrument will be in the future with good accuracy. Some people believe that there isn't any way to predict the future prices of the market any better than flipping a coin (Random walk theory, Here is a good explanation of it). This is totally not true though. The movement of markets is almost a random walk, but not 100% random. This does not mean that machine learning has no use for trading however. I won't give away too much, and anyone who has figured out how to use it to their advantage won't mention their details either, but you have to get outside the box a bit. Putting in price history and getting a future price is way too good to ever be true. A better approach is using multiple different networks for several different easier problems, and using what they come up with and your own knowledge to screen for a good stock to buy. If you really want to use machine learning for trading, you are going to have to be very dedicated to it and invest a huge amount of time. You not only need to master the machine learning side of it, but you will also have to master the market.
Recurrent networks mimicking previous / current input
This is a very common problem. Here is an article with a good explanation. People have been trying to do this for a very long time, and it is safe to say there is no such thing as model that can tell
Recurrent networks mimicking previous / current input This is a very common problem. Here is an article with a good explanation. People have been trying to do this for a very long time, and it is safe to say there is no such thing as model that can tell you what the price of a financial instrument will be in the future with good accuracy. Some people believe that there isn't any way to predict the future prices of the market any better than flipping a coin (Random walk theory, Here is a good explanation of it). This is totally not true though. The movement of markets is almost a random walk, but not 100% random. This does not mean that machine learning has no use for trading however. I won't give away too much, and anyone who has figured out how to use it to their advantage won't mention their details either, but you have to get outside the box a bit. Putting in price history and getting a future price is way too good to ever be true. A better approach is using multiple different networks for several different easier problems, and using what they come up with and your own knowledge to screen for a good stock to buy. If you really want to use machine learning for trading, you are going to have to be very dedicated to it and invest a huge amount of time. You not only need to master the machine learning side of it, but you will also have to master the market.
Recurrent networks mimicking previous / current input This is a very common problem. Here is an article with a good explanation. People have been trying to do this for a very long time, and it is safe to say there is no such thing as model that can tell
48,434
Why can't ARIMA model large lags and/or long range dependence?
As Pr. Hyndman explains in this blog post, there's nothing in the mathematics of ARMA models that would restrict forecasting long seasonal periods. The reason you can't forecast very long periods is the fact that most software tools (including R packages) have a threshold on the allowed seasonal lags due to the high computational demands of the estimation process. I can imagine that the estimation of MA(q) processes, in particular, can become extremely expensive since its complexity increases in a high polynomial degree with seasonal order (if I'm not mistaken). Besides the restrictions on computational demands, there is also little point in trying to forecast such a large series. As Hyndman points out, "seasonal differencing of very high order does not make a lot of sense - for daily data it involves comparing what happened today with what happened exactly a year ago and there is no constraint that the seasonal pattern is smooth". These long seasonal terms could result to overfitting and the best way to deal with this scenario would be to use a Fourier series.
Why can't ARIMA model large lags and/or long range dependence?
As Pr. Hyndman explains in this blog post, there's nothing in the mathematics of ARMA models that would restrict forecasting long seasonal periods. The reason you can't forecast very long periods is t
Why can't ARIMA model large lags and/or long range dependence? As Pr. Hyndman explains in this blog post, there's nothing in the mathematics of ARMA models that would restrict forecasting long seasonal periods. The reason you can't forecast very long periods is the fact that most software tools (including R packages) have a threshold on the allowed seasonal lags due to the high computational demands of the estimation process. I can imagine that the estimation of MA(q) processes, in particular, can become extremely expensive since its complexity increases in a high polynomial degree with seasonal order (if I'm not mistaken). Besides the restrictions on computational demands, there is also little point in trying to forecast such a large series. As Hyndman points out, "seasonal differencing of very high order does not make a lot of sense - for daily data it involves comparing what happened today with what happened exactly a year ago and there is no constraint that the seasonal pattern is smooth". These long seasonal terms could result to overfitting and the best way to deal with this scenario would be to use a Fourier series.
Why can't ARIMA model large lags and/or long range dependence? As Pr. Hyndman explains in this blog post, there's nothing in the mathematics of ARMA models that would restrict forecasting long seasonal periods. The reason you can't forecast very long periods is t
48,435
Learning from the flaws in the NHST and p-values
Even if you do get a significant p-value from a test of significance, you are supposed to look at the magnitude of the effect by constructing a confidence interval for it. Case 1: When examining the confidence interval, if you notice for example that the interval falls entirely below your predefined threshold for what constitutes a clinically important effect, you will have to conclude that while there is likely an effect in the underlying population, its magnitude is so small from a clinical perspective that it may not have any practical value. Case 2 If the interval does include your predefined threshold for what constitutes a clinically important effect, you will not be able to rule out the possibility that the effect you are interested in for the underlying population may be large enough to have practical importance. ————-/————- There is currently a push to replace tests of significance entirely with confidence intervals and, when using confidence intervals, to interpret them as compatibility intervals. Often, in practice, people will just perform a test of significance, without reporting a confidence interval for the effect they test. When they do report a confidence interval, they might not always have a clear sense of what constitutes a clinically (or practically) relevant effect size. So they might be happy to declare the effect is statistically significant (i.e., it is likely to exist in the underlying population) when its corresponding p-value is significant, without worrying about its clinical (or practical) relevance. For people who rely exclusively on reporting p-values for tests of significance, there is also the danger that they will invariably conclude a lack of effect when a p-value is not significant when an alternative explanation might be that there is an effect but the study was powered inadequately to detect it. A confidence interval would be easier to interpret in these cases. In general, the real problem is that people are wired to want definitive findings from one-off studies which are typically under-powered. So when they find inconclusive findings, they stretch them to be more conclusive by using ill-fated terms such as “the result is trending towards statistical significance”, etc. So I would say you can improve your current practice by always reporting confidence intervals for the effects you test (either in lieu of or as a supplement to tests of significance).
Learning from the flaws in the NHST and p-values
Even if you do get a significant p-value from a test of significance, you are supposed to look at the magnitude of the effect by constructing a confidence interval for it. Case 1: When examining the c
Learning from the flaws in the NHST and p-values Even if you do get a significant p-value from a test of significance, you are supposed to look at the magnitude of the effect by constructing a confidence interval for it. Case 1: When examining the confidence interval, if you notice for example that the interval falls entirely below your predefined threshold for what constitutes a clinically important effect, you will have to conclude that while there is likely an effect in the underlying population, its magnitude is so small from a clinical perspective that it may not have any practical value. Case 2 If the interval does include your predefined threshold for what constitutes a clinically important effect, you will not be able to rule out the possibility that the effect you are interested in for the underlying population may be large enough to have practical importance. ————-/————- There is currently a push to replace tests of significance entirely with confidence intervals and, when using confidence intervals, to interpret them as compatibility intervals. Often, in practice, people will just perform a test of significance, without reporting a confidence interval for the effect they test. When they do report a confidence interval, they might not always have a clear sense of what constitutes a clinically (or practically) relevant effect size. So they might be happy to declare the effect is statistically significant (i.e., it is likely to exist in the underlying population) when its corresponding p-value is significant, without worrying about its clinical (or practical) relevance. For people who rely exclusively on reporting p-values for tests of significance, there is also the danger that they will invariably conclude a lack of effect when a p-value is not significant when an alternative explanation might be that there is an effect but the study was powered inadequately to detect it. A confidence interval would be easier to interpret in these cases. In general, the real problem is that people are wired to want definitive findings from one-off studies which are typically under-powered. So when they find inconclusive findings, they stretch them to be more conclusive by using ill-fated terms such as “the result is trending towards statistical significance”, etc. So I would say you can improve your current practice by always reporting confidence intervals for the effects you test (either in lieu of or as a supplement to tests of significance).
Learning from the flaws in the NHST and p-values Even if you do get a significant p-value from a test of significance, you are supposed to look at the magnitude of the effect by constructing a confidence interval for it. Case 1: When examining the c
48,436
Learning from the flaws in the NHST and p-values
I am going to change your question slightly to "patient can only notice a change of more than 1 cm" (this makes the null a closed set, but a more complicated argument holds for open sets). Your reasoning does not overcome the issue because what you really want to test is $|\mu_0-\mu_1|\le 1{\rm cm}$ and not $\mu_o=\mu_1$, so the standard problems of NHST will come up for the hypothesis $|\mu_0-\mu_1|\le 1{\rm cm}$. Regardless, an almost sure hypothesis testing resolves these issues in any sufficiently large sample. Take your significance level to be $n^{-p}$ for $p>1$ where $n$ is sample size, then in any sufficiently large sample you will reject $\mu_o=\mu_1$ when it is false and accept $\mu_o=\mu_1$ when it is true with probability one. The same is true for the hypothesis $|\mu_0-\mu_1|\le 1{\rm cm}$. Almost sure hypothesis testing is robust to optional stopping, finitely many multiple comparisons, and publication bias. It can also be used for model selection. I wrote about this in a paper called, "Almost sure hypothesis testing and a resolution of the Jeffreys-Lindley paradox".
Learning from the flaws in the NHST and p-values
I am going to change your question slightly to "patient can only notice a change of more than 1 cm" (this makes the null a closed set, but a more complicated argument holds for open sets). Your reaso
Learning from the flaws in the NHST and p-values I am going to change your question slightly to "patient can only notice a change of more than 1 cm" (this makes the null a closed set, but a more complicated argument holds for open sets). Your reasoning does not overcome the issue because what you really want to test is $|\mu_0-\mu_1|\le 1{\rm cm}$ and not $\mu_o=\mu_1$, so the standard problems of NHST will come up for the hypothesis $|\mu_0-\mu_1|\le 1{\rm cm}$. Regardless, an almost sure hypothesis testing resolves these issues in any sufficiently large sample. Take your significance level to be $n^{-p}$ for $p>1$ where $n$ is sample size, then in any sufficiently large sample you will reject $\mu_o=\mu_1$ when it is false and accept $\mu_o=\mu_1$ when it is true with probability one. The same is true for the hypothesis $|\mu_0-\mu_1|\le 1{\rm cm}$. Almost sure hypothesis testing is robust to optional stopping, finitely many multiple comparisons, and publication bias. It can also be used for model selection. I wrote about this in a paper called, "Almost sure hypothesis testing and a resolution of the Jeffreys-Lindley paradox".
Learning from the flaws in the NHST and p-values I am going to change your question slightly to "patient can only notice a change of more than 1 cm" (this makes the null a closed set, but a more complicated argument holds for open sets). Your reaso
48,437
Overfitting in neural network
Without knowing a lot more about the model, nor the data used, it is hard to answer these questions with and rigour. That aside, the values you provide would make the think it is a reasonable model and does not necessarily overfit the training data. for your second question, my first line of action would always be to plot the training and test accuracy over each epoch (iteration), then look at how the curves develop. I generally hope to see a test curve that shadows the training curve, always a little lower. Here is a diagram with a short explanation taken from the amazing cs231n course from Stanford. Image source Course Homepage All the material and video lectures are freely available and would be a great place for you to improve your understanding whilst working on Deep Learning topics.
Overfitting in neural network
Without knowing a lot more about the model, nor the data used, it is hard to answer these questions with and rigour. That aside, the values you provide would make the think it is a reasonable model an
Overfitting in neural network Without knowing a lot more about the model, nor the data used, it is hard to answer these questions with and rigour. That aside, the values you provide would make the think it is a reasonable model and does not necessarily overfit the training data. for your second question, my first line of action would always be to plot the training and test accuracy over each epoch (iteration), then look at how the curves develop. I generally hope to see a test curve that shadows the training curve, always a little lower. Here is a diagram with a short explanation taken from the amazing cs231n course from Stanford. Image source Course Homepage All the material and video lectures are freely available and would be a great place for you to improve your understanding whilst working on Deep Learning topics.
Overfitting in neural network Without knowing a lot more about the model, nor the data used, it is hard to answer these questions with and rigour. That aside, the values you provide would make the think it is a reasonable model an
48,438
Overfitting in neural network
Overfitting is something that happens gradually, so it is sometimes hard to say. Also, whether a model is "good" or not depends a lot on context. If you need 99% accuracy for your model to be used in production then the values are not "good". However, the values you show for train and test loss, accuracy do not indicate a problem with overfitting to me. It is normal to see a slight drop in performance between training values and test values. Not only that, but is often acceptable to have a bigger difference between train and test provided that test performance is still better than any other test performance. One important detail missing is the size of the test data. The reported accuracy is only an estimate, and the smaller your test set, the less reliable it is for drawing conclusions from. For better detection of overfitting you can plot a learning graph of your loss metrics versus epoch number. If you see something like this (From Wikipedia page on Overfitting): where the blue line is your training loss and the red line is your test loss. Then you can see that overfitting has become a problem after the warning sign. This kind of learning behaviour, with an optimum number of epochs before overfitting occurs, is one reason why early stopping is a common approach in training.
Overfitting in neural network
Overfitting is something that happens gradually, so it is sometimes hard to say. Also, whether a model is "good" or not depends a lot on context. If you need 99% accuracy for your model to be used in
Overfitting in neural network Overfitting is something that happens gradually, so it is sometimes hard to say. Also, whether a model is "good" or not depends a lot on context. If you need 99% accuracy for your model to be used in production then the values are not "good". However, the values you show for train and test loss, accuracy do not indicate a problem with overfitting to me. It is normal to see a slight drop in performance between training values and test values. Not only that, but is often acceptable to have a bigger difference between train and test provided that test performance is still better than any other test performance. One important detail missing is the size of the test data. The reported accuracy is only an estimate, and the smaller your test set, the less reliable it is for drawing conclusions from. For better detection of overfitting you can plot a learning graph of your loss metrics versus epoch number. If you see something like this (From Wikipedia page on Overfitting): where the blue line is your training loss and the red line is your test loss. Then you can see that overfitting has become a problem after the warning sign. This kind of learning behaviour, with an optimum number of epochs before overfitting occurs, is one reason why early stopping is a common approach in training.
Overfitting in neural network Overfitting is something that happens gradually, so it is sometimes hard to say. Also, whether a model is "good" or not depends a lot on context. If you need 99% accuracy for your model to be used in
48,439
What happens if I do principal components of the principal components?
Turning my comment above into an answer: Since your first PCA identifies orthogonal vectors, your second PCA should in principle do nothing (since it should basically find the same axes as the first round). But as @NickCox points out, coefficients might be reversed. However, there may be small differences in practice for algorithmic reasons.
What happens if I do principal components of the principal components?
Turning my comment above into an answer: Since your first PCA identifies orthogonal vectors, your second PCA should in principle do nothing (since it should basically find the same axes as the first
What happens if I do principal components of the principal components? Turning my comment above into an answer: Since your first PCA identifies orthogonal vectors, your second PCA should in principle do nothing (since it should basically find the same axes as the first round). But as @NickCox points out, coefficients might be reversed. However, there may be small differences in practice for algorithmic reasons.
What happens if I do principal components of the principal components? Turning my comment above into an answer: Since your first PCA identifies orthogonal vectors, your second PCA should in principle do nothing (since it should basically find the same axes as the first
48,440
How to compute $\mathbb{E}\left[Y_1Y_2 \mid |U_1-U_2| <a\right]$ for $Y_i\sim N\left(\beta U_i, \sigma^2\right)$ and $U_i \sim Unif(0,1)$?
Suppose you know that $U_1$, $U_2$, obtain the values $u_1$, $u_2$, respectively. Then, because of the independence of the variables, $$ E[Y_1 Y_2 | U_1 = u_1, U_2 = u_2] = \beta^2 u_1 u_2. $$ Therefore, we need to calculate $$ \int_{u_1 = 0}^1 \int_{u_2 = u_1}^{u_1 + a} \beta^2 u_1 u_2 \text{d} u_2 \text{d} u_1 + \int_{u_2 = 0}^1 \int_{u_1 = u_2}^{u_2 + a} \beta^2 u_1 u_2 \text{d} u_1 \text{d} u_2 $$ This can be simplified to $$ 2 \beta^2 \int_{u_1 = 0}^1 u_1 \int_{u_2 = u_1}^{u_1 + a} u_2 \text{d} u_2 \text{d} u_1, $$ which is very easy to calculate.
How to compute $\mathbb{E}\left[Y_1Y_2 \mid |U_1-U_2| <a\right]$ for $Y_i\sim N\left(\beta U_i, \sig
Suppose you know that $U_1$, $U_2$, obtain the values $u_1$, $u_2$, respectively. Then, because of the independence of the variables, $$ E[Y_1 Y_2 | U_1 = u_1, U_2 = u_2] = \beta^2 u_1 u_2. $$ Theref
How to compute $\mathbb{E}\left[Y_1Y_2 \mid |U_1-U_2| <a\right]$ for $Y_i\sim N\left(\beta U_i, \sigma^2\right)$ and $U_i \sim Unif(0,1)$? Suppose you know that $U_1$, $U_2$, obtain the values $u_1$, $u_2$, respectively. Then, because of the independence of the variables, $$ E[Y_1 Y_2 | U_1 = u_1, U_2 = u_2] = \beta^2 u_1 u_2. $$ Therefore, we need to calculate $$ \int_{u_1 = 0}^1 \int_{u_2 = u_1}^{u_1 + a} \beta^2 u_1 u_2 \text{d} u_2 \text{d} u_1 + \int_{u_2 = 0}^1 \int_{u_1 = u_2}^{u_2 + a} \beta^2 u_1 u_2 \text{d} u_1 \text{d} u_2 $$ This can be simplified to $$ 2 \beta^2 \int_{u_1 = 0}^1 u_1 \int_{u_2 = u_1}^{u_1 + a} u_2 \text{d} u_2 \text{d} u_1, $$ which is very easy to calculate.
How to compute $\mathbb{E}\left[Y_1Y_2 \mid |U_1-U_2| <a\right]$ for $Y_i\sim N\left(\beta U_i, \sig Suppose you know that $U_1$, $U_2$, obtain the values $u_1$, $u_2$, respectively. Then, because of the independence of the variables, $$ E[Y_1 Y_2 | U_1 = u_1, U_2 = u_2] = \beta^2 u_1 u_2. $$ Theref
48,441
Are XGBoost probability outputs based on the number of examples in a terminal leaf
Are XGBoost probability outputs based on the number of examples in a terminal leaf? No. XGBoost is a gradient boosted tree, so it's estimating weights $c \in \mathbb{R^M}$ that assigns weight the $M$ leafs. A sample prediction (on the logit scale) is the sum of its leafs' weights. In the binary case, the inverse logistic function of the logit score yields a predicted probability. The XGBoost paper has a helpful description of how it works. Tianqi Chen, Carlos Guestrin, "XGBoost: A Scalable Tree Boosting System." See also: In XGboost are weights estimated for each sample and then averaged
Are XGBoost probability outputs based on the number of examples in a terminal leaf
Are XGBoost probability outputs based on the number of examples in a terminal leaf? No. XGBoost is a gradient boosted tree, so it's estimating weights $c \in \mathbb{R^M}$ that assigns weight the $M$
Are XGBoost probability outputs based on the number of examples in a terminal leaf Are XGBoost probability outputs based on the number of examples in a terminal leaf? No. XGBoost is a gradient boosted tree, so it's estimating weights $c \in \mathbb{R^M}$ that assigns weight the $M$ leafs. A sample prediction (on the logit scale) is the sum of its leafs' weights. In the binary case, the inverse logistic function of the logit score yields a predicted probability. The XGBoost paper has a helpful description of how it works. Tianqi Chen, Carlos Guestrin, "XGBoost: A Scalable Tree Boosting System." See also: In XGboost are weights estimated for each sample and then averaged
Are XGBoost probability outputs based on the number of examples in a terminal leaf Are XGBoost probability outputs based on the number of examples in a terminal leaf? No. XGBoost is a gradient boosted tree, so it's estimating weights $c \in \mathbb{R^M}$ that assigns weight the $M$
48,442
Are XGBoost probability outputs based on the number of examples in a terminal leaf
No. I do not know how XGBoost estimates probabilities, but from my experience if you have say 100 samples, the probabilities estimates will not (necessarily) be multiples of 0.01 (which would be the case for decision trees). Therefore, there must be something else in the estimation of probabilities with XGBoost.
Are XGBoost probability outputs based on the number of examples in a terminal leaf
No. I do not know how XGBoost estimates probabilities, but from my experience if you have say 100 samples, the probabilities estimates will not (necessarily) be multiples of 0.01 (which would be the c
Are XGBoost probability outputs based on the number of examples in a terminal leaf No. I do not know how XGBoost estimates probabilities, but from my experience if you have say 100 samples, the probabilities estimates will not (necessarily) be multiples of 0.01 (which would be the case for decision trees). Therefore, there must be something else in the estimation of probabilities with XGBoost.
Are XGBoost probability outputs based on the number of examples in a terminal leaf No. I do not know how XGBoost estimates probabilities, but from my experience if you have say 100 samples, the probabilities estimates will not (necessarily) be multiples of 0.01 (which would be the c
48,443
Replacing RNNs with dilated convolutions
Just in case anyone is interested: yes, it is possible to replace the RNN layers by Dilated Convolutions (DCs). The architectures described in speech recognition literature did not work out of the box for HTR, but with some modifications results got better. I will give a short summary. The NN contains CNN layers and a final CTC layer. In between, I integrated DCs. I grouped layers of DCs into blocks: each block has a layer with a sampling rate of 1, 2 and 4. Each kernel has size 3x3. The kernel weights (k1, k2, k4) across blocks are shared. The tested NN contains 2 blocks, and all intermediate outputs (o1, o2, ..., o6) are concatenated to form a large feature matrix. Finally, for each time-step the features are mapped to all possible characters, which are then fed into the CTC layer.
Replacing RNNs with dilated convolutions
Just in case anyone is interested: yes, it is possible to replace the RNN layers by Dilated Convolutions (DCs). The architectures described in speech recognition literature did not work out of the box
Replacing RNNs with dilated convolutions Just in case anyone is interested: yes, it is possible to replace the RNN layers by Dilated Convolutions (DCs). The architectures described in speech recognition literature did not work out of the box for HTR, but with some modifications results got better. I will give a short summary. The NN contains CNN layers and a final CTC layer. In between, I integrated DCs. I grouped layers of DCs into blocks: each block has a layer with a sampling rate of 1, 2 and 4. Each kernel has size 3x3. The kernel weights (k1, k2, k4) across blocks are shared. The tested NN contains 2 blocks, and all intermediate outputs (o1, o2, ..., o6) are concatenated to form a large feature matrix. Finally, for each time-step the features are mapped to all possible characters, which are then fed into the CTC layer.
Replacing RNNs with dilated convolutions Just in case anyone is interested: yes, it is possible to replace the RNN layers by Dilated Convolutions (DCs). The architectures described in speech recognition literature did not work out of the box
48,444
Low loss and low accuracy. What is the reason? [duplicate]
Lower cost function error not means better accuracy. The error of the cost function represents how well your model is learning/able to learn with respect to your training examples. Now the question is , Is the model learning something that I expect it to learn? It can show very low learning curves error but when you actually testing the results (Accuracy) you are getting wrong detection's , this is called high variance. The best is to monitor the both learning error and accuracy for each epoch/iteration, While cost function error goes down and accuracy goes up keep training, otherwise stop (: The accuracy is not good enough? check : 1. do I have high variance problem ? add more training examples to generalize the learning (better find more examples which reminds the problems where your model fails on). Do I have high bias problem ? my model is pure or to complex , need to fix it / try something else. http://www.holehouse.org/mlclass/10_Advice_for_applying_machine_learning.html Good luck (:
Low loss and low accuracy. What is the reason? [duplicate]
Lower cost function error not means better accuracy. The error of the cost function represents how well your model is learning/able to learn with respect to your training examples. Now the question is
Low loss and low accuracy. What is the reason? [duplicate] Lower cost function error not means better accuracy. The error of the cost function represents how well your model is learning/able to learn with respect to your training examples. Now the question is , Is the model learning something that I expect it to learn? It can show very low learning curves error but when you actually testing the results (Accuracy) you are getting wrong detection's , this is called high variance. The best is to monitor the both learning error and accuracy for each epoch/iteration, While cost function error goes down and accuracy goes up keep training, otherwise stop (: The accuracy is not good enough? check : 1. do I have high variance problem ? add more training examples to generalize the learning (better find more examples which reminds the problems where your model fails on). Do I have high bias problem ? my model is pure or to complex , need to fix it / try something else. http://www.holehouse.org/mlclass/10_Advice_for_applying_machine_learning.html Good luck (:
Low loss and low accuracy. What is the reason? [duplicate] Lower cost function error not means better accuracy. The error of the cost function represents how well your model is learning/able to learn with respect to your training examples. Now the question is
48,445
Coverage probability of credible intervals if we take Bayesian model literally
I asked a similar question: Methods for testing a Bayesian method's software implementation and got this answer from @jaradniemi: Bayesians don't lose the relative frequency-based interpretation of probability. In particular, if you define this procedure: simulate from the prior, then simulate from the model using those values from the prior, and estimate the parameters using the same prior. Then your credible intervals should have the appropriate frequentist coverage, i.e. 95% intervals should include the true parameter in 95% of your analyses, over repeated replicates of the procedure. I think he's right. You're allowed to stray from the relative-frequency concept of probability as a bayesian, but you don't automatically lose it. And if you're generating data, you definitely haven't lost it. Regarding your question about conditional vs unconditional, while each individual credible interval would be conditional on the data, the relative-frequency based coverage would be unconditional since you're averaging over draws of the data. You can also search the web for "frequentist properties of bayesian methods" and get quite a few hits.
Coverage probability of credible intervals if we take Bayesian model literally
I asked a similar question: Methods for testing a Bayesian method's software implementation and got this answer from @jaradniemi: Bayesians don't lose the relative frequency-based interpretation of
Coverage probability of credible intervals if we take Bayesian model literally I asked a similar question: Methods for testing a Bayesian method's software implementation and got this answer from @jaradniemi: Bayesians don't lose the relative frequency-based interpretation of probability. In particular, if you define this procedure: simulate from the prior, then simulate from the model using those values from the prior, and estimate the parameters using the same prior. Then your credible intervals should have the appropriate frequentist coverage, i.e. 95% intervals should include the true parameter in 95% of your analyses, over repeated replicates of the procedure. I think he's right. You're allowed to stray from the relative-frequency concept of probability as a bayesian, but you don't automatically lose it. And if you're generating data, you definitely haven't lost it. Regarding your question about conditional vs unconditional, while each individual credible interval would be conditional on the data, the relative-frequency based coverage would be unconditional since you're averaging over draws of the data. You can also search the web for "frequentist properties of bayesian methods" and get quite a few hits.
Coverage probability of credible intervals if we take Bayesian model literally I asked a similar question: Methods for testing a Bayesian method's software implementation and got this answer from @jaradniemi: Bayesians don't lose the relative frequency-based interpretation of
48,446
Coverage probability of credible intervals if we take Bayesian model literally
As there is no generally accepted / unique way to specify (uninformative) priors, and as different priors will lead to a different credible intervals, it seems obvious that the coverage of Bayesian CIs is not fixed, but will depend on the prior that you choose, in relation to the "true" parameter values. It will generally also depend on the data, in particular on the size of the data - in a low data situation, the prior dominates the CI, with the mentioned consequences of a strong prior influence on the coverage. When moving to large data / asymptotics, the Bayesian CI and the frequentist CI will usually become increasingly similar, including their coverage properties.
Coverage probability of credible intervals if we take Bayesian model literally
As there is no generally accepted / unique way to specify (uninformative) priors, and as different priors will lead to a different credible intervals, it seems obvious that the coverage of Bayesian CI
Coverage probability of credible intervals if we take Bayesian model literally As there is no generally accepted / unique way to specify (uninformative) priors, and as different priors will lead to a different credible intervals, it seems obvious that the coverage of Bayesian CIs is not fixed, but will depend on the prior that you choose, in relation to the "true" parameter values. It will generally also depend on the data, in particular on the size of the data - in a low data situation, the prior dominates the CI, with the mentioned consequences of a strong prior influence on the coverage. When moving to large data / asymptotics, the Bayesian CI and the frequentist CI will usually become increasingly similar, including their coverage properties.
Coverage probability of credible intervals if we take Bayesian model literally As there is no generally accepted / unique way to specify (uninformative) priors, and as different priors will lead to a different credible intervals, it seems obvious that the coverage of Bayesian CI
48,447
In what situations would one use Approximate Bayesian Computation instead of Bayesian inference?
Quoting the great Wikipedia article on ABC (emphasis added): Approximate Bayesian computation (ABC) constitutes a class of computational methods rooted in Bayesian statistics. In all model-based statistical inference, the likelihood function is of central importance, since it expresses the probability of the observed data under a particular statistical model, and thus quantifies the support data lend to particular values of parameters and to choices among different models. For simple models, an analytical formula for the likelihood function can typically be derived. However, for more complex models, an analytical formula might be elusive or the likelihood function might be computationally very costly to evaluate. ABC methods bypass the evaluation of the likelihood function. (...) When using ABC we approximate the likelihood function using some kind of summary statistics, so you rather would not use it instead of non-approximate Bayesian computation. We can use it in situations, where we cannot use the non-approximate methods. Check the famous socks example by Rasmus Bååth for some friendly introduction (see also here).
In what situations would one use Approximate Bayesian Computation instead of Bayesian inference?
Quoting the great Wikipedia article on ABC (emphasis added): Approximate Bayesian computation (ABC) constitutes a class of computational methods rooted in Bayesian statistics. In all model-based
In what situations would one use Approximate Bayesian Computation instead of Bayesian inference? Quoting the great Wikipedia article on ABC (emphasis added): Approximate Bayesian computation (ABC) constitutes a class of computational methods rooted in Bayesian statistics. In all model-based statistical inference, the likelihood function is of central importance, since it expresses the probability of the observed data under a particular statistical model, and thus quantifies the support data lend to particular values of parameters and to choices among different models. For simple models, an analytical formula for the likelihood function can typically be derived. However, for more complex models, an analytical formula might be elusive or the likelihood function might be computationally very costly to evaluate. ABC methods bypass the evaluation of the likelihood function. (...) When using ABC we approximate the likelihood function using some kind of summary statistics, so you rather would not use it instead of non-approximate Bayesian computation. We can use it in situations, where we cannot use the non-approximate methods. Check the famous socks example by Rasmus Bååth for some friendly introduction (see also here).
In what situations would one use Approximate Bayesian Computation instead of Bayesian inference? Quoting the great Wikipedia article on ABC (emphasis added): Approximate Bayesian computation (ABC) constitutes a class of computational methods rooted in Bayesian statistics. In all model-based
48,448
Mapping Frequentist Risk Notation to Regression
Because the main problem concerns applying a fully general and abstract formula to a somewhat complicated model (regression), let's address it by examining a simple concrete case. Ordinary regression is a good choice because it is well known, well understood, and serves as the archetype of all more complex regression models. But even this comes in several "flavors." The one that seems most relevant for prediction is the one in which the values of $p$ separate regressor ("independent") variables are specified by the experimenter, whose objective is to predict a random response whose distribution depends on the regressors. (As is usual, one of these $p$ regressors may take on a constant value.) The standard notation for this is that vectors of regressor values, $x_1, x_2, \ldots, x_n$ are available (as data). They have been measured precisely along with corresponding responses $y_i$. A model for these responses is that each $y_i$ is an independent realization of a Normal variable with variance $\sigma^2$ and mean $x_i\beta$. (Each $x_i$ is a $p$-covector and $\beta=(\beta_1,\ldots,\beta_p)^\prime$ is a $p$-vector.) Let's review: the values of the $x_i$ are known and not modeled as random variables; the values of the $y_i$ are modeled as realizations of random variables (which we could roll into an $n$-vector $y=(y_1,\ldots,y_n)^\prime$); and the values of the parameter $\theta=(\beta_0,\beta_1,\ldots,\beta_p,\sigma)$ are unknown. Suppose the objective is to predict a response $y_0 = x_0\beta$ for a regressor $x_0$. One standard method says to predict it to be $$\hat y_0 = x_0\hat\beta$$ where $$\hat\beta = (X^\prime X)^{-}X^\prime y \tag{1}$$ and I have let $X$ be the "model matrix" obtained by stacking all $n$ of the covectors $x_i$ into an $n\times p$ matrix. Let's pause for a moment to observe that the model and the model matrix $X$ completely determine the distribution of $\hat y_0$. This is because (a) the independence of the $y_i$ gives $y$ an $n$-variate Normal distribution; (b) its mean is given by $X\beta$; and (c) its covariance matrix is $\sigma^2$ times the $n\times n$ identity matrix. What is not routinely specified is the loss function $L$. This measures the cost to our client when they act as if the correct value of $y_0$ is $\hat y_0$. Because it can depend on both $y_0$ and $\hat y_0$, it is formally written $L(y_0, \hat y_0)$. In the generic notation of the question, the procedure to guess $\hat y_0$ from the data is called $\delta$ and "$x$" refers to the data, which in our application are $X, x_0$, and $y$. Often it is taken to be the squared difference, $L(u,v)=(u-v)^2$. In general, loss functions might as well be zero when $u=v$ (you can't do any better than that) and they increase as $u$ and $v$ get further apart. If you want to unwrap the preceding formulas, you could expand this out as $$L(y_0, \hat y_0) = (y_0-\hat y_0)^2 = (x_0\beta - x_0 (X^\prime X)^{-}X^\prime y)^2.$$ Because we model $y$ as a multivariate Normal vector, this loss is a random variable. Its expectation is taken with respect to the distribution of $y$. The expected loss is the risk of our procedure. It depends on the (unknown) parameter $\theta$ and on the procedure itself. Since we're talking about a definite procedure based on equation $(1)$, it really is just a function of $\theta$: $$R(\theta) = E(x_0\beta - x_0 (X^\prime X)^{-}X^\prime y)^2.$$ Since the right hand side is a random variable whose distribution is completely determined by $\theta$, this all makes sense and is well-defined. We could even write it out explicitly in terms of $X, x_0$ (specified constants all), and $\theta$. Incidentally, for the "expected prediction error" referenced in the question, where $L(u,v)=v-u$, it's easy to show in this case that the risk is zero.
Mapping Frequentist Risk Notation to Regression
Because the main problem concerns applying a fully general and abstract formula to a somewhat complicated model (regression), let's address it by examining a simple concrete case. Ordinary regression
Mapping Frequentist Risk Notation to Regression Because the main problem concerns applying a fully general and abstract formula to a somewhat complicated model (regression), let's address it by examining a simple concrete case. Ordinary regression is a good choice because it is well known, well understood, and serves as the archetype of all more complex regression models. But even this comes in several "flavors." The one that seems most relevant for prediction is the one in which the values of $p$ separate regressor ("independent") variables are specified by the experimenter, whose objective is to predict a random response whose distribution depends on the regressors. (As is usual, one of these $p$ regressors may take on a constant value.) The standard notation for this is that vectors of regressor values, $x_1, x_2, \ldots, x_n$ are available (as data). They have been measured precisely along with corresponding responses $y_i$. A model for these responses is that each $y_i$ is an independent realization of a Normal variable with variance $\sigma^2$ and mean $x_i\beta$. (Each $x_i$ is a $p$-covector and $\beta=(\beta_1,\ldots,\beta_p)^\prime$ is a $p$-vector.) Let's review: the values of the $x_i$ are known and not modeled as random variables; the values of the $y_i$ are modeled as realizations of random variables (which we could roll into an $n$-vector $y=(y_1,\ldots,y_n)^\prime$); and the values of the parameter $\theta=(\beta_0,\beta_1,\ldots,\beta_p,\sigma)$ are unknown. Suppose the objective is to predict a response $y_0 = x_0\beta$ for a regressor $x_0$. One standard method says to predict it to be $$\hat y_0 = x_0\hat\beta$$ where $$\hat\beta = (X^\prime X)^{-}X^\prime y \tag{1}$$ and I have let $X$ be the "model matrix" obtained by stacking all $n$ of the covectors $x_i$ into an $n\times p$ matrix. Let's pause for a moment to observe that the model and the model matrix $X$ completely determine the distribution of $\hat y_0$. This is because (a) the independence of the $y_i$ gives $y$ an $n$-variate Normal distribution; (b) its mean is given by $X\beta$; and (c) its covariance matrix is $\sigma^2$ times the $n\times n$ identity matrix. What is not routinely specified is the loss function $L$. This measures the cost to our client when they act as if the correct value of $y_0$ is $\hat y_0$. Because it can depend on both $y_0$ and $\hat y_0$, it is formally written $L(y_0, \hat y_0)$. In the generic notation of the question, the procedure to guess $\hat y_0$ from the data is called $\delta$ and "$x$" refers to the data, which in our application are $X, x_0$, and $y$. Often it is taken to be the squared difference, $L(u,v)=(u-v)^2$. In general, loss functions might as well be zero when $u=v$ (you can't do any better than that) and they increase as $u$ and $v$ get further apart. If you want to unwrap the preceding formulas, you could expand this out as $$L(y_0, \hat y_0) = (y_0-\hat y_0)^2 = (x_0\beta - x_0 (X^\prime X)^{-}X^\prime y)^2.$$ Because we model $y$ as a multivariate Normal vector, this loss is a random variable. Its expectation is taken with respect to the distribution of $y$. The expected loss is the risk of our procedure. It depends on the (unknown) parameter $\theta$ and on the procedure itself. Since we're talking about a definite procedure based on equation $(1)$, it really is just a function of $\theta$: $$R(\theta) = E(x_0\beta - x_0 (X^\prime X)^{-}X^\prime y)^2.$$ Since the right hand side is a random variable whose distribution is completely determined by $\theta$, this all makes sense and is well-defined. We could even write it out explicitly in terms of $X, x_0$ (specified constants all), and $\theta$. Incidentally, for the "expected prediction error" referenced in the question, where $L(u,v)=v-u$, it's easy to show in this case that the risk is zero.
Mapping Frequentist Risk Notation to Regression Because the main problem concerns applying a fully general and abstract formula to a somewhat complicated model (regression), let's address it by examining a simple concrete case. Ordinary regression
48,449
Higher-dimensional version of variance
It's just the sum of the variances of each component. Suppose $n=2$ and $X=(X_1,X_2)$. Then $$\mathbb{E}[\|X\|^2] = \mathbb{E}[X_1^2 + X_2^2] = \mathbb{E}[X_1^2] + \mathbb{E}[X_2^2].$$ Also $$\|\mathbb{E}[X]\|^2 = \|(\mathbb{E}[X_1],\mathbb{E}[X_2])\|^2 = \mathbb{E}[X_1]^2 + \mathbb{E}[X_2]^2.$$ Therefore $$\begin{align*} \mathbb{E}[\|X|^2] - \|\mathbb{E}[X]\|^2 &= \left( \mathbb{E}[X_1^2] - \mathbb{E}[X_1]^2 \right) + \left( \mathbb{E}[X_2^2] - \mathbb{E}[X_2]^2 \right) \\ &= \text{Var}(X_1) + \text{Var}(X_2).\end{align*}$$
Higher-dimensional version of variance
It's just the sum of the variances of each component. Suppose $n=2$ and $X=(X_1,X_2)$. Then $$\mathbb{E}[\|X\|^2] = \mathbb{E}[X_1^2 + X_2^2] = \mathbb{E}[X_1^2] + \mathbb{E}[X_2^2].$$ Also $$\|\math
Higher-dimensional version of variance It's just the sum of the variances of each component. Suppose $n=2$ and $X=(X_1,X_2)$. Then $$\mathbb{E}[\|X\|^2] = \mathbb{E}[X_1^2 + X_2^2] = \mathbb{E}[X_1^2] + \mathbb{E}[X_2^2].$$ Also $$\|\mathbb{E}[X]\|^2 = \|(\mathbb{E}[X_1],\mathbb{E}[X_2])\|^2 = \mathbb{E}[X_1]^2 + \mathbb{E}[X_2]^2.$$ Therefore $$\begin{align*} \mathbb{E}[\|X|^2] - \|\mathbb{E}[X]\|^2 &= \left( \mathbb{E}[X_1^2] - \mathbb{E}[X_1]^2 \right) + \left( \mathbb{E}[X_2^2] - \mathbb{E}[X_2]^2 \right) \\ &= \text{Var}(X_1) + \text{Var}(X_2).\end{align*}$$
Higher-dimensional version of variance It's just the sum of the variances of each component. Suppose $n=2$ and $X=(X_1,X_2)$. Then $$\mathbb{E}[\|X\|^2] = \mathbb{E}[X_1^2 + X_2^2] = \mathbb{E}[X_1^2] + \mathbb{E}[X_2^2].$$ Also $$\|\math
48,450
Higher-dimensional version of variance
I do not think $f(x)$ has any meaning, and absolutely it is not generalization of variance. The generalization of variance is variance-covaviance matrix defined by $E(XX')-E(X)E(X)'$ where $X$ is random column vector.
Higher-dimensional version of variance
I do not think $f(x)$ has any meaning, and absolutely it is not generalization of variance. The generalization of variance is variance-covaviance matrix defined by $E(XX')-E(X)E(X)'$ where $X$ is ran
Higher-dimensional version of variance I do not think $f(x)$ has any meaning, and absolutely it is not generalization of variance. The generalization of variance is variance-covaviance matrix defined by $E(XX')-E(X)E(X)'$ where $X$ is random column vector.
Higher-dimensional version of variance I do not think $f(x)$ has any meaning, and absolutely it is not generalization of variance. The generalization of variance is variance-covaviance matrix defined by $E(XX')-E(X)E(X)'$ where $X$ is ran
48,451
SMOTE for multiclass classification
I would agree with running multiple SMOTE passes across the dataset, but with a slightly different view than already expressed. If you merely run SMOTE for each minority class against the predominant class, you're going to be generating sample that models the difference between each minority class and the predominant class rather than sample that models the class as accurately as possible. We can fix this (as much as is possible in this case) by SMOTE oversampling each minority class against all data not in that class. For example, the first SMOTE run may be the "1" class against the union of the "-1" and "0" classes and the second might be the "-1" class against the union of the "1" and "0" classes. Conceptually, this is simply minority oversampling of "1" and "not 1" and the same with "-1". Alternatively, given enough available sample otherwise, another option would be to massively undersample the "0" class to balance the class distributions.
SMOTE for multiclass classification
I would agree with running multiple SMOTE passes across the dataset, but with a slightly different view than already expressed. If you merely run SMOTE for each minority class against the predominant
SMOTE for multiclass classification I would agree with running multiple SMOTE passes across the dataset, but with a slightly different view than already expressed. If you merely run SMOTE for each minority class against the predominant class, you're going to be generating sample that models the difference between each minority class and the predominant class rather than sample that models the class as accurately as possible. We can fix this (as much as is possible in this case) by SMOTE oversampling each minority class against all data not in that class. For example, the first SMOTE run may be the "1" class against the union of the "-1" and "0" classes and the second might be the "-1" class against the union of the "1" and "0" classes. Conceptually, this is simply minority oversampling of "1" and "not 1" and the same with "-1". Alternatively, given enough available sample otherwise, another option would be to massively undersample the "0" class to balance the class distributions.
SMOTE for multiclass classification I would agree with running multiple SMOTE passes across the dataset, but with a slightly different view than already expressed. If you merely run SMOTE for each minority class against the predominant
48,452
SMOTE for multiclass classification
As I can see from your question, you are trying to balance "-1" class and "1", but they are seemed to be almost equally. So, it would be more right to 1)apply SMOTE on classes -1 and 0, then 2) apply SMOTE on classes 0 and 1. Then you may get all classes balanced.
SMOTE for multiclass classification
As I can see from your question, you are trying to balance "-1" class and "1", but they are seemed to be almost equally. So, it would be more right to 1)apply SMOTE on classes -1 and 0, then 2) apply
SMOTE for multiclass classification As I can see from your question, you are trying to balance "-1" class and "1", but they are seemed to be almost equally. So, it would be more right to 1)apply SMOTE on classes -1 and 0, then 2) apply SMOTE on classes 0 and 1. Then you may get all classes balanced.
SMOTE for multiclass classification As I can see from your question, you are trying to balance "-1" class and "1", but they are seemed to be almost equally. So, it would be more right to 1)apply SMOTE on classes -1 and 0, then 2) apply
48,453
linear regression on exponential distributed dependent variable
I want to use linear regression on [...] independent variables x1,x2,...xn [...] while the dependent variable y is almost exponentially distributed If you expect the relationship between y and the x's to be linear, then a nonlinear transformation of y will make the relationship between it and the x's nonlinear. It will also alter the spread about the model (if the data had constant variance before transformation, it won't have it afterward). Note further that in regression, there's no assumption about the distribution of the dependent variable itself (unconditionally). That is, there's little value in looking at say a histogram of the $y$ values -- it doesn't directly relate to any regression assumption. The assumption of normality applies when you're using normal based tests or intervals, and applies to the conditional distribution, which you can't usually assess until you look at residuals. If you're not interested in hypothesis tests or confidence intervals, an ordinary regression with non-normal conditional distribution may in some situations be reasonable (non-constant variance may be more of an issue than distribution-shape anyway). If you do want to perform inference as well, there are several ways of going about it (some approximate) that may be suitable. If you thought that the conditional distribution $Y|x1,x2,...$ was distributed as exponential, and that the relationship between $Y$ and the $x$'s was linear, you could use a GLM with identity link. There's advice relating to fitting exponential models in this way on site. independent variables [...] are all more or less normally distributed, while The distribution of the independent variables doesn't matter, since you condition on them in regression. No assumption about their distribution is made. The only way it's relevant is that sometimes the joint distribution can help inform us how to interpret the marginal distribution of the dependent variable, y (e.g. jointly normal x's would not produce an exponential y from conditionally normal y, so it would lead us to doubt the y's were conditionally normal). I applied log transformation to y and then used ols, which seems fine to me, until a friend argued strongly against using log transform under such condition, but he did not provide any solution. If it makes sense to model $E(\log(y))$ as a linear function of the predictors, that may be fine, but note that if you exponentiate such a fit, you don't get a suitable estimate of $E(Y|X=x)$ out (unless there's almost no variation about the model, in which case the bias may sometimes be small enough to ignore). An alternative to that would be to use a GLM with log link (in which case you'd be modelling $\log(E(y))$ as a linear function of parameters -- and expected values do come straight out of that model. You should consider the spread about the relationship; if you know something about that it already it may help inform your choice of model (but beware your inferences if you're using the same data to identify the model as to make inferences about it) There are many alternative ways than least squares to fit linear relationships, and some might be more suitable in the case of some non-normal conditional distributions. You should clarify your expectations about what it is that will be linearly related to the x's and how you understand the variability about the line would behave (say as a function of the mean for example -- would it tend to spread more as the mean increased, or not?) on whatever that scale is.
linear regression on exponential distributed dependent variable
I want to use linear regression on [...] independent variables x1,x2,...xn [...] while the dependent variable y is almost exponentially distributed If you expect the relationship between y and the
linear regression on exponential distributed dependent variable I want to use linear regression on [...] independent variables x1,x2,...xn [...] while the dependent variable y is almost exponentially distributed If you expect the relationship between y and the x's to be linear, then a nonlinear transformation of y will make the relationship between it and the x's nonlinear. It will also alter the spread about the model (if the data had constant variance before transformation, it won't have it afterward). Note further that in regression, there's no assumption about the distribution of the dependent variable itself (unconditionally). That is, there's little value in looking at say a histogram of the $y$ values -- it doesn't directly relate to any regression assumption. The assumption of normality applies when you're using normal based tests or intervals, and applies to the conditional distribution, which you can't usually assess until you look at residuals. If you're not interested in hypothesis tests or confidence intervals, an ordinary regression with non-normal conditional distribution may in some situations be reasonable (non-constant variance may be more of an issue than distribution-shape anyway). If you do want to perform inference as well, there are several ways of going about it (some approximate) that may be suitable. If you thought that the conditional distribution $Y|x1,x2,...$ was distributed as exponential, and that the relationship between $Y$ and the $x$'s was linear, you could use a GLM with identity link. There's advice relating to fitting exponential models in this way on site. independent variables [...] are all more or less normally distributed, while The distribution of the independent variables doesn't matter, since you condition on them in regression. No assumption about their distribution is made. The only way it's relevant is that sometimes the joint distribution can help inform us how to interpret the marginal distribution of the dependent variable, y (e.g. jointly normal x's would not produce an exponential y from conditionally normal y, so it would lead us to doubt the y's were conditionally normal). I applied log transformation to y and then used ols, which seems fine to me, until a friend argued strongly against using log transform under such condition, but he did not provide any solution. If it makes sense to model $E(\log(y))$ as a linear function of the predictors, that may be fine, but note that if you exponentiate such a fit, you don't get a suitable estimate of $E(Y|X=x)$ out (unless there's almost no variation about the model, in which case the bias may sometimes be small enough to ignore). An alternative to that would be to use a GLM with log link (in which case you'd be modelling $\log(E(y))$ as a linear function of parameters -- and expected values do come straight out of that model. You should consider the spread about the relationship; if you know something about that it already it may help inform your choice of model (but beware your inferences if you're using the same data to identify the model as to make inferences about it) There are many alternative ways than least squares to fit linear relationships, and some might be more suitable in the case of some non-normal conditional distributions. You should clarify your expectations about what it is that will be linearly related to the x's and how you understand the variability about the line would behave (say as a function of the mean for example -- would it tend to spread more as the mean increased, or not?) on whatever that scale is.
linear regression on exponential distributed dependent variable I want to use linear regression on [...] independent variables x1,x2,...xn [...] while the dependent variable y is almost exponentially distributed If you expect the relationship between y and the
48,454
How does h2o handle time-series cross validation?
H2O algorithms can optionally use k-fold cross-validation. H2O does not yet support time-series (aka "walk-forward" or "rolling") cross-validation, however there is an open ticket to implement it here. There is an example of how you can manually implement time-series CV using the h2o R package referenced here, if you want to give that a try.
How does h2o handle time-series cross validation?
H2O algorithms can optionally use k-fold cross-validation. H2O does not yet support time-series (aka "walk-forward" or "rolling") cross-validation, however there is an open ticket to implement it her
How does h2o handle time-series cross validation? H2O algorithms can optionally use k-fold cross-validation. H2O does not yet support time-series (aka "walk-forward" or "rolling") cross-validation, however there is an open ticket to implement it here. There is an example of how you can manually implement time-series CV using the h2o R package referenced here, if you want to give that a try.
How does h2o handle time-series cross validation? H2O algorithms can optionally use k-fold cross-validation. H2O does not yet support time-series (aka "walk-forward" or "rolling") cross-validation, however there is an open ticket to implement it her
48,455
How does h2o handle time-series cross validation?
I implemented it using Sklearn TimeSeriesSplit like this: from sklearn.model_selection import TimeSeriesSplit from h2o.estimators import H2ORandomForestEstimator forest = h2o.estimators.H2ORandomForestEstimator forest.set_params(nfolds=0) tscv = TimeSeriesSplit(n_splits=5) Xcols=list(set(X.names)-set('NumberOfSales')) Ycol='NumberOfSales' for train_index, test_index in tscv.split(X): print("TRAIN:", train_index, "TEST:", test_index) train = X[min(train_index):max(train_index),:] test = X[min(test_index):max(test_index),:] print(len(train),len(test)) #Just to double check... forest.train(x=Xcols,y=Ycol, training_frame=train,validation_frame=test,verbose=False) y_pred=forest.predict(test[Xcols]) EVar.append(explained_variance_score(test[Ycol].as_data_frame(), y_pred.as_data_frame())) MAEar.append(mean_absolute_error(test[Ycol].as_data_frame(), y_pred.as_data_frame())) MSEar.append(mean_squared_error(test[Ycol].as_data_frame(), y_pred.as_data_frame())) R2ar.append(r2_score(test[Ycol].as_data_frame(), y_pred.as_data_frame())) EV = np.array(EVar).mean() MAE=np.array(MAEar).mean() MSE=np.array(MSEar).mean() RMSE=np.array(RMSEar).mean() R2=np.array(R2ar).mean() ```
How does h2o handle time-series cross validation?
I implemented it using Sklearn TimeSeriesSplit like this: from sklearn.model_selection import TimeSeriesSplit from h2o.estimators import H2ORandomForestEstimator forest = h2o.estimators.H2ORandomFore
How does h2o handle time-series cross validation? I implemented it using Sklearn TimeSeriesSplit like this: from sklearn.model_selection import TimeSeriesSplit from h2o.estimators import H2ORandomForestEstimator forest = h2o.estimators.H2ORandomForestEstimator forest.set_params(nfolds=0) tscv = TimeSeriesSplit(n_splits=5) Xcols=list(set(X.names)-set('NumberOfSales')) Ycol='NumberOfSales' for train_index, test_index in tscv.split(X): print("TRAIN:", train_index, "TEST:", test_index) train = X[min(train_index):max(train_index),:] test = X[min(test_index):max(test_index),:] print(len(train),len(test)) #Just to double check... forest.train(x=Xcols,y=Ycol, training_frame=train,validation_frame=test,verbose=False) y_pred=forest.predict(test[Xcols]) EVar.append(explained_variance_score(test[Ycol].as_data_frame(), y_pred.as_data_frame())) MAEar.append(mean_absolute_error(test[Ycol].as_data_frame(), y_pred.as_data_frame())) MSEar.append(mean_squared_error(test[Ycol].as_data_frame(), y_pred.as_data_frame())) R2ar.append(r2_score(test[Ycol].as_data_frame(), y_pred.as_data_frame())) EV = np.array(EVar).mean() MAE=np.array(MAEar).mean() MSE=np.array(MSEar).mean() RMSE=np.array(RMSEar).mean() R2=np.array(R2ar).mean() ```
How does h2o handle time-series cross validation? I implemented it using Sklearn TimeSeriesSplit like this: from sklearn.model_selection import TimeSeriesSplit from h2o.estimators import H2ORandomForestEstimator forest = h2o.estimators.H2ORandomFore
48,456
How does h2o handle time-series cross validation?
Another way to cross validate time series, which is worth sharing. Especially because the question is asked if H2o can support time-series cv. Existing h2o implementation is able support a variant of time-series cv shown below, with the help of fold_column variable. fold 1 : training [4 5 6 7 8 9], test [1 2 3] fold 2 : training [1 2 3 7 8 9], test [4 5 6] fold 3 : training [1 2 3 4 5 6], test [7 8 9] Solution: library(h2o) h2o.init() airquality$Year <- rep(2017,nrow(airquality)) airquality$Date <- as.Date(with(airquality,paste(Year,Month,Day,sep="-")),"%Y-%m-%d") df <- as.h2o(airquality[order(as.Date(airquality$Date, format="%m/%d/%Y")),]) df <- h2o.na_omit(df) # Number of folds NFOLDS <- 10 # Assign fold number sequentially to a window in data fold_numbers <- as.h2o((1:nrow(df))%%NFOLDS %>% sort()) # This will assign fold number randomly #fold_numbers <- h2o.kfold_column(df, nfolds = NFOLDS) names(fold_numbers) <- "fold_numbers" # set the predictor names and the response column name predictors <- c("Solar.R", "Wind", "Temp", "Month", "Day") response <- "Ozone" # append the fold_numbers column to the dataset df <- h2o.cbind(df, fold_numbers) # try using the fold_column parameter: airquality_gbm <- h2o.gbm(x = predictors, y = response, training_frame = df, fold_column="fold_numbers", seed = 4) # print the rmse for your model print(h2o.rmse(airquality_gbm)) Parts of code borrowed from link1 and link2
How does h2o handle time-series cross validation?
Another way to cross validate time series, which is worth sharing. Especially because the question is asked if H2o can support time-series cv. Existing h2o implementation is able support a variant of
How does h2o handle time-series cross validation? Another way to cross validate time series, which is worth sharing. Especially because the question is asked if H2o can support time-series cv. Existing h2o implementation is able support a variant of time-series cv shown below, with the help of fold_column variable. fold 1 : training [4 5 6 7 8 9], test [1 2 3] fold 2 : training [1 2 3 7 8 9], test [4 5 6] fold 3 : training [1 2 3 4 5 6], test [7 8 9] Solution: library(h2o) h2o.init() airquality$Year <- rep(2017,nrow(airquality)) airquality$Date <- as.Date(with(airquality,paste(Year,Month,Day,sep="-")),"%Y-%m-%d") df <- as.h2o(airquality[order(as.Date(airquality$Date, format="%m/%d/%Y")),]) df <- h2o.na_omit(df) # Number of folds NFOLDS <- 10 # Assign fold number sequentially to a window in data fold_numbers <- as.h2o((1:nrow(df))%%NFOLDS %>% sort()) # This will assign fold number randomly #fold_numbers <- h2o.kfold_column(df, nfolds = NFOLDS) names(fold_numbers) <- "fold_numbers" # set the predictor names and the response column name predictors <- c("Solar.R", "Wind", "Temp", "Month", "Day") response <- "Ozone" # append the fold_numbers column to the dataset df <- h2o.cbind(df, fold_numbers) # try using the fold_column parameter: airquality_gbm <- h2o.gbm(x = predictors, y = response, training_frame = df, fold_column="fold_numbers", seed = 4) # print the rmse for your model print(h2o.rmse(airquality_gbm)) Parts of code borrowed from link1 and link2
How does h2o handle time-series cross validation? Another way to cross validate time series, which is worth sharing. Especially because the question is asked if H2o can support time-series cv. Existing h2o implementation is able support a variant of
48,457
How to be absolutely sure that features do have predictive power to predict the labels (without domain knowledge) ? Does Mutual information help?
Does this mean that my data is worthless and i should probably look for more data ? No, a small mutual information between a target variable and single features does not render your dataset worthless since it neglects the information contained in the combination of features. I will give a most simple example (XOR problem): Assume a classfication problem with four datapoints such as: data = np.array([[1, 2], [1, 1], [2, 2], [2, 1]]) And four associated labels such as: label_num = [1, 2, 2, 1] The problem can be visualized like this: Evaluating the features using mutual information MI(feature, target) yields a mutual information of 0 in both cases. from sklearn import metrics metrics.mutual_info_score([1, 1, 2, 2], label_num) 0.0 metrics.mutual_info_score([2, 1, 2, 1], label_num) 0.0 Yet the problem is easy since combining both features allows efficient seperation of both classes such as explained in detail here.
How to be absolutely sure that features do have predictive power to predict the labels (without doma
Does this mean that my data is worthless and i should probably look for more data ? No, a small mutual information between a target variable and single features does not render your dataset worthless
How to be absolutely sure that features do have predictive power to predict the labels (without domain knowledge) ? Does Mutual information help? Does this mean that my data is worthless and i should probably look for more data ? No, a small mutual information between a target variable and single features does not render your dataset worthless since it neglects the information contained in the combination of features. I will give a most simple example (XOR problem): Assume a classfication problem with four datapoints such as: data = np.array([[1, 2], [1, 1], [2, 2], [2, 1]]) And four associated labels such as: label_num = [1, 2, 2, 1] The problem can be visualized like this: Evaluating the features using mutual information MI(feature, target) yields a mutual information of 0 in both cases. from sklearn import metrics metrics.mutual_info_score([1, 1, 2, 2], label_num) 0.0 metrics.mutual_info_score([2, 1, 2, 1], label_num) 0.0 Yet the problem is easy since combining both features allows efficient seperation of both classes such as explained in detail here.
How to be absolutely sure that features do have predictive power to predict the labels (without doma Does this mean that my data is worthless and i should probably look for more data ? No, a small mutual information between a target variable and single features does not render your dataset worthless
48,458
What does this sampling weight mean?
Let $N$ be the population size and $n$ the sample size, let $N_h$ and $n_h$ be the population and sample sizes for stratum $h$. Then, the weight you defined is given by $ W_h = \frac{N_h/N}{n_h/n} = \frac{N_h}{n_h}\frac{n}{N}$ where $\frac{n}{N}$ is the sampling fraction $f$ for the whole sample and $\frac{N_h}{n_h}$ is the inverse of the sampling fraction, i.e., of the probability of selection, in the $h$-th stratum, $f_h$. Put it differently, $w_{hi}=N_h/n_h$ is the inverse probability sampling weight of a unit $i$ in stratum $h$ that you are familiar with. Writing it as $W_h = \frac{f}{f_h}$, you can see that \begin{equation} \begin{cases} W_h < 1 ,\qquad f_h > f\\ W_h = 1 , \qquad f_h = f\\ W_h > 1 , \qquad f_h <f\\ \end{cases} \end{equation} These are relative weights showing by how much a given stratum was under- or oversampled. These are OK weights to deal with the ratio-type statistics (means, proportions, regression estimates). For the totals, e.g. total acreage under a given crop, or a total harvest, you need the correct inverse probability weights rather than relative weights.
What does this sampling weight mean?
Let $N$ be the population size and $n$ the sample size, let $N_h$ and $n_h$ be the population and sample sizes for stratum $h$. Then, the weight you defined is given by $ W_h = \frac{N_h/N}{n_h/n} = \
What does this sampling weight mean? Let $N$ be the population size and $n$ the sample size, let $N_h$ and $n_h$ be the population and sample sizes for stratum $h$. Then, the weight you defined is given by $ W_h = \frac{N_h/N}{n_h/n} = \frac{N_h}{n_h}\frac{n}{N}$ where $\frac{n}{N}$ is the sampling fraction $f$ for the whole sample and $\frac{N_h}{n_h}$ is the inverse of the sampling fraction, i.e., of the probability of selection, in the $h$-th stratum, $f_h$. Put it differently, $w_{hi}=N_h/n_h$ is the inverse probability sampling weight of a unit $i$ in stratum $h$ that you are familiar with. Writing it as $W_h = \frac{f}{f_h}$, you can see that \begin{equation} \begin{cases} W_h < 1 ,\qquad f_h > f\\ W_h = 1 , \qquad f_h = f\\ W_h > 1 , \qquad f_h <f\\ \end{cases} \end{equation} These are relative weights showing by how much a given stratum was under- or oversampled. These are OK weights to deal with the ratio-type statistics (means, proportions, regression estimates). For the totals, e.g. total acreage under a given crop, or a total harvest, you need the correct inverse probability weights rather than relative weights.
What does this sampling weight mean? Let $N$ be the population size and $n$ the sample size, let $N_h$ and $n_h$ be the population and sample sizes for stratum $h$. Then, the weight you defined is given by $ W_h = \frac{N_h/N}{n_h/n} = \
48,459
Interpret predictions of black box models
Ribeiro's "Why should I trust you?" paper and blog post provide a method of interpreting black-box models paper https://arxiv.org/abs/1602.04938 blog-post https://www.oreilly.com/learning/introduction-to-local-interpretable-model-agnostic-explanations-lime The model is called "LIME": locally interpretable model-agnostic explanations. The way it works is to: create a set of 'interpretable' features, which may or not be the original input features: could also be a mapping between the two for example, for images, the 'interpretable features' could be contiguous patches of pixels, whereas the input features to the black-box model will likely be pixel values sample input/interpretable input features near an example one wishes to explain fit a simple, probably linear, model locally, to these local samples use this local model to obtain an approximation of which features were most important in classifying the example one wishes to explain
Interpret predictions of black box models
Ribeiro's "Why should I trust you?" paper and blog post provide a method of interpreting black-box models paper https://arxiv.org/abs/1602.04938 blog-post https://www.oreilly.com/learning/introductio
Interpret predictions of black box models Ribeiro's "Why should I trust you?" paper and blog post provide a method of interpreting black-box models paper https://arxiv.org/abs/1602.04938 blog-post https://www.oreilly.com/learning/introduction-to-local-interpretable-model-agnostic-explanations-lime The model is called "LIME": locally interpretable model-agnostic explanations. The way it works is to: create a set of 'interpretable' features, which may or not be the original input features: could also be a mapping between the two for example, for images, the 'interpretable features' could be contiguous patches of pixels, whereas the input features to the black-box model will likely be pixel values sample input/interpretable input features near an example one wishes to explain fit a simple, probably linear, model locally, to these local samples use this local model to obtain an approximation of which features were most important in classifying the example one wishes to explain
Interpret predictions of black box models Ribeiro's "Why should I trust you?" paper and blog post provide a method of interpreting black-box models paper https://arxiv.org/abs/1602.04938 blog-post https://www.oreilly.com/learning/introductio
48,460
Backpropagation algorithm NN with Rectified Linear Unit (ReLU) activation
As for the confusing part. Softmax derivative is simply $$\frac{\partial L}{\partial t_i} = t_i - y_i$$ where $t_i$ is predicted output. Now, in this case $t_i, y_i \in \Re^3$, but $y_i$ has to be in the one-hot encoding form which looks like this $$y_i = (0, \dots, \overset{\text{k'th}}{1}, \dots, 0)$$ So, for example class 2 is represented as $(0, 1, 0)$ And in your code we have $y.index$ be the position of $1$ in above example. So the line dscores[Y.index] <- dscores[Y.index] - 1 Is a short and clever way for applying derivative to a whole dataset, i.e. $$t_i - y_i \equiv t_i[k] = t_i[k] - 1, \text{ for } y_i = (0, \dots, \overset{\text{k'th}}{1}, \dots, 0)$$ Backpropagation derivatives Notation: $i^k$ - input vector of $k$th layer $o^k$ - output vector of $k$th layer $W^k$ - transition matrix of $k$th layer $b^k$ - biases of $k$th layer $X = o^0$ - network input $T$ - predicted output $T = o^n$ assuming we have $n$ layers We have a transition between layers $$i^{k} = W^ko^{k-1} + b^k$$ $ReLU$ as activation function $$o^k = max(0, i^k)$$ where we assume element-wise application. Now the important part $$\frac{\partial L}{\partial o^{k-1}} = W^k\frac{\partial L}{\partial i^k} \ \ \ \ \text{ (1)}$$ $$ \frac{\partial L}{\partial i^k} = \frac{\partial L}{\partial o^k} \circ I[o^k > 0] \ \ \ \ \text{ (2)} $$ where $\circ$ means Hadamard product (element-wise) $$\frac{\partial L}{\partial W^k} = \frac{\partial L}{\partial i^k}(o^{k-1})^T$$ $$\frac{\partial L}{\partial b^k} = \frac{\partial L}{\partial i^k} \ \ \ \ \text{ (3)}$$ Since $\frac{\partial i^k}{\partial b^k} = I$ (identity matrix) and we use chain rule You can check that above equations hold when $i, o$ are matrices, i.e. we process whole batches at once. Now we can also update weights for a whole batch as follows \begin{align}\frac{\partial \sum_{l=1}^d L_{(l)}}{\partial W^k} &= \sum_{l=1}^d \frac{\partial L_{(l)}}{\partial W^k} \\ &= \sum_{l=1}^d \frac{\partial L_{(l)}}{\partial i_{(l)}^k}(o_{(l)}^{k-1})^T \\ &= \begin{pmatrix} \frac{\partial L_{(1)}}{\partial i_{(1)}^k} & \dots & \frac{\partial L_{(d)}}{\partial i_{(d)}^k} \end{pmatrix} \begin{pmatrix} o_{(1)}^{k-1})^T \\ \dots \\ o_{(d)}^{k-1})^T \end{pmatrix} \\ &= \frac{\partial \sum_{l=1}^d L_{(l)}}{\partial I^k} (O^{k-1})^T \ \ \ \ \text{ (4)} \end{align} dscores <- dscores / batchsize Since we process a whole batch at once and derivative of ReLU is constant we can divide $T - Y$ at start dW2 <- t(hidden.layer) %*% dscores # [6 x 3] matrix Using (4) db2 <- colSums(dscores) # a vector of 3 numbers (sums for each species) Apply (3) to a whole batch dhidden <- dscores %*% t(W2) # [90 x 6] matrix] # W2 is a [6 x 3] matrix of weights. # dhidden is [90 x 6] Applying (1) dhidden[hidden.layer <= 0] <- 0 # We get rid of negative values Using (2) dW1 <- t(X) %*% dhidden # X is the input matrix [90 x 4] db1 <- colSums(dhidden) # 6-element vector (sum columns across examples) Again using (4) and (3) to a whole batch for layer 1 # update .... dW2 <- dW2 + reg * W2 # reg is regularization rate reg = 1e-3 dW1 <- dW1 + reg * W1 W1 <- W1 - lr * dW1 # lr is the learning rate lr = 1e-2 b1 <- b1 - lr * db1 # b1 is the first bias W2 <- W2 - lr * dW2 b2 <- b2 - lr * db2 # b2 is the second bias Updates for a whole batch
Backpropagation algorithm NN with Rectified Linear Unit (ReLU) activation
As for the confusing part. Softmax derivative is simply $$\frac{\partial L}{\partial t_i} = t_i - y_i$$ where $t_i$ is predicted output. Now, in this case $t_i, y_i \in \Re^3$, but $y_i$ has to be in
Backpropagation algorithm NN with Rectified Linear Unit (ReLU) activation As for the confusing part. Softmax derivative is simply $$\frac{\partial L}{\partial t_i} = t_i - y_i$$ where $t_i$ is predicted output. Now, in this case $t_i, y_i \in \Re^3$, but $y_i$ has to be in the one-hot encoding form which looks like this $$y_i = (0, \dots, \overset{\text{k'th}}{1}, \dots, 0)$$ So, for example class 2 is represented as $(0, 1, 0)$ And in your code we have $y.index$ be the position of $1$ in above example. So the line dscores[Y.index] <- dscores[Y.index] - 1 Is a short and clever way for applying derivative to a whole dataset, i.e. $$t_i - y_i \equiv t_i[k] = t_i[k] - 1, \text{ for } y_i = (0, \dots, \overset{\text{k'th}}{1}, \dots, 0)$$ Backpropagation derivatives Notation: $i^k$ - input vector of $k$th layer $o^k$ - output vector of $k$th layer $W^k$ - transition matrix of $k$th layer $b^k$ - biases of $k$th layer $X = o^0$ - network input $T$ - predicted output $T = o^n$ assuming we have $n$ layers We have a transition between layers $$i^{k} = W^ko^{k-1} + b^k$$ $ReLU$ as activation function $$o^k = max(0, i^k)$$ where we assume element-wise application. Now the important part $$\frac{\partial L}{\partial o^{k-1}} = W^k\frac{\partial L}{\partial i^k} \ \ \ \ \text{ (1)}$$ $$ \frac{\partial L}{\partial i^k} = \frac{\partial L}{\partial o^k} \circ I[o^k > 0] \ \ \ \ \text{ (2)} $$ where $\circ$ means Hadamard product (element-wise) $$\frac{\partial L}{\partial W^k} = \frac{\partial L}{\partial i^k}(o^{k-1})^T$$ $$\frac{\partial L}{\partial b^k} = \frac{\partial L}{\partial i^k} \ \ \ \ \text{ (3)}$$ Since $\frac{\partial i^k}{\partial b^k} = I$ (identity matrix) and we use chain rule You can check that above equations hold when $i, o$ are matrices, i.e. we process whole batches at once. Now we can also update weights for a whole batch as follows \begin{align}\frac{\partial \sum_{l=1}^d L_{(l)}}{\partial W^k} &= \sum_{l=1}^d \frac{\partial L_{(l)}}{\partial W^k} \\ &= \sum_{l=1}^d \frac{\partial L_{(l)}}{\partial i_{(l)}^k}(o_{(l)}^{k-1})^T \\ &= \begin{pmatrix} \frac{\partial L_{(1)}}{\partial i_{(1)}^k} & \dots & \frac{\partial L_{(d)}}{\partial i_{(d)}^k} \end{pmatrix} \begin{pmatrix} o_{(1)}^{k-1})^T \\ \dots \\ o_{(d)}^{k-1})^T \end{pmatrix} \\ &= \frac{\partial \sum_{l=1}^d L_{(l)}}{\partial I^k} (O^{k-1})^T \ \ \ \ \text{ (4)} \end{align} dscores <- dscores / batchsize Since we process a whole batch at once and derivative of ReLU is constant we can divide $T - Y$ at start dW2 <- t(hidden.layer) %*% dscores # [6 x 3] matrix Using (4) db2 <- colSums(dscores) # a vector of 3 numbers (sums for each species) Apply (3) to a whole batch dhidden <- dscores %*% t(W2) # [90 x 6] matrix] # W2 is a [6 x 3] matrix of weights. # dhidden is [90 x 6] Applying (1) dhidden[hidden.layer <= 0] <- 0 # We get rid of negative values Using (2) dW1 <- t(X) %*% dhidden # X is the input matrix [90 x 4] db1 <- colSums(dhidden) # 6-element vector (sum columns across examples) Again using (4) and (3) to a whole batch for layer 1 # update .... dW2 <- dW2 + reg * W2 # reg is regularization rate reg = 1e-3 dW1 <- dW1 + reg * W1 W1 <- W1 - lr * dW1 # lr is the learning rate lr = 1e-2 b1 <- b1 - lr * db1 # b1 is the first bias W2 <- W2 - lr * dW2 b2 <- b2 - lr * db2 # b2 is the second bias Updates for a whole batch
Backpropagation algorithm NN with Rectified Linear Unit (ReLU) activation As for the confusing part. Softmax derivative is simply $$\frac{\partial L}{\partial t_i} = t_i - y_i$$ where $t_i$ is predicted output. Now, in this case $t_i, y_i \in \Re^3$, but $y_i$ has to be in
48,461
Backpropagation algorithm NN with Rectified Linear Unit (ReLU) activation
If anyone is concerned, this "answer" will never become the accepted answer. It's more like some notes on the issue, possibly helping other people as well. This post is very useful: $f$ is the array of class scores for a single example (e.g. array of 3 numbers here): $f= X\cdot W + b$, then the Softmax classifier computes the loss for that example as: $L_i = -\log\left(\frac{e^{f_{y_i}}}{ \sum_j e^{f_j} }\right)$ Recall also that the full Softmax classifier loss is then defined as the average cross-entropy loss over the training examples and the regularization: $L = \underbrace{ \frac{1}{N} \sum_i L_i }_\text{data loss} + > \underbrace{ \frac{1}{2} \lambda \sum_k\sum_l W_{k,l}^2 > }_\text{regularization loss} \\\\$ Lets introduce the intermediate variable $p$, which is a vector of the (normalized) probabilities. The loss for one example is: $$p_k = \frac{e^{f_k}}{ \sum_j e^{f_j} } \hspace{1in} L_i =-\log\left(p_{y_i}\right)$$ We now wish to understand how the computed scores inside $f$ should change to decrease the loss $L_i$ that this example contributes to the full objective. In other words, we want to derive the gradient $\partial L_i/\partial f_k$. The loss $L_i$ is computed from $p$, which in turn depends on $f$. It’s a fun exercise to the reader to use the chain rule to derive the gradient, but it turns out to be extremely simple and interpretible [sic] in the end, after a lot of things cancel out: $$\frac{\partial L_i }{ \partial f_k } = p_k - \mathbb{1}(y_i = k)$$ Notice how elegant and simple this expression is. Suppose the probabilities we computed were $p = [0.2, 0.3, 0.5]$, and that the correct class was the middle one (with probability $0.3$). According to this derivation the gradient on the scores would be $\text{df} = [0.2, -0.7, 0.5]$. Recalling what the interpretation of the gradient, we see that this result is highly intuitive: increasing the first or last element of the score vector f (the scores of the incorrect classes) leads to an increased loss (due to the positive signs $+0.2$ and $+0.5$) - and increasing the loss is bad, as expected. However, increasing the score of the correct class has negative influence on the loss. The gradient of $-0.7$ is telling us that increasing the correct class score would lead to a decrease of the loss $L_i$, which makes sense. The code implementation of scores in Python (the example in this linked post has no hidden layer) is: # compute class scores for a linear classifier scores = np.dot(X, W) + b This corresponds to the line providing the net input for the outer layer on the example in the OP: score <- sweep(hidden.layer %*% W2, 2, b2, '+') Given the array of scores we’ve computed above, we can compute the loss. First, the way to obtain the probabilities is straight forward: # get unnormalized probabilities exp_scores = np.exp(scores) # normalize them for each example probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) This corresponds to the lines in the OP: # softmax score.exp <- exp(score) # This is a [90 x 3] matrix probs <- sweep(score.exp, 1, rowSums(score.exp), '/') # Calculated probability mass function for every example All of this boils down to the following code. Recall that probs stores the probabilities of all classes (as rows) for each example. To get the gradient on the scores, which we call dscores, we proceed as follows: dscores = probs dscores[range(num_examples),y] -= 1 dscores /= num_examples This is the equivalent in the OP to: dscores <- probs #[90 x 3] matrix of PMF'S (ONE PER EXAMPLE) #dscores[Y.index] will pick up the probability associated with the #column that contains the true value (species). # subtracted "1", which is the gradient of partial L / partial f dscores[Y.index] <- dscores[Y.index] - 1 dscores <- dscores / batchsize Lastly, we had that scores = np.dot(X, W) + b, so armed with the gradient on scores (stored in dscores), we can now backpropagate into W and b: dW = np.dot(X.T, dscores) db = np.sum(dscores, axis=0, keepdims=True) dW += reg * W # don't forget the regularization gradient Where we see that we have backpropped through the matrix multiply operation, and also added the contribution from the regularization. Note that the regularization gradient has the very simple form reg*W since we used the constant $0.5$ for its loss contribution (i.e. $\frac{d}{dw} ( \frac{1}{2} \lambda w^2) = \lambda w$). This is a common convenience trick that simplifies the gradient expression. Here the matrix of weights is updated, and that's it, because the example quoted has no hidden layer. However, in the OP, there is a hidden layer, which explains that the first matrix of weights being updated are $W_2$ connecting the output of the hidden layer to the net input of the outer layer: Remembering that: hidden.layer <- pmax(hidden.layer, 0) is the activation function or the output of the hidden layer... dW2 <- t(hidden.layer) %*% dscores # [6 x 3] matrix dW2 <- dW2 + reg * W2 # reg is regularization rate W2 <- W2 - lr * dW2 # lr is the learning rate.
Backpropagation algorithm NN with Rectified Linear Unit (ReLU) activation
If anyone is concerned, this "answer" will never become the accepted answer. It's more like some notes on the issue, possibly helping other people as well. This post is very useful: $f$ is the array
Backpropagation algorithm NN with Rectified Linear Unit (ReLU) activation If anyone is concerned, this "answer" will never become the accepted answer. It's more like some notes on the issue, possibly helping other people as well. This post is very useful: $f$ is the array of class scores for a single example (e.g. array of 3 numbers here): $f= X\cdot W + b$, then the Softmax classifier computes the loss for that example as: $L_i = -\log\left(\frac{e^{f_{y_i}}}{ \sum_j e^{f_j} }\right)$ Recall also that the full Softmax classifier loss is then defined as the average cross-entropy loss over the training examples and the regularization: $L = \underbrace{ \frac{1}{N} \sum_i L_i }_\text{data loss} + > \underbrace{ \frac{1}{2} \lambda \sum_k\sum_l W_{k,l}^2 > }_\text{regularization loss} \\\\$ Lets introduce the intermediate variable $p$, which is a vector of the (normalized) probabilities. The loss for one example is: $$p_k = \frac{e^{f_k}}{ \sum_j e^{f_j} } \hspace{1in} L_i =-\log\left(p_{y_i}\right)$$ We now wish to understand how the computed scores inside $f$ should change to decrease the loss $L_i$ that this example contributes to the full objective. In other words, we want to derive the gradient $\partial L_i/\partial f_k$. The loss $L_i$ is computed from $p$, which in turn depends on $f$. It’s a fun exercise to the reader to use the chain rule to derive the gradient, but it turns out to be extremely simple and interpretible [sic] in the end, after a lot of things cancel out: $$\frac{\partial L_i }{ \partial f_k } = p_k - \mathbb{1}(y_i = k)$$ Notice how elegant and simple this expression is. Suppose the probabilities we computed were $p = [0.2, 0.3, 0.5]$, and that the correct class was the middle one (with probability $0.3$). According to this derivation the gradient on the scores would be $\text{df} = [0.2, -0.7, 0.5]$. Recalling what the interpretation of the gradient, we see that this result is highly intuitive: increasing the first or last element of the score vector f (the scores of the incorrect classes) leads to an increased loss (due to the positive signs $+0.2$ and $+0.5$) - and increasing the loss is bad, as expected. However, increasing the score of the correct class has negative influence on the loss. The gradient of $-0.7$ is telling us that increasing the correct class score would lead to a decrease of the loss $L_i$, which makes sense. The code implementation of scores in Python (the example in this linked post has no hidden layer) is: # compute class scores for a linear classifier scores = np.dot(X, W) + b This corresponds to the line providing the net input for the outer layer on the example in the OP: score <- sweep(hidden.layer %*% W2, 2, b2, '+') Given the array of scores we’ve computed above, we can compute the loss. First, the way to obtain the probabilities is straight forward: # get unnormalized probabilities exp_scores = np.exp(scores) # normalize them for each example probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) This corresponds to the lines in the OP: # softmax score.exp <- exp(score) # This is a [90 x 3] matrix probs <- sweep(score.exp, 1, rowSums(score.exp), '/') # Calculated probability mass function for every example All of this boils down to the following code. Recall that probs stores the probabilities of all classes (as rows) for each example. To get the gradient on the scores, which we call dscores, we proceed as follows: dscores = probs dscores[range(num_examples),y] -= 1 dscores /= num_examples This is the equivalent in the OP to: dscores <- probs #[90 x 3] matrix of PMF'S (ONE PER EXAMPLE) #dscores[Y.index] will pick up the probability associated with the #column that contains the true value (species). # subtracted "1", which is the gradient of partial L / partial f dscores[Y.index] <- dscores[Y.index] - 1 dscores <- dscores / batchsize Lastly, we had that scores = np.dot(X, W) + b, so armed with the gradient on scores (stored in dscores), we can now backpropagate into W and b: dW = np.dot(X.T, dscores) db = np.sum(dscores, axis=0, keepdims=True) dW += reg * W # don't forget the regularization gradient Where we see that we have backpropped through the matrix multiply operation, and also added the contribution from the regularization. Note that the regularization gradient has the very simple form reg*W since we used the constant $0.5$ for its loss contribution (i.e. $\frac{d}{dw} ( \frac{1}{2} \lambda w^2) = \lambda w$). This is a common convenience trick that simplifies the gradient expression. Here the matrix of weights is updated, and that's it, because the example quoted has no hidden layer. However, in the OP, there is a hidden layer, which explains that the first matrix of weights being updated are $W_2$ connecting the output of the hidden layer to the net input of the outer layer: Remembering that: hidden.layer <- pmax(hidden.layer, 0) is the activation function or the output of the hidden layer... dW2 <- t(hidden.layer) %*% dscores # [6 x 3] matrix dW2 <- dW2 + reg * W2 # reg is regularization rate W2 <- W2 - lr * dW2 # lr is the learning rate.
Backpropagation algorithm NN with Rectified Linear Unit (ReLU) activation If anyone is concerned, this "answer" will never become the accepted answer. It's more like some notes on the issue, possibly helping other people as well. This post is very useful: $f$ is the array
48,462
Distance measure between two multivariate normal distributions (with differing mean and covariances)
In the end I went for the Bhattacharyya distance. I adapted the R code referenced here: // In the following, Vec3 and Mat3 are C++ Eigen types. /// See: https://en.wikipedia.org/wiki/Mahalanobis_distance double mahalanobis(const Vec3& dist, const Mat3& cov) { return (dist.transpose()*cov.inverse()*dist).eval()(0); } /// See: https://en.wikipedia.org/wiki/Bhattacharyya_distance double bhattacharyya(const Vec3& dist, const Mat3& cov1, const Mat3& cov2) { const Mat3 cov = (cov1+cov2)/2; const double d1 = mahalanobis(dist, cov)/8; const double d2 = log(cov.determinant()/sqrt(cov1.determinant()*cov2.determinant()))/2; return d1+d2; }
Distance measure between two multivariate normal distributions (with differing mean and covariances)
In the end I went for the Bhattacharyya distance. I adapted the R code referenced here: // In the following, Vec3 and Mat3 are C++ Eigen types. /// See: https://en.wikipedia.org/wiki/Mahalanobis_dist
Distance measure between two multivariate normal distributions (with differing mean and covariances) In the end I went for the Bhattacharyya distance. I adapted the R code referenced here: // In the following, Vec3 and Mat3 are C++ Eigen types. /// See: https://en.wikipedia.org/wiki/Mahalanobis_distance double mahalanobis(const Vec3& dist, const Mat3& cov) { return (dist.transpose()*cov.inverse()*dist).eval()(0); } /// See: https://en.wikipedia.org/wiki/Bhattacharyya_distance double bhattacharyya(const Vec3& dist, const Mat3& cov1, const Mat3& cov2) { const Mat3 cov = (cov1+cov2)/2; const double d1 = mahalanobis(dist, cov)/8; const double d2 = log(cov.determinant()/sqrt(cov1.determinant()*cov2.determinant()))/2; return d1+d2; }
Distance measure between two multivariate normal distributions (with differing mean and covariances) In the end I went for the Bhattacharyya distance. I adapted the R code referenced here: // In the following, Vec3 and Mat3 are C++ Eigen types. /// See: https://en.wikipedia.org/wiki/Mahalanobis_dist
48,463
How to Interpret Interaction Between Two Categorical Variables
Your interpretation is true. This is another way to interpret these terms: If the person is male but not white, the wage is increased by $\beta_2$ (or decreased if $\beta_2$ is negative). If the person is not male but is white, the wage is increased by $\beta_3$. If the person is male and white, the wage is increased by $\beta_2+\beta_3+\beta_4$. That is, the term $sex *race$ makes your model non-linear. Without this term, if the person is male and white, the wage is increased by the amount of increase if he is male plus the amount of increase if he is white, which is one property of linear models. In other words, this term places more emphasise on the employees that are both male and white.
How to Interpret Interaction Between Two Categorical Variables
Your interpretation is true. This is another way to interpret these terms: If the person is male but not white, the wage is increased by $\beta_2$ (or decreased if $\beta_2$ is negative). If the pers
How to Interpret Interaction Between Two Categorical Variables Your interpretation is true. This is another way to interpret these terms: If the person is male but not white, the wage is increased by $\beta_2$ (or decreased if $\beta_2$ is negative). If the person is not male but is white, the wage is increased by $\beta_3$. If the person is male and white, the wage is increased by $\beta_2+\beta_3+\beta_4$. That is, the term $sex *race$ makes your model non-linear. Without this term, if the person is male and white, the wage is increased by the amount of increase if he is male plus the amount of increase if he is white, which is one property of linear models. In other words, this term places more emphasise on the employees that are both male and white.
How to Interpret Interaction Between Two Categorical Variables Your interpretation is true. This is another way to interpret these terms: If the person is male but not white, the wage is increased by $\beta_2$ (or decreased if $\beta_2$ is negative). If the pers
48,464
What is the difference between rate & probability?
Rate probably can mean different things, see https://en.wikipedia.org/wiki/Rate_(mathematics) for an overview, but in this context you probably think rate of occurence of events in some (temporal) random process. The rate is simply the expected number of events per some (time) unit (could also be spatial). That could easily be larger than one, there is indeed no upper limit on a rate, just make the time interval larger, then the rate becomes larger ... This shows clearly difference from probability. Rate is a kind of an expectation. You say that "rate looks at past events for a period of time vs. probability predicts the possibility of future events?". I know of no context that support your claim.
What is the difference between rate & probability?
Rate probably can mean different things, see https://en.wikipedia.org/wiki/Rate_(mathematics) for an overview, but in this context you probably think rate of occurence of events in some (temporal) ra
What is the difference between rate & probability? Rate probably can mean different things, see https://en.wikipedia.org/wiki/Rate_(mathematics) for an overview, but in this context you probably think rate of occurence of events in some (temporal) random process. The rate is simply the expected number of events per some (time) unit (could also be spatial). That could easily be larger than one, there is indeed no upper limit on a rate, just make the time interval larger, then the rate becomes larger ... This shows clearly difference from probability. Rate is a kind of an expectation. You say that "rate looks at past events for a period of time vs. probability predicts the possibility of future events?". I know of no context that support your claim.
What is the difference between rate & probability? Rate probably can mean different things, see https://en.wikipedia.org/wiki/Rate_(mathematics) for an overview, but in this context you probably think rate of occurence of events in some (temporal) ra
48,465
What is the difference between rate & probability?
Rates: The instantaneous potential for the occurrence of an event, expressed per number of patients at risk. Rates can be added and subtracted. Probabilities: A number ranging between 0 and 1. Represents the likelihood of an event happening over a specific period of time. Briggs, Andrew. Decision Modelling for Health Economic Evaluation (Handbooks in Health Economic Evaluation) (Kindle Locations 958-959). OUP Oxford. Kindle Edition.
What is the difference between rate & probability?
Rates: The instantaneous potential for the occurrence of an event, expressed per number of patients at risk. Rates can be added and subtracted. Probabilities: A number ranging between 0 and 1. Represe
What is the difference between rate & probability? Rates: The instantaneous potential for the occurrence of an event, expressed per number of patients at risk. Rates can be added and subtracted. Probabilities: A number ranging between 0 and 1. Represents the likelihood of an event happening over a specific period of time. Briggs, Andrew. Decision Modelling for Health Economic Evaluation (Handbooks in Health Economic Evaluation) (Kindle Locations 958-959). OUP Oxford. Kindle Edition.
What is the difference between rate & probability? Rates: The instantaneous potential for the occurrence of an event, expressed per number of patients at risk. Rates can be added and subtracted. Probabilities: A number ranging between 0 and 1. Represe
48,466
What is the difference between rate & probability?
The rate is defined is the relationship between numerator and denominator probability is a numerator is a part of the denominator, for example, a/a+b
What is the difference between rate & probability?
The rate is defined is the relationship between numerator and denominator probability is a numerator is a part of the denominator, for example, a/a+b
What is the difference between rate & probability? The rate is defined is the relationship between numerator and denominator probability is a numerator is a part of the denominator, for example, a/a+b
What is the difference between rate & probability? The rate is defined is the relationship between numerator and denominator probability is a numerator is a part of the denominator, for example, a/a+b
48,467
What is the difference between rate & probability?
On a temporal frame, Probability usually refers to the expectation of occurrence of an event within a given time span (eg. 5 years), whereas Rate is provided for 1 unit of time (eg. yearly rate). Converting one to the other goes as follows: Rate = -ln (1 - Prob) / time Prob = 1 - e^(-Rate * time) Consider this example: A patient with a given disease is likely to evolve from stage I to stage II in 2 years with a probability of 50%. Does this mean that the probability of that same patient evolving from stage I to stage II of the disease is 100% in 4 years? or does it imply a probability of 150% in 6 years? Certainly not, it wouldn't even be possible. To answer this question, one must first convert the initial probability into a yearly rate. (Note that this conversion assumes that the rate of occurrence of this event is constant along time.) Known probability and time (X): T.x = 2 years P.x = 0.50 Yearly rate: R = -ln(1 - P.x) / T.x = -ln(1 - 0.50) / 2 = 0,346574 Calculated probability in new time frame (Y): T.y = 4 years P.y = 1 - e^(-R * T.y) = 1 - e^(-0,346574 * 4) = 0,75 So our calculated probability in a different time frame, in this case, would be 75% in 4 years. Or 88% in 6 years, 97% in 10 years, etc.
What is the difference between rate & probability?
On a temporal frame, Probability usually refers to the expectation of occurrence of an event within a given time span (eg. 5 years), whereas Rate is provided for 1 unit of time (eg. yearly rate). Conv
What is the difference between rate & probability? On a temporal frame, Probability usually refers to the expectation of occurrence of an event within a given time span (eg. 5 years), whereas Rate is provided for 1 unit of time (eg. yearly rate). Converting one to the other goes as follows: Rate = -ln (1 - Prob) / time Prob = 1 - e^(-Rate * time) Consider this example: A patient with a given disease is likely to evolve from stage I to stage II in 2 years with a probability of 50%. Does this mean that the probability of that same patient evolving from stage I to stage II of the disease is 100% in 4 years? or does it imply a probability of 150% in 6 years? Certainly not, it wouldn't even be possible. To answer this question, one must first convert the initial probability into a yearly rate. (Note that this conversion assumes that the rate of occurrence of this event is constant along time.) Known probability and time (X): T.x = 2 years P.x = 0.50 Yearly rate: R = -ln(1 - P.x) / T.x = -ln(1 - 0.50) / 2 = 0,346574 Calculated probability in new time frame (Y): T.y = 4 years P.y = 1 - e^(-R * T.y) = 1 - e^(-0,346574 * 4) = 0,75 So our calculated probability in a different time frame, in this case, would be 75% in 4 years. Or 88% in 6 years, 97% in 10 years, etc.
What is the difference between rate & probability? On a temporal frame, Probability usually refers to the expectation of occurrence of an event within a given time span (eg. 5 years), whereas Rate is provided for 1 unit of time (eg. yearly rate). Conv
48,468
How to add 95% confidence bands to a nonlinear regression model?
I think the propagate package can do what you are looking for. require(propagate) pred_model <- predictNLS(model, newdata=mm) conf_model <- pred$summary plot(v~S) lines(conf_model$Prop.Mean.1 ~ S, lwd=2) lines(conf_model$"Sim.2.5%" ~ S, lwd=1) lines(conf_model$"Sim.97.5%" ~ S, lwd=1)
How to add 95% confidence bands to a nonlinear regression model?
I think the propagate package can do what you are looking for. require(propagate) pred_model <- predictNLS(model, newdata=mm) conf_model <- pred$summary plot(v~S) lines(conf_model$Prop.Mean.1 ~ S, l
How to add 95% confidence bands to a nonlinear regression model? I think the propagate package can do what you are looking for. require(propagate) pred_model <- predictNLS(model, newdata=mm) conf_model <- pred$summary plot(v~S) lines(conf_model$Prop.Mean.1 ~ S, lwd=2) lines(conf_model$"Sim.2.5%" ~ S, lwd=1) lines(conf_model$"Sim.97.5%" ~ S, lwd=1)
How to add 95% confidence bands to a nonlinear regression model? I think the propagate package can do what you are looking for. require(propagate) pred_model <- predictNLS(model, newdata=mm) conf_model <- pred$summary plot(v~S) lines(conf_model$Prop.Mean.1 ~ S, l
48,469
Find the maximum likelihood estimator
You can do an easy check of your answer by writing the density as an exponential family. It has sufficient statistic $x^2$, which means that the maximum likelihood estimate must be $\sqrt{\frac{\sum_i x_i^2}{n}}$ as you found.
Find the maximum likelihood estimator
You can do an easy check of your answer by writing the density as an exponential family. It has sufficient statistic $x^2$, which means that the maximum likelihood estimate must be $\sqrt{\frac{\sum_
Find the maximum likelihood estimator You can do an easy check of your answer by writing the density as an exponential family. It has sufficient statistic $x^2$, which means that the maximum likelihood estimate must be $\sqrt{\frac{\sum_i x_i^2}{n}}$ as you found.
Find the maximum likelihood estimator You can do an easy check of your answer by writing the density as an exponential family. It has sufficient statistic $x^2$, which means that the maximum likelihood estimate must be $\sqrt{\frac{\sum_
48,470
Where does the delta method's name come from?
The name "Delta" is from the symbol $\Delta$ for "change" which is used in limit expressions like let $\Delta X_i\rightarrow 0$, where $\Delta X_i=X_{i+1}-X_i$, and also $\Delta$ or lower case "δ" refers to an inexact, non-zero differential equation (i.e., before limits are taken) which reduces in the limits to a differential equation the latter using infinitesimals. For example, $\Delta f(x)= f(x+\Delta x)-f(x)$, which reduces to $\partial f$, a vanishingly small differential, for $\Delta x$ sufficiently small. Now sometimes we want to manipulate equations so that we are not dividing or multiplying by zeros, and in that case, we might use the $\Delta $ notation. The name delta method, is probably only used by statisticians. In other contexts, e.g., engineering, physics, it would be more commonly referred to as propagation of error. To see how the error propagation includes the $\Delta$ symbol, see propagation of error. Edit Error propagation is from Taylor series, useful examples. Indeed, when extended to the first two derivatives of Taylor series, i.e., $\mathbf{Var}[Y]\approx(g'(\mu_X))^2\sigma_{X}^{2}+g'(\mu_X)g''(\mu_X)\mu_3+\frac{1}{4}(g''(\mu_X))^2(\mu_4-\sigma_{X}^{4})$, it becomes more accurate, and I would venture that that is needed when the solution space curvature is of greater magnitude. BTW, in ancient Greek the letter $\Delta$ was pronounced as a "d" sound and in modern Greek this is a hybrid "d" and "th" sound. The etymology is purported to be as follows, c. 1200, Greek letter shaped like a triangle, equivalent to our "D," the name from Phoenician daleth "tent door." Herodotus used it of the mouth of the Nile, and it was so used in English from 1550s; applied to other river mouths from 1790.
Where does the delta method's name come from?
The name "Delta" is from the symbol $\Delta$ for "change" which is used in limit expressions like let $\Delta X_i\rightarrow 0$, where $\Delta X_i=X_{i+1}-X_i$, and also $\Delta$ or lower case "δ" ref
Where does the delta method's name come from? The name "Delta" is from the symbol $\Delta$ for "change" which is used in limit expressions like let $\Delta X_i\rightarrow 0$, where $\Delta X_i=X_{i+1}-X_i$, and also $\Delta$ or lower case "δ" refers to an inexact, non-zero differential equation (i.e., before limits are taken) which reduces in the limits to a differential equation the latter using infinitesimals. For example, $\Delta f(x)= f(x+\Delta x)-f(x)$, which reduces to $\partial f$, a vanishingly small differential, for $\Delta x$ sufficiently small. Now sometimes we want to manipulate equations so that we are not dividing or multiplying by zeros, and in that case, we might use the $\Delta $ notation. The name delta method, is probably only used by statisticians. In other contexts, e.g., engineering, physics, it would be more commonly referred to as propagation of error. To see how the error propagation includes the $\Delta$ symbol, see propagation of error. Edit Error propagation is from Taylor series, useful examples. Indeed, when extended to the first two derivatives of Taylor series, i.e., $\mathbf{Var}[Y]\approx(g'(\mu_X))^2\sigma_{X}^{2}+g'(\mu_X)g''(\mu_X)\mu_3+\frac{1}{4}(g''(\mu_X))^2(\mu_4-\sigma_{X}^{4})$, it becomes more accurate, and I would venture that that is needed when the solution space curvature is of greater magnitude. BTW, in ancient Greek the letter $\Delta$ was pronounced as a "d" sound and in modern Greek this is a hybrid "d" and "th" sound. The etymology is purported to be as follows, c. 1200, Greek letter shaped like a triangle, equivalent to our "D," the name from Phoenician daleth "tent door." Herodotus used it of the mouth of the Nile, and it was so used in English from 1550s; applied to other river mouths from 1790.
Where does the delta method's name come from? The name "Delta" is from the symbol $\Delta$ for "change" which is used in limit expressions like let $\Delta X_i\rightarrow 0$, where $\Delta X_i=X_{i+1}-X_i$, and also $\Delta$ or lower case "δ" ref
48,471
solid line from a local average series
What you want is a mean preserving interpolation. John D'Errico has the exact solution you're looking for, written in MATLAB however. https://www.mathworks.com/matlabcentral/newsreader/view_thread/31378 function [y,spl]=mean_series(ymeans,n,EndConditions) % mean_series: cubic spline resampling of series in x % (n times), maintaining the mean % % arguments: % ymeans - vector of means % n - % EndConditions - flag specifying natural or not-a-knot % end conditions on the spline. % EndConditions == 0 --> natural % EndConditions == 1 (default) --> not-a-knot % % y - interpolated series, y has the property that: % ymeans == sum(reshape(y,n,length(x))) % % spl - cubic spline as a piecewise cubic Hermite function % ensure that ymeans is a column vector ymeans=ymeans(:); nmeans=length(ymeans); % things will fail unless there are at least two % points in ymeans if nmeans<2 error 'I require length(ymeans)>=2 or dire things will happen' end % nmeans+1 implicit knots nk=nmeans+1; % implicit positions of points supplied xmeans=(0:(nmeans-1))'; % implicit positions of knots knots=(0:nmeans)'-0.5; % knot spacing delta=diff(knots); % implicit coordinates of the points to be predicted % (interpolations at these points) x=linspace(knots(1),knots(end),nmeans*n+1)'; x(end)=[]; ny=n*nmeans; % define the spline as a piecewise cubic Hermite at % the knots. This gives us nk function values and % nk derivatives. % Force the spline to be C2. compute the matrix % relating function values to first derivatives, % comes about from second derivative continuity at % the knots. these will be equality constraints on % the unknown spline coefficients. feq=zeros(nk-2,nk); deq=zeros(nk-2,nk); rhseq=zeros(nk-2,1); for i=2:(nk-1) j=i-1; feq(j,i+[-1 0 1])=-[-6/delta(j)^2 , ... (6/delta(j)^2)-(6/delta(i)^2) , 6/delta(i)^2]; deq(j,i+[-1 0 1])=[2/delta(j) , ... 4/delta(j)+4/delta(i) , 2/delta(i)]; end % next, "evaluate" the points through the implicitly % defined spline. We do not yet have the coefficients % defining the spline, but we will eventually. % k specifies which knot interval the points fall in. k=repmat(1:nmeans,n,1); k=k(:); t=(x-knots(k))./delta(k); t2=t.*t; t3=t2.*t; s2=(1-t).*(1-t); s3=s2.*(1-t); % build the matrix sparsely for efficiency, then convert % the system to full since its really not sparse enough % to save much. fmat=[3*s2-2*s3 , 3*t2-2*t3]; dmat=[-delta(k).*(s3-s2) , delta(k).*(t3-t2)]; imat=(1:ny)'; imat=[imat,imat]; jmat=[k,k+1]; fmat0=full(sparse(imat,jmat,fmat,ny,nk)); dmat0=full(sparse(imat,jmat,dmat,ny,nk)); % now, compute implicit means of every n points. % do it via a matrix multiply. M=kron(eye(nmeans,nmeans),ones(1,n)/n); fmat=M*fmat0; dmat=M*dmat0; % Since these means are to be forced, specify them % as equality constraints, appending them to the set % of equalities. feq=[feq;fmat]; deq=[deq;dmat]; rhseq=[rhseq;ymeans]; % End condotions are either: 'natural', 'not-a-knot' % test for default on EndConditions switch EndConditions case 0 % natural boundary conditions, i.e., zero second % derivative at ends fe=zeros(2,nk); de=zeros(2,nk); % at the bottom knot: fe(1,1:2)=[-1, 1]*6/(delta(1)^2); de(1,1:2)=[-2, -1]*2/delta(1); % at the top knot: fe(2,nk+[-1 0])=[1, -1]*6/(delta(nk-1)^2); de(2,nk+[-1 0])=[1, 2]*2/delta(nk-1); % append to equality constraints matrix feq=[feq;fe]; deq=[deq;de]; rhseq=[rhseq;zeros(2,1)]; case 1 % not-a-knot end conditions, 3rd derivative continuity at % 2nd knot and next to last knots fe=zeros(1+(nk>3),nk); de=fe; % at the second knot: fe(1,1:3)=[1 -1 0]*12/(delta(1)^3)-[0 1 -1]*12/(delta(2)^3); de(1,1:3)=[1 1 0]*6/(delta(1)^2)-[0 1 1]*6/(delta(2)^2); % at the top knot: if nk>3 fe(2,nk+(-2:0))=[1 -1 0]*12/(delta(nk-2)^3)- ... [0 1 -1]*12/(delta(nk-1)^3); de(2,nk+(-2:0))=[1 1 0]*6/(delta(nk-2)^2)- ... [0 1 1]*6/(delta(nk-1)^2); end % append to equality constraints matrix feq=[feq;fe]; deq=[deq;de]; rhseq=[rhseq;zeros(1+(nk>3),1)]; end % the second derivative regularizer is a quadratic form of the form % s'*regmat*s, % where s is the vector of (unknown) second derivatives at the knots. regmat=zeros(nk,nk); regmat(1,1:2)=[delta(1)/3 , delta(1)/6]; regmat(nk,nk+[-1 0])=[delta(nk-1)/6 , delta(nk-1)/3]; for i=2:(nk-1) regmat(i,i+[-1 0 1])=[delta(i-1)/6 , (delta(i-1)+delta(i))/3 , delta(i)/6]; end % next, write the second derivatives as a function of the % function values and first derivatives: s = [sf,sd]*[f;d] sf=zeros(nk,nk); sd=zeros(nk,nk); for i=1:(nk-1) sf(i,i+[0 1])=[-1 1].*(6/(delta(i)^2)); sd(i,i+[0 1])=[-4 -2]./delta(i); end sf(nk,nk+[-1 0])=[1 -1].*(6/(delta(nk-1)^2)); sd(nk,nk+[-1 0])=[2 4]./delta(nk-1); regmat=[sf,sd]'*regmat*[sf,sd]; % ensure numerical symmetry of the hessian regmat=regmat+regmat'; % now, solve this whole mess of a linear system % using a quadratic programming package. % assume quadprog from the optimization toolbox 2.0 H=regmat; f=zeros(2*nk,1); Aeq=[feq,deq]; beq=rhseq; options=optimset('quadprog'); coef=quadprog(H,f,[],[],Aeq,beq,[],[],[],options); % break the coeficients up into a spline. % first column is the knots, the second column % is function values at the knots, the third column % is first derivatives at the knots. spl=[knots,reshape(coef,nk,2)]; % return predictions at the original points y=fmat0*spl(:,2)+dmat0*spl(:,3); We can test out this function: ymeans=sin(1:22)'; n=3; EndConditions=1; [yhat,spl]=mean_series(ymeans,n,1); plot(yhat); hold on plot(kron(ymeans,ones(n,1))); hold off Beautiful!! Here's yhat, reshaped so that the mean of each row will be equal to the original input: >> reshape(yhat,3,22)' ans = 0.6038 0.8903 1.0303 1.0413 0.9407 0.7459 0.4743 0.1473 -0.1983 -0.5214 -0.7848 -0.9642 -1.0390 -0.9948 -0.8430 -0.6010 -0.2903 0.0531 0.3894 0.6811 0.9005 1.0219 1.0263 0.9198 0.7147 0.4279 0.0937 -0.2493 -0.5639 -0.8188 -0.9845 -1.0373 -0.9782 -0.8141 -0.5570 -0.2387 0.1042 0.4354 0.7210 0.9276 1.0275 1.0167 0.8968 0.6749 0.3792 0.0434 -0.2981 -0.6090 -0.8525 -0.9972 -1.0344 -0.9610 -0.7792 -0.5128 -0.1911 0.1548 0.4860 0.7618 0.9471 1.0300 1.0038 0.8673 0.6388 0.3414 -0.0014 -0.3666 Let's make sure the mean was preserved for each set of n points: >>yhat_means=kron(eye(length(ymeans)),repmat(1/n,1,n))*yhat; >>[yhat_means,ymeans] ans = 0.8415 0.8415 0.9093 0.9093 0.1411 0.1411 -0.7568 -0.7568 -0.9589 -0.9589 -0.2794 -0.2794 0.6570 0.6570 0.9894 0.9894 0.4121 0.4121 -0.5440 -0.5440 -1.0000 -1.0000 -0.5366 -0.5366 0.4202 0.4202 0.9906 0.9906 0.6503 0.6503 -0.2879 -0.2879 -0.9614 -0.9614 -0.7510 -0.7510 0.1499 0.1499 0.9129 0.9129 0.8367 0.8367 -0.0089 -0.0089 I think this code is extremely satisfying. I've tried to replicate it in R, but I have yet to find a QP solver that works well with equality constraints and no bounds (the Rcplex package might work, but you have to pay for it, which is dumb, since if you're paying for software, you'd pick MATLAB or some other software with decent support). The following R functions/packages that have QP solvers do NOT work for this problem (non-exclusive list): quadprog, ipop, ROI, auglag, nlminb, optimx, trust, COBYLA. If anyone is interested in that R code, here it is, with one of the dumb solvers (if a good solver becomes available, you can just replace that line, and the code will work as well as the MATLAB implementation - and don't forget to leave a comment here if you find it): library(alabama) library(fBasics) # identity matrix eye<-function(n){ if(n==0){ return(matrix(0,0,0)) }else{ M<-matrix(0,n,n) M[1+0:(n-1)*(n+1)]<-1 return(M) } } # function inspired by matlab's sparse() sparse<-function(i,j,v,n=0,m=0,nz=0){ S<-matrix(nz,max(max(i),n),max(max(j),m)) S[cbind(matrix(i,ncol=1),matrix(j,ncol=1))]<-matrix(v,ncol=1) return(S) } mean_series<-function(ymeans,n,EndConditions=1,Method="L-BFGS-B"){ # mean_series: cubic spline resampling of series in x # (n times), maintaining the mean # # arguments: # ymeans - vector of means # n - # EndConditions - flag specifying natural or not-a-knot # end conditions on the spline. # EndConditions <-<- 0 --> natural # EndConditions <-<- 1 (default) --> not-a-knot # # y - interpolated series, y has the property that: # ymeans <-<- sum(reshape(y,n,length(x))) # # spl - cubic spline as a piecewise cubic Hermite function # ensure that ymeans is a column vector ymeans<-matrix(ymeans,ncol = 1) nmeans<-length(ymeans) # things will fail unless there are at least two # points in ymeans if (nmeans<2){ stop('I require length(ymeans)><-2 or dire things will happen') } # nmeans+1 implicit knots nk<-nmeans+1 # implicit positions of knots knots<-cbind(0:nmeans)-0.5 # knot spacing delta<-diff(knots) # implicit coordinates of the points to be predicted # (interpolations at these points) x<-seq(knots[1],knots[length(knots)],length.out =nmeans*n+1) x<-cbind(x[-length(x)]) ny<-n*nmeans # define the spline as a piecewise cubic Hermite at # the knots. This gives us nk function values and # nk derivatives. # Force the spline to be C2. compute the matrix # relating function values to first derivatives, # comes about from second derivative continuity at # the knots. these will be equality constraints on # the unknown spline coefficients. feq<-matrix(0,nk-2,nk) deq<-matrix(0,nk-2,nk) rhseq<-matrix(0,nk-2,1) for(i in 2:(nk-1)){ j<-i-1 feq[j,i+(-1:1)]<--cbind(-6/delta[j]^2 ,(6/delta[j]^2)-(6/delta[i]^2) , 6/delta[i]^2) deq[j,i+(-1:1)]<- cbind(2/delta[j] , 4/delta[j]+4/delta[i] , 2/delta[i]) } # next, "evaluate" the points through the implicitly # defined spline. We do not yet have the coefficients # defining the spline, but we will eventually. # k specifies which knot interval the points fall in. k<-matrix(1:nmeans,n*nmeans,1) t<-(x-knots[k])/delta[k] t2<-t*t t3<-t2*t s2<-(1-t)*(1-t) s3<-s2*(1-t) # build the matrix sparsely for efficiency, then convert # the system to full since its really not sparse enough # to save much. fmat<-cbind(3*s2-2*s3 , 3*t2-2*t3) dmat<-cbind(-delta[k]*(s3-s2) , delta[k]*(t3-t2)) imat<-cbind(1:ny) imat<-cbind(imat,imat) jmat<-cbind(k,k+1) fmat0<-sparse(imat,jmat,fmat,ny,nk) dmat0<-sparse(imat,jmat,dmat,ny,nk) # now, compute implicit means of every n points. # do it via a matrix multiply. M<-kron(eye(nmeans),matrix(1,1,n)/n) fmat<-M%*%fmat0 dmat<-M%*%dmat0 # Since these means are to be forced, specify them # as equality constraints, appending them to the set # of equalities. feq<-rbind(feq,fmat) deq<-rbind(deq,dmat) rhseq<-rbind(rhseq,ymeans) # End condotions are either: 'natural', 'not-a-knot' # test for default on EndConditions if(EndConditions==0){ # natural boundary conditions, i.e., zero second # derivative at ends fe<-matrix(0,2,nk) de<-matrix(0,2,nk) # at the bottom knot: fe[1,1:2]<-c(-1, 1)*6/(delta[1]^2) de[1,1:2]<-c(-2, -1)*2/delta[1] # at the top knot: fe[2,nk+(-1:0)]<-c(1,-1)*6/(delta[nk-1]^2) de[2,nk+(-1:0)]<-c(1,2)*2/delta[nk-1] # append to equality constraints matrix feq<-rbind(feq,fe) deq<-rbind(deq,de) rhseq<-rbind(rhseq,matrix(0,2,1)) } if(EndConditions==1){ # not-a-knot end conditions, 3rd derivative continuity at # 2nd knot and next to last knots fe<-matrix(0,1+(nk>3),nk) de<-fe # at the second knot: fe[1,1:3]<-c(1,-1,0)*12/(delta[1]^3)-c(0,1,-1)*12/(delta[2]^3) de[1,1:3]<-c(1,1,0)*6/(delta[1]^2)-c(0,1,1)*6/(delta[2]^2) # at the top knot: if(nk>3){ fe[2,nk+(-2:0)]<-c(1,-1,0)*12/(delta[nk-2]^3)-c(0,1,-1)*12/(delta[nk-1]^3) de[2,nk+(-2:0)]<-c(1,1,0)*6/(delta[nk-2]^2)-c(0,1,1)*6/(delta[nk-1]^2) } # append to equality constraints matrix feq<-rbind(feq,fe) deq<-rbind(deq,de) rhseq<-rbind(rhseq,matrix(0,1+(nk>3),1)) } # the second derivative regularizer is a quadratic form of the form # s'*regmat*s, # where s is the vector of (unknown) second derivatives at the knots. regmat<-matrix(0,nk,nk) regmat[1,1:2]<-cbind(delta[1]/3 , delta[1]/6) regmat[nk,nk+(-1:0)]<-cbind(delta[nk-1]/6 , delta[nk-1]/3) for(i in 2:(nk-1)){ regmat[i,i+(-1:1)]<-c(delta[i-1]/6 , (delta[i-1]+delta[i])/3 , delta[i]/6) } # next, write the second derivatives as a function of the # function values and first derivatives: s <- [sf,sd]*[fd] sf<-matrix(0,nk,nk) sd<-matrix(0,nk,nk) for(i in 1:(nk-1)){ sf[i,i+(0:1)]<-c(-1,1)*(6/(delta[i]^2)) sd[i,i+(0:1)]<-c(-4,-2)/delta[i] } sf[nk,nk+(-1:0)]<-c(1,-1)*(6/(delta[nk-1]^2)) sd[nk,nk+(-1:0)]<-c(2,4)/delta[nk-1] regmat<-t(cbind(sf,sd))%*%regmat%*%cbind(sf,sd) # ensure numerical symmetry of the hessian regmat<-regmat+t(regmat) # now, solve this whole mess of a linear system # using a quadratic programming package. # assume quadprog from the optimization toolbox 2.0 H<-regmat f<-matrix(0,2*nk,1) Aeq<-cbind(feq,deq) beq<-rhseq # THIS QP SOLVER DOESN'T FREAKIN WORK AT ALL. coef<-cbind(auglag(cbind(rep(0,dim(H)[1])), fn=function(x){t(x)%*%H%*%x}, hin=function(x){Aeq%*%x-beq}, hin.jac=function(x){Aeq}, heq=function(x){1}, heq.jac=function(x){rbind(rep(0,dim(Aeq)[2]))}, control.outer = list(method=Method,trace=FALSE,itmax=100))$par) # break the coeficients up into a spline. # first column is the knots, the second column # is function values at the knots, the third column # is first derivatives at the knots. spl<-cbind(knots,matrix(coef,nk,2)) # return predictions at the original points y<-fmat0%*%spl[,2]+dmat0%*%spl[,3] return(y) } Let's test this stupid QP solver to see how absolutely useless it is: ymeans<-sin(1:22) n<-3 yhat<-mean_series(ymeans,n) lineplot(cbind(kron(ymeans,cbind(rep(1,n))),yhat),1:66,legend = FALSE)
solid line from a local average series
What you want is a mean preserving interpolation. John D'Errico has the exact solution you're looking for, written in MATLAB however. https://www.mathworks.com/matlabcentral/newsreader/view_thread/313
solid line from a local average series What you want is a mean preserving interpolation. John D'Errico has the exact solution you're looking for, written in MATLAB however. https://www.mathworks.com/matlabcentral/newsreader/view_thread/31378 function [y,spl]=mean_series(ymeans,n,EndConditions) % mean_series: cubic spline resampling of series in x % (n times), maintaining the mean % % arguments: % ymeans - vector of means % n - % EndConditions - flag specifying natural or not-a-knot % end conditions on the spline. % EndConditions == 0 --> natural % EndConditions == 1 (default) --> not-a-knot % % y - interpolated series, y has the property that: % ymeans == sum(reshape(y,n,length(x))) % % spl - cubic spline as a piecewise cubic Hermite function % ensure that ymeans is a column vector ymeans=ymeans(:); nmeans=length(ymeans); % things will fail unless there are at least two % points in ymeans if nmeans<2 error 'I require length(ymeans)>=2 or dire things will happen' end % nmeans+1 implicit knots nk=nmeans+1; % implicit positions of points supplied xmeans=(0:(nmeans-1))'; % implicit positions of knots knots=(0:nmeans)'-0.5; % knot spacing delta=diff(knots); % implicit coordinates of the points to be predicted % (interpolations at these points) x=linspace(knots(1),knots(end),nmeans*n+1)'; x(end)=[]; ny=n*nmeans; % define the spline as a piecewise cubic Hermite at % the knots. This gives us nk function values and % nk derivatives. % Force the spline to be C2. compute the matrix % relating function values to first derivatives, % comes about from second derivative continuity at % the knots. these will be equality constraints on % the unknown spline coefficients. feq=zeros(nk-2,nk); deq=zeros(nk-2,nk); rhseq=zeros(nk-2,1); for i=2:(nk-1) j=i-1; feq(j,i+[-1 0 1])=-[-6/delta(j)^2 , ... (6/delta(j)^2)-(6/delta(i)^2) , 6/delta(i)^2]; deq(j,i+[-1 0 1])=[2/delta(j) , ... 4/delta(j)+4/delta(i) , 2/delta(i)]; end % next, "evaluate" the points through the implicitly % defined spline. We do not yet have the coefficients % defining the spline, but we will eventually. % k specifies which knot interval the points fall in. k=repmat(1:nmeans,n,1); k=k(:); t=(x-knots(k))./delta(k); t2=t.*t; t3=t2.*t; s2=(1-t).*(1-t); s3=s2.*(1-t); % build the matrix sparsely for efficiency, then convert % the system to full since its really not sparse enough % to save much. fmat=[3*s2-2*s3 , 3*t2-2*t3]; dmat=[-delta(k).*(s3-s2) , delta(k).*(t3-t2)]; imat=(1:ny)'; imat=[imat,imat]; jmat=[k,k+1]; fmat0=full(sparse(imat,jmat,fmat,ny,nk)); dmat0=full(sparse(imat,jmat,dmat,ny,nk)); % now, compute implicit means of every n points. % do it via a matrix multiply. M=kron(eye(nmeans,nmeans),ones(1,n)/n); fmat=M*fmat0; dmat=M*dmat0; % Since these means are to be forced, specify them % as equality constraints, appending them to the set % of equalities. feq=[feq;fmat]; deq=[deq;dmat]; rhseq=[rhseq;ymeans]; % End condotions are either: 'natural', 'not-a-knot' % test for default on EndConditions switch EndConditions case 0 % natural boundary conditions, i.e., zero second % derivative at ends fe=zeros(2,nk); de=zeros(2,nk); % at the bottom knot: fe(1,1:2)=[-1, 1]*6/(delta(1)^2); de(1,1:2)=[-2, -1]*2/delta(1); % at the top knot: fe(2,nk+[-1 0])=[1, -1]*6/(delta(nk-1)^2); de(2,nk+[-1 0])=[1, 2]*2/delta(nk-1); % append to equality constraints matrix feq=[feq;fe]; deq=[deq;de]; rhseq=[rhseq;zeros(2,1)]; case 1 % not-a-knot end conditions, 3rd derivative continuity at % 2nd knot and next to last knots fe=zeros(1+(nk>3),nk); de=fe; % at the second knot: fe(1,1:3)=[1 -1 0]*12/(delta(1)^3)-[0 1 -1]*12/(delta(2)^3); de(1,1:3)=[1 1 0]*6/(delta(1)^2)-[0 1 1]*6/(delta(2)^2); % at the top knot: if nk>3 fe(2,nk+(-2:0))=[1 -1 0]*12/(delta(nk-2)^3)- ... [0 1 -1]*12/(delta(nk-1)^3); de(2,nk+(-2:0))=[1 1 0]*6/(delta(nk-2)^2)- ... [0 1 1]*6/(delta(nk-1)^2); end % append to equality constraints matrix feq=[feq;fe]; deq=[deq;de]; rhseq=[rhseq;zeros(1+(nk>3),1)]; end % the second derivative regularizer is a quadratic form of the form % s'*regmat*s, % where s is the vector of (unknown) second derivatives at the knots. regmat=zeros(nk,nk); regmat(1,1:2)=[delta(1)/3 , delta(1)/6]; regmat(nk,nk+[-1 0])=[delta(nk-1)/6 , delta(nk-1)/3]; for i=2:(nk-1) regmat(i,i+[-1 0 1])=[delta(i-1)/6 , (delta(i-1)+delta(i))/3 , delta(i)/6]; end % next, write the second derivatives as a function of the % function values and first derivatives: s = [sf,sd]*[f;d] sf=zeros(nk,nk); sd=zeros(nk,nk); for i=1:(nk-1) sf(i,i+[0 1])=[-1 1].*(6/(delta(i)^2)); sd(i,i+[0 1])=[-4 -2]./delta(i); end sf(nk,nk+[-1 0])=[1 -1].*(6/(delta(nk-1)^2)); sd(nk,nk+[-1 0])=[2 4]./delta(nk-1); regmat=[sf,sd]'*regmat*[sf,sd]; % ensure numerical symmetry of the hessian regmat=regmat+regmat'; % now, solve this whole mess of a linear system % using a quadratic programming package. % assume quadprog from the optimization toolbox 2.0 H=regmat; f=zeros(2*nk,1); Aeq=[feq,deq]; beq=rhseq; options=optimset('quadprog'); coef=quadprog(H,f,[],[],Aeq,beq,[],[],[],options); % break the coeficients up into a spline. % first column is the knots, the second column % is function values at the knots, the third column % is first derivatives at the knots. spl=[knots,reshape(coef,nk,2)]; % return predictions at the original points y=fmat0*spl(:,2)+dmat0*spl(:,3); We can test out this function: ymeans=sin(1:22)'; n=3; EndConditions=1; [yhat,spl]=mean_series(ymeans,n,1); plot(yhat); hold on plot(kron(ymeans,ones(n,1))); hold off Beautiful!! Here's yhat, reshaped so that the mean of each row will be equal to the original input: >> reshape(yhat,3,22)' ans = 0.6038 0.8903 1.0303 1.0413 0.9407 0.7459 0.4743 0.1473 -0.1983 -0.5214 -0.7848 -0.9642 -1.0390 -0.9948 -0.8430 -0.6010 -0.2903 0.0531 0.3894 0.6811 0.9005 1.0219 1.0263 0.9198 0.7147 0.4279 0.0937 -0.2493 -0.5639 -0.8188 -0.9845 -1.0373 -0.9782 -0.8141 -0.5570 -0.2387 0.1042 0.4354 0.7210 0.9276 1.0275 1.0167 0.8968 0.6749 0.3792 0.0434 -0.2981 -0.6090 -0.8525 -0.9972 -1.0344 -0.9610 -0.7792 -0.5128 -0.1911 0.1548 0.4860 0.7618 0.9471 1.0300 1.0038 0.8673 0.6388 0.3414 -0.0014 -0.3666 Let's make sure the mean was preserved for each set of n points: >>yhat_means=kron(eye(length(ymeans)),repmat(1/n,1,n))*yhat; >>[yhat_means,ymeans] ans = 0.8415 0.8415 0.9093 0.9093 0.1411 0.1411 -0.7568 -0.7568 -0.9589 -0.9589 -0.2794 -0.2794 0.6570 0.6570 0.9894 0.9894 0.4121 0.4121 -0.5440 -0.5440 -1.0000 -1.0000 -0.5366 -0.5366 0.4202 0.4202 0.9906 0.9906 0.6503 0.6503 -0.2879 -0.2879 -0.9614 -0.9614 -0.7510 -0.7510 0.1499 0.1499 0.9129 0.9129 0.8367 0.8367 -0.0089 -0.0089 I think this code is extremely satisfying. I've tried to replicate it in R, but I have yet to find a QP solver that works well with equality constraints and no bounds (the Rcplex package might work, but you have to pay for it, which is dumb, since if you're paying for software, you'd pick MATLAB or some other software with decent support). The following R functions/packages that have QP solvers do NOT work for this problem (non-exclusive list): quadprog, ipop, ROI, auglag, nlminb, optimx, trust, COBYLA. If anyone is interested in that R code, here it is, with one of the dumb solvers (if a good solver becomes available, you can just replace that line, and the code will work as well as the MATLAB implementation - and don't forget to leave a comment here if you find it): library(alabama) library(fBasics) # identity matrix eye<-function(n){ if(n==0){ return(matrix(0,0,0)) }else{ M<-matrix(0,n,n) M[1+0:(n-1)*(n+1)]<-1 return(M) } } # function inspired by matlab's sparse() sparse<-function(i,j,v,n=0,m=0,nz=0){ S<-matrix(nz,max(max(i),n),max(max(j),m)) S[cbind(matrix(i,ncol=1),matrix(j,ncol=1))]<-matrix(v,ncol=1) return(S) } mean_series<-function(ymeans,n,EndConditions=1,Method="L-BFGS-B"){ # mean_series: cubic spline resampling of series in x # (n times), maintaining the mean # # arguments: # ymeans - vector of means # n - # EndConditions - flag specifying natural or not-a-knot # end conditions on the spline. # EndConditions <-<- 0 --> natural # EndConditions <-<- 1 (default) --> not-a-knot # # y - interpolated series, y has the property that: # ymeans <-<- sum(reshape(y,n,length(x))) # # spl - cubic spline as a piecewise cubic Hermite function # ensure that ymeans is a column vector ymeans<-matrix(ymeans,ncol = 1) nmeans<-length(ymeans) # things will fail unless there are at least two # points in ymeans if (nmeans<2){ stop('I require length(ymeans)><-2 or dire things will happen') } # nmeans+1 implicit knots nk<-nmeans+1 # implicit positions of knots knots<-cbind(0:nmeans)-0.5 # knot spacing delta<-diff(knots) # implicit coordinates of the points to be predicted # (interpolations at these points) x<-seq(knots[1],knots[length(knots)],length.out =nmeans*n+1) x<-cbind(x[-length(x)]) ny<-n*nmeans # define the spline as a piecewise cubic Hermite at # the knots. This gives us nk function values and # nk derivatives. # Force the spline to be C2. compute the matrix # relating function values to first derivatives, # comes about from second derivative continuity at # the knots. these will be equality constraints on # the unknown spline coefficients. feq<-matrix(0,nk-2,nk) deq<-matrix(0,nk-2,nk) rhseq<-matrix(0,nk-2,1) for(i in 2:(nk-1)){ j<-i-1 feq[j,i+(-1:1)]<--cbind(-6/delta[j]^2 ,(6/delta[j]^2)-(6/delta[i]^2) , 6/delta[i]^2) deq[j,i+(-1:1)]<- cbind(2/delta[j] , 4/delta[j]+4/delta[i] , 2/delta[i]) } # next, "evaluate" the points through the implicitly # defined spline. We do not yet have the coefficients # defining the spline, but we will eventually. # k specifies which knot interval the points fall in. k<-matrix(1:nmeans,n*nmeans,1) t<-(x-knots[k])/delta[k] t2<-t*t t3<-t2*t s2<-(1-t)*(1-t) s3<-s2*(1-t) # build the matrix sparsely for efficiency, then convert # the system to full since its really not sparse enough # to save much. fmat<-cbind(3*s2-2*s3 , 3*t2-2*t3) dmat<-cbind(-delta[k]*(s3-s2) , delta[k]*(t3-t2)) imat<-cbind(1:ny) imat<-cbind(imat,imat) jmat<-cbind(k,k+1) fmat0<-sparse(imat,jmat,fmat,ny,nk) dmat0<-sparse(imat,jmat,dmat,ny,nk) # now, compute implicit means of every n points. # do it via a matrix multiply. M<-kron(eye(nmeans),matrix(1,1,n)/n) fmat<-M%*%fmat0 dmat<-M%*%dmat0 # Since these means are to be forced, specify them # as equality constraints, appending them to the set # of equalities. feq<-rbind(feq,fmat) deq<-rbind(deq,dmat) rhseq<-rbind(rhseq,ymeans) # End condotions are either: 'natural', 'not-a-knot' # test for default on EndConditions if(EndConditions==0){ # natural boundary conditions, i.e., zero second # derivative at ends fe<-matrix(0,2,nk) de<-matrix(0,2,nk) # at the bottom knot: fe[1,1:2]<-c(-1, 1)*6/(delta[1]^2) de[1,1:2]<-c(-2, -1)*2/delta[1] # at the top knot: fe[2,nk+(-1:0)]<-c(1,-1)*6/(delta[nk-1]^2) de[2,nk+(-1:0)]<-c(1,2)*2/delta[nk-1] # append to equality constraints matrix feq<-rbind(feq,fe) deq<-rbind(deq,de) rhseq<-rbind(rhseq,matrix(0,2,1)) } if(EndConditions==1){ # not-a-knot end conditions, 3rd derivative continuity at # 2nd knot and next to last knots fe<-matrix(0,1+(nk>3),nk) de<-fe # at the second knot: fe[1,1:3]<-c(1,-1,0)*12/(delta[1]^3)-c(0,1,-1)*12/(delta[2]^3) de[1,1:3]<-c(1,1,0)*6/(delta[1]^2)-c(0,1,1)*6/(delta[2]^2) # at the top knot: if(nk>3){ fe[2,nk+(-2:0)]<-c(1,-1,0)*12/(delta[nk-2]^3)-c(0,1,-1)*12/(delta[nk-1]^3) de[2,nk+(-2:0)]<-c(1,1,0)*6/(delta[nk-2]^2)-c(0,1,1)*6/(delta[nk-1]^2) } # append to equality constraints matrix feq<-rbind(feq,fe) deq<-rbind(deq,de) rhseq<-rbind(rhseq,matrix(0,1+(nk>3),1)) } # the second derivative regularizer is a quadratic form of the form # s'*regmat*s, # where s is the vector of (unknown) second derivatives at the knots. regmat<-matrix(0,nk,nk) regmat[1,1:2]<-cbind(delta[1]/3 , delta[1]/6) regmat[nk,nk+(-1:0)]<-cbind(delta[nk-1]/6 , delta[nk-1]/3) for(i in 2:(nk-1)){ regmat[i,i+(-1:1)]<-c(delta[i-1]/6 , (delta[i-1]+delta[i])/3 , delta[i]/6) } # next, write the second derivatives as a function of the # function values and first derivatives: s <- [sf,sd]*[fd] sf<-matrix(0,nk,nk) sd<-matrix(0,nk,nk) for(i in 1:(nk-1)){ sf[i,i+(0:1)]<-c(-1,1)*(6/(delta[i]^2)) sd[i,i+(0:1)]<-c(-4,-2)/delta[i] } sf[nk,nk+(-1:0)]<-c(1,-1)*(6/(delta[nk-1]^2)) sd[nk,nk+(-1:0)]<-c(2,4)/delta[nk-1] regmat<-t(cbind(sf,sd))%*%regmat%*%cbind(sf,sd) # ensure numerical symmetry of the hessian regmat<-regmat+t(regmat) # now, solve this whole mess of a linear system # using a quadratic programming package. # assume quadprog from the optimization toolbox 2.0 H<-regmat f<-matrix(0,2*nk,1) Aeq<-cbind(feq,deq) beq<-rhseq # THIS QP SOLVER DOESN'T FREAKIN WORK AT ALL. coef<-cbind(auglag(cbind(rep(0,dim(H)[1])), fn=function(x){t(x)%*%H%*%x}, hin=function(x){Aeq%*%x-beq}, hin.jac=function(x){Aeq}, heq=function(x){1}, heq.jac=function(x){rbind(rep(0,dim(Aeq)[2]))}, control.outer = list(method=Method,trace=FALSE,itmax=100))$par) # break the coeficients up into a spline. # first column is the knots, the second column # is function values at the knots, the third column # is first derivatives at the knots. spl<-cbind(knots,matrix(coef,nk,2)) # return predictions at the original points y<-fmat0%*%spl[,2]+dmat0%*%spl[,3] return(y) } Let's test this stupid QP solver to see how absolutely useless it is: ymeans<-sin(1:22) n<-3 yhat<-mean_series(ymeans,n) lineplot(cbind(kron(ymeans,cbind(rep(1,n))),yhat),1:66,legend = FALSE)
solid line from a local average series What you want is a mean preserving interpolation. John D'Errico has the exact solution you're looking for, written in MATLAB however. https://www.mathworks.com/matlabcentral/newsreader/view_thread/313
48,472
solid line from a local average series
I think there are a number of methods that suit what you're looking for - some options are: 1. kernel smoothing 2. spline smoothing 3. moving average There are many more, but I think those three are good candidates. Here is a very nice visual explanation of several smoothing techniques. The problem is that technically, between $t_a$ and $t_b$, the temperature could take on any value on your measurement scale. Fortunately, since we can probably assume at least moderate time-dependence, the temp at $t_b$ should at be at least partially related to the temp at $t_a$. Choosing a good smoothing method and parameters depends on how strong you think the time dependent effects are, how smooth you want your smoothing function to be, how variable you think think the temp is during the unobserved period. Hope that helps!
solid line from a local average series
I think there are a number of methods that suit what you're looking for - some options are: 1. kernel smoothing 2. spline smoothing 3. moving average There are many more, but I think those three ar
solid line from a local average series I think there are a number of methods that suit what you're looking for - some options are: 1. kernel smoothing 2. spline smoothing 3. moving average There are many more, but I think those three are good candidates. Here is a very nice visual explanation of several smoothing techniques. The problem is that technically, between $t_a$ and $t_b$, the temperature could take on any value on your measurement scale. Fortunately, since we can probably assume at least moderate time-dependence, the temp at $t_b$ should at be at least partially related to the temp at $t_a$. Choosing a good smoothing method and parameters depends on how strong you think the time dependent effects are, how smooth you want your smoothing function to be, how variable you think think the temp is during the unobserved period. Hope that helps!
solid line from a local average series I think there are a number of methods that suit what you're looking for - some options are: 1. kernel smoothing 2. spline smoothing 3. moving average There are many more, but I think those three ar
48,473
Time series forecasting using Gaussian Process regression
answering them in reverse order.. 2) let K be the sum (or multiple but I think in your case sum) of the two kernel functions. That is one with each period. 1) you want to minimise the negative log-likelihood as explained in sections 5.4.1 of GPML (link here).
Time series forecasting using Gaussian Process regression
answering them in reverse order.. 2) let K be the sum (or multiple but I think in your case sum) of the two kernel functions. That is one with each period. 1) you want to minimise the negative log-lik
Time series forecasting using Gaussian Process regression answering them in reverse order.. 2) let K be the sum (or multiple but I think in your case sum) of the two kernel functions. That is one with each period. 1) you want to minimise the negative log-likelihood as explained in sections 5.4.1 of GPML (link here).
Time series forecasting using Gaussian Process regression answering them in reverse order.. 2) let K be the sum (or multiple but I think in your case sum) of the two kernel functions. That is one with each period. 1) you want to minimise the negative log-lik
48,474
What is the moment generating function of the generalized (multivariate) chi-square distribution?
I will build on my answer from here: https://math.stackexchange.com/questions/442472/sum-of-squares-of-dependent-gaussian-random-variables/442916#442916 and use notation from there. First I will look at the case without the linear and constant term, then we will see how to take them into account. So let $Q(X)=X^T A X$ be a quadratic form in the multivariate normal vector $X$, with expectation $\mu$ and covariance matrix $\Sigma$. We found that $$ Q(X)=\sum_{j=1}^n \lambda_j (U_j+b_j)^2 $$ where $Z=Y-\Sigma^{-1/2}\mu$, we use the spectral theorem to write $\Sigma^{1/2}A \Sigma^{1/2} = P^T \Lambda P$, $P$ orthogonal and $\Lambda$ diagonal with positive diagonal elements $\lambda_j$, and $U=PZ$ so that $U$ has independent standard normal components $U_j$. The we can define $b=P \Sigma^{-1/2} \mu$. To summarize so far, $Q(X)$ is written above as the sum of independent scaled noncentral chisquare random variables. Using https://en.wikipedia.org/wiki/Noncentral_chi-squared_distribution we can see that $(U_j+b_j)^2$ is noncentral chisquare with one degree of freedom and noncentrality parameter $b_j^2$. Then its moment generating function (mgf) is given by $$ M_j(t) = \frac{\exp\left(\frac{t b_j^2}{1-2t} \right)}{(1-2t)^{1/2}} $$ Then we find the mgf of $\lambda_j (U_j+b_j)^2$ as $M_j(\lambda_j t)$, and the mgf $M(t)$ of the sum $Q(X)$ the product of this: $$ M(t) = \frac{\exp\left(\sum_{j=1}^n \frac{b_j^2 \lambda_j t}{1-2t\lambda_j} \right)}{\exp(\frac12 \sum_1^n \log(1-2t\lambda_j))} $$ which is the mgf for the quadratic form in the case without linear and constant term. To use this result for the general case, write as in the question, $$ Y=X^T B X + f^t X + g $$ (where we have changed name for the constants to avoid name clashes). To use the above result we must transform $X$ to eliminate the linear term. To obtain this, replace $X$ with $X-h$ where $$ h = -\frac12 B^{-1}f $$ Then we obtain $$ Y = (X-h)^T B (X-h) +g - h^T B h $$ And then we are ready to apply the mgf found in the first part: $$ \DeclareMathOperator{\E}{\mathbb{E}} \E e^{tY} = e^{g-h^T B h} M(t) $$ where $M(t)$ is the mgf from the first part.
What is the moment generating function of the generalized (multivariate) chi-square distribution?
I will build on my answer from here: https://math.stackexchange.com/questions/442472/sum-of-squares-of-dependent-gaussian-random-variables/442916#442916 and use notation from there. First I will l
What is the moment generating function of the generalized (multivariate) chi-square distribution? I will build on my answer from here: https://math.stackexchange.com/questions/442472/sum-of-squares-of-dependent-gaussian-random-variables/442916#442916 and use notation from there. First I will look at the case without the linear and constant term, then we will see how to take them into account. So let $Q(X)=X^T A X$ be a quadratic form in the multivariate normal vector $X$, with expectation $\mu$ and covariance matrix $\Sigma$. We found that $$ Q(X)=\sum_{j=1}^n \lambda_j (U_j+b_j)^2 $$ where $Z=Y-\Sigma^{-1/2}\mu$, we use the spectral theorem to write $\Sigma^{1/2}A \Sigma^{1/2} = P^T \Lambda P$, $P$ orthogonal and $\Lambda$ diagonal with positive diagonal elements $\lambda_j$, and $U=PZ$ so that $U$ has independent standard normal components $U_j$. The we can define $b=P \Sigma^{-1/2} \mu$. To summarize so far, $Q(X)$ is written above as the sum of independent scaled noncentral chisquare random variables. Using https://en.wikipedia.org/wiki/Noncentral_chi-squared_distribution we can see that $(U_j+b_j)^2$ is noncentral chisquare with one degree of freedom and noncentrality parameter $b_j^2$. Then its moment generating function (mgf) is given by $$ M_j(t) = \frac{\exp\left(\frac{t b_j^2}{1-2t} \right)}{(1-2t)^{1/2}} $$ Then we find the mgf of $\lambda_j (U_j+b_j)^2$ as $M_j(\lambda_j t)$, and the mgf $M(t)$ of the sum $Q(X)$ the product of this: $$ M(t) = \frac{\exp\left(\sum_{j=1}^n \frac{b_j^2 \lambda_j t}{1-2t\lambda_j} \right)}{\exp(\frac12 \sum_1^n \log(1-2t\lambda_j))} $$ which is the mgf for the quadratic form in the case without linear and constant term. To use this result for the general case, write as in the question, $$ Y=X^T B X + f^t X + g $$ (where we have changed name for the constants to avoid name clashes). To use the above result we must transform $X$ to eliminate the linear term. To obtain this, replace $X$ with $X-h$ where $$ h = -\frac12 B^{-1}f $$ Then we obtain $$ Y = (X-h)^T B (X-h) +g - h^T B h $$ And then we are ready to apply the mgf found in the first part: $$ \DeclareMathOperator{\E}{\mathbb{E}} \E e^{tY} = e^{g-h^T B h} M(t) $$ where $M(t)$ is the mgf from the first part.
What is the moment generating function of the generalized (multivariate) chi-square distribution? I will build on my answer from here: https://math.stackexchange.com/questions/442472/sum-of-squares-of-dependent-gaussian-random-variables/442916#442916 and use notation from there. First I will l
48,475
Different p-values for Chi squared and Fisher's Exact R
You should not run two different tests. Choose your test first, before you run any tests and preferably before you examine your data values (though it would be permissible to consider the marginal totals). By looking at both p-values before you decide which to use, you are (quite rightly) open to charges of p-hacking. Since you're prepared to condition on the margins (you did an exact test after all), you could consider using simulated p-values to deal with the low expected in the (1,1) cell... I just did a million such simulations in R, it only takes a couple of seconds (the chisq.test default of 2000 is a bit small) (However, you'll still have looked at the p-values... so that issue won't go away)
Different p-values for Chi squared and Fisher's Exact R
You should not run two different tests. Choose your test first, before you run any tests and preferably before you examine your data values (though it would be permissible to consider the marginal tot
Different p-values for Chi squared and Fisher's Exact R You should not run two different tests. Choose your test first, before you run any tests and preferably before you examine your data values (though it would be permissible to consider the marginal totals). By looking at both p-values before you decide which to use, you are (quite rightly) open to charges of p-hacking. Since you're prepared to condition on the margins (you did an exact test after all), you could consider using simulated p-values to deal with the low expected in the (1,1) cell... I just did a million such simulations in R, it only takes a couple of seconds (the chisq.test default of 2000 is a bit small) (However, you'll still have looked at the p-values... so that issue won't go away)
Different p-values for Chi squared and Fisher's Exact R You should not run two different tests. Choose your test first, before you run any tests and preferably before you examine your data values (though it would be permissible to consider the marginal tot
48,476
Different p-values for Chi squared and Fisher's Exact R
This is not surprising since the tests have different statistical bases. The Fisher Exact test is a randomization test computed assuming both the row and column marginals are fixed (which they very rarely are) and is very conservative when they are not. The Chi Squared test is an approximation but works well in practice, even with sample sizes much smaller than yours. The warning message doesn't make sense since it is a given that an approximation is not exact so it's unclear what is meant by "incorrect." You have expected frequencies less than 5 that some might say is a problem, but simulation studies indicate it is not in most cases. In short, your marginals are not fixed so I recommend you go with the Chi Squared Test.
Different p-values for Chi squared and Fisher's Exact R
This is not surprising since the tests have different statistical bases. The Fisher Exact test is a randomization test computed assuming both the row and column marginals are fixed (which they very ra
Different p-values for Chi squared and Fisher's Exact R This is not surprising since the tests have different statistical bases. The Fisher Exact test is a randomization test computed assuming both the row and column marginals are fixed (which they very rarely are) and is very conservative when they are not. The Chi Squared test is an approximation but works well in practice, even with sample sizes much smaller than yours. The warning message doesn't make sense since it is a given that an approximation is not exact so it's unclear what is meant by "incorrect." You have expected frequencies less than 5 that some might say is a problem, but simulation studies indicate it is not in most cases. In short, your marginals are not fixed so I recommend you go with the Chi Squared Test.
Different p-values for Chi squared and Fisher's Exact R This is not surprising since the tests have different statistical bases. The Fisher Exact test is a randomization test computed assuming both the row and column marginals are fixed (which they very ra
48,477
How should I be learning deep learning?
Deep learning is quite of broad topic. I can not say that you can not learn everything ( human capabilities are unlimited ) but working in every field is little difficult. As far as I can see you have grasped all the basic concepts so its time to choose a field where you want to apply your knowledge or do more research. If you want to work choose a field where you want to apply your knowledge and learn with it. Natural Language Processing , Image processing , Object recognition, Audio signal Processing and many more fields are there. Choose a field and build something useful. If you want to read more and do research, new experiments/research are being done daily. You can improve them or can develop your new concept. GAN ( Generative Adversarial Networks ), using Reinforcement learning with Deep learning, deep dream (Inceptionism: Going Deeper into Neural Networks ), Generative context aware encoder decoder and many more new things are there.
How should I be learning deep learning?
Deep learning is quite of broad topic. I can not say that you can not learn everything ( human capabilities are unlimited ) but working in every field is little difficult. As far as I can see you have
How should I be learning deep learning? Deep learning is quite of broad topic. I can not say that you can not learn everything ( human capabilities are unlimited ) but working in every field is little difficult. As far as I can see you have grasped all the basic concepts so its time to choose a field where you want to apply your knowledge or do more research. If you want to work choose a field where you want to apply your knowledge and learn with it. Natural Language Processing , Image processing , Object recognition, Audio signal Processing and many more fields are there. Choose a field and build something useful. If you want to read more and do research, new experiments/research are being done daily. You can improve them or can develop your new concept. GAN ( Generative Adversarial Networks ), using Reinforcement learning with Deep learning, deep dream (Inceptionism: Going Deeper into Neural Networks ), Generative context aware encoder decoder and many more new things are there.
How should I be learning deep learning? Deep learning is quite of broad topic. I can not say that you can not learn everything ( human capabilities are unlimited ) but working in every field is little difficult. As far as I can see you have
48,478
How should I be learning deep learning?
A good place to start is this book, you can download it online. Quick recap and starting points: If you're looking for image processing, CNN are a great choice and it seems you already played with it. For speech recognition - you can take a look at RNN (recurrent neural networks). Basically you can use them for images and videos too. And (sic!) you can use CNN to process audio (especially if it's preprocessed with FFT to get a 2D spectrum) NLP utilizes RNN as well. In order to extract features, you might take a look at Word2Vec. Additionally, encoder-decoder architecture is being used for machine translation. (Active research, not for production) for statistical inference and unsupervised learning (anomaly detection etc.) - you might take a look at auto-encoders and RBMs. Autoencoders are particularly used as an alternative for Factor Analysis: Factor Analysis vs Autoencoders Deep learning helps with reinforcement learning too: https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf Recommender Systems use deep-learning as well. TensorFlow models (they are usually state-of-the-art): https://github.com/tensorflow/models Small collection of Java-examples to complement those from TensorFlow: https://github.com/deeplearning4j/dl4j-examples
How should I be learning deep learning?
A good place to start is this book, you can download it online. Quick recap and starting points: If you're looking for image processing, CNN are a great choice and it seems you already played with it
How should I be learning deep learning? A good place to start is this book, you can download it online. Quick recap and starting points: If you're looking for image processing, CNN are a great choice and it seems you already played with it. For speech recognition - you can take a look at RNN (recurrent neural networks). Basically you can use them for images and videos too. And (sic!) you can use CNN to process audio (especially if it's preprocessed with FFT to get a 2D spectrum) NLP utilizes RNN as well. In order to extract features, you might take a look at Word2Vec. Additionally, encoder-decoder architecture is being used for machine translation. (Active research, not for production) for statistical inference and unsupervised learning (anomaly detection etc.) - you might take a look at auto-encoders and RBMs. Autoencoders are particularly used as an alternative for Factor Analysis: Factor Analysis vs Autoencoders Deep learning helps with reinforcement learning too: https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf Recommender Systems use deep-learning as well. TensorFlow models (they are usually state-of-the-art): https://github.com/tensorflow/models Small collection of Java-examples to complement those from TensorFlow: https://github.com/deeplearning4j/dl4j-examples
How should I be learning deep learning? A good place to start is this book, you can download it online. Quick recap and starting points: If you're looking for image processing, CNN are a great choice and it seems you already played with it
48,479
Why do we interpret neural networks as graphical models?
As a compilation of my comments on the question: The definition of a graphical model is: "a probabilistic model for which a graph expresses the conditional dependence structure between random variables." As we can draw a dependency graph to represent a NN, it falls into this category of "graphical models". About the question, why do we interpret them as graphical models? Well, we can take the question another way around for illustration purpose: "Why do we interpret a Gaussian as a continuous function?". Because, the Gaussian function verifies all the conditions that define what we call "continuous functions" and that theorems, techniques have been developed solely relying upon this set of conditions. It gives us tools that can be used to go forward. Then the community of scientists have defined what "graphical models" are. Tools have been developed that apply to models that match this definition. NN is one of them, it is a graphical model. I don't think there's anything more than this. Then maybe your question is, why did we decide to create a global name for this set of models that we call today "graphical models"? I do not think it was a decision made by people in a voluntarily conscious way. More something that appeared naturally with time and research works. Scientists noticing similarities between several models and reporting them. Slowly, the concept of graphical model was born. I would be happy if other people could share their opinion on this :) I do not consider myself an expert but I think that NNs are graphical models by definition. I found this very interesting chapter called "Graphical models in a nutshell" that should be able to answer your concerns and more way better than I can do: https://ai.stanford.edu/~koller/Papers/Koller+al:SRL07.pdf
Why do we interpret neural networks as graphical models?
As a compilation of my comments on the question: The definition of a graphical model is: "a probabilistic model for which a graph expresses the conditional dependence structure between random variable
Why do we interpret neural networks as graphical models? As a compilation of my comments on the question: The definition of a graphical model is: "a probabilistic model for which a graph expresses the conditional dependence structure between random variables." As we can draw a dependency graph to represent a NN, it falls into this category of "graphical models". About the question, why do we interpret them as graphical models? Well, we can take the question another way around for illustration purpose: "Why do we interpret a Gaussian as a continuous function?". Because, the Gaussian function verifies all the conditions that define what we call "continuous functions" and that theorems, techniques have been developed solely relying upon this set of conditions. It gives us tools that can be used to go forward. Then the community of scientists have defined what "graphical models" are. Tools have been developed that apply to models that match this definition. NN is one of them, it is a graphical model. I don't think there's anything more than this. Then maybe your question is, why did we decide to create a global name for this set of models that we call today "graphical models"? I do not think it was a decision made by people in a voluntarily conscious way. More something that appeared naturally with time and research works. Scientists noticing similarities between several models and reporting them. Slowly, the concept of graphical model was born. I would be happy if other people could share their opinion on this :) I do not consider myself an expert but I think that NNs are graphical models by definition. I found this very interesting chapter called "Graphical models in a nutshell" that should be able to answer your concerns and more way better than I can do: https://ai.stanford.edu/~koller/Papers/Koller+al:SRL07.pdf
Why do we interpret neural networks as graphical models? As a compilation of my comments on the question: The definition of a graphical model is: "a probabilistic model for which a graph expresses the conditional dependence structure between random variable
48,480
Weighted Least squares, why not use $\frac{1}{e_i^2}$ as weights?
It would be too noisy to estimate weights as squared residuals. Consider this: you're estimating n weights using n observations. It's one observation per parameter. It's like estimating the variance of the population having a sample size one. So, instead you observe that the variance seems to increase linearly with X, then you regress on X. You end up estimating just two coefficients from n observations. You get much more reliable estimate of the weight this way. On the residuals looking the same after weighted least squares: that's not surprising given that the estimated weights are not that different.
Weighted Least squares, why not use $\frac{1}{e_i^2}$ as weights?
It would be too noisy to estimate weights as squared residuals. Consider this: you're estimating n weights using n observations. It's one observation per parameter. It's like estimating the variance o
Weighted Least squares, why not use $\frac{1}{e_i^2}$ as weights? It would be too noisy to estimate weights as squared residuals. Consider this: you're estimating n weights using n observations. It's one observation per parameter. It's like estimating the variance of the population having a sample size one. So, instead you observe that the variance seems to increase linearly with X, then you regress on X. You end up estimating just two coefficients from n observations. You get much more reliable estimate of the weight this way. On the residuals looking the same after weighted least squares: that's not surprising given that the estimated weights are not that different.
Weighted Least squares, why not use $\frac{1}{e_i^2}$ as weights? It would be too noisy to estimate weights as squared residuals. Consider this: you're estimating n weights using n observations. It's one observation per parameter. It's like estimating the variance o
48,481
Weighted Least squares, why not use $\frac{1}{e_i^2}$ as weights?
I suspect the issue here is that the weighting $w_i = 1/e_i^2$ would make the regression estimates insufficiently sensitive to the response variable, since it would almost be tantamount to treating each deviation as having unit magnitude. To see what I mean, suppose you let $e_i$ be the residuals from the first model fit, and suppose you then fit a new model using your specified weighting, and let $e_i^*$ be the residuals from this second model fit. (And more generally, I will put a star on all estimated quantities from the second model.) The coefficient vector in the second model fit is being estimated by minimising the objective: $$\text{WRSS}(\boldsymbol{\hat{\beta}^*}) \equiv (\boldsymbol{y} - \boldsymbol{x} \boldsymbol{\hat{\beta}^*})^{\boldsymbol{\text{T}}} \boldsymbol{\text{W}} (\boldsymbol{y} - \boldsymbol{x} \boldsymbol{\hat{\beta}^*}) = \sum_{i=1}^n \Bigg( \frac {y_i - \sum_{k=0}^m \hat{\beta}_k^* x_{i,k}}{e_i} \Bigg)^2 = \sum_{i=1}^n \Bigg( \frac{e_i^*}{e_i} \Bigg)^2 .$$ Evaluating near the previous parameter estimate we have $\boldsymbol{\hat{\beta}^*} \approx \boldsymbol{\hat{\beta}}$ which gives $e_i^* \approx e_i$ so that: $$\text{WRSS}(\boldsymbol{\beta}) \approx \sum_{i=1}^n \Bigg( \frac {e_i^*}{e_i} \Bigg) ^2 = \sum_{i=1}^n 1^2 =n.$$ So you can see that under this method, when you fit the second model, you are effectively treating each deviation from the regression line as having approximately unit magnitude, regardless of the actual response value in the data. That is, you are looking to minimise the weighted residuals, but these weighted residuals are (almost by definition) close to unit magnitude.
Weighted Least squares, why not use $\frac{1}{e_i^2}$ as weights?
I suspect the issue here is that the weighting $w_i = 1/e_i^2$ would make the regression estimates insufficiently sensitive to the response variable, since it would almost be tantamount to treating ea
Weighted Least squares, why not use $\frac{1}{e_i^2}$ as weights? I suspect the issue here is that the weighting $w_i = 1/e_i^2$ would make the regression estimates insufficiently sensitive to the response variable, since it would almost be tantamount to treating each deviation as having unit magnitude. To see what I mean, suppose you let $e_i$ be the residuals from the first model fit, and suppose you then fit a new model using your specified weighting, and let $e_i^*$ be the residuals from this second model fit. (And more generally, I will put a star on all estimated quantities from the second model.) The coefficient vector in the second model fit is being estimated by minimising the objective: $$\text{WRSS}(\boldsymbol{\hat{\beta}^*}) \equiv (\boldsymbol{y} - \boldsymbol{x} \boldsymbol{\hat{\beta}^*})^{\boldsymbol{\text{T}}} \boldsymbol{\text{W}} (\boldsymbol{y} - \boldsymbol{x} \boldsymbol{\hat{\beta}^*}) = \sum_{i=1}^n \Bigg( \frac {y_i - \sum_{k=0}^m \hat{\beta}_k^* x_{i,k}}{e_i} \Bigg)^2 = \sum_{i=1}^n \Bigg( \frac{e_i^*}{e_i} \Bigg)^2 .$$ Evaluating near the previous parameter estimate we have $\boldsymbol{\hat{\beta}^*} \approx \boldsymbol{\hat{\beta}}$ which gives $e_i^* \approx e_i$ so that: $$\text{WRSS}(\boldsymbol{\beta}) \approx \sum_{i=1}^n \Bigg( \frac {e_i^*}{e_i} \Bigg) ^2 = \sum_{i=1}^n 1^2 =n.$$ So you can see that under this method, when you fit the second model, you are effectively treating each deviation from the regression line as having approximately unit magnitude, regardless of the actual response value in the data. That is, you are looking to minimise the weighted residuals, but these weighted residuals are (almost by definition) close to unit magnitude.
Weighted Least squares, why not use $\frac{1}{e_i^2}$ as weights? I suspect the issue here is that the weighting $w_i = 1/e_i^2$ would make the regression estimates insufficiently sensitive to the response variable, since it would almost be tantamount to treating ea
48,482
What differentiates the wilcoxon test from t test regarding ordinal variables?
The short answer is that you can always use either test in place of the other--but typically they will produce different results. That demonstrates the issue is not one of applicability, but suitability. The rest of this answer discusses what "suitability" might amount to. S. S. Stevens' original (but often misunderstood) classification of measurements into four types--nominal, ordinal, interval, and ratio--was based on the groups of transformations admitted by each type. Student t-tests are invariant under affine transformations (rescaling and recentering), and therefore are appropriate for data whose meaning is not changed by affine transformations. Consequently the result of a t-test does not depend on the units of measurement used (nor it origin or "zero" value) to record the data, but it usually will change if the data are transformed in any nonlinear way. The Wilcoxon tests are invariant under arbitrary monotonic transformations (which is a far larger transformation group): such transformations merely need to respect the order of the data (larger remain larger, smaller remain smaller). Therefore the result of a Wilcoxon test does not depend on the numeric codes used to designate ordinal data (provided those codes respect the ordering, of course). The implications are important. First, both tests apply to any type of data that can be meaningfully represented by (real) numbers. You always have the choice of which test to use. That choice needs to depend on what the test aims to accomplish, on what it might cost you to make errors, and on the statistical characteristics of the data. Therefore, a flowchart like the one shown in the question cannot be correct or universally applicable. (I would suggest throwing it away.) Second, because t-test results will change when data are transformed in nonlinear ways, it is crucial to decide how best to record one's data for test purposes. For instance, with positive data (such as concentrations), there is no a priori reason to prefer using the original numbers or (say) their logarithms--but t-tests based on the original numbers and t-tests based on the logarithms will usually produce different results. Since ignorance will not make this phenomenon go away, we always need to consider what the appropriate method of recording our data ought to be. (How to find such a method is another question, with a large literature and sizable body of techniques.) Third, many nominal datasets do not contain the information needed to record the values numerically in a meaningful or useful way. For instance, a nominal variable with the possible values "good," "better," and "best" could be encoded as 0, 1, and 2, respectively, or possibly 0, 1, and 10. Which should it be? Since these two sets of numbers are not related in a linear way, the results of a test can depend on which numbers you choose. That should be a concern if you want to produce defensible, non-arbitrary, non-subjective results. Using a Wilcoxon test (or any other rank-based test) will produce the same results regardless of your coding system and therefore can be one key part of defending the result. Fourth, the t-test will likely be misleading in the presence of outlying data or skewed distributions: it is not resistant to unexpected data and is only a little bit robust to departures from distributional assumptions. Although the Wilcoxon test makes distributional assumptions, they tend to be less restrictive and the test is more resistant and more robust. Fifth, the t-test will be more powerful than the Wilcoxon test (or any other rank-based test) provided its underlying statistical assumptions approximately hold. Thus, it can be superior in the sense of requiring less data (and therefore less cost and time) to detect an important difference provided you are confident in the assumptions you make. These implications show that the choice of a statistical test cannot possibly be reduced to a simple flow chart. At the very least, the choice involves the purpose of the test, the costs of potential errors, the assumptions you can make about the data-generation process, whether the data appear consistent with those assumptions, and on the flexibility you have to re-express the data in nonlinear ways.
What differentiates the wilcoxon test from t test regarding ordinal variables?
The short answer is that you can always use either test in place of the other--but typically they will produce different results. That demonstrates the issue is not one of applicability, but suitabil
What differentiates the wilcoxon test from t test regarding ordinal variables? The short answer is that you can always use either test in place of the other--but typically they will produce different results. That demonstrates the issue is not one of applicability, but suitability. The rest of this answer discusses what "suitability" might amount to. S. S. Stevens' original (but often misunderstood) classification of measurements into four types--nominal, ordinal, interval, and ratio--was based on the groups of transformations admitted by each type. Student t-tests are invariant under affine transformations (rescaling and recentering), and therefore are appropriate for data whose meaning is not changed by affine transformations. Consequently the result of a t-test does not depend on the units of measurement used (nor it origin or "zero" value) to record the data, but it usually will change if the data are transformed in any nonlinear way. The Wilcoxon tests are invariant under arbitrary monotonic transformations (which is a far larger transformation group): such transformations merely need to respect the order of the data (larger remain larger, smaller remain smaller). Therefore the result of a Wilcoxon test does not depend on the numeric codes used to designate ordinal data (provided those codes respect the ordering, of course). The implications are important. First, both tests apply to any type of data that can be meaningfully represented by (real) numbers. You always have the choice of which test to use. That choice needs to depend on what the test aims to accomplish, on what it might cost you to make errors, and on the statistical characteristics of the data. Therefore, a flowchart like the one shown in the question cannot be correct or universally applicable. (I would suggest throwing it away.) Second, because t-test results will change when data are transformed in nonlinear ways, it is crucial to decide how best to record one's data for test purposes. For instance, with positive data (such as concentrations), there is no a priori reason to prefer using the original numbers or (say) their logarithms--but t-tests based on the original numbers and t-tests based on the logarithms will usually produce different results. Since ignorance will not make this phenomenon go away, we always need to consider what the appropriate method of recording our data ought to be. (How to find such a method is another question, with a large literature and sizable body of techniques.) Third, many nominal datasets do not contain the information needed to record the values numerically in a meaningful or useful way. For instance, a nominal variable with the possible values "good," "better," and "best" could be encoded as 0, 1, and 2, respectively, or possibly 0, 1, and 10. Which should it be? Since these two sets of numbers are not related in a linear way, the results of a test can depend on which numbers you choose. That should be a concern if you want to produce defensible, non-arbitrary, non-subjective results. Using a Wilcoxon test (or any other rank-based test) will produce the same results regardless of your coding system and therefore can be one key part of defending the result. Fourth, the t-test will likely be misleading in the presence of outlying data or skewed distributions: it is not resistant to unexpected data and is only a little bit robust to departures from distributional assumptions. Although the Wilcoxon test makes distributional assumptions, they tend to be less restrictive and the test is more resistant and more robust. Fifth, the t-test will be more powerful than the Wilcoxon test (or any other rank-based test) provided its underlying statistical assumptions approximately hold. Thus, it can be superior in the sense of requiring less data (and therefore less cost and time) to detect an important difference provided you are confident in the assumptions you make. These implications show that the choice of a statistical test cannot possibly be reduced to a simple flow chart. At the very least, the choice involves the purpose of the test, the costs of potential errors, the assumptions you can make about the data-generation process, whether the data appear consistent with those assumptions, and on the flexibility you have to re-express the data in nonlinear ways.
What differentiates the wilcoxon test from t test regarding ordinal variables? The short answer is that you can always use either test in place of the other--but typically they will produce different results. That demonstrates the issue is not one of applicability, but suitabil
48,483
The effect of temperature in temperature sampling
Note that we start with a set of probabilities which sum to 1. We define a function ($f(p)$ where the $i$th probability component $f_\tau(p)_i=\frac{p_i^{1/\tau}}{\sum_j p_j^{1/\tau}}$) in order to modify those probabilities as a function of temperature (for which the original probabilities have temperature $\tau=1$). If we increase $\tau$ from $1$, the transformed probabilities would become more nearly equal and if we decrease $\tau$ toward 0, the transformed probabilities become "shifted" toward the larger ones, away from the smaller ones. For $\tau=1$: $\sum p_j=1$ so when $\tau=1$ you have $f(p)_i = p_i$ which is indeed the identity. For $\tau\to 0$ note that if you have two values of $p$, say $p_2 = k p_1$ (where $k<1$) then $(p_2/p_1)^m = k^m$. Now let $m \to \infty$. We see that the ratio of a smaller $p_i^m$ to a larger one will go to $0$. Consequently, if you have a set of $p$'s, then as $m$ increases $p_i^m/p_\text{largest}^m$ will all vanish, apart from the $p$ that is the largest (which is $1$). Now if you replace $p_\text{largest}^m$ on the denominator with the sum of the $p_j^m$ you just make the denominator slightly larger (you're just adding terms that all go to $0$). As a result, the scaled $f(p)_i=\frac{p_i^m}{\sum_j p_j^m}$'s will go to $0$ on everything but the largest, which will go to $1$. So if you select among the $i$'s using those set of $f$ values as probabilities, as $m\to\infty$, you'll select the largest. Now let $m=1/\tau$ and let $\tau\to 0$ and you get $m\to\infty$ and it corresponds to selecting the $\text{argmax}$. It's easy to see numerically. Here are 10 $p_i$ values -- they're generated as uniform random values sorted into order and normalized to sum to 1 (shown in black below). Note that the second and third largest values are quite close to the largest (the second largest is really close to the largest in value). Then we increase the power in $f$ progressively. The smaller terms rapidly decrease to a zero-share, while the largest term increases to 1. The ones close to the largest in size initially increase their share (they have $k$ close to $1$ in the above discussion, so their share initially stays close to the largest $p$, but the increasing power soon blows the largest one up much bigger than all the other terms) On this particular example, by the time we get to $m=300$ (i.e. $1/\tau=300$), the probability of selecting the largest term is very close to $1$. As $\tau$ goes closer to $0$, $m=1/\tau$ increases without limit, leaving only the argmax with any chance of being selected.
The effect of temperature in temperature sampling
Note that we start with a set of probabilities which sum to 1. We define a function ($f(p)$ where the $i$th probability component $f_\tau(p)_i=\frac{p_i^{1/\tau}}{\sum_j p_j^{1/\tau}}$) in order to mo
The effect of temperature in temperature sampling Note that we start with a set of probabilities which sum to 1. We define a function ($f(p)$ where the $i$th probability component $f_\tau(p)_i=\frac{p_i^{1/\tau}}{\sum_j p_j^{1/\tau}}$) in order to modify those probabilities as a function of temperature (for which the original probabilities have temperature $\tau=1$). If we increase $\tau$ from $1$, the transformed probabilities would become more nearly equal and if we decrease $\tau$ toward 0, the transformed probabilities become "shifted" toward the larger ones, away from the smaller ones. For $\tau=1$: $\sum p_j=1$ so when $\tau=1$ you have $f(p)_i = p_i$ which is indeed the identity. For $\tau\to 0$ note that if you have two values of $p$, say $p_2 = k p_1$ (where $k<1$) then $(p_2/p_1)^m = k^m$. Now let $m \to \infty$. We see that the ratio of a smaller $p_i^m$ to a larger one will go to $0$. Consequently, if you have a set of $p$'s, then as $m$ increases $p_i^m/p_\text{largest}^m$ will all vanish, apart from the $p$ that is the largest (which is $1$). Now if you replace $p_\text{largest}^m$ on the denominator with the sum of the $p_j^m$ you just make the denominator slightly larger (you're just adding terms that all go to $0$). As a result, the scaled $f(p)_i=\frac{p_i^m}{\sum_j p_j^m}$'s will go to $0$ on everything but the largest, which will go to $1$. So if you select among the $i$'s using those set of $f$ values as probabilities, as $m\to\infty$, you'll select the largest. Now let $m=1/\tau$ and let $\tau\to 0$ and you get $m\to\infty$ and it corresponds to selecting the $\text{argmax}$. It's easy to see numerically. Here are 10 $p_i$ values -- they're generated as uniform random values sorted into order and normalized to sum to 1 (shown in black below). Note that the second and third largest values are quite close to the largest (the second largest is really close to the largest in value). Then we increase the power in $f$ progressively. The smaller terms rapidly decrease to a zero-share, while the largest term increases to 1. The ones close to the largest in size initially increase their share (they have $k$ close to $1$ in the above discussion, so their share initially stays close to the largest $p$, but the increasing power soon blows the largest one up much bigger than all the other terms) On this particular example, by the time we get to $m=300$ (i.e. $1/\tau=300$), the probability of selecting the largest term is very close to $1$. As $\tau$ goes closer to $0$, $m=1/\tau$ increases without limit, leaving only the argmax with any chance of being selected.
The effect of temperature in temperature sampling Note that we start with a set of probabilities which sum to 1. We define a function ($f(p)$ where the $i$th probability component $f_\tau(p)_i=\frac{p_i^{1/\tau}}{\sum_j p_j^{1/\tau}}$) in order to mo
48,484
Understanding oscillating behaviour when using Q-learning on cart-pole problem
I don't believe your features can work. Disregarding your encoding of the action, you are simply using a linear function of the state to learn the value. The state given by OpenAI gym are positions and velocity. The ideal value function (V) would be symmetric around 0 for theta which a linear function cannot represent. Tile coding or RBF features would work for Cartpole.
Understanding oscillating behaviour when using Q-learning on cart-pole problem
I don't believe your features can work. Disregarding your encoding of the action, you are simply using a linear function of the state to learn the value. The state given by OpenAI gym are positions an
Understanding oscillating behaviour when using Q-learning on cart-pole problem I don't believe your features can work. Disregarding your encoding of the action, you are simply using a linear function of the state to learn the value. The state given by OpenAI gym are positions and velocity. The ideal value function (V) would be symmetric around 0 for theta which a linear function cannot represent. Tile coding or RBF features would work for Cartpole.
Understanding oscillating behaviour when using Q-learning on cart-pole problem I don't believe your features can work. Disregarding your encoding of the action, you are simply using a linear function of the state to learn the value. The state given by OpenAI gym are positions an
48,485
Understanding oscillating behaviour when using Q-learning on cart-pole problem
I want to clarify that in cartpole (and in gym's cartpole in particular), it is definitely possible to succeed with a linear Q function approximator. For example, taking s = [cart_pos, cart_vel, pole_pos, pole_vel] as in gym, try: Q(s,0) = -s[3] - 3*s[2] Q(s,1) = s[3] + 3*s[2] That will balance the pole for the required 200 time steps. To be clear, this isn't learning anything, but I regularly hear people say that cartpole can't be run with a linear Q function, so I wanted to point out this solution.
Understanding oscillating behaviour when using Q-learning on cart-pole problem
I want to clarify that in cartpole (and in gym's cartpole in particular), it is definitely possible to succeed with a linear Q function approximator. For example, taking s = [cart_pos, cart_vel, pole
Understanding oscillating behaviour when using Q-learning on cart-pole problem I want to clarify that in cartpole (and in gym's cartpole in particular), it is definitely possible to succeed with a linear Q function approximator. For example, taking s = [cart_pos, cart_vel, pole_pos, pole_vel] as in gym, try: Q(s,0) = -s[3] - 3*s[2] Q(s,1) = s[3] + 3*s[2] That will balance the pole for the required 200 time steps. To be clear, this isn't learning anything, but I regularly hear people say that cartpole can't be run with a linear Q function, so I wanted to point out this solution.
Understanding oscillating behaviour when using Q-learning on cart-pole problem I want to clarify that in cartpole (and in gym's cartpole in particular), it is definitely possible to succeed with a linear Q function approximator. For example, taking s = [cart_pos, cart_vel, pole
48,486
How do lotteries ensure that the drawings are sufficiently random, and what are some approaches to find possible vulnerabilities?
For the German lottery, it is said that the lottery balls with one numeral are labeled with 15 levels of paint; while balls with two numerals are labeled with 12 levels in order to make sure the balls have nearly equal weight. Also in contrast to the early years, the numbers are not drawn by hand anymore in most lotteries. The randomness has been examined for example by Harry Joe in "Tests of uniformity for sets of lotto numbers", Statistics & Probability Letters 16, 1993, 181--188 and by H. F. Coronel-Brizio et al. in "Statistical auditing and randomness test of lotto k / N-type games", Physica A 387 (2008) 6385–6390. They did find deviations between theoretical and observed frequencies in some lotteries. I am afraid that their results would not stand a power analysis. They did not develop strategies to exploit that.
How do lotteries ensure that the drawings are sufficiently random, and what are some approaches to f
For the German lottery, it is said that the lottery balls with one numeral are labeled with 15 levels of paint; while balls with two numerals are labeled with 12 levels in order to make sure the balls
How do lotteries ensure that the drawings are sufficiently random, and what are some approaches to find possible vulnerabilities? For the German lottery, it is said that the lottery balls with one numeral are labeled with 15 levels of paint; while balls with two numerals are labeled with 12 levels in order to make sure the balls have nearly equal weight. Also in contrast to the early years, the numbers are not drawn by hand anymore in most lotteries. The randomness has been examined for example by Harry Joe in "Tests of uniformity for sets of lotto numbers", Statistics & Probability Letters 16, 1993, 181--188 and by H. F. Coronel-Brizio et al. in "Statistical auditing and randomness test of lotto k / N-type games", Physica A 387 (2008) 6385–6390. They did find deviations between theoretical and observed frequencies in some lotteries. I am afraid that their results would not stand a power analysis. They did not develop strategies to exploit that.
How do lotteries ensure that the drawings are sufficiently random, and what are some approaches to f For the German lottery, it is said that the lottery balls with one numeral are labeled with 15 levels of paint; while balls with two numerals are labeled with 12 levels in order to make sure the balls
48,487
How do lotteries ensure that the drawings are sufficiently random, and what are some approaches to find possible vulnerabilities?
It really depends on the meaning you are giving to the word "random". The wikipedia definition of randomness is Randomness is the lack of pattern or predictability in events. A random sequence of events, symbols or steps has no order and does not follow an intelligible pattern or combination. The problem with this definition is that it is too broad for a single statistical test of randomness. To overcome this difficulty we do not test if a sequence is random, but if it follows a particular probability distribution. Consider the example of a casino roulette where we are interest in deciding if the results are trully random, in the sense that getting a odd number is equally probable of getting a even number. In this setting we can define the variable $X = 1$ if result is odd and $X = 0$ if the result is even. And besed on a set of observations $\{X_1,\ldots,X_n\}$ use a statistical test to check if we can reject the hypothesis that the probability of $X = 1$ is equal to that of $X = 0$. In the case where this hypothesis is rejected we can confidently affirm that the well is not fair. For more general situations you might want to check some goodness of fit tests.
How do lotteries ensure that the drawings are sufficiently random, and what are some approaches to f
It really depends on the meaning you are giving to the word "random". The wikipedia definition of randomness is Randomness is the lack of pattern or predictability in events. A random sequence of even
How do lotteries ensure that the drawings are sufficiently random, and what are some approaches to find possible vulnerabilities? It really depends on the meaning you are giving to the word "random". The wikipedia definition of randomness is Randomness is the lack of pattern or predictability in events. A random sequence of events, symbols or steps has no order and does not follow an intelligible pattern or combination. The problem with this definition is that it is too broad for a single statistical test of randomness. To overcome this difficulty we do not test if a sequence is random, but if it follows a particular probability distribution. Consider the example of a casino roulette where we are interest in deciding if the results are trully random, in the sense that getting a odd number is equally probable of getting a even number. In this setting we can define the variable $X = 1$ if result is odd and $X = 0$ if the result is even. And besed on a set of observations $\{X_1,\ldots,X_n\}$ use a statistical test to check if we can reject the hypothesis that the probability of $X = 1$ is equal to that of $X = 0$. In the case where this hypothesis is rejected we can confidently affirm that the well is not fair. For more general situations you might want to check some goodness of fit tests.
How do lotteries ensure that the drawings are sufficiently random, and what are some approaches to f It really depends on the meaning you are giving to the word "random". The wikipedia definition of randomness is Randomness is the lack of pattern or predictability in events. A random sequence of even
48,488
Intuitive explanation of desirable properties (Unbiasedness, Consistency, Efficiency) of statistical estimators?
Unbiasedness means that under the assumptions regarding the population distribution the estimator in repeated sampling will equal the population parameter on average. This is a nice property for the theory of minimum variance unbiased estimators. However, I think unbiasedness is overemphasized. The mean square error is a good measure of the accuracy of an estimator. It equals the square of the estimator's bias plus the variance. Sometimes estimators with small bias have smaller mean square error than unbiased estimators that have large variances. Biased estimators can be asymptotically unbiased, meaning the bias tends to 0 as the sample size gets large. If the estimator is both asymptotically unbiased and the variance goes to 0 as the sample size gets large, then the estimator is consistent (in probability). Technically, in measure theory, there is a difference between convergence in probability and convergence almost surely. The Cramer-Rao lower bound is a mathematical result that shows, in a particular parametric family of distributions, that no unbiased estimator can have a variance less than the bound. So if you can show that your estimator achieves the Cramer-Rao lower bound, you have an efficient estimator.
Intuitive explanation of desirable properties (Unbiasedness, Consistency, Efficiency) of statistical
Unbiasedness means that under the assumptions regarding the population distribution the estimator in repeated sampling will equal the population parameter on average. This is a nice property for the t
Intuitive explanation of desirable properties (Unbiasedness, Consistency, Efficiency) of statistical estimators? Unbiasedness means that under the assumptions regarding the population distribution the estimator in repeated sampling will equal the population parameter on average. This is a nice property for the theory of minimum variance unbiased estimators. However, I think unbiasedness is overemphasized. The mean square error is a good measure of the accuracy of an estimator. It equals the square of the estimator's bias plus the variance. Sometimes estimators with small bias have smaller mean square error than unbiased estimators that have large variances. Biased estimators can be asymptotically unbiased, meaning the bias tends to 0 as the sample size gets large. If the estimator is both asymptotically unbiased and the variance goes to 0 as the sample size gets large, then the estimator is consistent (in probability). Technically, in measure theory, there is a difference between convergence in probability and convergence almost surely. The Cramer-Rao lower bound is a mathematical result that shows, in a particular parametric family of distributions, that no unbiased estimator can have a variance less than the bound. So if you can show that your estimator achieves the Cramer-Rao lower bound, you have an efficient estimator.
Intuitive explanation of desirable properties (Unbiasedness, Consistency, Efficiency) of statistical Unbiasedness means that under the assumptions regarding the population distribution the estimator in repeated sampling will equal the population parameter on average. This is a nice property for the t
48,489
Intuitive explanation of desirable properties (Unbiasedness, Consistency, Efficiency) of statistical estimators?
Think of firing at a target. If you consistently hit the target too low you have a bias. If your arrows are closely grouped you have an efficient estimate. You might be interested in or amused by Maurice Kendall's poem on the subject http://www.columbia.edu/~to166/hiawatha.html
Intuitive explanation of desirable properties (Unbiasedness, Consistency, Efficiency) of statistical
Think of firing at a target. If you consistently hit the target too low you have a bias. If your arrows are closely grouped you have an efficient estimate. You might be interested in or amused by Maur
Intuitive explanation of desirable properties (Unbiasedness, Consistency, Efficiency) of statistical estimators? Think of firing at a target. If you consistently hit the target too low you have a bias. If your arrows are closely grouped you have an efficient estimate. You might be interested in or amused by Maurice Kendall's poem on the subject http://www.columbia.edu/~to166/hiawatha.html
Intuitive explanation of desirable properties (Unbiasedness, Consistency, Efficiency) of statistical Think of firing at a target. If you consistently hit the target too low you have a bias. If your arrows are closely grouped you have an efficient estimate. You might be interested in or amused by Maur
48,490
textbook example of KL Divergence [duplicate]
An enlightening example is its use in Stochastic Neighborhood Embedding devised by Hinton and Roweis. Essentially the authors are trying to represent data on a two or three dimensional manifold so that the data can be visually represented (similar in aim as PCA, for instance). The difference is that rather than preserve total variance in the data (as in PCA), SNE attempts to preserve local structure of the data -- if that is unclear, the KL divergence may help to illuminate what it means. To do this, they use a Gaussian kernel to estimate the probability that points $i$ and $j$ would be neighbours: $$P_i = \sum_j p_{i,j}\qquad \text{ where }\qquad p_{i,j} = \frac{\exp(-\|x_i-x_j\|^2\;/\; 2\sigma_i^2)}{\sum_{k\neq l} \exp(-\| x_i - x_k \|^2\;/\;2\sigma_i^2)}$$ They then use a Gaussian kernel to find a probability density for the new points in the low dimensional space. $$Q_i = \sum_j q_{i,j}\qquad \text{ where }\qquad q_{i,j} = \frac{\exp(-\|y_i-y_j\|^2)}{\sum_{k\neq l} \exp(-\| y_i - y_k \|^2)}\qquad\;\;$$ and they use a cost function $C=\sum_i D_{KL}(P_i||Q_i)$ to measure how well the low dimensional data represents the original data. If we fix the index $i$ for a moment and just look at a single point $i$, expanding out the notation we get: $$D_{KL}(P||Q) = \sum_j p_{i,j} log(\frac{p_{i,j}}{q_{i,j}})$$ Which is brilliant! For each point $i$, the KL divergence will be high if points which are close in high-dimensional space (large $p_{i,j}$) are far apart in low-dimensional space (small $q_{i,j}$). But it puts a much smaller penalty on points that are far apart in high-dimensional space which are close together in low-dimensions. In this way the asymmetry of the KL-divergence is actually beneficial! If we were to find a minimum Cost, we would have a method that preserves well the local structure of the data, as the authors set out to do, and the KL divergence played a pivotal role.
textbook example of KL Divergence [duplicate]
An enlightening example is its use in Stochastic Neighborhood Embedding devised by Hinton and Roweis. Essentially the authors are trying to represent data on a two or three dimensional manifold so th
textbook example of KL Divergence [duplicate] An enlightening example is its use in Stochastic Neighborhood Embedding devised by Hinton and Roweis. Essentially the authors are trying to represent data on a two or three dimensional manifold so that the data can be visually represented (similar in aim as PCA, for instance). The difference is that rather than preserve total variance in the data (as in PCA), SNE attempts to preserve local structure of the data -- if that is unclear, the KL divergence may help to illuminate what it means. To do this, they use a Gaussian kernel to estimate the probability that points $i$ and $j$ would be neighbours: $$P_i = \sum_j p_{i,j}\qquad \text{ where }\qquad p_{i,j} = \frac{\exp(-\|x_i-x_j\|^2\;/\; 2\sigma_i^2)}{\sum_{k\neq l} \exp(-\| x_i - x_k \|^2\;/\;2\sigma_i^2)}$$ They then use a Gaussian kernel to find a probability density for the new points in the low dimensional space. $$Q_i = \sum_j q_{i,j}\qquad \text{ where }\qquad q_{i,j} = \frac{\exp(-\|y_i-y_j\|^2)}{\sum_{k\neq l} \exp(-\| y_i - y_k \|^2)}\qquad\;\;$$ and they use a cost function $C=\sum_i D_{KL}(P_i||Q_i)$ to measure how well the low dimensional data represents the original data. If we fix the index $i$ for a moment and just look at a single point $i$, expanding out the notation we get: $$D_{KL}(P||Q) = \sum_j p_{i,j} log(\frac{p_{i,j}}{q_{i,j}})$$ Which is brilliant! For each point $i$, the KL divergence will be high if points which are close in high-dimensional space (large $p_{i,j}$) are far apart in low-dimensional space (small $q_{i,j}$). But it puts a much smaller penalty on points that are far apart in high-dimensional space which are close together in low-dimensions. In this way the asymmetry of the KL-divergence is actually beneficial! If we were to find a minimum Cost, we would have a method that preserves well the local structure of the data, as the authors set out to do, and the KL divergence played a pivotal role.
textbook example of KL Divergence [duplicate] An enlightening example is its use in Stochastic Neighborhood Embedding devised by Hinton and Roweis. Essentially the authors are trying to represent data on a two or three dimensional manifold so th
48,491
textbook example of KL Divergence [duplicate]
The K-L distance is also called relative entropy Books on Information Theory where it is discussed Elements of Information Theory, Second Edition by Thomas Cover and Joy Thomas, Wiley 2006. Information Theory and Statistics by Solomon Kullback, Dover paperback 1997. A reprint of an earlier book (Wiley 1959). Statistical Implications of Turing's Formula by Zhiyi Zhang, Wiley 2017. There is a great deal of useful information on this site! See also Intuition on the Kullback-Leibler (KL) Divergence
textbook example of KL Divergence [duplicate]
The K-L distance is also called relative entropy Books on Information Theory where it is discussed Elements of Information Theory, Second Edition by Thomas Cover and Joy Thomas, Wiley 2006. Informati
textbook example of KL Divergence [duplicate] The K-L distance is also called relative entropy Books on Information Theory where it is discussed Elements of Information Theory, Second Edition by Thomas Cover and Joy Thomas, Wiley 2006. Information Theory and Statistics by Solomon Kullback, Dover paperback 1997. A reprint of an earlier book (Wiley 1959). Statistical Implications of Turing's Formula by Zhiyi Zhang, Wiley 2017. There is a great deal of useful information on this site! See also Intuition on the Kullback-Leibler (KL) Divergence
textbook example of KL Divergence [duplicate] The K-L distance is also called relative entropy Books on Information Theory where it is discussed Elements of Information Theory, Second Edition by Thomas Cover and Joy Thomas, Wiley 2006. Informati
48,492
Difference between forecasting accuracy and forecasting error?
I love your quote: He was told to evaluate the whole supply chain demand with this metric but cannot explain why. You are completely correct that truncating "accuracy" makes no sense. It throws information away for no good reason. Much better to either accept negative "accuracy", or deal with the MAPE directly, and accept that MAPEs greater than 100% occur. The only rationale for truncation is that there is no good interpretation of negative "accuracy". But that is a result of trying to work with "accuracy" and defining it as 1-error - where the error can be unbounded. The following threads may be helpful: What are the shortcomings of the Mean Absolute Percentage Error (MAPE)? Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)?
Difference between forecasting accuracy and forecasting error?
I love your quote: He was told to evaluate the whole supply chain demand with this metric but cannot explain why. You are completely correct that truncating "accuracy" makes no sense. It throws info
Difference between forecasting accuracy and forecasting error? I love your quote: He was told to evaluate the whole supply chain demand with this metric but cannot explain why. You are completely correct that truncating "accuracy" makes no sense. It throws information away for no good reason. Much better to either accept negative "accuracy", or deal with the MAPE directly, and accept that MAPEs greater than 100% occur. The only rationale for truncation is that there is no good interpretation of negative "accuracy". But that is a result of trying to work with "accuracy" and defining it as 1-error - where the error can be unbounded. The following threads may be helpful: What are the shortcomings of the Mean Absolute Percentage Error (MAPE)? Why use a certain measure of forecast error (e.g. MAD) as opposed to another (e.g. MSE)?
Difference between forecasting accuracy and forecasting error? I love your quote: He was told to evaluate the whole supply chain demand with this metric but cannot explain why. You are completely correct that truncating "accuracy" makes no sense. It throws info
48,493
Difference between forecasting accuracy and forecasting error?
Actually, this is described in the link you provided: Error above 100% implies a zero forecast accuracy or a very inaccurate forecast. [...] What is the impact of Large Forecast Errors? Is Negative accuracy meaningful? Regardless of huge errors, and errors much higher than 100% of the Actuals or Forecast, we interpret accuracy a number between 0% and 100%. Either a forecast is perfect or relative accurate or inaccurate or just plain incorrect. So we constrain Accuracy to be between 0 and 100%. Negative accuracy does not make any sense. This measure simply assumes that if something has bigger errors then the predicted value itself, then no matter how much bigger they are, they are equally bad. If you'd take a loan and then to repay it you'd have to make monthly payments that are greater then your salary, then it really does not matter how much greater they are, since you can't afford to pay them.
Difference between forecasting accuracy and forecasting error?
Actually, this is described in the link you provided: Error above 100% implies a zero forecast accuracy or a very inaccurate forecast. [...] What is the impact of Large Forecast Errors? Is Negativ
Difference between forecasting accuracy and forecasting error? Actually, this is described in the link you provided: Error above 100% implies a zero forecast accuracy or a very inaccurate forecast. [...] What is the impact of Large Forecast Errors? Is Negative accuracy meaningful? Regardless of huge errors, and errors much higher than 100% of the Actuals or Forecast, we interpret accuracy a number between 0% and 100%. Either a forecast is perfect or relative accurate or inaccurate or just plain incorrect. So we constrain Accuracy to be between 0 and 100%. Negative accuracy does not make any sense. This measure simply assumes that if something has bigger errors then the predicted value itself, then no matter how much bigger they are, they are equally bad. If you'd take a loan and then to repay it you'd have to make monthly payments that are greater then your salary, then it really does not matter how much greater they are, since you can't afford to pay them.
Difference between forecasting accuracy and forecasting error? Actually, this is described in the link you provided: Error above 100% implies a zero forecast accuracy or a very inaccurate forecast. [...] What is the impact of Large Forecast Errors? Is Negativ
48,494
Can we prove Weierstrass Approximation using Strong Law of Large Numbers?
See also this question; the proof is sketched in the related comments by @cardinal. Without loss of generality we can assume that the interval is $[0, \,1]$. Consider the following Bernstein's polynomial $$ B_n(x) := \sum_{k= 0}^n f(k/n) { n \choose k} x^k (1 - x)^{n-k} $$ which will provide an approximation of $f(x)$: we can prove that $B_n(x)$ tends to $f(x)$ uniformly in $x$ for large $n$. Although this is standard mathematical analysis, we can use the formalism of probability theory, writing some sums as an expectation or a variance which makes things simpler. We can indeed write $B_n(x) = \mathbb{E}[f(S_n/n)]$ where $S_n$ follows the binomial distribution with size $n$ and probability $x$. We know by the law of large numbers that for $n$ large $S_n/n$ is close to $x$, hence that $\mathbb{E}[f(S_n /n)]$ is close to $\mathbb{E}[f(x)]= f(x)$. A little bit of extra work is needed to prove the wanted uniform convergence. Define the r.vs $D_n := | f(x) - f(S_n/n)|$ and $E_n := |x -S_n/n |$ the distribution of which depends on $n$ and $x$. For any $x$ in the interval $[0,\,1]$ $$ \left| f(x) - B_n(x) \right| = \left| \, \mathbb{E}[f(x)] - \mathbb{E}[f(S_n/n)] \, \right| \leqslant \mathbb{E}[D_n]. $$ Now for $\delta >0$ we have $$ \mathbb{E}[D_n] = \mathbb{E}[D_n \vert\, E_n \leqslant \delta] \, \text{Pr}\{ E_n \leqslant \delta \} + \mathbb{E}\left[D_n \vert\, E_n > \delta \right] \, \text{Pr}\{E_n > \delta \} =: a + b, $$ and we consider the two terms $a$ and $b$ separately. For the first term $$ a \leqslant \mathbb{E}[D_n \vert\, E_n \leqslant \delta] \leqslant \omega_f(\delta) $$ where $\omega_f(\delta)$ is the modulus of continuity of $f$ on $[0,\,1]$ defined as the supremum of $|f(u) - f(v)|$ for all $u$, $v$ with $|u - v| \leqslant \delta$. In the second term the expectation is $\leqslant 2B$ where $B:=\sup_x |f(x)|= \|f\|_{\infty}$ so $$ b \leqslant 2B \, \text{Pr}\{E_n > \delta \} \leqslant 2B \, \frac{x(1-x)}{n \delta^2} \leqslant \frac{2B}{n \delta^2} $$ where Chebyshev's inequality was used with $\text{Var}[S_n /n] = x(1-x) /n$. If $\epsilon >0$ the inequality $| f(x) - B_n(x) | < \epsilon$ can be seen to hold for all $x$ when $n$ is large enough. Indeed we can choose $\delta > 0$ such that $\omega_f(\delta) < \epsilon /2$ due to the uniform continuity of $f(x)$ on the compact interval $[0,\,1]$. Then for $n$ large enough the second term is $b < \epsilon /2$ hence $| f(x) - B_n(x) | < \epsilon$ as claimed. As a final remark, using Bernstein's polynomials is in practice a very inefficient method to approximate a given function.
Can we prove Weierstrass Approximation using Strong Law of Large Numbers?
See also this question; the proof is sketched in the related comments by @cardinal. Without loss of generality we can assume that the interval is $[0, \,1]$. Consider the following Bernstein's polynom
Can we prove Weierstrass Approximation using Strong Law of Large Numbers? See also this question; the proof is sketched in the related comments by @cardinal. Without loss of generality we can assume that the interval is $[0, \,1]$. Consider the following Bernstein's polynomial $$ B_n(x) := \sum_{k= 0}^n f(k/n) { n \choose k} x^k (1 - x)^{n-k} $$ which will provide an approximation of $f(x)$: we can prove that $B_n(x)$ tends to $f(x)$ uniformly in $x$ for large $n$. Although this is standard mathematical analysis, we can use the formalism of probability theory, writing some sums as an expectation or a variance which makes things simpler. We can indeed write $B_n(x) = \mathbb{E}[f(S_n/n)]$ where $S_n$ follows the binomial distribution with size $n$ and probability $x$. We know by the law of large numbers that for $n$ large $S_n/n$ is close to $x$, hence that $\mathbb{E}[f(S_n /n)]$ is close to $\mathbb{E}[f(x)]= f(x)$. A little bit of extra work is needed to prove the wanted uniform convergence. Define the r.vs $D_n := | f(x) - f(S_n/n)|$ and $E_n := |x -S_n/n |$ the distribution of which depends on $n$ and $x$. For any $x$ in the interval $[0,\,1]$ $$ \left| f(x) - B_n(x) \right| = \left| \, \mathbb{E}[f(x)] - \mathbb{E}[f(S_n/n)] \, \right| \leqslant \mathbb{E}[D_n]. $$ Now for $\delta >0$ we have $$ \mathbb{E}[D_n] = \mathbb{E}[D_n \vert\, E_n \leqslant \delta] \, \text{Pr}\{ E_n \leqslant \delta \} + \mathbb{E}\left[D_n \vert\, E_n > \delta \right] \, \text{Pr}\{E_n > \delta \} =: a + b, $$ and we consider the two terms $a$ and $b$ separately. For the first term $$ a \leqslant \mathbb{E}[D_n \vert\, E_n \leqslant \delta] \leqslant \omega_f(\delta) $$ where $\omega_f(\delta)$ is the modulus of continuity of $f$ on $[0,\,1]$ defined as the supremum of $|f(u) - f(v)|$ for all $u$, $v$ with $|u - v| \leqslant \delta$. In the second term the expectation is $\leqslant 2B$ where $B:=\sup_x |f(x)|= \|f\|_{\infty}$ so $$ b \leqslant 2B \, \text{Pr}\{E_n > \delta \} \leqslant 2B \, \frac{x(1-x)}{n \delta^2} \leqslant \frac{2B}{n \delta^2} $$ where Chebyshev's inequality was used with $\text{Var}[S_n /n] = x(1-x) /n$. If $\epsilon >0$ the inequality $| f(x) - B_n(x) | < \epsilon$ can be seen to hold for all $x$ when $n$ is large enough. Indeed we can choose $\delta > 0$ such that $\omega_f(\delta) < \epsilon /2$ due to the uniform continuity of $f(x)$ on the compact interval $[0,\,1]$. Then for $n$ large enough the second term is $b < \epsilon /2$ hence $| f(x) - B_n(x) | < \epsilon$ as claimed. As a final remark, using Bernstein's polynomials is in practice a very inefficient method to approximate a given function.
Can we prove Weierstrass Approximation using Strong Law of Large Numbers? See also this question; the proof is sketched in the related comments by @cardinal. Without loss of generality we can assume that the interval is $[0, \,1]$. Consider the following Bernstein's polynom
48,495
Can we prove Weierstrass Approximation using Strong Law of Large Numbers?
Weierstrass Approximation Theorem: Suppose $f$ is a continuous real-valued function defined on the real interval $[a,b]$. For every $\varepsilon > 0$ there exists a polynomial $p$ such that for all $x \in [a, b]$ we have $|f(x)−p(x)| < \varepsilon$ (or equivalently, the supremum norm $||f−p|| < \varepsilon$). The notes ask you to prove the result on the unit interval, so let's take $a=0$ and $b=1$ in the Weierstrass approximation theorem. (The proof can easily be generalised to the broader case.) The polynomial $p$ in the theorem is constructed by taking coin tosses $X_1,X_2,X_3,... \sim \text{IID Bern}(x)$ leading to $S_n \sim \text{Bin}(n,x)$. We use this statistic to construct the polynomial: $$\begin{align} p(x) &\equiv \mathbb{E}(f(S_n/n)) \\[6pt] &= \sum_{s=0}^n f(s/n) \text{Bin}(s|n,x) \\[6pt] &= \sum_{s=0}^n f(s/n) {n \choose s} x^{s} (1-x)^{n-x}. \\[6pt] \end{align}$$ The results in the linked question show that $p(x) = \mathbb{E}(f(S_n/n)) \rightarrow f(x)$ for all $0 \leqslant x \leqslant 1$, which is then used to prove the approximation theorem. In order to establish the approximation theorem you need to show uniform convergence, which is possible to prove as a result of the strong law of large numbers.
Can we prove Weierstrass Approximation using Strong Law of Large Numbers?
Weierstrass Approximation Theorem: Suppose $f$ is a continuous real-valued function defined on the real interval $[a,b]$. For every $\varepsilon > 0$ there exists a polynomial $p$ such that for all $
Can we prove Weierstrass Approximation using Strong Law of Large Numbers? Weierstrass Approximation Theorem: Suppose $f$ is a continuous real-valued function defined on the real interval $[a,b]$. For every $\varepsilon > 0$ there exists a polynomial $p$ such that for all $x \in [a, b]$ we have $|f(x)−p(x)| < \varepsilon$ (or equivalently, the supremum norm $||f−p|| < \varepsilon$). The notes ask you to prove the result on the unit interval, so let's take $a=0$ and $b=1$ in the Weierstrass approximation theorem. (The proof can easily be generalised to the broader case.) The polynomial $p$ in the theorem is constructed by taking coin tosses $X_1,X_2,X_3,... \sim \text{IID Bern}(x)$ leading to $S_n \sim \text{Bin}(n,x)$. We use this statistic to construct the polynomial: $$\begin{align} p(x) &\equiv \mathbb{E}(f(S_n/n)) \\[6pt] &= \sum_{s=0}^n f(s/n) \text{Bin}(s|n,x) \\[6pt] &= \sum_{s=0}^n f(s/n) {n \choose s} x^{s} (1-x)^{n-x}. \\[6pt] \end{align}$$ The results in the linked question show that $p(x) = \mathbb{E}(f(S_n/n)) \rightarrow f(x)$ for all $0 \leqslant x \leqslant 1$, which is then used to prove the approximation theorem. In order to establish the approximation theorem you need to show uniform convergence, which is possible to prove as a result of the strong law of large numbers.
Can we prove Weierstrass Approximation using Strong Law of Large Numbers? Weierstrass Approximation Theorem: Suppose $f$ is a continuous real-valued function defined on the real interval $[a,b]$. For every $\varepsilon > 0$ there exists a polynomial $p$ such that for all $
48,496
Can we prove Weierstrass Approximation using Strong Law of Large Numbers?
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. Let Sn satisfies strong law, then it satisfies weak law and then proceed with the standard weak law proof you mentioned above
Can we prove Weierstrass Approximation using Strong Law of Large Numbers?
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.
Can we prove Weierstrass Approximation using Strong Law of Large Numbers? 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. Let Sn satisfies strong law, then it satisfies weak law and then proceed with the standard weak law proof you mentioned above
Can we prove Weierstrass Approximation using Strong Law of Large Numbers? 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.
48,497
Simulating the impact of non-IID data on a model
I have data that is non-IID, and I want to estimate if the dependence is bad enough that it will have a noticeable effect on a fitted classifier. I don't think the exact model type will matter in this case, but for argument's sake let's say I'm using elastic-net logistic regression. On the importance of the i.i.d. assumption in statistical learning Regularized Logistic Regression: Lasso vs. Ridge vs. Elastic Net Predictive Modeling - Should we care about mixed modeling? Ideally, I would like to be able to compare the fitted model from the non-IID data set to a "comparable" or "similar" IID data set. So I'm thinking I could just simulate such a data set, fit the model on the fake data and the real data, Is there a formal or rigorous definition of "similarity" that makes sense in this case? I certainly know a dissimilar data set when I see one, but it's hard to quantify exactly how I know. An R software library can help, consider: "Statistical Patterns in Genomic Sequences" by Hart and Martínez which could be extended to work with arbitrary symbolic sequences, not only DNA sequences. It features easy to use functions: diid.disturbance - Construct feasible Random Noise Generating a Bernoulli Process Produces a sequence of random noise which would generate an observed sequence of finite symbols provided that the sequence of symbols results from a Bernoulli process. diid.test - A Test for a Bernoulli Scheme (IID Sequence) Tests whether or not a data series constitutes a Bernoulli scheme, that is, an independent and identically distributed (IID) sequence of symbols, by inferring the sequence of IID U(0,1) random noise that might have generated it. Category Function Test Uniformity ks.unif.test Kolmogorov-Smirnov test for uniform$(0,1)$ data chisq.unif.test Pearson’s chi-squared test for discrete uniform data, Independence lb.test Ljung-Box $Q$ test for uncorrelated data diffsign.test signed difference test of independence turningpoint.test turning point test of independence rank.test rank test of independence Search for a library that exactly meets your requirements or modify one that nearly does. Also check out the NIST SP 800-22 Statistical Tests which can be used to test your data. Is there a straightforward way to generate an IID dataset from a non-IID data set that otherwise preserves some structure from the joint distribution of features? Create something like a k-distribution by compounding some existing distributions to meet your requirements. Use something like DistributionFitTest to check the generated IID. Is this an X-Y problem? Is there a better way to evaluate the effect of data dependence on my estimates? A tiny bit XY, maybe; you've waited a year and a half for an answer, even Tweeted it. You made a minor edit. If I don't get an answer in less than a week I make certain to check if I missed something. You've been asked a few questions and answered one. I have no complaints or questions ... Test with both (non-IID, IID) generated random models (easy with the software suggested above, though probably more power in a different package), your own data, and both. Create a set of "Ensemble Algorithms" that don't blow up. For a purely predictive task, does non-IID data even make a difference as long as the cross-validation procedure is constructed correctly? This answer suggests the answer is "no": Predictive Modeling - Should we care about mixed modeling?. The answer requested further information and links, further it was not an absolute "no". See also: "Choosing the Correct Statistical Test" (Derived from Dr. Leeper's work) - General guidelines for choosing a statistical analysis and links showing how-to using SAS, Stata, SPSS and R. Choosing a statistical test, Data Analysis Resource Center, and GraphPad Analysis Checklist. I might have time to return for another edit and improve this answer.
Simulating the impact of non-IID data on a model
I have data that is non-IID, and I want to estimate if the dependence is bad enough that it will have a noticeable effect on a fitted classifier. I don't think the exact model type will matter in this
Simulating the impact of non-IID data on a model I have data that is non-IID, and I want to estimate if the dependence is bad enough that it will have a noticeable effect on a fitted classifier. I don't think the exact model type will matter in this case, but for argument's sake let's say I'm using elastic-net logistic regression. On the importance of the i.i.d. assumption in statistical learning Regularized Logistic Regression: Lasso vs. Ridge vs. Elastic Net Predictive Modeling - Should we care about mixed modeling? Ideally, I would like to be able to compare the fitted model from the non-IID data set to a "comparable" or "similar" IID data set. So I'm thinking I could just simulate such a data set, fit the model on the fake data and the real data, Is there a formal or rigorous definition of "similarity" that makes sense in this case? I certainly know a dissimilar data set when I see one, but it's hard to quantify exactly how I know. An R software library can help, consider: "Statistical Patterns in Genomic Sequences" by Hart and Martínez which could be extended to work with arbitrary symbolic sequences, not only DNA sequences. It features easy to use functions: diid.disturbance - Construct feasible Random Noise Generating a Bernoulli Process Produces a sequence of random noise which would generate an observed sequence of finite symbols provided that the sequence of symbols results from a Bernoulli process. diid.test - A Test for a Bernoulli Scheme (IID Sequence) Tests whether or not a data series constitutes a Bernoulli scheme, that is, an independent and identically distributed (IID) sequence of symbols, by inferring the sequence of IID U(0,1) random noise that might have generated it. Category Function Test Uniformity ks.unif.test Kolmogorov-Smirnov test for uniform$(0,1)$ data chisq.unif.test Pearson’s chi-squared test for discrete uniform data, Independence lb.test Ljung-Box $Q$ test for uncorrelated data diffsign.test signed difference test of independence turningpoint.test turning point test of independence rank.test rank test of independence Search for a library that exactly meets your requirements or modify one that nearly does. Also check out the NIST SP 800-22 Statistical Tests which can be used to test your data. Is there a straightforward way to generate an IID dataset from a non-IID data set that otherwise preserves some structure from the joint distribution of features? Create something like a k-distribution by compounding some existing distributions to meet your requirements. Use something like DistributionFitTest to check the generated IID. Is this an X-Y problem? Is there a better way to evaluate the effect of data dependence on my estimates? A tiny bit XY, maybe; you've waited a year and a half for an answer, even Tweeted it. You made a minor edit. If I don't get an answer in less than a week I make certain to check if I missed something. You've been asked a few questions and answered one. I have no complaints or questions ... Test with both (non-IID, IID) generated random models (easy with the software suggested above, though probably more power in a different package), your own data, and both. Create a set of "Ensemble Algorithms" that don't blow up. For a purely predictive task, does non-IID data even make a difference as long as the cross-validation procedure is constructed correctly? This answer suggests the answer is "no": Predictive Modeling - Should we care about mixed modeling?. The answer requested further information and links, further it was not an absolute "no". See also: "Choosing the Correct Statistical Test" (Derived from Dr. Leeper's work) - General guidelines for choosing a statistical analysis and links showing how-to using SAS, Stata, SPSS and R. Choosing a statistical test, Data Analysis Resource Center, and GraphPad Analysis Checklist. I might have time to return for another edit and improve this answer.
Simulating the impact of non-IID data on a model I have data that is non-IID, and I want to estimate if the dependence is bad enough that it will have a noticeable effect on a fitted classifier. I don't think the exact model type will matter in this
48,498
Evaluating models by Loglogss, AUC, and Accuracy
A very non-mathematical intuition: A has a higher accuracy than B, but a lower log-loss: it means A is shy, i.e. its probabilities tend to me closer to 0.5 than 0/1. B is bolder, i.e. its probalities are closer to 0/1, but makes more mistakes than A. A has a higher accuracy than B, but a lower AUROC: it means A is "better" than B for the threshold with which the accuracy was computed, but when considering all thresholds on average B is "better".
Evaluating models by Loglogss, AUC, and Accuracy
A very non-mathematical intuition: A has a higher accuracy than B, but a lower log-loss: it means A is shy, i.e. its probabilities tend to me closer to 0.5 than 0/1. B is bolder, i.e. its probalities
Evaluating models by Loglogss, AUC, and Accuracy A very non-mathematical intuition: A has a higher accuracy than B, but a lower log-loss: it means A is shy, i.e. its probabilities tend to me closer to 0.5 than 0/1. B is bolder, i.e. its probalities are closer to 0/1, but makes more mistakes than A. A has a higher accuracy than B, but a lower AUROC: it means A is "better" than B for the threshold with which the accuracy was computed, but when considering all thresholds on average B is "better".
Evaluating models by Loglogss, AUC, and Accuracy A very non-mathematical intuition: A has a higher accuracy than B, but a lower log-loss: it means A is shy, i.e. its probabilities tend to me closer to 0.5 than 0/1. B is bolder, i.e. its probalities
48,499
How to normalized a similarity matrix?
Assuming it's composed solely of positive values, and if your diagonal isn't already composed solely of ones, do: $$A_{ij}:=\frac{A_{ij}}{\sqrt{A_{jj}\cdot A_{ii}}}$$ This is analogous to the transformation from a covariance to correlation matrix, i.e. diagonals become one, off-diagonal is rescaled.
How to normalized a similarity matrix?
Assuming it's composed solely of positive values, and if your diagonal isn't already composed solely of ones, do: $$A_{ij}:=\frac{A_{ij}}{\sqrt{A_{jj}\cdot A_{ii}}}$$ This is analogous to the transfor
How to normalized a similarity matrix? Assuming it's composed solely of positive values, and if your diagonal isn't already composed solely of ones, do: $$A_{ij}:=\frac{A_{ij}}{\sqrt{A_{jj}\cdot A_{ii}}}$$ This is analogous to the transformation from a covariance to correlation matrix, i.e. diagonals become one, off-diagonal is rescaled.
How to normalized a similarity matrix? Assuming it's composed solely of positive values, and if your diagonal isn't already composed solely of ones, do: $$A_{ij}:=\frac{A_{ij}}{\sqrt{A_{jj}\cdot A_{ii}}}$$ This is analogous to the transfor
48,500
Are Neural Nets viable to extract Date patterns in a text
This is technically possible, but there would be several issues you would run into, for example: What would be your output? You could use a soft-max and then do classification for the days and months. However, classification on the year number would limit you to a specific time range and might lead to thousand of unused or sparsely used classes. You could use regression and use the fact that this is the 292nd day of 366 (leap year!) of year 2016 to have 2016 292/366 as the target value for the current date. However you would need to train this network to be accurate to 7 significant figures to give accurate dates. What would be your input? You could just input the ASCII values of the characters and then perform some normalization. However that would mean the input could have variable length (especially if you allow words like 'Thursday' and 'March' in your dates). You could handle that with a recurrent neural network, but training such a network to learn words like 'Thursday' is going to be an incredible amount of work for such a simple problem. Otherwise you will need to do pre-processing. Assigning numerical values to the names of the months and while you're at it you can just as well combine consecutive digit-characters into the numbers they represent. You could feed that into a neural network, but you'd be a long way into parsing the dates with regex. So why not finish the job using regex? A more general problem: how do you deal with ambiguity? Is 10-11-2016 a day in October or November? In conclusion, neural networks are the wrong tools for the job. However if you really wanted to, you could give yourself a whole lot of extra work and do it with the wrong tools anyway. Edit: ok, so responding to OP's edit. If you wanted to do it anyway, my answer would depend on the amount of preprocessing you would allow for. Without any pre-processing and assuming ASCII input, I would represent each of the 256 ASCII characters as a vector of 255 zeros and a single 1 at the location corresponding to their ASCII encoding. So 'A' would have a 1 on index 65 and 'h' would have a 1 at index 104 and the rest zeros. Now first we want translation invariance, that simply means that the same string should be recognized as a date or not, no matter where it is positioned in the text. We can achieve this by feeding n characters (each represented as vectors) into our network at a time. So first we take characters 1-n, then characters 2-n+1, then 3-n+2 etc. until we are at the end of the text. Now the obvious question is what is a good value for n. We would like n to be the same as the length of a date-string. This brings us to the issue that dates might have different lengths (compare: 10-8-16, 10-08-16, 10-08-2016 and 10-October-2016). The only solution I can come up with is to train a classifier for each length that dates might have in your training set. If you are willing to do pre-processing, you can make it a lot easier for the algorithm. First of all it is a bit silly to pretend '0' has as much in common with 'a' as with '1'. So instead of representing the digits as 10 different places to put a 1 in a vector, you could make the vector 9 indices shorter and represent the digits 0-9 as the numbers 1-10 in a single spot (remember, 0 means no character). That would save on the number of inputs and save the network the trouble of learning what digits are. Next in this specific use-case, it would probably help a lot to combine 2 consecutive digits as a single vector with the numerical value in the digit slot. First of all, this would represent '8' and '08' as the same thing and therefor cut back on the number of different lengths dates can have (in this representation 8/8/16, 08/8/16, 8/08/16 and 08/08/16 all would have the same length). Second of all, this would make it very easy to learn that 24 could be a day of the month, but 42 can't. And by only combining at most 2 consecutive digits, it is relatively easy to learn that 2016 and 16 are similar in the date context.
Are Neural Nets viable to extract Date patterns in a text
This is technically possible, but there would be several issues you would run into, for example: What would be your output? You could use a soft-max and then do classification for the days and mont
Are Neural Nets viable to extract Date patterns in a text This is technically possible, but there would be several issues you would run into, for example: What would be your output? You could use a soft-max and then do classification for the days and months. However, classification on the year number would limit you to a specific time range and might lead to thousand of unused or sparsely used classes. You could use regression and use the fact that this is the 292nd day of 366 (leap year!) of year 2016 to have 2016 292/366 as the target value for the current date. However you would need to train this network to be accurate to 7 significant figures to give accurate dates. What would be your input? You could just input the ASCII values of the characters and then perform some normalization. However that would mean the input could have variable length (especially if you allow words like 'Thursday' and 'March' in your dates). You could handle that with a recurrent neural network, but training such a network to learn words like 'Thursday' is going to be an incredible amount of work for such a simple problem. Otherwise you will need to do pre-processing. Assigning numerical values to the names of the months and while you're at it you can just as well combine consecutive digit-characters into the numbers they represent. You could feed that into a neural network, but you'd be a long way into parsing the dates with regex. So why not finish the job using regex? A more general problem: how do you deal with ambiguity? Is 10-11-2016 a day in October or November? In conclusion, neural networks are the wrong tools for the job. However if you really wanted to, you could give yourself a whole lot of extra work and do it with the wrong tools anyway. Edit: ok, so responding to OP's edit. If you wanted to do it anyway, my answer would depend on the amount of preprocessing you would allow for. Without any pre-processing and assuming ASCII input, I would represent each of the 256 ASCII characters as a vector of 255 zeros and a single 1 at the location corresponding to their ASCII encoding. So 'A' would have a 1 on index 65 and 'h' would have a 1 at index 104 and the rest zeros. Now first we want translation invariance, that simply means that the same string should be recognized as a date or not, no matter where it is positioned in the text. We can achieve this by feeding n characters (each represented as vectors) into our network at a time. So first we take characters 1-n, then characters 2-n+1, then 3-n+2 etc. until we are at the end of the text. Now the obvious question is what is a good value for n. We would like n to be the same as the length of a date-string. This brings us to the issue that dates might have different lengths (compare: 10-8-16, 10-08-16, 10-08-2016 and 10-October-2016). The only solution I can come up with is to train a classifier for each length that dates might have in your training set. If you are willing to do pre-processing, you can make it a lot easier for the algorithm. First of all it is a bit silly to pretend '0' has as much in common with 'a' as with '1'. So instead of representing the digits as 10 different places to put a 1 in a vector, you could make the vector 9 indices shorter and represent the digits 0-9 as the numbers 1-10 in a single spot (remember, 0 means no character). That would save on the number of inputs and save the network the trouble of learning what digits are. Next in this specific use-case, it would probably help a lot to combine 2 consecutive digits as a single vector with the numerical value in the digit slot. First of all, this would represent '8' and '08' as the same thing and therefor cut back on the number of different lengths dates can have (in this representation 8/8/16, 08/8/16, 8/08/16 and 08/08/16 all would have the same length). Second of all, this would make it very easy to learn that 24 could be a day of the month, but 42 can't. And by only combining at most 2 consecutive digits, it is relatively easy to learn that 2016 and 16 are similar in the date context.
Are Neural Nets viable to extract Date patterns in a text This is technically possible, but there would be several issues you would run into, for example: What would be your output? You could use a soft-max and then do classification for the days and mont