idx
int64
1
56k
question
stringlengths
15
155
answer
stringlengths
2
29.2k
question_cut
stringlengths
15
100
answer_cut
stringlengths
2
200
conversation
stringlengths
47
29.3k
conversation_cut
stringlengths
47
301
16,601
Calculating the probability of gene list overlap between an RNA seq and a ChIP-chip data set
You are close, with your use of dhyper and phyper, but I don't understand where 0:2 and -1:2 are coming from. The p-value you want is the probability of getting 100 or more white balls in a sample of size 400 from an urn with 3000 white balls and 12000 black balls. Here are four ways to calculate it. sum(dhyper(100:400, 3000, 12000, 400)) 1 - sum(dhyper(0:99, 3000, 12000, 400)) phyper(99, 3000, 12000, 400, lower.tail=FALSE) 1-phyper(99, 3000, 12000, 400) These give 0.0078. dhyper(x, m, n, k) gives the probability of drawing exactly x. In the first line, we sum up the probabilities for 100 – 400; in the second line, we take 1 minus the sum of the probabilities of 0 – 99. phyper(x, m, n, k) gives the probability of getting x or fewer, so phyper(x, m, n, k) is the same as sum(dhyper(0:x, m, n, k)). The lower.tail=FALSE is a bit confusing. phyper(x, m, n, k, lower.tail=FALSE) is the same as 1-phyper(x, m, n, k), and so is the probability of x+1 or more. [I never remember this and so always have to double check.] At that stattrek.com site, you want to look at the last row, "Cumulative Probability: P(X $\ge$ 100)," rather than the first row "Hypergeometric Probability: P(X = 100)." Any particular number that you draw is going to have small probability (in fact, max(dhyper(0:400, 3000, 12000, 400)) gives $\sim$0.050), and getting 101 or 102 or any larger number is even more interesting that 100, and the p-value is the probability, if the null hypothesis were true, of getting a result as interesting or more so than what was observed. Here's a picture of the hypergeometric distribution in this case. You can see that it's centered at 80 (20% of 400) and that 100 is pretty far out in the right tail.
Calculating the probability of gene list overlap between an RNA seq and a ChIP-chip data set
You are close, with your use of dhyper and phyper, but I don't understand where 0:2 and -1:2 are coming from. The p-value you want is the probability of getting 100 or more white balls in a sample of
Calculating the probability of gene list overlap between an RNA seq and a ChIP-chip data set You are close, with your use of dhyper and phyper, but I don't understand where 0:2 and -1:2 are coming from. The p-value you want is the probability of getting 100 or more white balls in a sample of size 400 from an urn with 3000 white balls and 12000 black balls. Here are four ways to calculate it. sum(dhyper(100:400, 3000, 12000, 400)) 1 - sum(dhyper(0:99, 3000, 12000, 400)) phyper(99, 3000, 12000, 400, lower.tail=FALSE) 1-phyper(99, 3000, 12000, 400) These give 0.0078. dhyper(x, m, n, k) gives the probability of drawing exactly x. In the first line, we sum up the probabilities for 100 – 400; in the second line, we take 1 minus the sum of the probabilities of 0 – 99. phyper(x, m, n, k) gives the probability of getting x or fewer, so phyper(x, m, n, k) is the same as sum(dhyper(0:x, m, n, k)). The lower.tail=FALSE is a bit confusing. phyper(x, m, n, k, lower.tail=FALSE) is the same as 1-phyper(x, m, n, k), and so is the probability of x+1 or more. [I never remember this and so always have to double check.] At that stattrek.com site, you want to look at the last row, "Cumulative Probability: P(X $\ge$ 100)," rather than the first row "Hypergeometric Probability: P(X = 100)." Any particular number that you draw is going to have small probability (in fact, max(dhyper(0:400, 3000, 12000, 400)) gives $\sim$0.050), and getting 101 or 102 or any larger number is even more interesting that 100, and the p-value is the probability, if the null hypothesis were true, of getting a result as interesting or more so than what was observed. Here's a picture of the hypergeometric distribution in this case. You can see that it's centered at 80 (20% of 400) and that 100 is pretty far out in the right tail.
Calculating the probability of gene list overlap between an RNA seq and a ChIP-chip data set You are close, with your use of dhyper and phyper, but I don't understand where 0:2 and -1:2 are coming from. The p-value you want is the probability of getting 100 or more white balls in a sample of
16,602
Calculating the probability of gene list overlap between an RNA seq and a ChIP-chip data set
Look at it this way.. If you assumed it as a binomial, which may not be correct, but it should be fairly approximate.. your sigma^2 is .8*.2*400= 64, then sigma = 8. So from 80 to 100 you've gone 2.5 standard deviations.. This is pretty significant.. It should have a small p-value.
Calculating the probability of gene list overlap between an RNA seq and a ChIP-chip data set
Look at it this way.. If you assumed it as a binomial, which may not be correct, but it should be fairly approximate.. your sigma^2 is .8*.2*400= 64, then sigma = 8. So from 80 to 100 you've gone 2.5
Calculating the probability of gene list overlap between an RNA seq and a ChIP-chip data set Look at it this way.. If you assumed it as a binomial, which may not be correct, but it should be fairly approximate.. your sigma^2 is .8*.2*400= 64, then sigma = 8. So from 80 to 100 you've gone 2.5 standard deviations.. This is pretty significant.. It should have a small p-value.
Calculating the probability of gene list overlap between an RNA seq and a ChIP-chip data set Look at it this way.. If you assumed it as a binomial, which may not be correct, but it should be fairly approximate.. your sigma^2 is .8*.2*400= 64, then sigma = 8. So from 80 to 100 you've gone 2.5
16,603
Forecasting binary time series
You can use generalized ARMA (GLARMA) models. See, for example, Kedem and Fokianos (2002), Regression Models for Time Series Analysis. See also R package glarma (on CRAN)
Forecasting binary time series
You can use generalized ARMA (GLARMA) models. See, for example, Kedem and Fokianos (2002), Regression Models for Time Series Analysis. See also R package glarma (on CRAN)
Forecasting binary time series You can use generalized ARMA (GLARMA) models. See, for example, Kedem and Fokianos (2002), Regression Models for Time Series Analysis. See also R package glarma (on CRAN)
Forecasting binary time series You can use generalized ARMA (GLARMA) models. See, for example, Kedem and Fokianos (2002), Regression Models for Time Series Analysis. See also R package glarma (on CRAN)
16,604
Forecasting binary time series
The R package bsts allows you to estimate Bayesian structural time series models with binary targets by setting family = 'logit'. Note, though, that these models often require longer runs than Gaussian data (e.g., niter = 10000).
Forecasting binary time series
The R package bsts allows you to estimate Bayesian structural time series models with binary targets by setting family = 'logit'. Note, though, that these models often require longer runs than Gaussia
Forecasting binary time series The R package bsts allows you to estimate Bayesian structural time series models with binary targets by setting family = 'logit'. Note, though, that these models often require longer runs than Gaussian data (e.g., niter = 10000).
Forecasting binary time series The R package bsts allows you to estimate Bayesian structural time series models with binary targets by setting family = 'logit'. Note, though, that these models often require longer runs than Gaussia
16,605
Forecasting binary time series
The Hidden markov model is the sequential version of Naive Bayes. In naive bayes, you have a label with several possible values (in your case 0/1) and a set of features. The value for y is selected by modeling p(features | label) * p(label). In a hidden markov model, a sequence of labels is predicted by modeling p(label | previous label) and P(features | label).
Forecasting binary time series
The Hidden markov model is the sequential version of Naive Bayes. In naive bayes, you have a label with several possible values (in your case 0/1) and a set of features. The value for y is selected
Forecasting binary time series The Hidden markov model is the sequential version of Naive Bayes. In naive bayes, you have a label with several possible values (in your case 0/1) and a set of features. The value for y is selected by modeling p(features | label) * p(label). In a hidden markov model, a sequence of labels is predicted by modeling p(label | previous label) and P(features | label).
Forecasting binary time series The Hidden markov model is the sequential version of Naive Bayes. In naive bayes, you have a label with several possible values (in your case 0/1) and a set of features. The value for y is selected
16,606
Forecasting binary time series
How about using logistic regression with some time lags (daily, weekly) as predictors? (most statistical software packages have logistic regression). It's a bit of shooting in the dark -- can you share the data or a plot?
Forecasting binary time series
How about using logistic regression with some time lags (daily, weekly) as predictors? (most statistical software packages have logistic regression). It's a bit of shooting in the dark -- can you shar
Forecasting binary time series How about using logistic regression with some time lags (daily, weekly) as predictors? (most statistical software packages have logistic regression). It's a bit of shooting in the dark -- can you share the data or a plot?
Forecasting binary time series How about using logistic regression with some time lags (daily, weekly) as predictors? (most statistical software packages have logistic regression). It's a bit of shooting in the dark -- can you shar
16,607
How do you calculate confidence intervals for Cohen's d?
According to p238 of standard text on meta-analysis in social science The Handbook of Research Synthesis, the variance of Cohen's $d$ is $$\left( \frac{n_1 + n_2}{n_1 n_2} + \frac{d^2}{2(n_1+n_2-2)}\right) \left(\frac{n_1 + n_2}{n_1+n_2-2} \right), $$ where $n_1$ and $n_2$ are the sample sizes of the two groups being compared and $d$ is Cohen's $d$. Taking the square-root of this variance gives the standard error of $d$, needed as input by several of the user-written meta-analysis packages for Stata. (Some of them also accept confidence intervals as input, but they simply convert them to standard errors internally anyway.)
How do you calculate confidence intervals for Cohen's d?
According to p238 of standard text on meta-analysis in social science The Handbook of Research Synthesis, the variance of Cohen's $d$ is $$\left( \frac{n_1 + n_2}{n_1 n_2} + \frac{d^2}{2(n_1+n_2-2)}\r
How do you calculate confidence intervals for Cohen's d? According to p238 of standard text on meta-analysis in social science The Handbook of Research Synthesis, the variance of Cohen's $d$ is $$\left( \frac{n_1 + n_2}{n_1 n_2} + \frac{d^2}{2(n_1+n_2-2)}\right) \left(\frac{n_1 + n_2}{n_1+n_2-2} \right), $$ where $n_1$ and $n_2$ are the sample sizes of the two groups being compared and $d$ is Cohen's $d$. Taking the square-root of this variance gives the standard error of $d$, needed as input by several of the user-written meta-analysis packages for Stata. (Some of them also accept confidence intervals as input, but they simply convert them to standard errors internally anyway.)
How do you calculate confidence intervals for Cohen's d? According to p238 of standard text on meta-analysis in social science The Handbook of Research Synthesis, the variance of Cohen's $d$ is $$\left( \frac{n_1 + n_2}{n_1 n_2} + \frac{d^2}{2(n_1+n_2-2)}\r
16,608
How do you calculate confidence intervals for Cohen's d?
This is an old question, but someone may be looking for a quick answer (this is in R, but quite quick). The package MBESS provides a straightforward conversion tool. install.packages("MBESS") library(MBESS) e.g. ci.smd(smd=SOMEVAR,n.1=X, n.2=Y)
How do you calculate confidence intervals for Cohen's d?
This is an old question, but someone may be looking for a quick answer (this is in R, but quite quick). The package MBESS provides a straightforward conversion tool. install.packages("MBESS") library(
How do you calculate confidence intervals for Cohen's d? This is an old question, but someone may be looking for a quick answer (this is in R, but quite quick). The package MBESS provides a straightforward conversion tool. install.packages("MBESS") library(MBESS) e.g. ci.smd(smd=SOMEVAR,n.1=X, n.2=Y)
How do you calculate confidence intervals for Cohen's d? This is an old question, but someone may be looking for a quick answer (this is in R, but quite quick). The package MBESS provides a straightforward conversion tool. install.packages("MBESS") library(
16,609
Where do the full conditionals come from in Gibbs sampling?
Yes, you are right, the conditional distribution needs to be found analytically, but I think there are lots of examples where the full conditional distribution is easy to find, and has a far simpler form than the joint distribution. The intuition for this is as follows, in most "realistic" joint distributions $P(X_1,\dots,X_n)$, most of the $X_i$'s are generally conditionally independent of most of the other random variables. That is to say, some of the variables have local interactions, say $X_i$ depends on $X_{i-1}$ and $X_{i+1}$, but doesn't interact with everything, hence the conditional distributions should simplify significantly as $Pr(X_i|X_1, \dots, X_i) = Pr(X_i|X_{i-1}, X_{i+1})$
Where do the full conditionals come from in Gibbs sampling?
Yes, you are right, the conditional distribution needs to be found analytically, but I think there are lots of examples where the full conditional distribution is easy to find, and has a far simpler f
Where do the full conditionals come from in Gibbs sampling? Yes, you are right, the conditional distribution needs to be found analytically, but I think there are lots of examples where the full conditional distribution is easy to find, and has a far simpler form than the joint distribution. The intuition for this is as follows, in most "realistic" joint distributions $P(X_1,\dots,X_n)$, most of the $X_i$'s are generally conditionally independent of most of the other random variables. That is to say, some of the variables have local interactions, say $X_i$ depends on $X_{i-1}$ and $X_{i+1}$, but doesn't interact with everything, hence the conditional distributions should simplify significantly as $Pr(X_i|X_1, \dots, X_i) = Pr(X_i|X_{i-1}, X_{i+1})$
Where do the full conditionals come from in Gibbs sampling? Yes, you are right, the conditional distribution needs to be found analytically, but I think there are lots of examples where the full conditional distribution is easy to find, and has a far simpler f
16,610
Where do the full conditionals come from in Gibbs sampling?
I think you've missed the main advantage of algorithms like of Metropolis-Hastings. For Gibbs sampling, you will need to sample from the full conditionals. You are right, that is rarely easy to do. The main advantage of Metropolis-Hastings algorithms is that you can still sample one parameter at a time, but you only need to know the full conditionals up to proportionality. This is because the denominators cancel in the acceptance criteria function The unnormalized full conditionals are often available. For instance, in your example $P(x_1 | x_2,...,x_n) \propto P(x_1,...,x_n)$, which you have. You don't need to do any integrals analytically. In most applications, a lot more will likely cancel too. Programs like WinBugs/Jags typically take Metropolis-Hastings or slice sampling steps that only require the conditionals up to proportionality. These are easily available from the DAG. Given conjugacy, they also sometimes take straight Gibbs steps or fancy block stops.
Where do the full conditionals come from in Gibbs sampling?
I think you've missed the main advantage of algorithms like of Metropolis-Hastings. For Gibbs sampling, you will need to sample from the full conditionals. You are right, that is rarely easy to do. T
Where do the full conditionals come from in Gibbs sampling? I think you've missed the main advantage of algorithms like of Metropolis-Hastings. For Gibbs sampling, you will need to sample from the full conditionals. You are right, that is rarely easy to do. The main advantage of Metropolis-Hastings algorithms is that you can still sample one parameter at a time, but you only need to know the full conditionals up to proportionality. This is because the denominators cancel in the acceptance criteria function The unnormalized full conditionals are often available. For instance, in your example $P(x_1 | x_2,...,x_n) \propto P(x_1,...,x_n)$, which you have. You don't need to do any integrals analytically. In most applications, a lot more will likely cancel too. Programs like WinBugs/Jags typically take Metropolis-Hastings or slice sampling steps that only require the conditionals up to proportionality. These are easily available from the DAG. Given conjugacy, they also sometimes take straight Gibbs steps or fancy block stops.
Where do the full conditionals come from in Gibbs sampling? I think you've missed the main advantage of algorithms like of Metropolis-Hastings. For Gibbs sampling, you will need to sample from the full conditionals. You are right, that is rarely easy to do. T
16,611
Unbalanced mixed effect ANOVA for repeated measures
The lme/lmer functions from the nlme/lme4 packages are able to deal with unbalanced designs. You should make sure that time is a numeric variable. You would also probably want to test for different types of curves as well. The code will look something like this: library(lme4) #plot data with a plot per person including a regression line for each xyplot(heart.rate ~ time|id, groups=treatment, type= c("p", "r"), data=heart) #Mixed effects modelling #variation in intercept by participant lmera.1 <- lmer(heart.rate ~ treatment * time + (1|id), data=heart) #variation in intercept and slope without correlation between the two lmera.2 <- lmer(heart.rate ~ treatment * time + (1|id) + (0+time|id), data=heart) #As lmera.1 but with correlation between slope and intercept lmera.3 <- lmer(heart.rate ~ treatment * time + (1+time|id), data=heart) #Determine which random effects structure fits the data best anova(lmera.1, lmera.2, lmera.3) To get quadratic models use the formula "heart.rate ~ treatment * time * I(time^2) + (random effects)". Update: In this case where treatment is a between-subjects factor, I would stick with the model specifications above. I don't think the term (0+treatment|time) is one that you want included in the model, to me it doesn't make sense in this instance to treat time as a random-effects grouping variable. But to answer your question of "what does the correlation -0.504 mean between treat0 and treat1" this is the correlation coefficient between the two treatments where each time grouping is one pair of values. This makes more sense if id is the grouping factor and treatment is a within-subjects variable. Then you have an estimate of the correlation between the intercepts of the two conditions. Before making any conclusions about the model, refit it with lmera.2 and include REML=F. Then load the "languageR" package and run: plmera.2<-pvals.fnc(lmera.2) plmera.2 Then you can get p-values, but by the looks of it, there is probably a significant effect of time and a significant effect of treatment.
Unbalanced mixed effect ANOVA for repeated measures
The lme/lmer functions from the nlme/lme4 packages are able to deal with unbalanced designs. You should make sure that time is a numeric variable. You would also probably want to test for different ty
Unbalanced mixed effect ANOVA for repeated measures The lme/lmer functions from the nlme/lme4 packages are able to deal with unbalanced designs. You should make sure that time is a numeric variable. You would also probably want to test for different types of curves as well. The code will look something like this: library(lme4) #plot data with a plot per person including a regression line for each xyplot(heart.rate ~ time|id, groups=treatment, type= c("p", "r"), data=heart) #Mixed effects modelling #variation in intercept by participant lmera.1 <- lmer(heart.rate ~ treatment * time + (1|id), data=heart) #variation in intercept and slope without correlation between the two lmera.2 <- lmer(heart.rate ~ treatment * time + (1|id) + (0+time|id), data=heart) #As lmera.1 but with correlation between slope and intercept lmera.3 <- lmer(heart.rate ~ treatment * time + (1+time|id), data=heart) #Determine which random effects structure fits the data best anova(lmera.1, lmera.2, lmera.3) To get quadratic models use the formula "heart.rate ~ treatment * time * I(time^2) + (random effects)". Update: In this case where treatment is a between-subjects factor, I would stick with the model specifications above. I don't think the term (0+treatment|time) is one that you want included in the model, to me it doesn't make sense in this instance to treat time as a random-effects grouping variable. But to answer your question of "what does the correlation -0.504 mean between treat0 and treat1" this is the correlation coefficient between the two treatments where each time grouping is one pair of values. This makes more sense if id is the grouping factor and treatment is a within-subjects variable. Then you have an estimate of the correlation between the intercepts of the two conditions. Before making any conclusions about the model, refit it with lmera.2 and include REML=F. Then load the "languageR" package and run: plmera.2<-pvals.fnc(lmera.2) plmera.2 Then you can get p-values, but by the looks of it, there is probably a significant effect of time and a significant effect of treatment.
Unbalanced mixed effect ANOVA for repeated measures The lme/lmer functions from the nlme/lme4 packages are able to deal with unbalanced designs. You should make sure that time is a numeric variable. You would also probably want to test for different ty
16,612
What are the advantages of linear regression over quantile regression?
It is very often stated that minimizing least squared residuals is preferred over minimizing absolute residuals because of the reason that it is computationally simpler. But, it may also be better for other reasons. Namely, if the assumptions are true (and this is not so uncommon) then it provides a solution that is (on average) more accurate. Maximum likelihood Least squares regression and quantile regression (when performed by minimizing the absolute residuals) can be seen as maximizing the likelihood function for Gaussian/Laplace distributed errors, and are in this sense very much related. Gaussian distribution: $$f(x) = \frac{1}{\sqrt{2\pi \sigma^2}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}$$ with the log-likelihood being maximized when minimizing the sum of squared residuals $$\log \mathcal{L}(x) = -\frac{n}{2} \log (2 \pi) - n \log(\sigma) - \frac{1}{2\sigma^2} \underbrace{\sum_{i=1}^n (x_i-\mu)^2}_{\text{sum of squared residuals}} $$ Laplace distribution: $$f(x) = \frac{1}{2b} e^{-\frac{\vert x-\mu \vert}{b}}$$ with the log-likelihood being maximized when minimizing the sum of absolute residuals $$\log \mathcal{L}(x) = -n \log (2) - n \log(b) - \frac{1}{b} \underbrace{\sum_{i=1}^n |x_i-\mu|}_{\text{sum of absolute residuals}} $$ Note: the Laplace distribution and the sum of absolute residuals relates to the median, but it can be generalized to other quantiles by giving different weights to negative and positive residuals. Known error distribution When we know the error-distribution (when the assumptions are likely true) it makes sense to choose the associated likelihood function. Minimizing that function is more optimal. Very often the errors are (approximately) normal distributed. In that case using least squares is the best way to find the parameter $\mu$ (which relates to both the mean and the median). It is the best way because it has the lowest sample variance (lowest of all unbiased estimators). Or you can say more strongly: that it is stochastically dominant (see the illustration in this question comparing the distribution of the sample median and the sample mean). So, when the errors are normal distributed, then the sample mean is a better estimator of the distribution median than the sample median. The least squares regression is a more optimal estimator of the quantiles. It is better than using the least sum of absolute residuals. Because so many problems deal with normal distributed errors the use of the least squares method is very popular. To work with other type of distributions one can use the Generalized linear model. And, the method of iterative least squares, which can be used to solve GLMs, also works for the Laplace distribution (ie. for absolute deviations), which is equivalent to finding the median (or in the generalized version other quantiles). Unknown error distribution Robustness The median or other quantiles have the advantage that they are very robust regarding the type of distribution. The actual values do not matter much and the quantiles only care about the order. So no matter what the distribution is, minimizing the absolute residuals (which is equivalent to finding the quantiles) is working very well. The question becomes complex and broad here and it is dependent on what type of knowledge we have or do not have about the distribution function. For instance a distribution may be approximately normal distributed but only with some additional outliers. This can be dealt with by removing the outer values. This removal of the extreme values even works in estimating the location parameter of the Cauchy distribution where the truncated mean can be a better estimator than the median. So not only for the ideal situation when the assumptions hold, but also for some less ideal applications (e.g. additional outliers) there might be good robust methods that still use some form of a sum of squared residuals instead of sum of absolute residuals. I imagine that regression with truncated residuals might be computationally much more complex. So it may actually be quantile regression which is the type of regression that is performed because of the reason that it is computationally simpler (not simpler than ordinary least squares, but simpler than truncated least squares). Biased/unbiased Another issue is biased versus unbiased estimators. In the above I described the maximum likelihood estimate for the mean, ie the least squares solution, as a good or preferable estimator because it often has the lowest variance of all unbiased estimators (when the errors are normal distributed). But, biased estimators may be better (lower expected sum of squared error). This makes the question again broad and complex. There are many different estimators and many different situations to apply them. The use of an adapted sum of squared residuals loss function often works well to reduce the error (e.g. all kinds of regularization methods), but it may not need to work well for all cases. Intuitively it is not strange to imagine that, since the sum of squared residuals loss function often works well for all unbiased estimators, the optimal biased estimators is probably something close to a sum of squared residuals loss function.
What are the advantages of linear regression over quantile regression?
It is very often stated that minimizing least squared residuals is preferred over minimizing absolute residuals because of the reason that it is computationally simpler. But, it may also be better for
What are the advantages of linear regression over quantile regression? It is very often stated that minimizing least squared residuals is preferred over minimizing absolute residuals because of the reason that it is computationally simpler. But, it may also be better for other reasons. Namely, if the assumptions are true (and this is not so uncommon) then it provides a solution that is (on average) more accurate. Maximum likelihood Least squares regression and quantile regression (when performed by minimizing the absolute residuals) can be seen as maximizing the likelihood function for Gaussian/Laplace distributed errors, and are in this sense very much related. Gaussian distribution: $$f(x) = \frac{1}{\sqrt{2\pi \sigma^2}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}$$ with the log-likelihood being maximized when minimizing the sum of squared residuals $$\log \mathcal{L}(x) = -\frac{n}{2} \log (2 \pi) - n \log(\sigma) - \frac{1}{2\sigma^2} \underbrace{\sum_{i=1}^n (x_i-\mu)^2}_{\text{sum of squared residuals}} $$ Laplace distribution: $$f(x) = \frac{1}{2b} e^{-\frac{\vert x-\mu \vert}{b}}$$ with the log-likelihood being maximized when minimizing the sum of absolute residuals $$\log \mathcal{L}(x) = -n \log (2) - n \log(b) - \frac{1}{b} \underbrace{\sum_{i=1}^n |x_i-\mu|}_{\text{sum of absolute residuals}} $$ Note: the Laplace distribution and the sum of absolute residuals relates to the median, but it can be generalized to other quantiles by giving different weights to negative and positive residuals. Known error distribution When we know the error-distribution (when the assumptions are likely true) it makes sense to choose the associated likelihood function. Minimizing that function is more optimal. Very often the errors are (approximately) normal distributed. In that case using least squares is the best way to find the parameter $\mu$ (which relates to both the mean and the median). It is the best way because it has the lowest sample variance (lowest of all unbiased estimators). Or you can say more strongly: that it is stochastically dominant (see the illustration in this question comparing the distribution of the sample median and the sample mean). So, when the errors are normal distributed, then the sample mean is a better estimator of the distribution median than the sample median. The least squares regression is a more optimal estimator of the quantiles. It is better than using the least sum of absolute residuals. Because so many problems deal with normal distributed errors the use of the least squares method is very popular. To work with other type of distributions one can use the Generalized linear model. And, the method of iterative least squares, which can be used to solve GLMs, also works for the Laplace distribution (ie. for absolute deviations), which is equivalent to finding the median (or in the generalized version other quantiles). Unknown error distribution Robustness The median or other quantiles have the advantage that they are very robust regarding the type of distribution. The actual values do not matter much and the quantiles only care about the order. So no matter what the distribution is, minimizing the absolute residuals (which is equivalent to finding the quantiles) is working very well. The question becomes complex and broad here and it is dependent on what type of knowledge we have or do not have about the distribution function. For instance a distribution may be approximately normal distributed but only with some additional outliers. This can be dealt with by removing the outer values. This removal of the extreme values even works in estimating the location parameter of the Cauchy distribution where the truncated mean can be a better estimator than the median. So not only for the ideal situation when the assumptions hold, but also for some less ideal applications (e.g. additional outliers) there might be good robust methods that still use some form of a sum of squared residuals instead of sum of absolute residuals. I imagine that regression with truncated residuals might be computationally much more complex. So it may actually be quantile regression which is the type of regression that is performed because of the reason that it is computationally simpler (not simpler than ordinary least squares, but simpler than truncated least squares). Biased/unbiased Another issue is biased versus unbiased estimators. In the above I described the maximum likelihood estimate for the mean, ie the least squares solution, as a good or preferable estimator because it often has the lowest variance of all unbiased estimators (when the errors are normal distributed). But, biased estimators may be better (lower expected sum of squared error). This makes the question again broad and complex. There are many different estimators and many different situations to apply them. The use of an adapted sum of squared residuals loss function often works well to reduce the error (e.g. all kinds of regularization methods), but it may not need to work well for all cases. Intuitively it is not strange to imagine that, since the sum of squared residuals loss function often works well for all unbiased estimators, the optimal biased estimators is probably something close to a sum of squared residuals loss function.
What are the advantages of linear regression over quantile regression? It is very often stated that minimizing least squared residuals is preferred over minimizing absolute residuals because of the reason that it is computationally simpler. But, it may also be better for
16,613
What are the advantages of linear regression over quantile regression?
Linear regression (LR) boils down to least squares optimization when computing its coefficients. This implies a symmetry in the deviations from the regression model. A good explanation of quantile regression (QR) is in https://data.library.virginia.edu/getting-started-with-quantile-regression/. If LR assumptions (needed for inference: p-values, confidence intervals, etc.) are satisfied QR and LR predictions will be similar. But if the assumptions are strongly violated, your standard LR inference will be wrong. So a 0.5 quantile (median) regression presents an advantage over LR. It also gives more flexibility in providing regression for other quantiles. The equivalent for linear models would be a confidence bound computed from a LR (although this would be wrong if iid is strongly violated). So what is the advantage of LR? Of course it's easier to compute but if your data set is of reasonable size that may not be very noticeable. But more importantly, the LR inference assumptions provide information that lowers uncertainty. As a result, LR confidence intervals on predictions will typically be narrower. So if there is strong theoretical support for the assumptions, narrower confidence intervals may be an advantage.
What are the advantages of linear regression over quantile regression?
Linear regression (LR) boils down to least squares optimization when computing its coefficients. This implies a symmetry in the deviations from the regression model. A good explanation of quantile reg
What are the advantages of linear regression over quantile regression? Linear regression (LR) boils down to least squares optimization when computing its coefficients. This implies a symmetry in the deviations from the regression model. A good explanation of quantile regression (QR) is in https://data.library.virginia.edu/getting-started-with-quantile-regression/. If LR assumptions (needed for inference: p-values, confidence intervals, etc.) are satisfied QR and LR predictions will be similar. But if the assumptions are strongly violated, your standard LR inference will be wrong. So a 0.5 quantile (median) regression presents an advantage over LR. It also gives more flexibility in providing regression for other quantiles. The equivalent for linear models would be a confidence bound computed from a LR (although this would be wrong if iid is strongly violated). So what is the advantage of LR? Of course it's easier to compute but if your data set is of reasonable size that may not be very noticeable. But more importantly, the LR inference assumptions provide information that lowers uncertainty. As a result, LR confidence intervals on predictions will typically be narrower. So if there is strong theoretical support for the assumptions, narrower confidence intervals may be an advantage.
What are the advantages of linear regression over quantile regression? Linear regression (LR) boils down to least squares optimization when computing its coefficients. This implies a symmetry in the deviations from the regression model. A good explanation of quantile reg
16,614
What are the advantages of linear regression over quantile regression?
Linear regression is used to estimate the conditional mean response given the data, i.e. $E(Y \vert X)$ where $Y$ is the response and $X$ is the data. The regression tells us that $E(Y \vert X)= X \beta$. There are certain assumptions (you can find them in any stats text) for inference to be valid. If these are satisfied then generally the standard estimator for $\beta$ is the BLUE (best linear unbiased estimator -- see Gauss-Markov theorem). Quantile regression can be used to estimate ANY quantile of the conditional distribution including the median. This provides potentially a lot more information than the mean about the conditional distribution. If the conditional distribution is not symmetric or the tails are possibly thick (e.g. risk analysis), quantile regression is helpful EVEN if all the assumptions of linear regression are satisfied. Of course, it is numerically more intensive to carry out quantile estimation relative to linear regression but it is generally much more robust (e.g. just as the median is more robust than the mean to outliers). In addition, it is appropriate when linear regression is not -- e.g. for censored data. Inference may be trickier as direct estimation of variance-covariance matrix may be difficult or computationally expensive. In those cases, one can bootstrap.
What are the advantages of linear regression over quantile regression?
Linear regression is used to estimate the conditional mean response given the data, i.e. $E(Y \vert X)$ where $Y$ is the response and $X$ is the data. The regression tells us that $E(Y \vert X)= X \be
What are the advantages of linear regression over quantile regression? Linear regression is used to estimate the conditional mean response given the data, i.e. $E(Y \vert X)$ where $Y$ is the response and $X$ is the data. The regression tells us that $E(Y \vert X)= X \beta$. There are certain assumptions (you can find them in any stats text) for inference to be valid. If these are satisfied then generally the standard estimator for $\beta$ is the BLUE (best linear unbiased estimator -- see Gauss-Markov theorem). Quantile regression can be used to estimate ANY quantile of the conditional distribution including the median. This provides potentially a lot more information than the mean about the conditional distribution. If the conditional distribution is not symmetric or the tails are possibly thick (e.g. risk analysis), quantile regression is helpful EVEN if all the assumptions of linear regression are satisfied. Of course, it is numerically more intensive to carry out quantile estimation relative to linear regression but it is generally much more robust (e.g. just as the median is more robust than the mean to outliers). In addition, it is appropriate when linear regression is not -- e.g. for censored data. Inference may be trickier as direct estimation of variance-covariance matrix may be difficult or computationally expensive. In those cases, one can bootstrap.
What are the advantages of linear regression over quantile regression? Linear regression is used to estimate the conditional mean response given the data, i.e. $E(Y \vert X)$ where $Y$ is the response and $X$ is the data. The regression tells us that $E(Y \vert X)= X \be
16,615
Why lasso for feature selection?
First, be careful in specifying what you mean by "the most important features" in a dataset. See this page for different perspectives on this issue. For example, features that are deemed "unimportant" individually might be needed to help improve predictions based on other features, so you might not want to throw them away. What LASSO does well is to provide a principled way to reduce the number of features in a model. In contrast, automated feature selection based on standard linear regression by stepwise selection or choosing features with the lowest p-values has many drawbacks. Advantages of LASSO over other regression-based approaches are specifically described here. LASSO involves a penalty factor that determines how many features are retained; using cross-validation to choose the penalty factor helps assure that the model will generalize well to future data samples. Ridge regression does not attempt to select features at all, it instead uses a penalty applied to the sum of the squares of all regression coefficients. Again, choice of penalty by cross-validation helps assure generalization. Elastic net can be thought of as a hybrid of LASSO with ridge. See this page for details on the differences among these penalized methods. If your main interest is in prediction and it's not too expensive to gather information about all the features, you might not need to do feature selection at all and instead use ridge regression to keep information about all the predictors in the model. If you need to cut down on the number of predictors for practical reasons, LASSO is a good choice. But all it does is give you a useful set of selected predictors, not necessarily the most important in some general sense. When features are correlated, LASSO will choose one or the other based on its performance in the particular data sample at hand. With a different sample it could well choose a different feature from a set of correlated features. This doesn't typically affect the predictive performance of the LASSO model, but it does give pause about what is meant by "the most important features." See this page for discussion about such instability in LASSO modeling.
Why lasso for feature selection?
First, be careful in specifying what you mean by "the most important features" in a dataset. See this page for different perspectives on this issue. For example, features that are deemed "unimportant"
Why lasso for feature selection? First, be careful in specifying what you mean by "the most important features" in a dataset. See this page for different perspectives on this issue. For example, features that are deemed "unimportant" individually might be needed to help improve predictions based on other features, so you might not want to throw them away. What LASSO does well is to provide a principled way to reduce the number of features in a model. In contrast, automated feature selection based on standard linear regression by stepwise selection or choosing features with the lowest p-values has many drawbacks. Advantages of LASSO over other regression-based approaches are specifically described here. LASSO involves a penalty factor that determines how many features are retained; using cross-validation to choose the penalty factor helps assure that the model will generalize well to future data samples. Ridge regression does not attempt to select features at all, it instead uses a penalty applied to the sum of the squares of all regression coefficients. Again, choice of penalty by cross-validation helps assure generalization. Elastic net can be thought of as a hybrid of LASSO with ridge. See this page for details on the differences among these penalized methods. If your main interest is in prediction and it's not too expensive to gather information about all the features, you might not need to do feature selection at all and instead use ridge regression to keep information about all the predictors in the model. If you need to cut down on the number of predictors for practical reasons, LASSO is a good choice. But all it does is give you a useful set of selected predictors, not necessarily the most important in some general sense. When features are correlated, LASSO will choose one or the other based on its performance in the particular data sample at hand. With a different sample it could well choose a different feature from a set of correlated features. This doesn't typically affect the predictive performance of the LASSO model, but it does give pause about what is meant by "the most important features." See this page for discussion about such instability in LASSO modeling.
Why lasso for feature selection? First, be careful in specifying what you mean by "the most important features" in a dataset. See this page for different perspectives on this issue. For example, features that are deemed "unimportant"
16,616
Measures of ordinal classification error for ordinal regression
Gaudette and Japkowicz 2009 compared various metrics for ordinal classification accuracy and they showed that, as a single statistic, the RMSE (root mean squared error) or MSE (mean squared error) performed better than the other measures that they found in the literature. Although RMSE/MSE is designed for continuous data, its property of penalizing deviations from the mean more severely works well for ordinal data converted to small integers. However, Baccianella et al 2009 showed that MAE (mean absolute error) performed very poorly for measuring performance when the ordinal categories were imbalanced in real-life data that they tested; they also implied that MSE also performs poorly. (They mentioned, though, that in an artificial dataset, the performance difference was not as severe.) So, they proposed an adapted measure which they called macroaveraged MAE that gives equal weight to all categories, thus nullifying the effects of imbalance. As far as I understand it, their adaptation basically calculates the MAE one category at a time and then takes the average of all categories, giving each category equal weight: see the article for details. However, they also showed that their adapted version of MAE was mathematically identical to the regular version when the categories were balanced. So, based on these two articles, I recommend that you attempt to use Baccianella's adapted version of MAE or MSE in general, especially if your target variable categories are significantly imbalanced. However, if the categories are balanced, then the simple RMSE or MSE should be a good measure, and might be preferred for its simplicity.
Measures of ordinal classification error for ordinal regression
Gaudette and Japkowicz 2009 compared various metrics for ordinal classification accuracy and they showed that, as a single statistic, the RMSE (root mean squared error) or MSE (mean squared error) per
Measures of ordinal classification error for ordinal regression Gaudette and Japkowicz 2009 compared various metrics for ordinal classification accuracy and they showed that, as a single statistic, the RMSE (root mean squared error) or MSE (mean squared error) performed better than the other measures that they found in the literature. Although RMSE/MSE is designed for continuous data, its property of penalizing deviations from the mean more severely works well for ordinal data converted to small integers. However, Baccianella et al 2009 showed that MAE (mean absolute error) performed very poorly for measuring performance when the ordinal categories were imbalanced in real-life data that they tested; they also implied that MSE also performs poorly. (They mentioned, though, that in an artificial dataset, the performance difference was not as severe.) So, they proposed an adapted measure which they called macroaveraged MAE that gives equal weight to all categories, thus nullifying the effects of imbalance. As far as I understand it, their adaptation basically calculates the MAE one category at a time and then takes the average of all categories, giving each category equal weight: see the article for details. However, they also showed that their adapted version of MAE was mathematically identical to the regular version when the categories were balanced. So, based on these two articles, I recommend that you attempt to use Baccianella's adapted version of MAE or MSE in general, especially if your target variable categories are significantly imbalanced. However, if the categories are balanced, then the simple RMSE or MSE should be a good measure, and might be preferred for its simplicity.
Measures of ordinal classification error for ordinal regression Gaudette and Japkowicz 2009 compared various metrics for ordinal classification accuracy and they showed that, as a single statistic, the RMSE (root mean squared error) or MSE (mean squared error) per
16,617
Measures of ordinal classification error for ordinal regression
Jianlin Cheng, A Neural Network Approach to Ordinal Regression, 2007 and Niu et al., Ordinal Regression with Multiple Output CNN for Age Estimation, 2016 utilize a clever representation of the labels to measure error with cross entropy. They present the the total error as the sum of errors in predicting whether or not the "rank" of a sample $x_i$ is greater than rank $k_i$. In other words, we would generate predictions of vectors with elements $r(x_i) > k_i$, representing the prediction of the classifier for whether or not the rank of the sample is greater than each rank. This becomes a multiclass classification problem and error functions for that problem can be utilized. Total error, then, can be considered a sum of the individual binary classifier loss functions (such as cross-entropy). E.g., Predicted rank = 2 results in a predicted vector = [1, 0, 0]. Actual rank = 3 results in a label vector = [1, 1, 0]. Then calculate loss between each prediction in the vector. Another explanation of this method can be found here.
Measures of ordinal classification error for ordinal regression
Jianlin Cheng, A Neural Network Approach to Ordinal Regression, 2007 and Niu et al., Ordinal Regression with Multiple Output CNN for Age Estimation, 2016 utilize a clever representation of the labels
Measures of ordinal classification error for ordinal regression Jianlin Cheng, A Neural Network Approach to Ordinal Regression, 2007 and Niu et al., Ordinal Regression with Multiple Output CNN for Age Estimation, 2016 utilize a clever representation of the labels to measure error with cross entropy. They present the the total error as the sum of errors in predicting whether or not the "rank" of a sample $x_i$ is greater than rank $k_i$. In other words, we would generate predictions of vectors with elements $r(x_i) > k_i$, representing the prediction of the classifier for whether or not the rank of the sample is greater than each rank. This becomes a multiclass classification problem and error functions for that problem can be utilized. Total error, then, can be considered a sum of the individual binary classifier loss functions (such as cross-entropy). E.g., Predicted rank = 2 results in a predicted vector = [1, 0, 0]. Actual rank = 3 results in a label vector = [1, 1, 0]. Then calculate loss between each prediction in the vector. Another explanation of this method can be found here.
Measures of ordinal classification error for ordinal regression Jianlin Cheng, A Neural Network Approach to Ordinal Regression, 2007 and Niu et al., Ordinal Regression with Multiple Output CNN for Age Estimation, 2016 utilize a clever representation of the labels
16,618
Measures of ordinal classification error for ordinal regression
This problem can be converted to regular regression by simply casting the ranks of the respective labels into integers. E.g., "HIGH" = 2, "MEDIUM"=1, "LOW"=0. Regression loss functions can then be used.
Measures of ordinal classification error for ordinal regression
This problem can be converted to regular regression by simply casting the ranks of the respective labels into integers. E.g., "HIGH" = 2, "MEDIUM"=1, "LOW"=0. Regression loss functions can then be use
Measures of ordinal classification error for ordinal regression This problem can be converted to regular regression by simply casting the ranks of the respective labels into integers. E.g., "HIGH" = 2, "MEDIUM"=1, "LOW"=0. Regression loss functions can then be used.
Measures of ordinal classification error for ordinal regression This problem can be converted to regular regression by simply casting the ranks of the respective labels into integers. E.g., "HIGH" = 2, "MEDIUM"=1, "LOW"=0. Regression loss functions can then be use
16,619
Generalized additive models (GAMs), interactions, and covariates
Q1 What's the difference between models 3 and 4? Model 3 is a purely additive model $$y = \alpha + f_1(x) + f_2(w) + \varepsilon$$ so we have a constant $\alpha$ plus the smooth effect of $x$ plus the smooth effect of $w$. Model 4 is a smooth interaction of two continuous variables $$y = \alpha + f_1(x, w) + \varepsilon$$ In a practical sense, Model 3 says that no matter what the effect of $w$, the effect of $x$ on the response is the same; if we fix $x$ at some known value and vary $w$ over some range, the contributions from $f_1(x)$ to the fitted model remains the same. Verify this if you want by predict()-ing from model 3 for a fixed value of x and a few different values of w and use the type = 'terms' argument of the predict() method. You'll see a constant contribution to the fitted/predicted values for s(x). This is not the case of model 4; this model says that the smooth effect of $x$ varies smoothly with the value of $w$ and vice-versa. Note that unless $x$ and $w$ are in the same units or we expect the same wiggliness in both variables, you should be using te() to fit the interaction. m4a <- gam(y ~ te(x, w), data = data.ex, method = 'REML') pdata <- mutate(data.ex, Fittedm4a = predict(m4a)) ggplot(pdata, aes(x = x, y = y)) + geom_point() + geom_line(aes(y = Fittedm4a), col = 'red') In one sense, model 4 is fitting $$y = \alpha + f_1(x) + f_2(w) + f_3(x, w) + \varepsilon$$ where $f_3$ is the pure smooth interaction of the "main" smooth effects of $x$ and $w$, and which have been removed, for sake of identifiability, from the basis of $f_3$. You can get this model via m4b <- gam(y ~ ti(x) + ti(w) + ti(x, w), data = data.ex, method = 'REML') but note this estimates 4 smoothness parameters: the one associated with the main smooth effect of $x$ the one associated with the main smooth effect of $w$ the one associated with the marginal smooth of $x$ in the interaction tensor product smooth the one associated with the marginal smooth of $w$ in the interaction tensor product smooth The te() model contains just two smoothness parameters, one per marginal basis. A fundamental problem with all these models is that the effect of $w$ is not strictly smooth; there's a discontinuity where the effect of $w$ falls to 0 (or 1 in w2). This is showing up in your plots (and the one I show in detail here). Q2 What, exactly, is "by" doing here? by variable smooths can do a number of different things depending on what you pass to the by argument. In your examples the by variable, $w$ is continuous. In that case what you get a varying coefficient model. This is a model in which the linear effect of $w$ varies smoothly with $x$. In equation terms this is what your, say model 5, is doing $$y = \alpha + f_1(x)w + \varepsilon$$ If this isn't immediately clear (it wasn't to me when I first looked at these models) for some given values of $x$ we evaluate the smooth function at this value and this then become the equivalent of $\beta_1 w$; in other words, it is the linear effect of $w$ at the given value of $x$, and those linear effects vary smoothly with $x$. See section 7.5.3 in the second edition of Simon's book for a concrete example where the linear effect of a covariate varies a smooth function of space (lat and long). Q3 Why would there be such a notable difference between Models 5 and 9? The difference between models 5 and 9 I think is simply due to multiplying by 0 or multiplying by 1. With the former, the effect of the only term in the model $f_1(x)w$ is 0 because $f_1(x) \times 0 = 0$. In model 9 you have $f_1(x) \times 1 = f_1(x)$ in those areas where there is no contribution from the gaussians of $w$. As $f_1(x)$ is an ~ exponential function, you get this superimposed upon the overall effect of $w$. In other words, model 5 contains zero trend everywhere $w$ is 0, but model 9 includes an ~ exponential trend everywhere $w$ is 0 (1), upon which the varying coefficient effect of $w$ is superimposed.
Generalized additive models (GAMs), interactions, and covariates
Q1 What's the difference between models 3 and 4? Model 3 is a purely additive model $$y = \alpha + f_1(x) + f_2(w) + \varepsilon$$ so we have a constant $\alpha$ plus the smooth effect of $x$ plus the
Generalized additive models (GAMs), interactions, and covariates Q1 What's the difference between models 3 and 4? Model 3 is a purely additive model $$y = \alpha + f_1(x) + f_2(w) + \varepsilon$$ so we have a constant $\alpha$ plus the smooth effect of $x$ plus the smooth effect of $w$. Model 4 is a smooth interaction of two continuous variables $$y = \alpha + f_1(x, w) + \varepsilon$$ In a practical sense, Model 3 says that no matter what the effect of $w$, the effect of $x$ on the response is the same; if we fix $x$ at some known value and vary $w$ over some range, the contributions from $f_1(x)$ to the fitted model remains the same. Verify this if you want by predict()-ing from model 3 for a fixed value of x and a few different values of w and use the type = 'terms' argument of the predict() method. You'll see a constant contribution to the fitted/predicted values for s(x). This is not the case of model 4; this model says that the smooth effect of $x$ varies smoothly with the value of $w$ and vice-versa. Note that unless $x$ and $w$ are in the same units or we expect the same wiggliness in both variables, you should be using te() to fit the interaction. m4a <- gam(y ~ te(x, w), data = data.ex, method = 'REML') pdata <- mutate(data.ex, Fittedm4a = predict(m4a)) ggplot(pdata, aes(x = x, y = y)) + geom_point() + geom_line(aes(y = Fittedm4a), col = 'red') In one sense, model 4 is fitting $$y = \alpha + f_1(x) + f_2(w) + f_3(x, w) + \varepsilon$$ where $f_3$ is the pure smooth interaction of the "main" smooth effects of $x$ and $w$, and which have been removed, for sake of identifiability, from the basis of $f_3$. You can get this model via m4b <- gam(y ~ ti(x) + ti(w) + ti(x, w), data = data.ex, method = 'REML') but note this estimates 4 smoothness parameters: the one associated with the main smooth effect of $x$ the one associated with the main smooth effect of $w$ the one associated with the marginal smooth of $x$ in the interaction tensor product smooth the one associated with the marginal smooth of $w$ in the interaction tensor product smooth The te() model contains just two smoothness parameters, one per marginal basis. A fundamental problem with all these models is that the effect of $w$ is not strictly smooth; there's a discontinuity where the effect of $w$ falls to 0 (or 1 in w2). This is showing up in your plots (and the one I show in detail here). Q2 What, exactly, is "by" doing here? by variable smooths can do a number of different things depending on what you pass to the by argument. In your examples the by variable, $w$ is continuous. In that case what you get a varying coefficient model. This is a model in which the linear effect of $w$ varies smoothly with $x$. In equation terms this is what your, say model 5, is doing $$y = \alpha + f_1(x)w + \varepsilon$$ If this isn't immediately clear (it wasn't to me when I first looked at these models) for some given values of $x$ we evaluate the smooth function at this value and this then become the equivalent of $\beta_1 w$; in other words, it is the linear effect of $w$ at the given value of $x$, and those linear effects vary smoothly with $x$. See section 7.5.3 in the second edition of Simon's book for a concrete example where the linear effect of a covariate varies a smooth function of space (lat and long). Q3 Why would there be such a notable difference between Models 5 and 9? The difference between models 5 and 9 I think is simply due to multiplying by 0 or multiplying by 1. With the former, the effect of the only term in the model $f_1(x)w$ is 0 because $f_1(x) \times 0 = 0$. In model 9 you have $f_1(x) \times 1 = f_1(x)$ in those areas where there is no contribution from the gaussians of $w$. As $f_1(x)$ is an ~ exponential function, you get this superimposed upon the overall effect of $w$. In other words, model 5 contains zero trend everywhere $w$ is 0, but model 9 includes an ~ exponential trend everywhere $w$ is 0 (1), upon which the varying coefficient effect of $w$ is superimposed.
Generalized additive models (GAMs), interactions, and covariates Q1 What's the difference between models 3 and 4? Model 3 is a purely additive model $$y = \alpha + f_1(x) + f_2(w) + \varepsilon$$ so we have a constant $\alpha$ plus the smooth effect of $x$ plus the
16,620
Terms "cut off" and "tail off" about ACF, PACF functions
"Cuts off" means that it becomes zero abruptly, and "tails off" means that it decays to zero asymptotically (usually exponentially). In your picture, the PACF "cuts off" after the 2nd lag, while the ACF "tails off" to zero. You probably have something like an AR(2).
Terms "cut off" and "tail off" about ACF, PACF functions
"Cuts off" means that it becomes zero abruptly, and "tails off" means that it decays to zero asymptotically (usually exponentially). In your picture, the PACF "cuts off" after the 2nd lag, while the A
Terms "cut off" and "tail off" about ACF, PACF functions "Cuts off" means that it becomes zero abruptly, and "tails off" means that it decays to zero asymptotically (usually exponentially). In your picture, the PACF "cuts off" after the 2nd lag, while the ACF "tails off" to zero. You probably have something like an AR(2).
Terms "cut off" and "tail off" about ACF, PACF functions "Cuts off" means that it becomes zero abruptly, and "tails off" means that it decays to zero asymptotically (usually exponentially). In your picture, the PACF "cuts off" after the 2nd lag, while the A
16,621
State of the art in general learning from data in '69
I was curious about this, so I did some digging. I was surprised to find that recognizable versions of many common classification algorithms were already available in 1969 or thereabouts. Links and citations are given below. It is worth noting that AI research was not always so focused on classification. There was a lot of interest in planning and symbolic reasoning, which are no longer in vogue, and labelled data was much harder to find. Not all of these articles may have been widely available then either: for example, the proto-SVM work was mostly published in Russian. Thus, this might over-estimate how much an average scientist knew about classification in 1969. Discriminant Analysis In a 1936 article in the Annals of Eugenics, Fisher described a procedure for finding a linear function which discriminates between three species of iris flowers, on the basis of their petal and sepal dimensions. That paper mentions that Fisher had already applied a similar technique to predict the sex of human mandibles (jaw bones) excavated in Egypt, in a collaboration with E. S Martin and Karl Pearson (jstor), as well as in a separate cranial measurement project with a Miss Mildred Barnard (which I couldn't track down). Logistic Regression The logistic function itself has been known since the 19th century, but mostly as a model for saturating processes, such as population growth or biochemical reactions. Tim links to JS Cramer's article above, which is a nice history of its early days. By 1969, however, Cox had published the first edition of Analysis of Binary Data. I could not find the original, but a later edition contains an entire chapter on using logistic regression to perform classification. For example: In discriminant analysis, the primary notion is that there are two distinct populations, defined by $y=0,1$, usually two intrinsically different groups, like two species of bacteria or plants, two different kinds of product, two distinct but rather similar drugs, and so on....Esentially the focus in discriminant analysis is on the question: how do the two distributions differ most sharply? Often, this is put into a more specific form as follows. There is given a new vector $x'$ from an individual of unknown $y$. What can we say about that $y$.... $k$-Nearest Neighbors Cover and Hart are often credited with inventing/discovering the $k$-nearest neighbor rule. Their 1967 paper contains a proof that $k$-NN's error rate is at most twice the Bayes error rate. However, they actually credit Fix and Hodge with inventing it in 1951, citing a technical report they prepared for the USAF School of Aviation Medicine (reprint via jstor). Neural networks Rosenblatt published a technical report describing the perceptron in 1957 and followed it up with a book, Principles of Neurodynamics in 1962. Continuous versions of backpropagation have been around since the early 1960s, including work by Kelley, Bryson, and Bryson & Ho (revised in 1975, but the original is from 1969. However, it wasn't applied to neural networks until a bit later, and methods for training very deep networks are much more recent. This scholarpedia article on deep learning has more information. Statistical Methods I suspect using Bayes' Rule for classification has been discovered and rediscovered many times--it is a pretty natural consequence of the rule itself. Signal detection theory developed a quantitative framework for deciding whether a given input was a "signal" or noise. Some of it came out of radar research after WWII, but it was rapidly adapted for perceptual experiments (e.g., by Green and Swets). I do not know who discovered that assuming independence between predictors works well, but work from the early 1970s seems to have exploited this idea, as summarized in this article. Incidentally, that article also points out that Naive Bayes was once called "idiot Bayes"! Support Vector Machines In 1962, Vapnik and Chervonenkis described the "Generalised Portrait Algorithm" (terrible scan, sorry), which looks like a special case of a support vector machine (or actually, a one-class SVM). Chervonenkis wrote an article entitled "Early History of Support Vector Machines" which describes this and their follow-up work in more detail. The kernel trick (kernels as inner products) was described by Aizerman, Braverman and Rozonoer in 1964. svms.org has a bit more about the history of support vector machines here.
State of the art in general learning from data in '69
I was curious about this, so I did some digging. I was surprised to find that recognizable versions of many common classification algorithms were already available in 1969 or thereabouts. Links and c
State of the art in general learning from data in '69 I was curious about this, so I did some digging. I was surprised to find that recognizable versions of many common classification algorithms were already available in 1969 or thereabouts. Links and citations are given below. It is worth noting that AI research was not always so focused on classification. There was a lot of interest in planning and symbolic reasoning, which are no longer in vogue, and labelled data was much harder to find. Not all of these articles may have been widely available then either: for example, the proto-SVM work was mostly published in Russian. Thus, this might over-estimate how much an average scientist knew about classification in 1969. Discriminant Analysis In a 1936 article in the Annals of Eugenics, Fisher described a procedure for finding a linear function which discriminates between three species of iris flowers, on the basis of their petal and sepal dimensions. That paper mentions that Fisher had already applied a similar technique to predict the sex of human mandibles (jaw bones) excavated in Egypt, in a collaboration with E. S Martin and Karl Pearson (jstor), as well as in a separate cranial measurement project with a Miss Mildred Barnard (which I couldn't track down). Logistic Regression The logistic function itself has been known since the 19th century, but mostly as a model for saturating processes, such as population growth or biochemical reactions. Tim links to JS Cramer's article above, which is a nice history of its early days. By 1969, however, Cox had published the first edition of Analysis of Binary Data. I could not find the original, but a later edition contains an entire chapter on using logistic regression to perform classification. For example: In discriminant analysis, the primary notion is that there are two distinct populations, defined by $y=0,1$, usually two intrinsically different groups, like two species of bacteria or plants, two different kinds of product, two distinct but rather similar drugs, and so on....Esentially the focus in discriminant analysis is on the question: how do the two distributions differ most sharply? Often, this is put into a more specific form as follows. There is given a new vector $x'$ from an individual of unknown $y$. What can we say about that $y$.... $k$-Nearest Neighbors Cover and Hart are often credited with inventing/discovering the $k$-nearest neighbor rule. Their 1967 paper contains a proof that $k$-NN's error rate is at most twice the Bayes error rate. However, they actually credit Fix and Hodge with inventing it in 1951, citing a technical report they prepared for the USAF School of Aviation Medicine (reprint via jstor). Neural networks Rosenblatt published a technical report describing the perceptron in 1957 and followed it up with a book, Principles of Neurodynamics in 1962. Continuous versions of backpropagation have been around since the early 1960s, including work by Kelley, Bryson, and Bryson & Ho (revised in 1975, but the original is from 1969. However, it wasn't applied to neural networks until a bit later, and methods for training very deep networks are much more recent. This scholarpedia article on deep learning has more information. Statistical Methods I suspect using Bayes' Rule for classification has been discovered and rediscovered many times--it is a pretty natural consequence of the rule itself. Signal detection theory developed a quantitative framework for deciding whether a given input was a "signal" or noise. Some of it came out of radar research after WWII, but it was rapidly adapted for perceptual experiments (e.g., by Green and Swets). I do not know who discovered that assuming independence between predictors works well, but work from the early 1970s seems to have exploited this idea, as summarized in this article. Incidentally, that article also points out that Naive Bayes was once called "idiot Bayes"! Support Vector Machines In 1962, Vapnik and Chervonenkis described the "Generalised Portrait Algorithm" (terrible scan, sorry), which looks like a special case of a support vector machine (or actually, a one-class SVM). Chervonenkis wrote an article entitled "Early History of Support Vector Machines" which describes this and their follow-up work in more detail. The kernel trick (kernels as inner products) was described by Aizerman, Braverman and Rozonoer in 1964. svms.org has a bit more about the history of support vector machines here.
State of the art in general learning from data in '69 I was curious about this, so I did some digging. I was surprised to find that recognizable versions of many common classification algorithms were already available in 1969 or thereabouts. Links and c
16,622
State of the art in general learning from data in '69
DISCLAIMER: This answer is incomplete, but I don't have time to make it current right now. I hope to work on it later this week. Question: what were the state-of-the-art methods of solving genera problems of predicting from data circa 1969? Note: this is not going to repeat the excellent answer by 'Matt Krause'. "State of the Art" means "best and most modern" but not necessarily reduced to practice as an industry norm. In contrast, US Patent law looks for "non-obvious" as defined by "ordinary skill in the art". The "state of the art" for 1969 was likely put into patents over the next decade. It is extremely likely that the "best and brightest" approaches of 1969 were used or evaluated for use in ECHELON (1) (2). It will also show in evaluation of the other, quite mathematically capable superpower of the era, the USSR. (3) I takes several years to fabricate a satellite, and so one would also expect that the technology or content for the next ~5 years of communication, telemetry, or reconnaissance satellites to show the state of the art of 1969. One example is the Meteor-2 weather satellite started in 1967 and with preliminary design completed in 1971. (4) The spectrometric and actinometric payloads engineering is informed by the data-processing capabilities of the day, and by the envisioned "near-future" data handling of the time. The processing of this sort of data is where to look for best practices of the period. A perusal of the "Journal of Optimization Theory and Applications" had been operating for several years and has its contents accessible. (5) Consider this (6) evaluation of optimal estimators, and this one for recursive estimators. (7) The SETI project, started in the 1970's, was likely using lower budget technology and techniques that were older to fit the technology of the time. Exploration of the early SETI techniques can also speak to what was considered leading around 1969. One likely candidate is the precurser to "suitcase SETI". The "suitcase SETI" used DSP to build autocorrelation receivers in ~130k narrow-band channels. The SETI folks were particularly looking to perform spectrum analysis. The approach was first used offline to process Aricebo data. It was later connected it to the Aricebo radio telescope in 1978 for live data and result were published the same year. The actual Suitecase-SETI was completed in 1982. Here (link) is a block diagram showing the process. The approach was to use off-line long-Fourier transforms (~64k samples) to search bandwidth segments including handling chirp, and real-time compensation for Doppler shift. The approach is "not new" and references were provided including: See, for instance, A. G. W. Cameron, Ed., In- terstellar Communication (Benjamin, New York,1963); I. S. Shklovskii and C. Sagan, In-telligent Life in the Universe (Holden-Day, San Francisco, 1966); C. Sagan, Ed., Communication with Extraterrestrial Intelligence (MIT Press, Cambridge, Mass., 1973); P. Morrison, J. B. M. Oliver and J. Billingham, "Project Cyclops: A Design Study of a System for Detecting Extraterrestrial Intelligent Life," NASA Contract. Rep. CR114445 (1973). Tools used for prediction of the next state given the previous state that were popular at the time include: Kalman (and derivative) filters (Weiner, Bucy, nonlinear...) Time series (and derivative) methods Frequency domain methods (Fourier) including filtering, and amplification Common "keywords" (or buzz-words) include "adjoint, variational, gradient, optimal, second order, and conjugate". The premise of a Kalman filter is optimal mixing of real world data with an analytic and predictive model. They were used for making things like missiles hit a moving target.
State of the art in general learning from data in '69
DISCLAIMER: This answer is incomplete, but I don't have time to make it current right now. I hope to work on it later this week. Question: what were the state-of-the-art methods of solving genera pr
State of the art in general learning from data in '69 DISCLAIMER: This answer is incomplete, but I don't have time to make it current right now. I hope to work on it later this week. Question: what were the state-of-the-art methods of solving genera problems of predicting from data circa 1969? Note: this is not going to repeat the excellent answer by 'Matt Krause'. "State of the Art" means "best and most modern" but not necessarily reduced to practice as an industry norm. In contrast, US Patent law looks for "non-obvious" as defined by "ordinary skill in the art". The "state of the art" for 1969 was likely put into patents over the next decade. It is extremely likely that the "best and brightest" approaches of 1969 were used or evaluated for use in ECHELON (1) (2). It will also show in evaluation of the other, quite mathematically capable superpower of the era, the USSR. (3) I takes several years to fabricate a satellite, and so one would also expect that the technology or content for the next ~5 years of communication, telemetry, or reconnaissance satellites to show the state of the art of 1969. One example is the Meteor-2 weather satellite started in 1967 and with preliminary design completed in 1971. (4) The spectrometric and actinometric payloads engineering is informed by the data-processing capabilities of the day, and by the envisioned "near-future" data handling of the time. The processing of this sort of data is where to look for best practices of the period. A perusal of the "Journal of Optimization Theory and Applications" had been operating for several years and has its contents accessible. (5) Consider this (6) evaluation of optimal estimators, and this one for recursive estimators. (7) The SETI project, started in the 1970's, was likely using lower budget technology and techniques that were older to fit the technology of the time. Exploration of the early SETI techniques can also speak to what was considered leading around 1969. One likely candidate is the precurser to "suitcase SETI". The "suitcase SETI" used DSP to build autocorrelation receivers in ~130k narrow-band channels. The SETI folks were particularly looking to perform spectrum analysis. The approach was first used offline to process Aricebo data. It was later connected it to the Aricebo radio telescope in 1978 for live data and result were published the same year. The actual Suitecase-SETI was completed in 1982. Here (link) is a block diagram showing the process. The approach was to use off-line long-Fourier transforms (~64k samples) to search bandwidth segments including handling chirp, and real-time compensation for Doppler shift. The approach is "not new" and references were provided including: See, for instance, A. G. W. Cameron, Ed., In- terstellar Communication (Benjamin, New York,1963); I. S. Shklovskii and C. Sagan, In-telligent Life in the Universe (Holden-Day, San Francisco, 1966); C. Sagan, Ed., Communication with Extraterrestrial Intelligence (MIT Press, Cambridge, Mass., 1973); P. Morrison, J. B. M. Oliver and J. Billingham, "Project Cyclops: A Design Study of a System for Detecting Extraterrestrial Intelligent Life," NASA Contract. Rep. CR114445 (1973). Tools used for prediction of the next state given the previous state that were popular at the time include: Kalman (and derivative) filters (Weiner, Bucy, nonlinear...) Time series (and derivative) methods Frequency domain methods (Fourier) including filtering, and amplification Common "keywords" (or buzz-words) include "adjoint, variational, gradient, optimal, second order, and conjugate". The premise of a Kalman filter is optimal mixing of real world data with an analytic and predictive model. They were used for making things like missiles hit a moving target.
State of the art in general learning from data in '69 DISCLAIMER: This answer is incomplete, but I don't have time to make it current right now. I hope to work on it later this week. Question: what were the state-of-the-art methods of solving genera pr
16,623
How to develop intuition for conditional probability?
To aid the intuition, consider visualizing two events (sets of outcomes): The conditioning event, which is the information given. The conditioned event, whose probability you would like to find. The conditional probability is found by dividing the chance of the second by the chance of the first. There are $52 \times 51$ equally likely ways to deal two cards at random. A convenient way to visualize these deals is to lay them out in a table with rows (say) designating the first card dealt and columns the second card in the deal. Here is a part of this table, with ellipses ($\cdots$) designating the missing parts. Notice that because the two cards cannot be the same, no entries exist along the main diagonal of the table. The rows and columns are ordered from aces up through kings: The questions focus on aces. The information "we have at least one ace" locates the pair within either the first four rows or the first four columns. In our mind we can visualize that schematically by coloring these rows and columns. I have colored them red, but where both aces appear I have colored them black: There are $2\times 6 = 12$ pairs of all aces and $2\times (4\times 48) = 384$ other pairs with at least one ace, for a total of $12+384=396$ pairs on which you are conditioning, as represented by both the red and black areas. Because all such pairs are equally likely, the chance of the former is $$\frac{12}{396} = \frac{1}{33}.$$ It is the black fraction of the red+black region. The second question asserts "we have the ace of spades." This corresponds only to the very first row and column: Now there are just $2\times 3 = 6$ such pairs with two aces and $2\times 48=96$ other pairs with the ace of spades, for a total of $96+6 = 102$ such pairs. Reasoning exactly as before, the chance of two aces is $$\frac{6}{102} = \frac{1}{17}.$$ Again it is the black fraction of the red+black region. For reference, the last figure includes the previous one shown in pink and gray. Comparing these regions reveals what happened: in going from the first question to the second, the number of pairs in the conditioning event (pink) dropped to about one-quarter of its original count (red), while the number of pairs in question dropped by only one-half (from gray to black, $12$ to $6$). I have found such schematic figures to be helpful even--perhaps especially--when trying to understand more complicated concepts of probability, such as filtrations of sigma algebras.
How to develop intuition for conditional probability?
To aid the intuition, consider visualizing two events (sets of outcomes): The conditioning event, which is the information given. The conditioned event, whose probability you would like to find. The
How to develop intuition for conditional probability? To aid the intuition, consider visualizing two events (sets of outcomes): The conditioning event, which is the information given. The conditioned event, whose probability you would like to find. The conditional probability is found by dividing the chance of the second by the chance of the first. There are $52 \times 51$ equally likely ways to deal two cards at random. A convenient way to visualize these deals is to lay them out in a table with rows (say) designating the first card dealt and columns the second card in the deal. Here is a part of this table, with ellipses ($\cdots$) designating the missing parts. Notice that because the two cards cannot be the same, no entries exist along the main diagonal of the table. The rows and columns are ordered from aces up through kings: The questions focus on aces. The information "we have at least one ace" locates the pair within either the first four rows or the first four columns. In our mind we can visualize that schematically by coloring these rows and columns. I have colored them red, but where both aces appear I have colored them black: There are $2\times 6 = 12$ pairs of all aces and $2\times (4\times 48) = 384$ other pairs with at least one ace, for a total of $12+384=396$ pairs on which you are conditioning, as represented by both the red and black areas. Because all such pairs are equally likely, the chance of the former is $$\frac{12}{396} = \frac{1}{33}.$$ It is the black fraction of the red+black region. The second question asserts "we have the ace of spades." This corresponds only to the very first row and column: Now there are just $2\times 3 = 6$ such pairs with two aces and $2\times 48=96$ other pairs with the ace of spades, for a total of $96+6 = 102$ such pairs. Reasoning exactly as before, the chance of two aces is $$\frac{6}{102} = \frac{1}{17}.$$ Again it is the black fraction of the red+black region. For reference, the last figure includes the previous one shown in pink and gray. Comparing these regions reveals what happened: in going from the first question to the second, the number of pairs in the conditioning event (pink) dropped to about one-quarter of its original count (red), while the number of pairs in question dropped by only one-half (from gray to black, $12$ to $6$). I have found such schematic figures to be helpful even--perhaps especially--when trying to understand more complicated concepts of probability, such as filtrations of sigma algebras.
How to develop intuition for conditional probability? To aid the intuition, consider visualizing two events (sets of outcomes): The conditioning event, which is the information given. The conditioned event, whose probability you would like to find. The
16,624
How to develop intuition for conditional probability?
A different way to set up a problem that leads to the second calculation is the following: You draw two cards from the deck. What is the probability of two aces given that the first card you drew was an ace? This phrasing makes it easier to contrast with the first calculation. The underlying chance of having picked two aces does not change, but the condition to have the first card as an ace is more restrictive than the condition if either being an ace. This means that in the conditional probability calculation the desired combination has to occur among fewer options, so it has a larger probability. The two different phrasings (ace of spades versus first card as ace) are similar, because they break the symmetry / exchangeability between the aces: the suit or the order cannot be arbitrarily swapped.
How to develop intuition for conditional probability?
A different way to set up a problem that leads to the second calculation is the following: You draw two cards from the deck. What is the probability of two aces given that the first card you drew wa
How to develop intuition for conditional probability? A different way to set up a problem that leads to the second calculation is the following: You draw two cards from the deck. What is the probability of two aces given that the first card you drew was an ace? This phrasing makes it easier to contrast with the first calculation. The underlying chance of having picked two aces does not change, but the condition to have the first card as an ace is more restrictive than the condition if either being an ace. This means that in the conditional probability calculation the desired combination has to occur among fewer options, so it has a larger probability. The two different phrasings (ace of spades versus first card as ace) are similar, because they break the symmetry / exchangeability between the aces: the suit or the order cannot be arbitrarily swapped.
How to develop intuition for conditional probability? A different way to set up a problem that leads to the second calculation is the following: You draw two cards from the deck. What is the probability of two aces given that the first card you drew wa
16,625
How to develop intuition for conditional probability?
At the beginning it was hard to me to have some intuition about. One idea is to take the problem to the limit. In this case as Steve noted one identical problem is: My neighbor has two kids--you know that one of them is a boy. What's the probability that she has two boys. Thje first idea is, ok, I have one boy, the other child has 1/2 chance to be a girl and 1/2 to be a boy, but in this case you are not taking all the information that gives you the fact (at least you have a boy) because it is implicit that this boy can be the youngest child being the oldest a girl or viceversa or both are boys which means that only one of the three possible outcomes is favorable. As I said this is easier taking the problem to the limit... Case1: Abstract case identical to "we have one ace"-> In this case imagines My neighbour has not 2 children but 27, and you know 26 are boys, the probability of this is almost zero. In this case it is clear that this information gives you a lot of information that the probabilistically speaking the remain child is a girl. To be precise, you will have one case with 27 boys, let's say a tuple (b,b,b,b,b,b...,b) and 27 cases with 1 girl and 26 boys (g,b,b,b...), (b,g,b,b,b...), so the probability of all boys is 1/27, in general it will be 1/(N+1) case2: Concrete information. This would be identical to "We have the ace of spades" or "we have the first card being an ace". In this case imagine our neighbour have 26 children all boys and is pregnant with the 27th. What is the probability that the 27th will be a boy? With case2 I am pretty sure we all can have a grasp of the intuition needed for this kind of not-so-obvious conditional probabilities problems. If you want to become rich, you have to bet on the first case with 26 boys and a 27th because the lack of concrete information means a lot of probabilistic energy on the remain child while in the second case, the entropy is huge, we have not information to know where to bet. I hope this is useful
How to develop intuition for conditional probability?
At the beginning it was hard to me to have some intuition about. One idea is to take the problem to the limit. In this case as Steve noted one identical problem is: My neighbor has two kids--you know
How to develop intuition for conditional probability? At the beginning it was hard to me to have some intuition about. One idea is to take the problem to the limit. In this case as Steve noted one identical problem is: My neighbor has two kids--you know that one of them is a boy. What's the probability that she has two boys. Thje first idea is, ok, I have one boy, the other child has 1/2 chance to be a girl and 1/2 to be a boy, but in this case you are not taking all the information that gives you the fact (at least you have a boy) because it is implicit that this boy can be the youngest child being the oldest a girl or viceversa or both are boys which means that only one of the three possible outcomes is favorable. As I said this is easier taking the problem to the limit... Case1: Abstract case identical to "we have one ace"-> In this case imagines My neighbour has not 2 children but 27, and you know 26 are boys, the probability of this is almost zero. In this case it is clear that this information gives you a lot of information that the probabilistically speaking the remain child is a girl. To be precise, you will have one case with 27 boys, let's say a tuple (b,b,b,b,b,b...,b) and 27 cases with 1 girl and 26 boys (g,b,b,b...), (b,g,b,b,b...), so the probability of all boys is 1/27, in general it will be 1/(N+1) case2: Concrete information. This would be identical to "We have the ace of spades" or "we have the first card being an ace". In this case imagine our neighbour have 26 children all boys and is pregnant with the 27th. What is the probability that the 27th will be a boy? With case2 I am pretty sure we all can have a grasp of the intuition needed for this kind of not-so-obvious conditional probabilities problems. If you want to become rich, you have to bet on the first case with 26 boys and a 27th because the lack of concrete information means a lot of probabilistic energy on the remain child while in the second case, the entropy is huge, we have not information to know where to bet. I hope this is useful
How to develop intuition for conditional probability? At the beginning it was hard to me to have some intuition about. One idea is to take the problem to the limit. In this case as Steve noted one identical problem is: My neighbor has two kids--you know
16,626
How to develop intuition for conditional probability?
How one can tell the answer is 3/51 without calculating? If you took the ace of spades in the first place. I know which cards ar in the package. So there is stil 3 aces on 51 cards. so for the second one, you have 3/51 chances to have two aces. And how to understand the difference between the two scenarios intuitively? It's because "Have one ace" is included in "Have two aces". But "Have the ace of spades" is not included in "Have two aces". This is the difference. In fact, if you have two ace, you have one but maybe not the ace of spades So it's not the same probability. This answered was for a other post which has been moved on this one ..
How to develop intuition for conditional probability?
How one can tell the answer is 3/51 without calculating? If you took the ace of spades in the first place. I know which cards ar in the package. So there is stil 3 aces on 51 cards. so for the second
How to develop intuition for conditional probability? How one can tell the answer is 3/51 without calculating? If you took the ace of spades in the first place. I know which cards ar in the package. So there is stil 3 aces on 51 cards. so for the second one, you have 3/51 chances to have two aces. And how to understand the difference between the two scenarios intuitively? It's because "Have one ace" is included in "Have two aces". But "Have the ace of spades" is not included in "Have two aces". This is the difference. In fact, if you have two ace, you have one but maybe not the ace of spades So it's not the same probability. This answered was for a other post which has been moved on this one ..
How to develop intuition for conditional probability? How one can tell the answer is 3/51 without calculating? If you took the ace of spades in the first place. I know which cards ar in the package. So there is stil 3 aces on 51 cards. so for the second
16,627
How do you compare two Gaussian Processes?
Remark that the distribution of Gaussian processes $\mathcal{X}\to\mathbb{R}$ is the extension of multivariate Gaussian for possibly infinite $\mathcal{X}$. Thus, you can use the KL divergence between the GP probability distributions by integrating over $\mathbb{R}^\mathcal{X}$ : $$D_{KL}(P|Q)=\int_{\mathbb{R}^\mathcal{X}} \log \frac{dP}{dQ} dP\,.$$ You can use MC methods to approximate numerically this quantity over a discretized $\mathcal{X}$ by repeatedly sampling processes according to their GP distribution. I don't know if the convergence speed is sufficiently good... Remark that if $\mathcal{X}$ is finite with $|\mathcal{X}|=n$, then you fall back to the usual KL divergence for multivariate Normal distributions: $$D_{KL}\big(\mathcal{GP}(\mu_1,K_1), \mathcal{GP}(\mu_2,K_2)\big) = \frac 1 2 \Big(tr(K_2^{-1}K_1) + (\mu_2\!-\!\mu_1)^\top K_2^{-1}(\mu_2\!-\!\mu_1)-n+\log\frac{|K_2|}{|K_1|}\Big)$$
How do you compare two Gaussian Processes?
Remark that the distribution of Gaussian processes $\mathcal{X}\to\mathbb{R}$ is the extension of multivariate Gaussian for possibly infinite $\mathcal{X}$. Thus, you can use the KL divergence between
How do you compare two Gaussian Processes? Remark that the distribution of Gaussian processes $\mathcal{X}\to\mathbb{R}$ is the extension of multivariate Gaussian for possibly infinite $\mathcal{X}$. Thus, you can use the KL divergence between the GP probability distributions by integrating over $\mathbb{R}^\mathcal{X}$ : $$D_{KL}(P|Q)=\int_{\mathbb{R}^\mathcal{X}} \log \frac{dP}{dQ} dP\,.$$ You can use MC methods to approximate numerically this quantity over a discretized $\mathcal{X}$ by repeatedly sampling processes according to their GP distribution. I don't know if the convergence speed is sufficiently good... Remark that if $\mathcal{X}$ is finite with $|\mathcal{X}|=n$, then you fall back to the usual KL divergence for multivariate Normal distributions: $$D_{KL}\big(\mathcal{GP}(\mu_1,K_1), \mathcal{GP}(\mu_2,K_2)\big) = \frac 1 2 \Big(tr(K_2^{-1}K_1) + (\mu_2\!-\!\mu_1)^\top K_2^{-1}(\mu_2\!-\!\mu_1)-n+\log\frac{|K_2|}{|K_1|}\Big)$$
How do you compare two Gaussian Processes? Remark that the distribution of Gaussian processes $\mathcal{X}\to\mathbb{R}$ is the extension of multivariate Gaussian for possibly infinite $\mathcal{X}$. Thus, you can use the KL divergence between
16,628
How do you compare two Gaussian Processes?
Remember that if $X:T\times \Omega\to\mathbb{R}$ is a Gaussian Process with mean function $m$ and covariance function $K$, then, for every $t_1,\dots,t_k\in T$, the random vector $(X(t_1),\dots,X(t_k))$ has a multivariate normal distribution with mean vector $(m(t_1),\dots,m(t_k))$ and covariance matrix $\Sigma=(\sigma_{ij})=(K(t_i,t_j))$, where we have used the common abbreviation $X(t)=X(t,\,\cdot\,)$. Each realization $X(\,\cdot\,,\omega)$ is a real function whose domain is the index set $T$. Suppose that $T=[0,1]$. Given two Gaussian Processes $X$ and $Y$, one common distance between two realizations $X(\,\cdot\,,\omega)$ and $Y(\,\cdot\,,\omega)$ is $\sup_{t\in[0,1]} |X(t,\omega) - Y(t,\omega)|$. Hence, it seems natural to define the distance between the two processes $X$ and $Y$ as $$ d(X,Y) = \mathbb{E}\!\left[\sup_{t\in[0,1]} \left| X(t) - Y(t)\right|\right] \, . \qquad (*) $$ I don't know if there is an analytical expression for this distance, but I believe you can compute a Monte Carlo approximation as follows. Fix some fine grid $0\leq t_1<\dots<t_k\leq 1$, and draw samples $(x_{i1},\dots,x_{ik})$ and $(y_{i1},\dots,y_{ik})$ from the normal random vectors $(X(t_1),\dots,X(t_k))$ and $(Y(t_1),\dots,Y(t_k))$, respectively, for $i=1,\dots,N$. Approximate $d(X,Y)$ by $$ \frac{1}{N} \sum_{i=1}^N \max_{1\leq j\leq k} |x_{ij}-y_{ij}| \, . $$
How do you compare two Gaussian Processes?
Remember that if $X:T\times \Omega\to\mathbb{R}$ is a Gaussian Process with mean function $m$ and covariance function $K$, then, for every $t_1,\dots,t_k\in T$, the random vector $(X(t_1),\dots,X(t_k)
How do you compare two Gaussian Processes? Remember that if $X:T\times \Omega\to\mathbb{R}$ is a Gaussian Process with mean function $m$ and covariance function $K$, then, for every $t_1,\dots,t_k\in T$, the random vector $(X(t_1),\dots,X(t_k))$ has a multivariate normal distribution with mean vector $(m(t_1),\dots,m(t_k))$ and covariance matrix $\Sigma=(\sigma_{ij})=(K(t_i,t_j))$, where we have used the common abbreviation $X(t)=X(t,\,\cdot\,)$. Each realization $X(\,\cdot\,,\omega)$ is a real function whose domain is the index set $T$. Suppose that $T=[0,1]$. Given two Gaussian Processes $X$ and $Y$, one common distance between two realizations $X(\,\cdot\,,\omega)$ and $Y(\,\cdot\,,\omega)$ is $\sup_{t\in[0,1]} |X(t,\omega) - Y(t,\omega)|$. Hence, it seems natural to define the distance between the two processes $X$ and $Y$ as $$ d(X,Y) = \mathbb{E}\!\left[\sup_{t\in[0,1]} \left| X(t) - Y(t)\right|\right] \, . \qquad (*) $$ I don't know if there is an analytical expression for this distance, but I believe you can compute a Monte Carlo approximation as follows. Fix some fine grid $0\leq t_1<\dots<t_k\leq 1$, and draw samples $(x_{i1},\dots,x_{ik})$ and $(y_{i1},\dots,y_{ik})$ from the normal random vectors $(X(t_1),\dots,X(t_k))$ and $(Y(t_1),\dots,Y(t_k))$, respectively, for $i=1,\dots,N$. Approximate $d(X,Y)$ by $$ \frac{1}{N} \sum_{i=1}^N \max_{1\leq j\leq k} |x_{ij}-y_{ij}| \, . $$
How do you compare two Gaussian Processes? Remember that if $X:T\times \Omega\to\mathbb{R}$ is a Gaussian Process with mean function $m$ and covariance function $K$, then, for every $t_1,\dots,t_k\in T$, the random vector $(X(t_1),\dots,X(t_k)
16,629
What is the precise definition of a "Heywood Case"?
Googling "Heywood negative variance" quickly answers these questions. Looking at a recent (2008) paper by Kolenikov & Bollen, for example, indicates that: " “Heywood cases” [are] negative estimates of variances or correlation estimates greater than one in absolute value..." "The original paper (Heywood 1931) considers specific parameterizations of factor analytic models, in which some parameters necessary to describe the correlation matrices were greater than 1." Reference "Heywood, H. B. (1931), ‘On finite sequences of real numbers’, Proceedings of the Royal Society of London. Series A, Containing Papers of a Mathematical and Physical Character 134(824), 486–501."
What is the precise definition of a "Heywood Case"?
Googling "Heywood negative variance" quickly answers these questions. Looking at a recent (2008) paper by Kolenikov & Bollen, for example, indicates that: " “Heywood cases” [are] negative estimates
What is the precise definition of a "Heywood Case"? Googling "Heywood negative variance" quickly answers these questions. Looking at a recent (2008) paper by Kolenikov & Bollen, for example, indicates that: " “Heywood cases” [are] negative estimates of variances or correlation estimates greater than one in absolute value..." "The original paper (Heywood 1931) considers specific parameterizations of factor analytic models, in which some parameters necessary to describe the correlation matrices were greater than 1." Reference "Heywood, H. B. (1931), ‘On finite sequences of real numbers’, Proceedings of the Royal Society of London. Series A, Containing Papers of a Mathematical and Physical Character 134(824), 486–501."
What is the precise definition of a "Heywood Case"? Googling "Heywood negative variance" quickly answers these questions. Looking at a recent (2008) paper by Kolenikov & Bollen, for example, indicates that: " “Heywood cases” [are] negative estimates
16,630
Understanding negative ridge regression
Here is a geometric illustration of what is going on with negative ridge. I will consider estimators of the form $$\hat{\boldsymbol\beta}_\lambda = (\mathbf X^\top \mathbf X + \lambda \mathbf I)^{-1}\mathbf X^\top\mathbf y$$ arising from the loss function $$\mathcal L_\lambda = \|\mathbf y - \mathbf X\boldsymbol\beta\|^2 + \lambda \|\boldsymbol\beta\|^2.$$ Here is a rather standard illustration of what happens in a two-dimensional case with $\lambda\in[0,\infty)$. Zero lambda corresponds to the OLS solution, infinite lambda shrinks the estimated beta to zero: Now consider what happens when $\lambda\in(-\infty, -s^2_\max)$, where $s_\mathrm{max}$ is the largest singular value of $\mathbf X$. For very large negative lambdas, $\hat{\boldsymbol\beta}_\lambda$ is of course close to zero. When lambda approaches $-s^2_\max$, the term $(\mathbf X^\top \mathbf X + \lambda \mathbf I)$ gets one singular value approaching zero, meaning that the inverse has one singular value going to minus infinity. This singular value corresponds to the first principal component of $\mathbf X$, so in the limit one gets $\hat{\boldsymbol\beta}_\lambda$ pointing in the direction of PC1 but with absolute value growing to infinity. What is really nice, is that one can draw it on the same figure in the same way: betas are given by points where circles touch the ellipses from the inside: When $\lambda\in(-s^2_\mathrm{min},0]$, a similar logic applies, allowing to continue the ridge path on the other side of the OLS estimator. Now the circles touch the ellipses from the outside. In the limit, betas approach the PC2 direction (but it happens far outside this sketch): The $(-s^2_\mathrm{max}, -s^2_\mathrm{min})$ range is something of an energy gap: estimators there do not live on the same curve. UPDATE: In the comments @MartinL explains that for $\lambda<-s^2_\mathrm{max}$ the loss $\mathcal L_\lambda$ does not have a minimum but has a maximum. And this maximum is given by $\hat{\boldsymbol\beta}_\lambda$. This is why the same geometric construction with the circle/ellipse touching keeps working: we are still looking for zero-gradient points. When $-s^2_\mathrm{min}<\lambda\le 0$, the loss $\mathcal L_\lambda$ does have a minimum and it is given by $\hat{\boldsymbol\beta}_\lambda$, exactly as in the normal $\lambda>0$ case. But when $-s^2_\mathrm{max}<\lambda<-s^2_\mathrm{min}$, the loss $\mathcal L_\lambda$ does not have either maximum or minimum; $\hat{\boldsymbol\beta}_\lambda$ would correspond to a saddle point. This explains the "energy gap". The $\lambda\in(-\infty, -s^2_\max)$ naturally arises from a particular constrained ridge regression, see The limit of "unit-variance" ridge regression estimator when $\lambda\to\infty$. This is related to what is known in the chemometrics literature as "continuum regression", see my answer in the linked thread. The $\lambda\in(-s^2_\mathrm{min},0]$ can be treated in exactly the same way as $\lambda>0$: the loss function stays the same and the ridge estimator provides its minimum.
Understanding negative ridge regression
Here is a geometric illustration of what is going on with negative ridge. I will consider estimators of the form $$\hat{\boldsymbol\beta}_\lambda = (\mathbf X^\top \mathbf X + \lambda \mathbf I)^{-1}\
Understanding negative ridge regression Here is a geometric illustration of what is going on with negative ridge. I will consider estimators of the form $$\hat{\boldsymbol\beta}_\lambda = (\mathbf X^\top \mathbf X + \lambda \mathbf I)^{-1}\mathbf X^\top\mathbf y$$ arising from the loss function $$\mathcal L_\lambda = \|\mathbf y - \mathbf X\boldsymbol\beta\|^2 + \lambda \|\boldsymbol\beta\|^2.$$ Here is a rather standard illustration of what happens in a two-dimensional case with $\lambda\in[0,\infty)$. Zero lambda corresponds to the OLS solution, infinite lambda shrinks the estimated beta to zero: Now consider what happens when $\lambda\in(-\infty, -s^2_\max)$, where $s_\mathrm{max}$ is the largest singular value of $\mathbf X$. For very large negative lambdas, $\hat{\boldsymbol\beta}_\lambda$ is of course close to zero. When lambda approaches $-s^2_\max$, the term $(\mathbf X^\top \mathbf X + \lambda \mathbf I)$ gets one singular value approaching zero, meaning that the inverse has one singular value going to minus infinity. This singular value corresponds to the first principal component of $\mathbf X$, so in the limit one gets $\hat{\boldsymbol\beta}_\lambda$ pointing in the direction of PC1 but with absolute value growing to infinity. What is really nice, is that one can draw it on the same figure in the same way: betas are given by points where circles touch the ellipses from the inside: When $\lambda\in(-s^2_\mathrm{min},0]$, a similar logic applies, allowing to continue the ridge path on the other side of the OLS estimator. Now the circles touch the ellipses from the outside. In the limit, betas approach the PC2 direction (but it happens far outside this sketch): The $(-s^2_\mathrm{max}, -s^2_\mathrm{min})$ range is something of an energy gap: estimators there do not live on the same curve. UPDATE: In the comments @MartinL explains that for $\lambda<-s^2_\mathrm{max}$ the loss $\mathcal L_\lambda$ does not have a minimum but has a maximum. And this maximum is given by $\hat{\boldsymbol\beta}_\lambda$. This is why the same geometric construction with the circle/ellipse touching keeps working: we are still looking for zero-gradient points. When $-s^2_\mathrm{min}<\lambda\le 0$, the loss $\mathcal L_\lambda$ does have a minimum and it is given by $\hat{\boldsymbol\beta}_\lambda$, exactly as in the normal $\lambda>0$ case. But when $-s^2_\mathrm{max}<\lambda<-s^2_\mathrm{min}$, the loss $\mathcal L_\lambda$ does not have either maximum or minimum; $\hat{\boldsymbol\beta}_\lambda$ would correspond to a saddle point. This explains the "energy gap". The $\lambda\in(-\infty, -s^2_\max)$ naturally arises from a particular constrained ridge regression, see The limit of "unit-variance" ridge regression estimator when $\lambda\to\infty$. This is related to what is known in the chemometrics literature as "continuum regression", see my answer in the linked thread. The $\lambda\in(-s^2_\mathrm{min},0]$ can be treated in exactly the same way as $\lambda>0$: the loss function stays the same and the ridge estimator provides its minimum.
Understanding negative ridge regression Here is a geometric illustration of what is going on with negative ridge. I will consider estimators of the form $$\hat{\boldsymbol\beta}_\lambda = (\mathbf X^\top \mathbf X + \lambda \mathbf I)^{-1}\
16,631
CNN xavier weight initialization
In this case the amount of neurons should be 5*5*3. I found it especially useful for convolutional layers. Often a uniform distribution over the interval $[-c/(in+out), c/(in+out)]$ works as well. It is implemented as an option in almost all neural network libraries. Here you can find the source code of Keras's implementation of Xavier Glorot's initialization.
CNN xavier weight initialization
In this case the amount of neurons should be 5*5*3. I found it especially useful for convolutional layers. Often a uniform distribution over the interval $[-c/(in+out), c/(in+out)]$ works as well.
CNN xavier weight initialization In this case the amount of neurons should be 5*5*3. I found it especially useful for convolutional layers. Often a uniform distribution over the interval $[-c/(in+out), c/(in+out)]$ works as well. It is implemented as an option in almost all neural network libraries. Here you can find the source code of Keras's implementation of Xavier Glorot's initialization.
CNN xavier weight initialization In this case the amount of neurons should be 5*5*3. I found it especially useful for convolutional layers. Often a uniform distribution over the interval $[-c/(in+out), c/(in+out)]$ works as well.
16,632
CNN xavier weight initialization
I second Eric's answer here. I also take the "sqrt" of the term and not just that term. In spite of that, when you connect sigmoid deep in your net to "RelU" output.... it can cause the training to stall. This is because of unbounded "Relu" output which can make the gradient at sigmoid to fall to 0 and no learning happens. So, in the cases, I have a "scaleDown" factor for my net which will weigh down the initialization deviation by that factor. I keep empirically tuning the weights until learning happens. A simple way to find is to save the model immediately after 1 iteration and have a look at RELU output (that is connected to sigmoid). Keep tuning the weights until this RELU output is reasonable. And then use those weights for training. It is a good start. If it still collapses after a few iterations, weigh them down slightly bit more until you reach stability. Its just a hack I used. It worked for me for my setup. So sharing my experience. Different things work for different setups. So... Good Luck!
CNN xavier weight initialization
I second Eric's answer here. I also take the "sqrt" of the term and not just that term. In spite of that, when you connect sigmoid deep in your net to "RelU" output.... it can cause the training to st
CNN xavier weight initialization I second Eric's answer here. I also take the "sqrt" of the term and not just that term. In spite of that, when you connect sigmoid deep in your net to "RelU" output.... it can cause the training to stall. This is because of unbounded "Relu" output which can make the gradient at sigmoid to fall to 0 and no learning happens. So, in the cases, I have a "scaleDown" factor for my net which will weigh down the initialization deviation by that factor. I keep empirically tuning the weights until learning happens. A simple way to find is to save the model immediately after 1 iteration and have a look at RELU output (that is connected to sigmoid). Keep tuning the weights until this RELU output is reasonable. And then use those weights for training. It is a good start. If it still collapses after a few iterations, weigh them down slightly bit more until you reach stability. Its just a hack I used. It worked for me for my setup. So sharing my experience. Different things work for different setups. So... Good Luck!
CNN xavier weight initialization I second Eric's answer here. I also take the "sqrt" of the term and not just that term. In spite of that, when you connect sigmoid deep in your net to "RelU" output.... it can cause the training to st
16,633
Meaning of "reconstruction error" in PCA and LDA
For PCA what you do is that you project your data on a subset of your input space. Basically, everything holds on this image above: you project data on the subspace with maximum variance. When you reconstruct your data from the projection, you'll get the red points, and the reconstruction error is the sum of the distances from blue to red points: it indeed corresponds to the error you've made by projecting your data on the green line. It can be generalized in any dimension of course! As pointed out in the comments, it does not seem that simple for LDA and I can't find a proper definition on the internet. Sorry.
Meaning of "reconstruction error" in PCA and LDA
For PCA what you do is that you project your data on a subset of your input space. Basically, everything holds on this image above: you project data on the subspace with maximum variance. When you rec
Meaning of "reconstruction error" in PCA and LDA For PCA what you do is that you project your data on a subset of your input space. Basically, everything holds on this image above: you project data on the subspace with maximum variance. When you reconstruct your data from the projection, you'll get the red points, and the reconstruction error is the sum of the distances from blue to red points: it indeed corresponds to the error you've made by projecting your data on the green line. It can be generalized in any dimension of course! As pointed out in the comments, it does not seem that simple for LDA and I can't find a proper definition on the internet. Sorry.
Meaning of "reconstruction error" in PCA and LDA For PCA what you do is that you project your data on a subset of your input space. Basically, everything holds on this image above: you project data on the subspace with maximum variance. When you rec
16,634
Meaning of "reconstruction error" in PCA and LDA
What I usually use as the measure of reconstruction error (in the context of PCA, but also other methods) is the coefficient of determination $R^2$ and the Root Mean Squared Error (or normalised RMSE). These two are easy to compute and give you a quick idea of what the reconstruction did. Calculation Let's assume $X$ is your original data and $f$ is the compressed data. The $R^2$ of the $i^{th}$ variable can be computed as: $R^2_i = 1 - \frac{\sum_{j=1}^n (X_{j,i} - f_{j,i})^2}{\sum_{j=1}^n X_{j,i}^2}$ Since $R^2 = 1.0$ for a perfect fit, you can judge the reconstruction by how close the $R^2$ is to 1.0. The RMSE of the $i^{th}$ variable can be computed as: $ \text{RMSE}_i = \sqrt{\overline{(X_i - f_i)^2}} $ which you can also normalise by a quantity that suits you (norm $N$), I often normalise by the mean value, the NRMSE is thus: $\text{NRMSE}_i = \frac{\text{RMSE}_i}{N_i} = \sqrt{\frac{\overline{(X_i - f_i)^2}}{\overline{X_i^2}}}$ Computation In case you are using Python you can compute these as: from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error from math import sqrt import numpy as np r2 = r2_score(X, f) rmse = sqrt(mean_squared_error(X, f)) # RMSE normalised by mean: nrmse = rmse/sqrt(np.mean(X**2)) where X is the original data and f is the compressed data. Visualization In case it is helpful for you to do some sensitivity analysis you can then judge visually how the $R^2$ or RMSE change when you change parameters of your compression. For instance, this can be handy in the context of PCA when you want to compare reconstructions with increasing number of the retained Principal Components. Below you see that increasing the number of modes is getting your fit closer to the model:
Meaning of "reconstruction error" in PCA and LDA
What I usually use as the measure of reconstruction error (in the context of PCA, but also other methods) is the coefficient of determination $R^2$ and the Root Mean Squared Error (or normalised RMSE)
Meaning of "reconstruction error" in PCA and LDA What I usually use as the measure of reconstruction error (in the context of PCA, but also other methods) is the coefficient of determination $R^2$ and the Root Mean Squared Error (or normalised RMSE). These two are easy to compute and give you a quick idea of what the reconstruction did. Calculation Let's assume $X$ is your original data and $f$ is the compressed data. The $R^2$ of the $i^{th}$ variable can be computed as: $R^2_i = 1 - \frac{\sum_{j=1}^n (X_{j,i} - f_{j,i})^2}{\sum_{j=1}^n X_{j,i}^2}$ Since $R^2 = 1.0$ for a perfect fit, you can judge the reconstruction by how close the $R^2$ is to 1.0. The RMSE of the $i^{th}$ variable can be computed as: $ \text{RMSE}_i = \sqrt{\overline{(X_i - f_i)^2}} $ which you can also normalise by a quantity that suits you (norm $N$), I often normalise by the mean value, the NRMSE is thus: $\text{NRMSE}_i = \frac{\text{RMSE}_i}{N_i} = \sqrt{\frac{\overline{(X_i - f_i)^2}}{\overline{X_i^2}}}$ Computation In case you are using Python you can compute these as: from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error from math import sqrt import numpy as np r2 = r2_score(X, f) rmse = sqrt(mean_squared_error(X, f)) # RMSE normalised by mean: nrmse = rmse/sqrt(np.mean(X**2)) where X is the original data and f is the compressed data. Visualization In case it is helpful for you to do some sensitivity analysis you can then judge visually how the $R^2$ or RMSE change when you change parameters of your compression. For instance, this can be handy in the context of PCA when you want to compare reconstructions with increasing number of the retained Principal Components. Below you see that increasing the number of modes is getting your fit closer to the model:
Meaning of "reconstruction error" in PCA and LDA What I usually use as the measure of reconstruction error (in the context of PCA, but also other methods) is the coefficient of determination $R^2$ and the Root Mean Squared Error (or normalised RMSE)
16,635
Meaning of "reconstruction error" in PCA and LDA
The general definition of the reconstruction error would be the distance between the original data point and its projection onto a lower-dimensional subspace (its 'estimate'). Source: Mathematics of Machine Learning Specialization by Imperial College London
Meaning of "reconstruction error" in PCA and LDA
The general definition of the reconstruction error would be the distance between the original data point and its projection onto a lower-dimensional subspace (its 'estimate'). Source: Mathematics of M
Meaning of "reconstruction error" in PCA and LDA The general definition of the reconstruction error would be the distance between the original data point and its projection onto a lower-dimensional subspace (its 'estimate'). Source: Mathematics of Machine Learning Specialization by Imperial College London
Meaning of "reconstruction error" in PCA and LDA The general definition of the reconstruction error would be the distance between the original data point and its projection onto a lower-dimensional subspace (its 'estimate'). Source: Mathematics of M
16,636
Meaning of "reconstruction error" in PCA and LDA
It seems like there are three valid definitions in the case of PCA: Matrix-wise L2: Whole matrix $\bf{X}$ $ || \bf{X} - \bf{X_r} ||$ Row-wise L2: Feature vectors on dataset $\bf{Y}$: $ \sum_i{|| \it{y^i} - \it{y^i_r} ||}$ Elemental L1: Per-element (or pixel) error on dataset $\bf{Z}$: $ \sum_{ij}{|z^{ij} - z^{ij}_r|}$ Where each of the three cases could wind up being slightly different. The definitive norm and reconstruction error would be the type 3 L1 norm summed per-element. However, the other two may be more forgiving and relevant in different domains. In terms of the LDA, when you go about implementing the LDA you can reconstruct the data with computed intermediate components. But, you will still be using covariances or other computed components that rely on the SVD. So, analyzing a PCA based on your SVD solver that you use for your LDA implies that your LDA has the same reconstructive ability, assuming it is implemented correctly.
Meaning of "reconstruction error" in PCA and LDA
It seems like there are three valid definitions in the case of PCA: Matrix-wise L2: Whole matrix $\bf{X}$ $ || \bf{X} - \bf{X_r} ||$ Row-wise L2: Feature vectors on dataset $\bf{Y}$: $ \sum_i{|| \
Meaning of "reconstruction error" in PCA and LDA It seems like there are three valid definitions in the case of PCA: Matrix-wise L2: Whole matrix $\bf{X}$ $ || \bf{X} - \bf{X_r} ||$ Row-wise L2: Feature vectors on dataset $\bf{Y}$: $ \sum_i{|| \it{y^i} - \it{y^i_r} ||}$ Elemental L1: Per-element (or pixel) error on dataset $\bf{Z}$: $ \sum_{ij}{|z^{ij} - z^{ij}_r|}$ Where each of the three cases could wind up being slightly different. The definitive norm and reconstruction error would be the type 3 L1 norm summed per-element. However, the other two may be more forgiving and relevant in different domains. In terms of the LDA, when you go about implementing the LDA you can reconstruct the data with computed intermediate components. But, you will still be using covariances or other computed components that rely on the SVD. So, analyzing a PCA based on your SVD solver that you use for your LDA implies that your LDA has the same reconstructive ability, assuming it is implemented correctly.
Meaning of "reconstruction error" in PCA and LDA It seems like there are three valid definitions in the case of PCA: Matrix-wise L2: Whole matrix $\bf{X}$ $ || \bf{X} - \bf{X_r} ||$ Row-wise L2: Feature vectors on dataset $\bf{Y}$: $ \sum_i{|| \
16,637
Meaning of "reconstruction error" in PCA and LDA
Reconstruction error in the PCA context is variability of the data which we are not able to capture in the lower dimensional space. Principle subspace - lower dimensional subspace on which data is projected Reconstruction error as contribution from ignored subspace In PCA Reconstruction error or loss is sum of eigen values of the ignored subspace. Lets say you have 10 Dimensional data, and you are selecting first 4 principal components, what this means is your principle subspace has 4 dimensions and corresponds to 4 largest eigen values and respective vectors, So reconstruction error is sum of 6 eigen values of the ignored subspace, (the smallest 6). Minimizing the reconstruction error means minimizing the contribution of ignored eigenvalues which depends on the distribution of the data and how many components we are selecting. Reconstruction error as average squared distance Ignored subspace is orthogonal complement of principal subspace, so reconstruction error can be seen as average squared distance between the original data points and respective projections onto principal subspace as shared in another answer.
Meaning of "reconstruction error" in PCA and LDA
Reconstruction error in the PCA context is variability of the data which we are not able to capture in the lower dimensional space. Principle subspace - lower dimensional subspace on which data is pro
Meaning of "reconstruction error" in PCA and LDA Reconstruction error in the PCA context is variability of the data which we are not able to capture in the lower dimensional space. Principle subspace - lower dimensional subspace on which data is projected Reconstruction error as contribution from ignored subspace In PCA Reconstruction error or loss is sum of eigen values of the ignored subspace. Lets say you have 10 Dimensional data, and you are selecting first 4 principal components, what this means is your principle subspace has 4 dimensions and corresponds to 4 largest eigen values and respective vectors, So reconstruction error is sum of 6 eigen values of the ignored subspace, (the smallest 6). Minimizing the reconstruction error means minimizing the contribution of ignored eigenvalues which depends on the distribution of the data and how many components we are selecting. Reconstruction error as average squared distance Ignored subspace is orthogonal complement of principal subspace, so reconstruction error can be seen as average squared distance between the original data points and respective projections onto principal subspace as shared in another answer.
Meaning of "reconstruction error" in PCA and LDA Reconstruction error in the PCA context is variability of the data which we are not able to capture in the lower dimensional space. Principle subspace - lower dimensional subspace on which data is pro
16,638
Imputation of missing data before or after centering and scaling?
It really depends on the Imputation technique being used. For example if we Impute using distance based measure (eg. KNN), then it is recommended to first standardize the data and then Impute. That is because lower magnitude values converge faster. One idea could be using preprocess function from caret package. When you use method = knnImpute, it first center and scale the data before imputation. preProcValues <- preProcess(data, method = c("knnImpute","center","scale"))
Imputation of missing data before or after centering and scaling?
It really depends on the Imputation technique being used. For example if we Impute using distance based measure (eg. KNN), then it is recommended to first standardize the data and then Impute. That is
Imputation of missing data before or after centering and scaling? It really depends on the Imputation technique being used. For example if we Impute using distance based measure (eg. KNN), then it is recommended to first standardize the data and then Impute. That is because lower magnitude values converge faster. One idea could be using preprocess function from caret package. When you use method = knnImpute, it first center and scale the data before imputation. preProcValues <- preProcess(data, method = c("knnImpute","center","scale"))
Imputation of missing data before or after centering and scaling? It really depends on the Imputation technique being used. For example if we Impute using distance based measure (eg. KNN), then it is recommended to first standardize the data and then Impute. That is
16,639
Imputation of missing data before or after centering and scaling?
Presumably, if you really need to center & scale the data, that should be done after imputation, as the imputation could influence on the correct center and scale to use! Generally, the imputation should be the very first step in any analysis you do. EDIT answer to comment by @Inon: You say that imputation should preserve center & scale, and also standardization. Why? If the missing values truly are missing at random, maybe it does not matter much, but generally missingness might depend on other observed variables, and then estimates of mean and scale could be skewed by this pattern in the missingness. Imputation (better multiple imputation) is a way to fight this skewing. But if you do imputation after scaling, you just preserve the bias introduced by the missingness mechanism. Imputation is meant to fight this, and doing imputation after scaling just defeats this.
Imputation of missing data before or after centering and scaling?
Presumably, if you really need to center & scale the data, that should be done after imputation, as the imputation could influence on the correct center and scale to use! Generally, the imputation s
Imputation of missing data before or after centering and scaling? Presumably, if you really need to center & scale the data, that should be done after imputation, as the imputation could influence on the correct center and scale to use! Generally, the imputation should be the very first step in any analysis you do. EDIT answer to comment by @Inon: You say that imputation should preserve center & scale, and also standardization. Why? If the missing values truly are missing at random, maybe it does not matter much, but generally missingness might depend on other observed variables, and then estimates of mean and scale could be skewed by this pattern in the missingness. Imputation (better multiple imputation) is a way to fight this skewing. But if you do imputation after scaling, you just preserve the bias introduced by the missingness mechanism. Imputation is meant to fight this, and doing imputation after scaling just defeats this.
Imputation of missing data before or after centering and scaling? Presumably, if you really need to center & scale the data, that should be done after imputation, as the imputation could influence on the correct center and scale to use! Generally, the imputation s
16,640
Explanation of formula for median closest point to origin of N samples from unit ball
The volume of an $p$-dimensional hyperball of radius $r$ has a volume proportional to $r^p$. So the proportion of the volume more than a distance $kr$ from the origin is $\frac{r^p-(kr)^p}{r^p}=1-k^p$. The probability that all $N$ randomly chosen points are more than a distance $kr$ from the origin is $\left(1-k^p\right)^N$. To get the median distance to the nearest random point, set this probability equal to $\frac12$. So $$\left(1-k^p\right)^N=\tfrac12 $$ $$\implies k=\left(1-\tfrac1{2^{1/N}}\right)^{1/p}.$$ Intuitively this makes some sort of sense: the more random points there are, the closer you expect the nearest one to the origin to be, so you should expect $k$ to be a decreasing function of $N$. Here $2^{1/N}$ is a decreasing function of $N$, so $\tfrac1{2^{1/N}}$ is an increasing function of $N$, and thus $1-\tfrac1{2^{1/N}}$ is a decreasing function of $N$ as is its $p$th root.
Explanation of formula for median closest point to origin of N samples from unit ball
The volume of an $p$-dimensional hyperball of radius $r$ has a volume proportional to $r^p$. So the proportion of the volume more than a distance $kr$ from the origin is $\frac{r^p-(kr)^p}{r^p}=1-k^p
Explanation of formula for median closest point to origin of N samples from unit ball The volume of an $p$-dimensional hyperball of radius $r$ has a volume proportional to $r^p$. So the proportion of the volume more than a distance $kr$ from the origin is $\frac{r^p-(kr)^p}{r^p}=1-k^p$. The probability that all $N$ randomly chosen points are more than a distance $kr$ from the origin is $\left(1-k^p\right)^N$. To get the median distance to the nearest random point, set this probability equal to $\frac12$. So $$\left(1-k^p\right)^N=\tfrac12 $$ $$\implies k=\left(1-\tfrac1{2^{1/N}}\right)^{1/p}.$$ Intuitively this makes some sort of sense: the more random points there are, the closer you expect the nearest one to the origin to be, so you should expect $k$ to be a decreasing function of $N$. Here $2^{1/N}$ is a decreasing function of $N$, so $\tfrac1{2^{1/N}}$ is an increasing function of $N$, and thus $1-\tfrac1{2^{1/N}}$ is a decreasing function of $N$ as is its $p$th root.
Explanation of formula for median closest point to origin of N samples from unit ball The volume of an $p$-dimensional hyperball of radius $r$ has a volume proportional to $r^p$. So the proportion of the volume more than a distance $kr$ from the origin is $\frac{r^p-(kr)^p}{r^p}=1-k^p
16,641
Explanation of formula for median closest point to origin of N samples from unit ball
And now without hand waving For any sequence of i.i.d rv's, $$P( \min_{1\le i\le N} Y_i > y ) = (1-F(y))^N,$$ where $F$ is the common CDF Thus if we have $N$ i.i.d uniformly distributed $X_i$ in the unit ball in $p$ dimensions, then $$P( \min_{1\le i\le N} ||X_i|| > r ) = (1-F(r))^N,$$ where $F$ is the common CDF of the distances, $||X_i||, i=1,2,\ldots,N$. Finally, what is the CDF, $F$, for a uniformly distributed point in the unit ball in $R^p$? The probability that the point lies in the ball of radius r within the ball of unit radius equal the ratio of volumes: $$F(r) = P ( ||X_i|| \le r ) = C r^p/( C 1^p) = r^p$$ Thus the solution to $$1/2 = P( \min_{1\le i\le N} ||X_i|| > r ) = (1- r^p)^N$$ is $$r = (1 - (1/2)^{1/N})^{1/p}.$$ Also your question about dependence on the sample size, $N$. For $p$ fixed, as the ball fills up with more points, naturally the minimum distance to the origin should become smaller. Finally, there is something amiss in your ratio of volumes. It looks like $k$ should be the volume of the unit ball in $R^p$.
Explanation of formula for median closest point to origin of N samples from unit ball
And now without hand waving For any sequence of i.i.d rv's, $$P( \min_{1\le i\le N} Y_i > y ) = (1-F(y))^N,$$ where $F$ is the common CDF Thus if we have $N$ i.i.d uniformly distributed $X_i$ in th
Explanation of formula for median closest point to origin of N samples from unit ball And now without hand waving For any sequence of i.i.d rv's, $$P( \min_{1\le i\le N} Y_i > y ) = (1-F(y))^N,$$ where $F$ is the common CDF Thus if we have $N$ i.i.d uniformly distributed $X_i$ in the unit ball in $p$ dimensions, then $$P( \min_{1\le i\le N} ||X_i|| > r ) = (1-F(r))^N,$$ where $F$ is the common CDF of the distances, $||X_i||, i=1,2,\ldots,N$. Finally, what is the CDF, $F$, for a uniformly distributed point in the unit ball in $R^p$? The probability that the point lies in the ball of radius r within the ball of unit radius equal the ratio of volumes: $$F(r) = P ( ||X_i|| \le r ) = C r^p/( C 1^p) = r^p$$ Thus the solution to $$1/2 = P( \min_{1\le i\le N} ||X_i|| > r ) = (1- r^p)^N$$ is $$r = (1 - (1/2)^{1/N})^{1/p}.$$ Also your question about dependence on the sample size, $N$. For $p$ fixed, as the ball fills up with more points, naturally the minimum distance to the origin should become smaller. Finally, there is something amiss in your ratio of volumes. It looks like $k$ should be the volume of the unit ball in $R^p$.
Explanation of formula for median closest point to origin of N samples from unit ball And now without hand waving For any sequence of i.i.d rv's, $$P( \min_{1\le i\le N} Y_i > y ) = (1-F(y))^N,$$ where $F$ is the common CDF Thus if we have $N$ i.i.d uniformly distributed $X_i$ in th
16,642
Explanation of formula for median closest point to origin of N samples from unit ball
As concise but in words: We want to find the median distance of the closest point to the origin in $N$ uniformly distributed points in the ball at the origin of unit radius in $p$ dimensions. The probability that the smallest distance exceeds $r$, (call this quantity expression [1]) is the $N^{th}$ power of the probability that a single uniformly distributed point exceeds $r$, because of statistical independence. The latter is one minus the probability that a single uniformly distributed point is less than $r$. The latter is the ratio of volumes of the ball of radius $r$ to the ball of unit radius, or $r^p$. We can now write expression [1] as $$ P( \min_{1\le i\le N} ||X_i|| > r ) = (1- r^p)^N.$$ To find the median of the distribution of the minimum of the distances, set the above probability to $1/2$ and solve for $r$, obtaining the answer.
Explanation of formula for median closest point to origin of N samples from unit ball
As concise but in words: We want to find the median distance of the closest point to the origin in $N$ uniformly distributed points in the ball at the origin of unit radius in $p$ dimensions. The prob
Explanation of formula for median closest point to origin of N samples from unit ball As concise but in words: We want to find the median distance of the closest point to the origin in $N$ uniformly distributed points in the ball at the origin of unit radius in $p$ dimensions. The probability that the smallest distance exceeds $r$, (call this quantity expression [1]) is the $N^{th}$ power of the probability that a single uniformly distributed point exceeds $r$, because of statistical independence. The latter is one minus the probability that a single uniformly distributed point is less than $r$. The latter is the ratio of volumes of the ball of radius $r$ to the ball of unit radius, or $r^p$. We can now write expression [1] as $$ P( \min_{1\le i\le N} ||X_i|| > r ) = (1- r^p)^N.$$ To find the median of the distribution of the minimum of the distances, set the above probability to $1/2$ and solve for $r$, obtaining the answer.
Explanation of formula for median closest point to origin of N samples from unit ball As concise but in words: We want to find the median distance of the closest point to the origin in $N$ uniformly distributed points in the ball at the origin of unit radius in $p$ dimensions. The prob
16,643
Does there exist a conjugate prior for the Laplace distribution?
At least sort of. While the answer is formally no (it's not exponential family after all), I think we can construct a "family" of priors that do work in a specific way. Let's look at them one at a time first (taking the other as given). From the link (with the modification of following the convention of using Greek symbols for parameters): $f(x|\mu,\tau) = \frac{1}{2\tau} \exp \left( -\frac{|x-\mu|}{\tau} \right) \,$ - scale parameter: $\cal{L}(\tau) \propto \tau^{-k-1} e^{-\frac{S}{\tau}} \,$ for certain values of $k$ and $S$. That is the likelihood is of inverse-gamma form. So the scale parameter has a conjugate prior - by inspection the conjugate prior is inverse gamma. - location parameter This is, indeed, more tricky, because $\sum_i|x_i-\mu|$ doesn't simplify into something convenient in $\mu$; I don't think there's any way to 'collect the terms' (well in a way there sort of is, but we don't need to anyway). A uniform prior will simply truncate the posterior, which isn't so bad to work with if that seems plausible as a prior. One interesting possibility that may occasionally be useful is it's rather easy to include a Laplace prior (one with the same scale as the data) by use of a pseudo-observation. One might also approximate some other (tighter) prior via several pseudo-observations) In fact, to generalize from that, if I were working with a Laplace, I'd be tempted to simply generalize from constant-scale-constant-weight to working with a weighted-observation version of Laplace (equivalently, a potentially different scale for every data point) - the log-likelihood is still just a continuous piecewise linear function, but the slope can change by non-integer amounts at the join points. Then a convenient "conjugate" prior exists - just another 'weighted' Laplace or, indeed, anything of the form $\exp(-\sum_j |\mu-\theta_j|/\phi_j)$ or $\exp(-\sum_j w^*_j|\mu-\theta_j|)$ (though it would need to be appropriately scaled to make an actual density) - a very flexible family of distributions, and which apparently results in a posterior "of the same form" as the weighted-observation likelihood, and something easy to work with and draw; indeed even the pseudo-observation thing still works. It is also flexible enough that it can be used to approximate other priors. (More generally still, one could work on the log-scale and use a continuous, piece-wise-linear log-concave prior and the posterior would also be of that form; this would include asymmetric Laplace as a special case) Example Just to show that it's pretty easy to deal with - below is a prior (dotted grey), likelihood (dashed, black) and posterior (solid, red) for the location parameter for a weighted Laplace (... this was with known scales). The weighted Laplace approach would work nicely in MCMC, I think. -- I wonder if the resulting posterior's mode is a weighted median? -- actually (to answer my own question), it looks like the answer to that is 'yes'. That makes it rather nice to work with. -- Joint prior The obvious approach would be to write $f(\mu,\tau)=f(\mu|\tau)f(\tau)$: it would be relatively easy to have $\mu|\tau$ in the same form as above - where $\tau$ could be a scaling factor on the prior, so the prior would be specified relative to $\tau$ - and then an inverse gamma prior on $\tau$, unconditionally. Doubtless something more general for the joint prior is quite possible, but I don't think I'll pursue the joint case further than that here. -- I've never seen or heard of this weighted-laplace prior approach before, but it was rather simple to come up with so it's probably been done already. (References are welcome, if anyone knows of any.) If nobody knows of any references at all, maybe I should write something up, but that would be astonishing.
Does there exist a conjugate prior for the Laplace distribution?
At least sort of. While the answer is formally no (it's not exponential family after all), I think we can construct a "family" of priors that do work in a specific way. Let's look at them one at a tim
Does there exist a conjugate prior for the Laplace distribution? At least sort of. While the answer is formally no (it's not exponential family after all), I think we can construct a "family" of priors that do work in a specific way. Let's look at them one at a time first (taking the other as given). From the link (with the modification of following the convention of using Greek symbols for parameters): $f(x|\mu,\tau) = \frac{1}{2\tau} \exp \left( -\frac{|x-\mu|}{\tau} \right) \,$ - scale parameter: $\cal{L}(\tau) \propto \tau^{-k-1} e^{-\frac{S}{\tau}} \,$ for certain values of $k$ and $S$. That is the likelihood is of inverse-gamma form. So the scale parameter has a conjugate prior - by inspection the conjugate prior is inverse gamma. - location parameter This is, indeed, more tricky, because $\sum_i|x_i-\mu|$ doesn't simplify into something convenient in $\mu$; I don't think there's any way to 'collect the terms' (well in a way there sort of is, but we don't need to anyway). A uniform prior will simply truncate the posterior, which isn't so bad to work with if that seems plausible as a prior. One interesting possibility that may occasionally be useful is it's rather easy to include a Laplace prior (one with the same scale as the data) by use of a pseudo-observation. One might also approximate some other (tighter) prior via several pseudo-observations) In fact, to generalize from that, if I were working with a Laplace, I'd be tempted to simply generalize from constant-scale-constant-weight to working with a weighted-observation version of Laplace (equivalently, a potentially different scale for every data point) - the log-likelihood is still just a continuous piecewise linear function, but the slope can change by non-integer amounts at the join points. Then a convenient "conjugate" prior exists - just another 'weighted' Laplace or, indeed, anything of the form $\exp(-\sum_j |\mu-\theta_j|/\phi_j)$ or $\exp(-\sum_j w^*_j|\mu-\theta_j|)$ (though it would need to be appropriately scaled to make an actual density) - a very flexible family of distributions, and which apparently results in a posterior "of the same form" as the weighted-observation likelihood, and something easy to work with and draw; indeed even the pseudo-observation thing still works. It is also flexible enough that it can be used to approximate other priors. (More generally still, one could work on the log-scale and use a continuous, piece-wise-linear log-concave prior and the posterior would also be of that form; this would include asymmetric Laplace as a special case) Example Just to show that it's pretty easy to deal with - below is a prior (dotted grey), likelihood (dashed, black) and posterior (solid, red) for the location parameter for a weighted Laplace (... this was with known scales). The weighted Laplace approach would work nicely in MCMC, I think. -- I wonder if the resulting posterior's mode is a weighted median? -- actually (to answer my own question), it looks like the answer to that is 'yes'. That makes it rather nice to work with. -- Joint prior The obvious approach would be to write $f(\mu,\tau)=f(\mu|\tau)f(\tau)$: it would be relatively easy to have $\mu|\tau$ in the same form as above - where $\tau$ could be a scaling factor on the prior, so the prior would be specified relative to $\tau$ - and then an inverse gamma prior on $\tau$, unconditionally. Doubtless something more general for the joint prior is quite possible, but I don't think I'll pursue the joint case further than that here. -- I've never seen or heard of this weighted-laplace prior approach before, but it was rather simple to come up with so it's probably been done already. (References are welcome, if anyone knows of any.) If nobody knows of any references at all, maybe I should write something up, but that would be astonishing.
Does there exist a conjugate prior for the Laplace distribution? At least sort of. While the answer is formally no (it's not exponential family after all), I think we can construct a "family" of priors that do work in a specific way. Let's look at them one at a tim
16,644
Does there exist a conjugate prior for the Laplace distribution?
I think an exponential, or more generally, a gamma density does the job. See also: Md. Habibur Rahman and M. K. Roy (2018): Bayes Estimation under Conjugate Prior for the Case of Laplace Double Exponential Distribution. The Chittagong Univ. J. Sci. 40: 151-168.
Does there exist a conjugate prior for the Laplace distribution?
I think an exponential, or more generally, a gamma density does the job. See also: Md. Habibur Rahman and M. K. Roy (2018): Bayes Estimation under Conjugate Prior for the Case of Laplace Double Expone
Does there exist a conjugate prior for the Laplace distribution? I think an exponential, or more generally, a gamma density does the job. See also: Md. Habibur Rahman and M. K. Roy (2018): Bayes Estimation under Conjugate Prior for the Case of Laplace Double Exponential Distribution. The Chittagong Univ. J. Sci. 40: 151-168.
Does there exist a conjugate prior for the Laplace distribution? I think an exponential, or more generally, a gamma density does the job. See also: Md. Habibur Rahman and M. K. Roy (2018): Bayes Estimation under Conjugate Prior for the Case of Laplace Double Expone
16,645
Bootstrapping residuals: Am I doing it right?
Here is the general (semi-parametric-bootstrap) algorithm in more detail: $\text{B}$ = number of bootstraps the model: $y = x\beta + \epsilon$ let $\hat{\epsilon}$ be the residuals Run the regression and obtain the estimator(s) $\hat\beta$ and residuals $\hat\epsilon$. Resample the residuals with replacement and obtain the bootstrapped residual vector $\hat\epsilon_\text{B}$. Obtain the bootstrapped dependent variable by multiplying the estimator(s) from (1) with the original regressors and adding the bootstrapped residual: $y_\text{B} = x\hat\beta + \hat\epsilon_\text{B}$. Run the regression with the bootstrapped dependent variables and the original regressors, this gives the bootstrapped estimator, i.e. regress $y_B$ on $x$, this gives $\hat\beta_\text{B}$. Repeat the procedure $\text{B}$-times by going back to (2).
Bootstrapping residuals: Am I doing it right?
Here is the general (semi-parametric-bootstrap) algorithm in more detail: $\text{B}$ = number of bootstraps the model: $y = x\beta + \epsilon$ let $\hat{\epsilon}$ be the residuals Run the regression
Bootstrapping residuals: Am I doing it right? Here is the general (semi-parametric-bootstrap) algorithm in more detail: $\text{B}$ = number of bootstraps the model: $y = x\beta + \epsilon$ let $\hat{\epsilon}$ be the residuals Run the regression and obtain the estimator(s) $\hat\beta$ and residuals $\hat\epsilon$. Resample the residuals with replacement and obtain the bootstrapped residual vector $\hat\epsilon_\text{B}$. Obtain the bootstrapped dependent variable by multiplying the estimator(s) from (1) with the original regressors and adding the bootstrapped residual: $y_\text{B} = x\hat\beta + \hat\epsilon_\text{B}$. Run the regression with the bootstrapped dependent variables and the original regressors, this gives the bootstrapped estimator, i.e. regress $y_B$ on $x$, this gives $\hat\beta_\text{B}$. Repeat the procedure $\text{B}$-times by going back to (2).
Bootstrapping residuals: Am I doing it right? Here is the general (semi-parametric-bootstrap) algorithm in more detail: $\text{B}$ = number of bootstraps the model: $y = x\beta + \epsilon$ let $\hat{\epsilon}$ be the residuals Run the regression
16,646
Bootstrapping residuals: Am I doing it right?
To see how an algorithm performs in terms of predictive accuracy/mean squared error, you probably need the Efron-Gong "optimism" bootstrap. This is implemented for easy use in the R rms package. See its functions ols, validate.ols, calibrate.
Bootstrapping residuals: Am I doing it right?
To see how an algorithm performs in terms of predictive accuracy/mean squared error, you probably need the Efron-Gong "optimism" bootstrap. This is implemented for easy use in the R rms package. See
Bootstrapping residuals: Am I doing it right? To see how an algorithm performs in terms of predictive accuracy/mean squared error, you probably need the Efron-Gong "optimism" bootstrap. This is implemented for easy use in the R rms package. See its functions ols, validate.ols, calibrate.
Bootstrapping residuals: Am I doing it right? To see how an algorithm performs in terms of predictive accuracy/mean squared error, you probably need the Efron-Gong "optimism" bootstrap. This is implemented for easy use in the R rms package. See
16,647
Bootstrapping residuals: Am I doing it right?
I'm not sure that my understanding is correct. But here is my suggestion to modify your code ("ordinary bootstrapping of residuals", lines 28-34) into: for i = 2:n_boot x_res_boot = x_residuals( randi(n_data,n_data,1) ); x_boot = x_res_boot+ x_best_fit; p_est(:, i) = polyfit( t, x_boot, 1 ); x_best_fit2 = polyval( p_est(:, i), t ); x_residuals = x_best_fit2 - x_boot; x_best_fit=x_best_fit2; end The idea is that each time you are using residuals not from the first run, but from the previous bootstrap fit. As for me, all other seems to be valid. This is revised version that has been checked in MATLAB. Two errors have been fixed.
Bootstrapping residuals: Am I doing it right?
I'm not sure that my understanding is correct. But here is my suggestion to modify your code ("ordinary bootstrapping of residuals", lines 28-34) into: for i = 2:n_boot x_res_boot = x_residuals( ran
Bootstrapping residuals: Am I doing it right? I'm not sure that my understanding is correct. But here is my suggestion to modify your code ("ordinary bootstrapping of residuals", lines 28-34) into: for i = 2:n_boot x_res_boot = x_residuals( randi(n_data,n_data,1) ); x_boot = x_res_boot+ x_best_fit; p_est(:, i) = polyfit( t, x_boot, 1 ); x_best_fit2 = polyval( p_est(:, i), t ); x_residuals = x_best_fit2 - x_boot; x_best_fit=x_best_fit2; end The idea is that each time you are using residuals not from the first run, but from the previous bootstrap fit. As for me, all other seems to be valid. This is revised version that has been checked in MATLAB. Two errors have been fixed.
Bootstrapping residuals: Am I doing it right? I'm not sure that my understanding is correct. But here is my suggestion to modify your code ("ordinary bootstrapping of residuals", lines 28-34) into: for i = 2:n_boot x_res_boot = x_residuals( ran
16,648
Bootstrapping residuals: Am I doing it right?
Spatiotemporal application I applied @Sweetbabyjesus's answer. Unfortunately my model is more complex than an OLS regression (it's a distributed-lag 'hhh4 framework' spatiotemporal model from surveillance R package) causing instability when making such data changes, resulting in non-convergence messages. If this happens to you then a second-best solution is producing jackknifed estimates by fitting the model to your dataset with one data point missing and repeating for $N$ to get a distribution of model estimates; in a spatiotemporal model context I interpret this as subtracting 1 from the response variable $y$ e.g. disease case counts while avoiding negative counts, so it is a trimmed subtraction function. Since I cannot fit the entire model if I make a single space x time cell go missing i.e. NA, subtracting by 1 count was the only option. The mean of jackknifed estimates was very close to the model point estimates, however the jackknifed sd estimates underestimated the model sd by 1-3 orders of magnitude! Generally speak jackknifing is a 'first order approximation' to a bootstrap, hence why I see this solution as suboptimal.
Bootstrapping residuals: Am I doing it right?
Spatiotemporal application I applied @Sweetbabyjesus's answer. Unfortunately my model is more complex than an OLS regression (it's a distributed-lag 'hhh4 framework' spatiotemporal model from surveill
Bootstrapping residuals: Am I doing it right? Spatiotemporal application I applied @Sweetbabyjesus's answer. Unfortunately my model is more complex than an OLS regression (it's a distributed-lag 'hhh4 framework' spatiotemporal model from surveillance R package) causing instability when making such data changes, resulting in non-convergence messages. If this happens to you then a second-best solution is producing jackknifed estimates by fitting the model to your dataset with one data point missing and repeating for $N$ to get a distribution of model estimates; in a spatiotemporal model context I interpret this as subtracting 1 from the response variable $y$ e.g. disease case counts while avoiding negative counts, so it is a trimmed subtraction function. Since I cannot fit the entire model if I make a single space x time cell go missing i.e. NA, subtracting by 1 count was the only option. The mean of jackknifed estimates was very close to the model point estimates, however the jackknifed sd estimates underestimated the model sd by 1-3 orders of magnitude! Generally speak jackknifing is a 'first order approximation' to a bootstrap, hence why I see this solution as suboptimal.
Bootstrapping residuals: Am I doing it right? Spatiotemporal application I applied @Sweetbabyjesus's answer. Unfortunately my model is more complex than an OLS regression (it's a distributed-lag 'hhh4 framework' spatiotemporal model from surveill
16,649
What processes could generate Laplace-distributed (double exponential) data or parameters?
At the bottom of the Wikipedia page you linked are a few examples: If $X_1$ and $X_2$ are IID exponential distributions, $X_1 - X_2$ has a Laplace distribution. If $X_1, X_2, X_3, X_4$ are IID standard normal distributions, $X_1X_4 - X_2X_3$ has a standard Laplace distribution. So, the determinant of a random $2\times 2$ matrix with IID standard normal entries $\begin{pmatrix}X_1 & X_2 \\\ X_3 & X_4 \end{pmatrix} $ has a Laplace distribution. If $X_1, X_2$ are IID uniform on $[0,1]$, then $\log \frac{X_1}{X_2}$ has a standard Laplace distribution.
What processes could generate Laplace-distributed (double exponential) data or parameters?
At the bottom of the Wikipedia page you linked are a few examples: If $X_1$ and $X_2$ are IID exponential distributions, $X_1 - X_2$ has a Laplace distribution. If $X_1, X_2, X_3, X_4$ are IID standa
What processes could generate Laplace-distributed (double exponential) data or parameters? At the bottom of the Wikipedia page you linked are a few examples: If $X_1$ and $X_2$ are IID exponential distributions, $X_1 - X_2$ has a Laplace distribution. If $X_1, X_2, X_3, X_4$ are IID standard normal distributions, $X_1X_4 - X_2X_3$ has a standard Laplace distribution. So, the determinant of a random $2\times 2$ matrix with IID standard normal entries $\begin{pmatrix}X_1 & X_2 \\\ X_3 & X_4 \end{pmatrix} $ has a Laplace distribution. If $X_1, X_2$ are IID uniform on $[0,1]$, then $\log \frac{X_1}{X_2}$ has a standard Laplace distribution.
What processes could generate Laplace-distributed (double exponential) data or parameters? At the bottom of the Wikipedia page you linked are a few examples: If $X_1$ and $X_2$ are IID exponential distributions, $X_1 - X_2$ has a Laplace distribution. If $X_1, X_2, X_3, X_4$ are IID standa
16,650
What processes could generate Laplace-distributed (double exponential) data or parameters?
Define a compound geometric distribution as the sum of $N_p$ iid random variables $X_N = \sum_i^{N_p} X_i$, where $N_p$ is distributed like a geometric distribution with parameter $p$. Assume that the iid random variables $X_i$ have finite mean $\mu$ and variance $v$. It was shown by Gnedenko that in the limit $p\to 0$, the compound geometric distribution approaches a Laplace distribution. $Y:= \lim_{p\to 0} \sqrt{p} (X_N - N_p\mu) = Laplace(0,\sqrt{\frac{v}{2}})$ The density of the $Laplace(a,b)$ is $\phi(x) = \frac{1}{2b} \exp\left( - \frac{|x-a|}{2b}\right)$ B.V Gnedenko, Limit theorems for Sums of random number of positive independent random variables, Proc. 6th Berkeley Syposium Math. Stat. Probabil. 2, 537-549, 1970.
What processes could generate Laplace-distributed (double exponential) data or parameters?
Define a compound geometric distribution as the sum of $N_p$ iid random variables $X_N = \sum_i^{N_p} X_i$, where $N_p$ is distributed like a geometric distribution with parameter $p$. Assume that the
What processes could generate Laplace-distributed (double exponential) data or parameters? Define a compound geometric distribution as the sum of $N_p$ iid random variables $X_N = \sum_i^{N_p} X_i$, where $N_p$ is distributed like a geometric distribution with parameter $p$. Assume that the iid random variables $X_i$ have finite mean $\mu$ and variance $v$. It was shown by Gnedenko that in the limit $p\to 0$, the compound geometric distribution approaches a Laplace distribution. $Y:= \lim_{p\to 0} \sqrt{p} (X_N - N_p\mu) = Laplace(0,\sqrt{\frac{v}{2}})$ The density of the $Laplace(a,b)$ is $\phi(x) = \frac{1}{2b} \exp\left( - \frac{|x-a|}{2b}\right)$ B.V Gnedenko, Limit theorems for Sums of random number of positive independent random variables, Proc. 6th Berkeley Syposium Math. Stat. Probabil. 2, 537-549, 1970.
What processes could generate Laplace-distributed (double exponential) data or parameters? Define a compound geometric distribution as the sum of $N_p$ iid random variables $X_N = \sum_i^{N_p} X_i$, where $N_p$ is distributed like a geometric distribution with parameter $p$. Assume that the
16,651
Definition and origin of “cross entropy”
It seems to be closely related to the concept of Kullback–Leibler divergence (see Kullback and Leibler, 1951). In their article Kullback and Leibler discuss the mean information for discriminating between two hypotheses (defined as $I_{1:2}(E)$ in eqs. $2.2-2.4$) and cite pp. 18-19 of Shannon and Weaver's The Mathematical Theory of Communication (1949) and p. 76 of Wiener's Cybernetics (1948). EDIT: Additional aliases include the Kullback-Leibler information measure, the relative information measure, cross-entropy, I-divergence and Kerridge inaccuracy.
Definition and origin of “cross entropy”
It seems to be closely related to the concept of Kullback–Leibler divergence (see Kullback and Leibler, 1951). In their article Kullback and Leibler discuss the mean information for discriminating bet
Definition and origin of “cross entropy” It seems to be closely related to the concept of Kullback–Leibler divergence (see Kullback and Leibler, 1951). In their article Kullback and Leibler discuss the mean information for discriminating between two hypotheses (defined as $I_{1:2}(E)$ in eqs. $2.2-2.4$) and cite pp. 18-19 of Shannon and Weaver's The Mathematical Theory of Communication (1949) and p. 76 of Wiener's Cybernetics (1948). EDIT: Additional aliases include the Kullback-Leibler information measure, the relative information measure, cross-entropy, I-divergence and Kerridge inaccuracy.
Definition and origin of “cross entropy” It seems to be closely related to the concept of Kullback–Leibler divergence (see Kullback and Leibler, 1951). In their article Kullback and Leibler discuss the mean information for discriminating bet
16,652
Definition and origin of “cross entropy”
Thanks to @Itamar's suggestion, I found a mention in: I. J. Good, "Some Terminology and Notation in Information Theory," Proceedings of the IEE - Part C: Monographs, vol. 103, no. 3, pp. 200-204, Mar. 1956. It would still be really useful for me to find a nice presentation of cross-entropy.
Definition and origin of “cross entropy”
Thanks to @Itamar's suggestion, I found a mention in: I. J. Good, "Some Terminology and Notation in Information Theory," Proceedings of the IEE - Part C: Monographs, vol. 103, no. 3, pp. 200-204, Mar.
Definition and origin of “cross entropy” Thanks to @Itamar's suggestion, I found a mention in: I. J. Good, "Some Terminology and Notation in Information Theory," Proceedings of the IEE - Part C: Monographs, vol. 103, no. 3, pp. 200-204, Mar. 1956. It would still be really useful for me to find a nice presentation of cross-entropy.
Definition and origin of “cross entropy” Thanks to @Itamar's suggestion, I found a mention in: I. J. Good, "Some Terminology and Notation in Information Theory," Proceedings of the IEE - Part C: Monographs, vol. 103, no. 3, pp. 200-204, Mar.
16,653
Definition and origin of “cross entropy”
Thanx for this - good summary of background literature. The 1980 Shore and Johnson article in IEEE is a good start, but @itamar's pointer to the Good monograph from 1956 is even better. The concept seems to come from Shannon's work, with Kullback & Leibler's 1951 AMS note being the origin of the current use of the term. As far as the origin of the term "cross entropy" relates to artificial neural networks, there is a term used in a paper in Science, submitted 1994, published 1995, by G. E. Hinton, P. Dayan, B. J. Frey & R. M. Neal, in which there is an early use of the term "Hemholtz Machine" - possibly the first. Url for copy In that paper, "The Wake-sleep algorithm for unsupervised neural networks", the note before equation #5 says: When there are many alternative ways of describing an input vector it is possible to design a stochastic coding scheme that takes advantage of the entropy across alternative descriptions[1]. The cost is then:" (see paper for eqn#5) The second term is then the entropy of the distribution that the recognition weights assign to the various alternative representations. Later in the paper, eqn#5 is rewritten as eqn#8, with the last term described as the Kullback-Leibler divergence between the initial probability distribution, and the posterior probability distribution. The paper states: So for two generative models which assign equal probability to d, minimizing equation #8 with respect to the generative weights will tend to favour the model whose posterior distribution is most similar to Q(.|d) (Where Q(.|d) is the initial distribution you are training your net towards.) This paper still describes the minimization process for this specific algorithm as minimizing the Kullback-Leibler divergence, but it looks like it could be where the term "entropy across alternative descriptions" was shortened to just "cross entropy". For an numerical example of cross entropy, using TensorFlow, see the posting here, it is helpful: What is cross-entropy? Note that the solution of CE = 0.47965 is derived simply by taking the natural log of the .619 probability. In the above example, the use of "one hot" encoding means that the other two initial and posterior probabilities are ignored due to multiplication by zero-valued initial probability, in the summation for cross entropy.
Definition and origin of “cross entropy”
Thanx for this - good summary of background literature. The 1980 Shore and Johnson article in IEEE is a good start, but @itamar's pointer to the Good monograph from 1956 is even better. The concept
Definition and origin of “cross entropy” Thanx for this - good summary of background literature. The 1980 Shore and Johnson article in IEEE is a good start, but @itamar's pointer to the Good monograph from 1956 is even better. The concept seems to come from Shannon's work, with Kullback & Leibler's 1951 AMS note being the origin of the current use of the term. As far as the origin of the term "cross entropy" relates to artificial neural networks, there is a term used in a paper in Science, submitted 1994, published 1995, by G. E. Hinton, P. Dayan, B. J. Frey & R. M. Neal, in which there is an early use of the term "Hemholtz Machine" - possibly the first. Url for copy In that paper, "The Wake-sleep algorithm for unsupervised neural networks", the note before equation #5 says: When there are many alternative ways of describing an input vector it is possible to design a stochastic coding scheme that takes advantage of the entropy across alternative descriptions[1]. The cost is then:" (see paper for eqn#5) The second term is then the entropy of the distribution that the recognition weights assign to the various alternative representations. Later in the paper, eqn#5 is rewritten as eqn#8, with the last term described as the Kullback-Leibler divergence between the initial probability distribution, and the posterior probability distribution. The paper states: So for two generative models which assign equal probability to d, minimizing equation #8 with respect to the generative weights will tend to favour the model whose posterior distribution is most similar to Q(.|d) (Where Q(.|d) is the initial distribution you are training your net towards.) This paper still describes the minimization process for this specific algorithm as minimizing the Kullback-Leibler divergence, but it looks like it could be where the term "entropy across alternative descriptions" was shortened to just "cross entropy". For an numerical example of cross entropy, using TensorFlow, see the posting here, it is helpful: What is cross-entropy? Note that the solution of CE = 0.47965 is derived simply by taking the natural log of the .619 probability. In the above example, the use of "one hot" encoding means that the other two initial and posterior probabilities are ignored due to multiplication by zero-valued initial probability, in the summation for cross entropy.
Definition and origin of “cross entropy” Thanx for this - good summary of background literature. The 1980 Shore and Johnson article in IEEE is a good start, but @itamar's pointer to the Good monograph from 1956 is even better. The concept
16,654
Predictions using glmnet in R
You need to specify for which value of lambda you want to predict the response. All you need to do is to call like like e.g.: results <-predict(GLMnet_model_1, s=0.01, newx, type="response")
Predictions using glmnet in R
You need to specify for which value of lambda you want to predict the response. All you need to do is to call like like e.g.: results <-predict(GLMnet_model_1, s=0.01, newx, type="response")
Predictions using glmnet in R You need to specify for which value of lambda you want to predict the response. All you need to do is to call like like e.g.: results <-predict(GLMnet_model_1, s=0.01, newx, type="response")
Predictions using glmnet in R You need to specify for which value of lambda you want to predict the response. All you need to do is to call like like e.g.: results <-predict(GLMnet_model_1, s=0.01, newx, type="response")
16,655
Why are ties so difficult in nonparametric statistics?
Most of the work on non-parametrics was originally done assuming that there was an underlying continuous distribution in which ties would be impossible (if measured accurately enough). The theory can then be based on the distributions of order statistics (which are a lot simpler without ties) or other formulas. In some cases the statistic works out to be approximately normal which makes things really easy. When ties are introduced either because the data was rounded or is naturally discrete, then the standard assumptions do not hold. The approximation may still be good enough in some cases, but not in others, so often the easiest thing to do is just give a warning that these formulas don't work with ties. There are tools for some of the standard non-parametric tests that have worked out the exact distribution when ties are present. The exactRankTests package for R is one example. One simple way to deal with ties is to use randomization tests like permutation tests or bootstrapping. These don't worry about asymptotic distributions, but use the data as it is, ties and all (note that with a lot of ties, even these techniques may have low power). There was an article a few years back (I thought in the American Statistician, but I am not finding it) that discussed the ideas of ties and some of the things that you can do with them. One point is that it depends on what question you are asking, what to do with ties can be very different in a superiority test vs. a non-inferiority test.
Why are ties so difficult in nonparametric statistics?
Most of the work on non-parametrics was originally done assuming that there was an underlying continuous distribution in which ties would be impossible (if measured accurately enough). The theory can
Why are ties so difficult in nonparametric statistics? Most of the work on non-parametrics was originally done assuming that there was an underlying continuous distribution in which ties would be impossible (if measured accurately enough). The theory can then be based on the distributions of order statistics (which are a lot simpler without ties) or other formulas. In some cases the statistic works out to be approximately normal which makes things really easy. When ties are introduced either because the data was rounded or is naturally discrete, then the standard assumptions do not hold. The approximation may still be good enough in some cases, but not in others, so often the easiest thing to do is just give a warning that these formulas don't work with ties. There are tools for some of the standard non-parametric tests that have worked out the exact distribution when ties are present. The exactRankTests package for R is one example. One simple way to deal with ties is to use randomization tests like permutation tests or bootstrapping. These don't worry about asymptotic distributions, but use the data as it is, ties and all (note that with a lot of ties, even these techniques may have low power). There was an article a few years back (I thought in the American Statistician, but I am not finding it) that discussed the ideas of ties and some of the things that you can do with them. One point is that it depends on what question you are asking, what to do with ties can be very different in a superiority test vs. a non-inferiority test.
Why are ties so difficult in nonparametric statistics? Most of the work on non-parametrics was originally done assuming that there was an underlying continuous distribution in which ties would be impossible (if measured accurately enough). The theory can
16,656
Interpretation of the Granger causality test [duplicate]
To begin with, the source you added has almost all you need to get acquainted with Granger (non)causality concept (though I like the scholarpedia's article more). The most crucial is that G-causality in practice looks for the answer: would variable $x$ be useful predicting variable $y$, meaning that information containing in variables up to lag $p$ is statistically significant. Thus G-causality is purely statistical property of the data, that may be though supported by theoretically sound hypothesis. Some practical considerations: If you have more than two stationary signals, it may happen that they have to be jointly described by a vector autoregressive model (VAR). Therefore pairwise G-causality could be misleading, since you ignore the impacts that come from the other variables. Suggestion in $R$: try library(vars) and ?causality for instantaneous and G-causality, when you have more than two variables, and VAR seems meaningful (well it is a separate answer when it really is, some ideas are also related to G-causality concept). Previous suggestion is better in multivariate case, comparing to pairwise case library(lmtest) and ?grangertest. On the other hand pairwise case is an option when you do have to work with two variables only. Even in multivariate case you may still perform grangertest just to mark possible useful covariates or decide on statistical possible endogeneity issues. I usually do so when lacking in time, since identification of subsets of variables and hyper-parameters (lag order) selection for VAR models is a not-so-quick task. So for quick useful-predictive-information-containing variables detection it is alright to go pairwise (but do not stop with this results, they are just auxiliary). Note, that under null hypothesis you do test non-G-causality, thus $p$ values will mark G-causal relationships. Conclusions from G-causality tests would be "We know that if $x$ G-cause $y$ statistically significantly, thus it contains useful information that helps to predict future values of $y$". However if we conclude the same about $y$ (feedback effect) it would mean that $x$ and $y$ are both endogenous and VAR type of the model is needed. You may also conclude that if none of the variables G-cause another, it is one of the signs that VAR specification is not necessary. And you may go for separate ARMA models (note, that your variables have to be stationary to perform G-causality tests correctly). Any other suggestions from the community are welcome, @zik you may try gretl as an alternative to $R$ to implement Granger-causality tests.
Interpretation of the Granger causality test [duplicate]
To begin with, the source you added has almost all you need to get acquainted with Granger (non)causality concept (though I like the scholarpedia's article more). The most crucial is that G-causality
Interpretation of the Granger causality test [duplicate] To begin with, the source you added has almost all you need to get acquainted with Granger (non)causality concept (though I like the scholarpedia's article more). The most crucial is that G-causality in practice looks for the answer: would variable $x$ be useful predicting variable $y$, meaning that information containing in variables up to lag $p$ is statistically significant. Thus G-causality is purely statistical property of the data, that may be though supported by theoretically sound hypothesis. Some practical considerations: If you have more than two stationary signals, it may happen that they have to be jointly described by a vector autoregressive model (VAR). Therefore pairwise G-causality could be misleading, since you ignore the impacts that come from the other variables. Suggestion in $R$: try library(vars) and ?causality for instantaneous and G-causality, when you have more than two variables, and VAR seems meaningful (well it is a separate answer when it really is, some ideas are also related to G-causality concept). Previous suggestion is better in multivariate case, comparing to pairwise case library(lmtest) and ?grangertest. On the other hand pairwise case is an option when you do have to work with two variables only. Even in multivariate case you may still perform grangertest just to mark possible useful covariates or decide on statistical possible endogeneity issues. I usually do so when lacking in time, since identification of subsets of variables and hyper-parameters (lag order) selection for VAR models is a not-so-quick task. So for quick useful-predictive-information-containing variables detection it is alright to go pairwise (but do not stop with this results, they are just auxiliary). Note, that under null hypothesis you do test non-G-causality, thus $p$ values will mark G-causal relationships. Conclusions from G-causality tests would be "We know that if $x$ G-cause $y$ statistically significantly, thus it contains useful information that helps to predict future values of $y$". However if we conclude the same about $y$ (feedback effect) it would mean that $x$ and $y$ are both endogenous and VAR type of the model is needed. You may also conclude that if none of the variables G-cause another, it is one of the signs that VAR specification is not necessary. And you may go for separate ARMA models (note, that your variables have to be stationary to perform G-causality tests correctly). Any other suggestions from the community are welcome, @zik you may try gretl as an alternative to $R$ to implement Granger-causality tests.
Interpretation of the Granger causality test [duplicate] To begin with, the source you added has almost all you need to get acquainted with Granger (non)causality concept (though I like the scholarpedia's article more). The most crucial is that G-causality
16,657
Online algorithm for mean absolute deviation and large data set
If you can accept some inaccuracy, this problem can be solved easily by binning counts. That is, pick some largeish number $M$ (say $M = 1000$), then initialize some integer bins $B_{i,j}$ for $i = 1\ldots M$ and $j = 1\ldots N$, where $N$ is the vector size, as zero. Then when you see the $k$th observation of a percentual vector, increment $B_{i,j}$ if the $j$th element of this vector is between $(i-1)/M$ and $i/M$, looping over the $N$ elements of the vector. (I am assuming your input vectors are non-negative, so that when you compute your 'percentuals', the vectors are in the range $[0,1]$. ) At any point in time, you can estimate the mean vector from the bins, and the mean absolute deviation. After observing $K$ such vectors, the $j$th element of the mean is estimated by $$\bar{X}_j = \frac{1}{K} \sum_i \frac{i - 1/2}{M} B_{i,j},$$ and the $j$th element of the mean absolute deviation is estimated by $$\frac{1}{K} \sum_i | \bar{X_j} - \frac{i - 1/2}{M} | B_{i,j}$$ edit: this is a specific case of a more general approach where you are building an empirical density estimate. This could be done with polynomials, splines, etc, but the binning approach is the easiest to describe and implement.
Online algorithm for mean absolute deviation and large data set
If you can accept some inaccuracy, this problem can be solved easily by binning counts. That is, pick some largeish number $M$ (say $M = 1000$), then initialize some integer bins $B_{i,j}$ for $i = 1\
Online algorithm for mean absolute deviation and large data set If you can accept some inaccuracy, this problem can be solved easily by binning counts. That is, pick some largeish number $M$ (say $M = 1000$), then initialize some integer bins $B_{i,j}$ for $i = 1\ldots M$ and $j = 1\ldots N$, where $N$ is the vector size, as zero. Then when you see the $k$th observation of a percentual vector, increment $B_{i,j}$ if the $j$th element of this vector is between $(i-1)/M$ and $i/M$, looping over the $N$ elements of the vector. (I am assuming your input vectors are non-negative, so that when you compute your 'percentuals', the vectors are in the range $[0,1]$. ) At any point in time, you can estimate the mean vector from the bins, and the mean absolute deviation. After observing $K$ such vectors, the $j$th element of the mean is estimated by $$\bar{X}_j = \frac{1}{K} \sum_i \frac{i - 1/2}{M} B_{i,j},$$ and the $j$th element of the mean absolute deviation is estimated by $$\frac{1}{K} \sum_i | \bar{X_j} - \frac{i - 1/2}{M} | B_{i,j}$$ edit: this is a specific case of a more general approach where you are building an empirical density estimate. This could be done with polynomials, splines, etc, but the binning approach is the easiest to describe and implement.
Online algorithm for mean absolute deviation and large data set If you can accept some inaccuracy, this problem can be solved easily by binning counts. That is, pick some largeish number $M$ (say $M = 1000$), then initialize some integer bins $B_{i,j}$ for $i = 1\
16,658
Online algorithm for mean absolute deviation and large data set
I've used the following approach in the past to calculate absolution deviation moderately efficiently (note, this a programmers approach, not a statisticians, so indubitably there may be clever tricks like shabbychef's that might be more efficient). WARNING: This is not an online algorithm. It requires O(n) memory. Furthermore, it has a worst case performance of O(n), for datasets like [1, -2, 4, -8, 16, -32, ...] (i.e. the same as the full recalculation). [1] However, because it still performs well in many use cases it might be worth posting here. For example, in order to calculate the absolute deviance of 10000 random numbers between -100 and 100 as each item arrives, my algorithm takes less than one second, while the full recalculation takes over 17 seconds (on my machine, will vary per machine and according to input data). You need to maintain the entire vector in memory however, which may be a constraint for some uses. The outline of the algorithm is as follows: Instead of having a single vector to store past measurements, use three sorted priority queues (something like a min/max heap). These three lists partition the input into three: items greater than the mean, items less than the mean and items equal to the mean. (Almost) every time you add an item the mean changes, so we need to repartition. The crucial thing is the sorted nature of the partitions which means that instead of scanning every item in the list to repartion, we only need to read those items we are moving. While in the worst case this will still require O(n) move operations, for many use-cases this is not so. Using some clever bookkeeping, we can make sure that the deviance is correctly calculated at all times, when repartitioning and when adding new items. Some sample code, in python, is below. Note that it only allows items to be added to the list, not removed. This could easily be added, but at the time I wrote this I had no need for it. Rather than implement the priority queues myself, I have used the sortedlist from Daniel Stutzbach's excellent blist package, which use B+Trees internally. Consider this code licensed under the MIT license. It has not been significantly optimised or polished, but has worked for me in the past. New versions will be available here. Let me know if you have any questions, or find any bugs. from blist import sortedlist import operator class deviance_list: def __init__(self): self.mean = 0.0 self._old_mean = 0.0 self._sum = 0L self._n = 0 #n items # items greater than the mean self._toplist = sortedlist() # items less than the mean self._bottomlist = sortedlist(key = operator.neg) # Since all items in the "eq list" have the same value (self.mean) we don't need # to maintain an eq list, only a count self._eqlistlen = 0 self._top_deviance = 0 self._bottom_deviance = 0 @property def absolute_deviance(self): return self._top_deviance + self._bottom_deviance def append(self, n): # Update summary stats self._sum += n self._n += 1 self._old_mean = self.mean self.mean = self._sum / float(self._n) # Move existing things around going_up = self.mean > self._old_mean self._rebalance(going_up) # Add new item to appropriate list if n > self.mean: self._toplist.add(n) self._top_deviance += n - self.mean elif n == self.mean: self._eqlistlen += 1 else: self._bottomlist.add(n) self._bottom_deviance += self.mean - n def _move_eqs(self, going_up): if going_up: self._bottomlist.update([self._old_mean] * self._eqlistlen) self._bottom_deviance += (self.mean - self._old_mean) * self._eqlistlen self._eqlistlen = 0 else: self._toplist.update([self._old_mean] * self._eqlistlen) self._top_deviance += (self._old_mean - self.mean) * self._eqlistlen self._eqlistlen = 0 def _rebalance(self, going_up): move_count, eq_move_count = 0, 0 if going_up: # increase the bottom deviance of the items already in the bottomlist if self.mean != self._old_mean: self._bottom_deviance += len(self._bottomlist) * (self.mean - self._old_mean) self._move_eqs(going_up) # transfer items from top to bottom (or eq) list, and change the deviances for n in iter(self._toplist): if n < self.mean: self._top_deviance -= n - self._old_mean self._bottom_deviance += (self.mean - n) # we increment movecount and move them after the list # has finished iterating so we don't modify the list during iteration move_count += 1 elif n == self.mean: self._top_deviance -= n - self._old_mean self._eqlistlen += 1 eq_move_count += 1 else: break for _ in xrange(0, move_count): self._bottomlist.add(self._toplist.pop(0)) for _ in xrange(0, eq_move_count): self._toplist.pop(0) # decrease the top deviance of the items remain in the toplist self._top_deviance -= len(self._toplist) * (self.mean - self._old_mean) else: if self.mean != self._old_mean: self._top_deviance += len(self._toplist) * (self._old_mean - self.mean) self._move_eqs(going_up) for n in iter(self._bottomlist): if n > self.mean: self._bottom_deviance -= self._old_mean - n self._top_deviance += n - self.mean move_count += 1 elif n == self.mean: self._bottom_deviance -= self._old_mean - n self._eqlistlen += 1 eq_move_count += 1 else: break for _ in xrange(0, move_count): self._toplist.add(self._bottomlist.pop(0)) for _ in xrange(0, eq_move_count): self._bottomlist.pop(0) # decrease the bottom deviance of the items remain in the bottomlist self._bottom_deviance -= len(self._bottomlist) * (self._old_mean - self.mean) if __name__ == "__main__": import random dv = deviance_list() # Test against some random data, and calculate result manually (nb. slowly) to ensure correctness rands = [random.randint(-100, 100) for _ in range(0, 1000)] ns = [] for n in rands: dv.append(n) ns.append(n) print("added:%4d, mean:%3.2f, oldmean:%3.2f, mean ad:%3.2f" % (n, dv.mean, dv._old_mean, dv.absolute_deviance / dv.mean)) assert sum(ns) == dv._sum, "Sums not equal!" assert len(ns) == dv._n, "Counts not equal!" m = sum(ns) / float(len(ns)) assert m == dv.mean, "Means not equal!" real_abs_dev = sum([abs(m - x) for x in ns]) # Due to floating point imprecision, we check if the difference between the # two ways of calculating the asb. dev. is small rather than checking equality assert abs(real_abs_dev - dv.absolute_deviance) < 0.01, ( "Absolute deviances not equal. Real:%.2f, calc:%.2f" % (real_abs_dev, dv.absolute_deviance)) [1] If symptoms persist, see your doctor.
Online algorithm for mean absolute deviation and large data set
I've used the following approach in the past to calculate absolution deviation moderately efficiently (note, this a programmers approach, not a statisticians, so indubitably there may be clever tricks
Online algorithm for mean absolute deviation and large data set I've used the following approach in the past to calculate absolution deviation moderately efficiently (note, this a programmers approach, not a statisticians, so indubitably there may be clever tricks like shabbychef's that might be more efficient). WARNING: This is not an online algorithm. It requires O(n) memory. Furthermore, it has a worst case performance of O(n), for datasets like [1, -2, 4, -8, 16, -32, ...] (i.e. the same as the full recalculation). [1] However, because it still performs well in many use cases it might be worth posting here. For example, in order to calculate the absolute deviance of 10000 random numbers between -100 and 100 as each item arrives, my algorithm takes less than one second, while the full recalculation takes over 17 seconds (on my machine, will vary per machine and according to input data). You need to maintain the entire vector in memory however, which may be a constraint for some uses. The outline of the algorithm is as follows: Instead of having a single vector to store past measurements, use three sorted priority queues (something like a min/max heap). These three lists partition the input into three: items greater than the mean, items less than the mean and items equal to the mean. (Almost) every time you add an item the mean changes, so we need to repartition. The crucial thing is the sorted nature of the partitions which means that instead of scanning every item in the list to repartion, we only need to read those items we are moving. While in the worst case this will still require O(n) move operations, for many use-cases this is not so. Using some clever bookkeeping, we can make sure that the deviance is correctly calculated at all times, when repartitioning and when adding new items. Some sample code, in python, is below. Note that it only allows items to be added to the list, not removed. This could easily be added, but at the time I wrote this I had no need for it. Rather than implement the priority queues myself, I have used the sortedlist from Daniel Stutzbach's excellent blist package, which use B+Trees internally. Consider this code licensed under the MIT license. It has not been significantly optimised or polished, but has worked for me in the past. New versions will be available here. Let me know if you have any questions, or find any bugs. from blist import sortedlist import operator class deviance_list: def __init__(self): self.mean = 0.0 self._old_mean = 0.0 self._sum = 0L self._n = 0 #n items # items greater than the mean self._toplist = sortedlist() # items less than the mean self._bottomlist = sortedlist(key = operator.neg) # Since all items in the "eq list" have the same value (self.mean) we don't need # to maintain an eq list, only a count self._eqlistlen = 0 self._top_deviance = 0 self._bottom_deviance = 0 @property def absolute_deviance(self): return self._top_deviance + self._bottom_deviance def append(self, n): # Update summary stats self._sum += n self._n += 1 self._old_mean = self.mean self.mean = self._sum / float(self._n) # Move existing things around going_up = self.mean > self._old_mean self._rebalance(going_up) # Add new item to appropriate list if n > self.mean: self._toplist.add(n) self._top_deviance += n - self.mean elif n == self.mean: self._eqlistlen += 1 else: self._bottomlist.add(n) self._bottom_deviance += self.mean - n def _move_eqs(self, going_up): if going_up: self._bottomlist.update([self._old_mean] * self._eqlistlen) self._bottom_deviance += (self.mean - self._old_mean) * self._eqlistlen self._eqlistlen = 0 else: self._toplist.update([self._old_mean] * self._eqlistlen) self._top_deviance += (self._old_mean - self.mean) * self._eqlistlen self._eqlistlen = 0 def _rebalance(self, going_up): move_count, eq_move_count = 0, 0 if going_up: # increase the bottom deviance of the items already in the bottomlist if self.mean != self._old_mean: self._bottom_deviance += len(self._bottomlist) * (self.mean - self._old_mean) self._move_eqs(going_up) # transfer items from top to bottom (or eq) list, and change the deviances for n in iter(self._toplist): if n < self.mean: self._top_deviance -= n - self._old_mean self._bottom_deviance += (self.mean - n) # we increment movecount and move them after the list # has finished iterating so we don't modify the list during iteration move_count += 1 elif n == self.mean: self._top_deviance -= n - self._old_mean self._eqlistlen += 1 eq_move_count += 1 else: break for _ in xrange(0, move_count): self._bottomlist.add(self._toplist.pop(0)) for _ in xrange(0, eq_move_count): self._toplist.pop(0) # decrease the top deviance of the items remain in the toplist self._top_deviance -= len(self._toplist) * (self.mean - self._old_mean) else: if self.mean != self._old_mean: self._top_deviance += len(self._toplist) * (self._old_mean - self.mean) self._move_eqs(going_up) for n in iter(self._bottomlist): if n > self.mean: self._bottom_deviance -= self._old_mean - n self._top_deviance += n - self.mean move_count += 1 elif n == self.mean: self._bottom_deviance -= self._old_mean - n self._eqlistlen += 1 eq_move_count += 1 else: break for _ in xrange(0, move_count): self._toplist.add(self._bottomlist.pop(0)) for _ in xrange(0, eq_move_count): self._bottomlist.pop(0) # decrease the bottom deviance of the items remain in the bottomlist self._bottom_deviance -= len(self._bottomlist) * (self._old_mean - self.mean) if __name__ == "__main__": import random dv = deviance_list() # Test against some random data, and calculate result manually (nb. slowly) to ensure correctness rands = [random.randint(-100, 100) for _ in range(0, 1000)] ns = [] for n in rands: dv.append(n) ns.append(n) print("added:%4d, mean:%3.2f, oldmean:%3.2f, mean ad:%3.2f" % (n, dv.mean, dv._old_mean, dv.absolute_deviance / dv.mean)) assert sum(ns) == dv._sum, "Sums not equal!" assert len(ns) == dv._n, "Counts not equal!" m = sum(ns) / float(len(ns)) assert m == dv.mean, "Means not equal!" real_abs_dev = sum([abs(m - x) for x in ns]) # Due to floating point imprecision, we check if the difference between the # two ways of calculating the asb. dev. is small rather than checking equality assert abs(real_abs_dev - dv.absolute_deviance) < 0.01, ( "Absolute deviances not equal. Real:%.2f, calc:%.2f" % (real_abs_dev, dv.absolute_deviance)) [1] If symptoms persist, see your doctor.
Online algorithm for mean absolute deviation and large data set I've used the following approach in the past to calculate absolution deviation moderately efficiently (note, this a programmers approach, not a statisticians, so indubitably there may be clever tricks
16,659
Online algorithm for mean absolute deviation and large data set
There is also a parametric approach. Ignoring the vector nature of your data, and looking only at the marginals, it suffices to solve the problem: find an online algorithm to compute the mean absolute deviation of scalar $X$. If (and this is the big 'if' here) you thought that $X$ followed some probability distribution with unknown parameters, you could estimate the parameters using some online algorithm, then compute the mean absolute deviation based on that parametrized distribution. For example, if you thought that $X$ was (approximately) normally distributed, you could estimate its standard deviation, as $s$, and the mean absolute deviation would be estimated by $s \sqrt{2 / \pi}$ (see Half Normal Distribution).
Online algorithm for mean absolute deviation and large data set
There is also a parametric approach. Ignoring the vector nature of your data, and looking only at the marginals, it suffices to solve the problem: find an online algorithm to compute the mean absolute
Online algorithm for mean absolute deviation and large data set There is also a parametric approach. Ignoring the vector nature of your data, and looking only at the marginals, it suffices to solve the problem: find an online algorithm to compute the mean absolute deviation of scalar $X$. If (and this is the big 'if' here) you thought that $X$ followed some probability distribution with unknown parameters, you could estimate the parameters using some online algorithm, then compute the mean absolute deviation based on that parametrized distribution. For example, if you thought that $X$ was (approximately) normally distributed, you could estimate its standard deviation, as $s$, and the mean absolute deviation would be estimated by $s \sqrt{2 / \pi}$ (see Half Normal Distribution).
Online algorithm for mean absolute deviation and large data set There is also a parametric approach. Ignoring the vector nature of your data, and looking only at the marginals, it suffices to solve the problem: find an online algorithm to compute the mean absolute
16,660
Online algorithm for mean absolute deviation and large data set
MAD(x) is just two concurrent median computation, each of which can be made online through the binmedian algorithm. You can find the associated paper as well as C and FORTRAN code online here. (this is just the use of a clever trick on top of Shabbychef's clever trick, to save on memory). Addendum: There exist a host of older multi-pass methods for computing quantiles. A popular approach is to maintain/update a deterministically sized reservoir of observations randomly selected from the stream and recursively compute quantiles (see this review) on this reservoir. This (and related) approach are superseded by the one proposed above.
Online algorithm for mean absolute deviation and large data set
MAD(x) is just two concurrent median computation, each of which can be made online through the binmedian algorithm. You can find the associated paper as well as C and FORTRAN code online here. (this i
Online algorithm for mean absolute deviation and large data set MAD(x) is just two concurrent median computation, each of which can be made online through the binmedian algorithm. You can find the associated paper as well as C and FORTRAN code online here. (this is just the use of a clever trick on top of Shabbychef's clever trick, to save on memory). Addendum: There exist a host of older multi-pass methods for computing quantiles. A popular approach is to maintain/update a deterministically sized reservoir of observations randomly selected from the stream and recursively compute quantiles (see this review) on this reservoir. This (and related) approach are superseded by the one proposed above.
Online algorithm for mean absolute deviation and large data set MAD(x) is just two concurrent median computation, each of which can be made online through the binmedian algorithm. You can find the associated paper as well as C and FORTRAN code online here. (this i
16,661
Online algorithm for mean absolute deviation and large data set
The following provides an inaccurate approximation, although the inaccuracy will depend on the distribution of the input data. It is an online algorithm, but only approximates the absolute deviance. It is based on a well known algorithm for calculating variance online, described by Welford in the 1960s. His algorithm, translated into R, looks like: M2 <- 0 mean <- 0 n <- 0 var.online <- function(x){ n <<- n + 1 diff <- x - mean mean <<- mean + diff / n M2 <<- M2 + diff * (x - mean) variance <- M2 / (n - 1) return(variance) } It performs very similarly to R's builtin variance function: set.seed(2099) n.testitems <- 1000 n.tests <- 100 differences <- rep(NA, n.tests) for (i in 1:n.tests){ # Reset counters M2 <- 0 mean <- 0 n <- 0 xs <- rnorm(n.testitems) for (j in 1:n.testitems){ v <- var.online(xs[j]) } differences[i] <- abs(v - var(xs)) } summary(differences) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.000e+00 2.220e-16 4.996e-16 6.595e-16 9.992e-16 1.887e-15 Modifying the algorithm to calculate absolute deviation simply involves an additional sqrt call. However, the sqrt introduces inaccuracies that are reflected in the result: absolute.deviance.online <- function(x){ n <<- n + 1 diff <- x - mean mean <<- mean + diff / n a.dev <<- a.dev + sqrt(diff * (x - mean)) return(a.dev) } The errors, calculated as above, are much greater than for the variance calculation: Min. 1st Qu. Median Mean 3rd Qu. Max. 0.005126 0.364600 0.808000 0.958800 1.360000 3.312000 However, depending on your use case, this magnitude of error might be acceptable.
Online algorithm for mean absolute deviation and large data set
The following provides an inaccurate approximation, although the inaccuracy will depend on the distribution of the input data. It is an online algorithm, but only approximates the absolute deviance.
Online algorithm for mean absolute deviation and large data set The following provides an inaccurate approximation, although the inaccuracy will depend on the distribution of the input data. It is an online algorithm, but only approximates the absolute deviance. It is based on a well known algorithm for calculating variance online, described by Welford in the 1960s. His algorithm, translated into R, looks like: M2 <- 0 mean <- 0 n <- 0 var.online <- function(x){ n <<- n + 1 diff <- x - mean mean <<- mean + diff / n M2 <<- M2 + diff * (x - mean) variance <- M2 / (n - 1) return(variance) } It performs very similarly to R's builtin variance function: set.seed(2099) n.testitems <- 1000 n.tests <- 100 differences <- rep(NA, n.tests) for (i in 1:n.tests){ # Reset counters M2 <- 0 mean <- 0 n <- 0 xs <- rnorm(n.testitems) for (j in 1:n.testitems){ v <- var.online(xs[j]) } differences[i] <- abs(v - var(xs)) } summary(differences) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.000e+00 2.220e-16 4.996e-16 6.595e-16 9.992e-16 1.887e-15 Modifying the algorithm to calculate absolute deviation simply involves an additional sqrt call. However, the sqrt introduces inaccuracies that are reflected in the result: absolute.deviance.online <- function(x){ n <<- n + 1 diff <- x - mean mean <<- mean + diff / n a.dev <<- a.dev + sqrt(diff * (x - mean)) return(a.dev) } The errors, calculated as above, are much greater than for the variance calculation: Min. 1st Qu. Median Mean 3rd Qu. Max. 0.005126 0.364600 0.808000 0.958800 1.360000 3.312000 However, depending on your use case, this magnitude of error might be acceptable.
Online algorithm for mean absolute deviation and large data set The following provides an inaccurate approximation, although the inaccuracy will depend on the distribution of the input data. It is an online algorithm, but only approximates the absolute deviance.
16,662
Problems with one-hot encoding vs. dummy encoding
The issue with representing a categorical variable that has $k$ levels with $k$ variables in regression is that, if the model also has a constant term, then the terms will be linearly dependent and hence the model will be unidentifiable. For example, if the model is $μ = a_0 + a_1X_1 + a_2X_2$ and $X_2 = 1 - X_1$, then any choice $(β_0, β_1, β_2)$ of the parameter vector is indistinguishable from $(β_0 + β_2,\; β_1 - β_2,\; 0)$. So although software may be willing to give you estimates for these parameters, they aren't uniquely determined and hence probably won't be very useful. Penalization will make the model identifiable, but redundant coding will still affect the parameter values in weird ways, given the above. The effect of a redundant coding on a decision tree (or ensemble of trees) will likely be to overweight the feature in question relative to others, since it's represented with an extra redundant variable and therefore will be chosen more often than it otherwise would be for splits.
Problems with one-hot encoding vs. dummy encoding
The issue with representing a categorical variable that has $k$ levels with $k$ variables in regression is that, if the model also has a constant term, then the terms will be linearly dependent and he
Problems with one-hot encoding vs. dummy encoding The issue with representing a categorical variable that has $k$ levels with $k$ variables in regression is that, if the model also has a constant term, then the terms will be linearly dependent and hence the model will be unidentifiable. For example, if the model is $μ = a_0 + a_1X_1 + a_2X_2$ and $X_2 = 1 - X_1$, then any choice $(β_0, β_1, β_2)$ of the parameter vector is indistinguishable from $(β_0 + β_2,\; β_1 - β_2,\; 0)$. So although software may be willing to give you estimates for these parameters, they aren't uniquely determined and hence probably won't be very useful. Penalization will make the model identifiable, but redundant coding will still affect the parameter values in weird ways, given the above. The effect of a redundant coding on a decision tree (or ensemble of trees) will likely be to overweight the feature in question relative to others, since it's represented with an extra redundant variable and therefore will be chosen more often than it otherwise would be for splits.
Problems with one-hot encoding vs. dummy encoding The issue with representing a categorical variable that has $k$ levels with $k$ variables in regression is that, if the model also has a constant term, then the terms will be linearly dependent and he
16,663
Problems with one-hot encoding vs. dummy encoding
I feel the best answer to this question is buried in the comments by @MatthewDrury, which states that there is a difference and that you should use the seemingly redundant column in any regularized approach. @MatthewDrury's reasoning is [In regularized regression], the intercept is not penalized, so if you are inferring the effect of a level as not part of the intercept, its hard to say you are penalizing all levels equally. Instead, always include all the levels, so each is symmetric with respect to the penalty. I think he's got a point.
Problems with one-hot encoding vs. dummy encoding
I feel the best answer to this question is buried in the comments by @MatthewDrury, which states that there is a difference and that you should use the seemingly redundant column in any regularized ap
Problems with one-hot encoding vs. dummy encoding I feel the best answer to this question is buried in the comments by @MatthewDrury, which states that there is a difference and that you should use the seemingly redundant column in any regularized approach. @MatthewDrury's reasoning is [In regularized regression], the intercept is not penalized, so if you are inferring the effect of a level as not part of the intercept, its hard to say you are penalizing all levels equally. Instead, always include all the levels, so each is symmetric with respect to the penalty. I think he's got a point.
Problems with one-hot encoding vs. dummy encoding I feel the best answer to this question is buried in the comments by @MatthewDrury, which states that there is a difference and that you should use the seemingly redundant column in any regularized ap
16,664
Problems with one-hot encoding vs. dummy encoding
Kodiologist had a great answer (+1). One-hot encoding vs. dummy encoding encoding methods are the same, in terms of the design matrix are in the same space, with different basis. (although the one-hot encoding has more columns) Therefore if you are focusing on accuracy instead of interpretability. Two encoding methods makes no difference.
Problems with one-hot encoding vs. dummy encoding
Kodiologist had a great answer (+1). One-hot encoding vs. dummy encoding encoding methods are the same, in terms of the design matrix are in the same space, with different basis. (although the one-hot
Problems with one-hot encoding vs. dummy encoding Kodiologist had a great answer (+1). One-hot encoding vs. dummy encoding encoding methods are the same, in terms of the design matrix are in the same space, with different basis. (although the one-hot encoding has more columns) Therefore if you are focusing on accuracy instead of interpretability. Two encoding methods makes no difference.
Problems with one-hot encoding vs. dummy encoding Kodiologist had a great answer (+1). One-hot encoding vs. dummy encoding encoding methods are the same, in terms of the design matrix are in the same space, with different basis. (although the one-hot
16,665
How to make LSTM predict multiple time steps ahead?
There are different approaches Recursive strategy one many-to-one model prediction(t+1) = model(obs(t-1), obs(t-2), ..., obs(t-n)) prediction(t+2) = model(prediction(t+1), obs(t-1), ..., obs(t-n)) Direct strategy multiple many-to-one models prediction(t+1) = model1(obs(t-1), obs(t-2), ..., obs(t-n)) prediction(t+2) = model2(obs(t-2), obs(t-3), ..., obs(t-n))` Multiple output strategy one many-to-many model prediction(t+1), prediction(t+2) = model(obs(t-1), obs(t-2), ..., obs(t-n))` Hybrid Strategies combine two or more above strategies Reference : Multi-Step Time Series Forecasting
How to make LSTM predict multiple time steps ahead?
There are different approaches Recursive strategy one many-to-one model prediction(t+1) = model(obs(t-1), obs(t-2), ..., obs(t-n)) prediction(t+2) = model(prediction(t+1), obs(t-1), ..., obs(t-n))
How to make LSTM predict multiple time steps ahead? There are different approaches Recursive strategy one many-to-one model prediction(t+1) = model(obs(t-1), obs(t-2), ..., obs(t-n)) prediction(t+2) = model(prediction(t+1), obs(t-1), ..., obs(t-n)) Direct strategy multiple many-to-one models prediction(t+1) = model1(obs(t-1), obs(t-2), ..., obs(t-n)) prediction(t+2) = model2(obs(t-2), obs(t-3), ..., obs(t-n))` Multiple output strategy one many-to-many model prediction(t+1), prediction(t+2) = model(obs(t-1), obs(t-2), ..., obs(t-n))` Hybrid Strategies combine two or more above strategies Reference : Multi-Step Time Series Forecasting
How to make LSTM predict multiple time steps ahead? There are different approaches Recursive strategy one many-to-one model prediction(t+1) = model(obs(t-1), obs(t-2), ..., obs(t-n)) prediction(t+2) = model(prediction(t+1), obs(t-1), ..., obs(t-n))
16,666
How to make LSTM predict multiple time steps ahead?
From https://machinelearningmastery.com/multi-step-time-series-forecasting-long-short-term-memory-networks-python/ train = [[t-120,t-199...t,t+1...t+60],[...],[...]] # fit an LSTM network to training data def fit_lstm(train, n_lag, n_seq, n_batch, nb_epoch, n_neurons): # reshape training into [samples, timesteps, features] X, y = train[:, 0:n_lag], train[:, n_lag:] X = X.reshape(X.shape[0], 1, X.shape[1]) # design network model = Sequential() model.add(LSTM(n_neurons, batch_input_shape=(n_batch, X.shape[1], X.shape[2]), stateful=True)) model.add(Dense(y.shape[1])) model.compile(loss='mean_squared_error', optimizer='adam') # fit network for i in range(nb_epoch): model.fit(X, y, epochs=1, batch_size=n_batch, verbose=0, shuffle=False) model.reset_states() return model
How to make LSTM predict multiple time steps ahead?
From https://machinelearningmastery.com/multi-step-time-series-forecasting-long-short-term-memory-networks-python/ train = [[t-120,t-199...t,t+1...t+60],[...],[...]] # fit an LSTM network to training
How to make LSTM predict multiple time steps ahead? From https://machinelearningmastery.com/multi-step-time-series-forecasting-long-short-term-memory-networks-python/ train = [[t-120,t-199...t,t+1...t+60],[...],[...]] # fit an LSTM network to training data def fit_lstm(train, n_lag, n_seq, n_batch, nb_epoch, n_neurons): # reshape training into [samples, timesteps, features] X, y = train[:, 0:n_lag], train[:, n_lag:] X = X.reshape(X.shape[0], 1, X.shape[1]) # design network model = Sequential() model.add(LSTM(n_neurons, batch_input_shape=(n_batch, X.shape[1], X.shape[2]), stateful=True)) model.add(Dense(y.shape[1])) model.compile(loss='mean_squared_error', optimizer='adam') # fit network for i in range(nb_epoch): model.fit(X, y, epochs=1, batch_size=n_batch, verbose=0, shuffle=False) model.reset_states() return model
How to make LSTM predict multiple time steps ahead? From https://machinelearningmastery.com/multi-step-time-series-forecasting-long-short-term-memory-networks-python/ train = [[t-120,t-199...t,t+1...t+60],[...],[...]] # fit an LSTM network to training
16,667
Hamiltonian monte carlo
I believe the most up-to-date source on Hamiltonian Monte Carlo, its practical applications and comparison to other MCMC methods is this 2017-dated review paper by Betancourt: The ultimate challenge in estimating probabilistic expectations is quantifying the typical set of the target distribution, a set which concentrates near a complex surface in parameter space. Hamiltonian Monte Carlo generates coherent exploration of smooth target distributions by exploiting the geometry of the typical set. This effective exploration yields not only better computational efficiency than other Markov chain Monte Carlo algorithms, but also stronger guarantees on the validity of the resulting estimators. Moreover, careful analysis of this geometry facilitates principled strategies for automatically constructing optimal implementations of the method, allowing users to focus their expertise into building better models instead of wrestling with the frustrations of statistical computation. As a result, Hamiltonian Monte Carlo is uniquely suited to tackling the most challenging problems at the frontiers of applied statistics, as demonstrated by the huge success of tools like Stan (Stan Development Team, 2017).
Hamiltonian monte carlo
I believe the most up-to-date source on Hamiltonian Monte Carlo, its practical applications and comparison to other MCMC methods is this 2017-dated review paper by Betancourt: The ultimate challenge
Hamiltonian monte carlo I believe the most up-to-date source on Hamiltonian Monte Carlo, its practical applications and comparison to other MCMC methods is this 2017-dated review paper by Betancourt: The ultimate challenge in estimating probabilistic expectations is quantifying the typical set of the target distribution, a set which concentrates near a complex surface in parameter space. Hamiltonian Monte Carlo generates coherent exploration of smooth target distributions by exploiting the geometry of the typical set. This effective exploration yields not only better computational efficiency than other Markov chain Monte Carlo algorithms, but also stronger guarantees on the validity of the resulting estimators. Moreover, careful analysis of this geometry facilitates principled strategies for automatically constructing optimal implementations of the method, allowing users to focus their expertise into building better models instead of wrestling with the frustrations of statistical computation. As a result, Hamiltonian Monte Carlo is uniquely suited to tackling the most challenging problems at the frontiers of applied statistics, as demonstrated by the huge success of tools like Stan (Stan Development Team, 2017).
Hamiltonian monte carlo I believe the most up-to-date source on Hamiltonian Monte Carlo, its practical applications and comparison to other MCMC methods is this 2017-dated review paper by Betancourt: The ultimate challenge
16,668
Hamiltonian monte carlo
Hamiltonian Monte Carlo (HMC), originally called Hybrid Monte Carlo, is a form of Markov Chain Monte Carlo with a momentum term and corrections. The "Hamiltonian" refers to Hamiltonian mechanics. The use-case is stochastically (randomly) exploring high dimensions for numeric integration over a probability space. Contrast with MCMC Plain/vanilla Markov Chain Monte Carlo (MCMC) uses only the last state to determine the next state. That means that you are as likely to go forward as you are to go back over space you have already explored. MCMC also is likely to drift outside of the primary area of interest in high dimensional spaces as well. This makes MCMC very inefficient for the purposes of numeric integration over a multidimensional probability space. How HMC handles these issues By adding in a momentum term, HMC makes the exploration of the probability space more efficient, as you are now more likely to make forward progress with each step through your probability space. HMC also uses Metropolis-Hastings corrections to ensure it stays in and explores the region of greater probability. In writing up this answer, I found this presentation on HMC to be quite illuminating.
Hamiltonian monte carlo
Hamiltonian Monte Carlo (HMC), originally called Hybrid Monte Carlo, is a form of Markov Chain Monte Carlo with a momentum term and corrections. The "Hamiltonian" refers to Hamiltonian mechanics. The
Hamiltonian monte carlo Hamiltonian Monte Carlo (HMC), originally called Hybrid Monte Carlo, is a form of Markov Chain Monte Carlo with a momentum term and corrections. The "Hamiltonian" refers to Hamiltonian mechanics. The use-case is stochastically (randomly) exploring high dimensions for numeric integration over a probability space. Contrast with MCMC Plain/vanilla Markov Chain Monte Carlo (MCMC) uses only the last state to determine the next state. That means that you are as likely to go forward as you are to go back over space you have already explored. MCMC also is likely to drift outside of the primary area of interest in high dimensional spaces as well. This makes MCMC very inefficient for the purposes of numeric integration over a multidimensional probability space. How HMC handles these issues By adding in a momentum term, HMC makes the exploration of the probability space more efficient, as you are now more likely to make forward progress with each step through your probability space. HMC also uses Metropolis-Hastings corrections to ensure it stays in and explores the region of greater probability. In writing up this answer, I found this presentation on HMC to be quite illuminating.
Hamiltonian monte carlo Hamiltonian Monte Carlo (HMC), originally called Hybrid Monte Carlo, is a form of Markov Chain Monte Carlo with a momentum term and corrections. The "Hamiltonian" refers to Hamiltonian mechanics. The
16,669
When does maximum likelihood work and when it doesn't?
While the arithmetic mean $\bar{x}$ may sound as the "natural" estimator, one could ask why it should be preferred to the MLE! The only sure property associated with the arithmetic mean is that it is an unbiased estimator of $\mathbb{E}[X]$ when this expectation is defined. (Think of the Cauchy distribution as a counter-example.) The later indeed enjoys a wide range of properties under regularity conditions on the likelihood function. To borrow from the wikipedia page, the MLE is consistent asymptotically normal efficient in that it achieves the minimum asymptotic variance invariant under bijective transforms within the parameter set even for constrained parameter sets In comparison with the arithmetic mean, most of those properties are also satisfied for regular enough distributions. Except 4 and 5. In the case of exponential families, the MLE and the arithmetic mean are identical for estimating the parameter in the mean parameterisation (but not for other parameterisations). And the MLE exists for a sample from the Cauchy distribution. However, when turning to finite sample optimality properties like minimaxity or admissibility, it may happen that the MLE is neither minimax nor admissible. For instance, the Stein effect shows there exist estimators with a smaller quadratic risk for all values of the parameter under some constraints on the distribution of the sample and the dimension of the parameter. This is the case when $x\sim\mathcal{N}_p(\theta,I_p)$ and $p\ge 3$.
When does maximum likelihood work and when it doesn't?
While the arithmetic mean $\bar{x}$ may sound as the "natural" estimator, one could ask why it should be preferred to the MLE! The only sure property associated with the arithmetic mean is that it is
When does maximum likelihood work and when it doesn't? While the arithmetic mean $\bar{x}$ may sound as the "natural" estimator, one could ask why it should be preferred to the MLE! The only sure property associated with the arithmetic mean is that it is an unbiased estimator of $\mathbb{E}[X]$ when this expectation is defined. (Think of the Cauchy distribution as a counter-example.) The later indeed enjoys a wide range of properties under regularity conditions on the likelihood function. To borrow from the wikipedia page, the MLE is consistent asymptotically normal efficient in that it achieves the minimum asymptotic variance invariant under bijective transforms within the parameter set even for constrained parameter sets In comparison with the arithmetic mean, most of those properties are also satisfied for regular enough distributions. Except 4 and 5. In the case of exponential families, the MLE and the arithmetic mean are identical for estimating the parameter in the mean parameterisation (but not for other parameterisations). And the MLE exists for a sample from the Cauchy distribution. However, when turning to finite sample optimality properties like minimaxity or admissibility, it may happen that the MLE is neither minimax nor admissible. For instance, the Stein effect shows there exist estimators with a smaller quadratic risk for all values of the parameter under some constraints on the distribution of the sample and the dimension of the parameter. This is the case when $x\sim\mathcal{N}_p(\theta,I_p)$ and $p\ge 3$.
When does maximum likelihood work and when it doesn't? While the arithmetic mean $\bar{x}$ may sound as the "natural" estimator, one could ask why it should be preferred to the MLE! The only sure property associated with the arithmetic mean is that it is
16,670
When does maximum likelihood work and when it doesn't?
Let's interpret "computing the arithmetic mean" as estimation using the Method of Moments (MoM). I believe that's faithful to the original question since the method substitutes sample averages for theoretical ones. It also address @Xi'an's concern about an arbitrary parameter (from an arbitrary model). If you're still with me, then I think a great place to go is Examples where method of moments can beat maximum likelihood in small samples? The question text points out that "Maximum likelihood estimators (MLE) are asymptotically efficient; we see the practical upshot in that they often do better than method of moments (MoM) estimates (when they differ)," and seeks specific cases where MoM estimators achieve a smaller mean squared error than its MLE counterpart. A few examples that are provided are in the context of linear regression, the two-parameter Inverse Gaussian distribution, and an asymmetric exponential power distribution. This idea of "asymptotic efficiency" means that maximum likelihood estimators are probably close to using the data to its fullest potential (to estimate the parameter in question), a guarantee you don't get with method of moments in general. While maximum likelihood is not always "better" than working with averages, this efficiency property (if only in the limit) makes it a go-to method for most frequentists. Of course, the contrarian could argue that with the increasing size of data sets, if you're pointing at the right target with a function of averages, go with it.
When does maximum likelihood work and when it doesn't?
Let's interpret "computing the arithmetic mean" as estimation using the Method of Moments (MoM). I believe that's faithful to the original question since the method substitutes sample averages for the
When does maximum likelihood work and when it doesn't? Let's interpret "computing the arithmetic mean" as estimation using the Method of Moments (MoM). I believe that's faithful to the original question since the method substitutes sample averages for theoretical ones. It also address @Xi'an's concern about an arbitrary parameter (from an arbitrary model). If you're still with me, then I think a great place to go is Examples where method of moments can beat maximum likelihood in small samples? The question text points out that "Maximum likelihood estimators (MLE) are asymptotically efficient; we see the practical upshot in that they often do better than method of moments (MoM) estimates (when they differ)," and seeks specific cases where MoM estimators achieve a smaller mean squared error than its MLE counterpart. A few examples that are provided are in the context of linear regression, the two-parameter Inverse Gaussian distribution, and an asymmetric exponential power distribution. This idea of "asymptotic efficiency" means that maximum likelihood estimators are probably close to using the data to its fullest potential (to estimate the parameter in question), a guarantee you don't get with method of moments in general. While maximum likelihood is not always "better" than working with averages, this efficiency property (if only in the limit) makes it a go-to method for most frequentists. Of course, the contrarian could argue that with the increasing size of data sets, if you're pointing at the right target with a function of averages, go with it.
When does maximum likelihood work and when it doesn't? Let's interpret "computing the arithmetic mean" as estimation using the Method of Moments (MoM). I believe that's faithful to the original question since the method substitutes sample averages for the
16,671
When does maximum likelihood work and when it doesn't?
There are several famous examples where maximum likelihood (ML) doesn't provide the best solution. See Lucien Le Cam's 1990 paper: "Maximum Likelihood: an introduction" [1], which is from his invited lectures at the Univ. of Maryland. The example that I like the most, because it's so straightforward, is this: Consider two sequences of independent random variables $X_j$ and $Y_j$ indexed by $j = 1,...,n$. Let's assume that $X_j\sim N(\mu_j,\sigma^2)$ and $Y_j\sim N(\mu_j,\sigma^2)$. In other words, for each $j$ the pair $X_j$ and $Y_j$ are identically distributed with the same mean and variance and the mean is a function of $j$. What is the ML estimate of $\sigma^2$? I won't ruin the fun by giving you the answer, but (no surprise) there are two ways to solve this using ML and they give different solutions. One is the "arithmetic mean" of the squared residuals (as one would expect), and the other is half the arithmetic mean. You can find the answer here on my Github page.
When does maximum likelihood work and when it doesn't?
There are several famous examples where maximum likelihood (ML) doesn't provide the best solution. See Lucien Le Cam's 1990 paper: "Maximum Likelihood: an introduction" [1], which is from his invited
When does maximum likelihood work and when it doesn't? There are several famous examples where maximum likelihood (ML) doesn't provide the best solution. See Lucien Le Cam's 1990 paper: "Maximum Likelihood: an introduction" [1], which is from his invited lectures at the Univ. of Maryland. The example that I like the most, because it's so straightforward, is this: Consider two sequences of independent random variables $X_j$ and $Y_j$ indexed by $j = 1,...,n$. Let's assume that $X_j\sim N(\mu_j,\sigma^2)$ and $Y_j\sim N(\mu_j,\sigma^2)$. In other words, for each $j$ the pair $X_j$ and $Y_j$ are identically distributed with the same mean and variance and the mean is a function of $j$. What is the ML estimate of $\sigma^2$? I won't ruin the fun by giving you the answer, but (no surprise) there are two ways to solve this using ML and they give different solutions. One is the "arithmetic mean" of the squared residuals (as one would expect), and the other is half the arithmetic mean. You can find the answer here on my Github page.
When does maximum likelihood work and when it doesn't? There are several famous examples where maximum likelihood (ML) doesn't provide the best solution. See Lucien Le Cam's 1990 paper: "Maximum Likelihood: an introduction" [1], which is from his invited
16,672
Metropolis-Hastings integration - why isn't my strategy working?
This is a most interesting question, which relates to the issue of approximating a normalising constant of a density $g$ based on an MCMC output from the same density $g$. (A side remark is that the correct assumption to make is that $g$ is integrable, going to zero at infinity is not sufficient.) In my opinion, the most relevant entry on this topic in regard to your suggestion is a paper by Gelfand and Dey (1994, JRSS B), where the authors develop a very similar approach to find$$\int_\mathcal{X} g(x) \,\text{d}x$$when generating from $p(x)\propto g(x)$. One result in this paper is that, for any probability density $\alpha(x)$ [this is equivalent to your $U(x)$] such that $$\{x;\alpha(x)>0\}\subset\{x;g(x)>0\}$$the following identity $$\int_\mathcal{X} \dfrac{\alpha(x)}{g(x)}p(x) \,\text{d}x=\int_\mathcal{X} \dfrac{\alpha(x)}{N} \,\text{d}x=\dfrac{1}{N}$$ shows that a sample from $p$ can produce an unbiased evaluation of $1/N$ by the importance sampling estimator $$\hat\eta=\frac{1}{n}\sum_{i=1}^n \dfrac{\alpha(x_i)}{g(x_i)}\qquad x_i\stackrel{\text{iid}}{\sim}p(x)$$ Obviously, the performances (convergence speed, existence of a variance, &tc.) of the estimator $\hat\eta$ do depend on the choice of $\alpha$ [even though its expectation does not]. In a Bayesian framework, a choice advocated by Gelfand and Dey is to take $\alpha=\pi$, the prior density. This leads to $$\dfrac{\alpha(x)}{g(x)} = \dfrac{1}{\ell(x)}$$ where $\ell(x)$ is the likelihood function, since $g(x)=\pi(x)\ell(x)$. Unfortunately, the resulting estimator $$\hat{N}=\dfrac{n}{\sum_{i=1}^n1\big/\ell(x_i)}$$ is the harmonic mean estimator, also called the worst Monte Carlo estimator ever by Radford Neal, from the University of Toronto. So it does not always work out nicely. Or even hardly ever. Your idea of using the range of your sample $(\min(x_i),\max(x_i))$ and the uniform over that range is connected with the harmonic mean issue: this estimator does not have a variance if only because because of the $\exp\{x^2\}$ appearing in the numerator (I suspect it could always be the case for an unbounded support!) and it thus converges very slowly to the normalising constant. For instance, if you rerun your code several times, you get very different numerical values after 10⁶ iterations. This means you cannot even trust the magnitude of the answer. A generic fix to this infinite variance issue is to use for $\alpha$ a more concentrated density, using for instance the quartiles of your sample $(q_{.25}(x_i),q_{.75}(x_i))$, because $g$ then remains lower-bounded over this interval. When adapting your code to this new density, the approximation is much closer to $1/\sqrt{\pi}$: ys = rnorm(1e6, 0, 1/sqrt(2)) r = quantile(ys,.75) - quantile(ys,.25) yc=ys[(ys>quantile(ys,.25))&(ys<quantile(ys,.75))] sum(sapply(yc, function(x) 1/( r * exp(-x^2))))/length(ys) ## evaluates to 0.5649015. 1/sqrt(pi) = 0.5641896 We discuss this method in details in two papers with Darren Wraith and with Jean-Michel Marin.
Metropolis-Hastings integration - why isn't my strategy working?
This is a most interesting question, which relates to the issue of approximating a normalising constant of a density $g$ based on an MCMC output from the same density $g$. (A side remark is that the c
Metropolis-Hastings integration - why isn't my strategy working? This is a most interesting question, which relates to the issue of approximating a normalising constant of a density $g$ based on an MCMC output from the same density $g$. (A side remark is that the correct assumption to make is that $g$ is integrable, going to zero at infinity is not sufficient.) In my opinion, the most relevant entry on this topic in regard to your suggestion is a paper by Gelfand and Dey (1994, JRSS B), where the authors develop a very similar approach to find$$\int_\mathcal{X} g(x) \,\text{d}x$$when generating from $p(x)\propto g(x)$. One result in this paper is that, for any probability density $\alpha(x)$ [this is equivalent to your $U(x)$] such that $$\{x;\alpha(x)>0\}\subset\{x;g(x)>0\}$$the following identity $$\int_\mathcal{X} \dfrac{\alpha(x)}{g(x)}p(x) \,\text{d}x=\int_\mathcal{X} \dfrac{\alpha(x)}{N} \,\text{d}x=\dfrac{1}{N}$$ shows that a sample from $p$ can produce an unbiased evaluation of $1/N$ by the importance sampling estimator $$\hat\eta=\frac{1}{n}\sum_{i=1}^n \dfrac{\alpha(x_i)}{g(x_i)}\qquad x_i\stackrel{\text{iid}}{\sim}p(x)$$ Obviously, the performances (convergence speed, existence of a variance, &tc.) of the estimator $\hat\eta$ do depend on the choice of $\alpha$ [even though its expectation does not]. In a Bayesian framework, a choice advocated by Gelfand and Dey is to take $\alpha=\pi$, the prior density. This leads to $$\dfrac{\alpha(x)}{g(x)} = \dfrac{1}{\ell(x)}$$ where $\ell(x)$ is the likelihood function, since $g(x)=\pi(x)\ell(x)$. Unfortunately, the resulting estimator $$\hat{N}=\dfrac{n}{\sum_{i=1}^n1\big/\ell(x_i)}$$ is the harmonic mean estimator, also called the worst Monte Carlo estimator ever by Radford Neal, from the University of Toronto. So it does not always work out nicely. Or even hardly ever. Your idea of using the range of your sample $(\min(x_i),\max(x_i))$ and the uniform over that range is connected with the harmonic mean issue: this estimator does not have a variance if only because because of the $\exp\{x^2\}$ appearing in the numerator (I suspect it could always be the case for an unbounded support!) and it thus converges very slowly to the normalising constant. For instance, if you rerun your code several times, you get very different numerical values after 10⁶ iterations. This means you cannot even trust the magnitude of the answer. A generic fix to this infinite variance issue is to use for $\alpha$ a more concentrated density, using for instance the quartiles of your sample $(q_{.25}(x_i),q_{.75}(x_i))$, because $g$ then remains lower-bounded over this interval. When adapting your code to this new density, the approximation is much closer to $1/\sqrt{\pi}$: ys = rnorm(1e6, 0, 1/sqrt(2)) r = quantile(ys,.75) - quantile(ys,.25) yc=ys[(ys>quantile(ys,.25))&(ys<quantile(ys,.75))] sum(sapply(yc, function(x) 1/( r * exp(-x^2))))/length(ys) ## evaluates to 0.5649015. 1/sqrt(pi) = 0.5641896 We discuss this method in details in two papers with Darren Wraith and with Jean-Michel Marin.
Metropolis-Hastings integration - why isn't my strategy working? This is a most interesting question, which relates to the issue of approximating a normalising constant of a density $g$ based on an MCMC output from the same density $g$. (A side remark is that the c
16,673
Transforming extremely skewed distributions
Try straight Box-Cox transform as per Box, G. E. P. and Cox, D. R. (1964), "An Analysis of Transformations," Journal of the Royal Statistical Society, Series B, 26, 211--234. SAS has the description of its loglikelihood function in Normalizing Transformations, which you can use to find the optimal $\lambda$ parameter, which is described in Atkinson, A. C. (1985), Plots, Transformations, and Regression, New York: Oxford University Press. It's very easy to implement it having the LL function, or if you have a stat package like SAS or MATLAB use their commands: it's boxcox command in MATLAB and PROC TRANSREG in SAS. Also, in R this is in the MASS package, function boxcox().
Transforming extremely skewed distributions
Try straight Box-Cox transform as per Box, G. E. P. and Cox, D. R. (1964), "An Analysis of Transformations," Journal of the Royal Statistical Society, Series B, 26, 211--234. SAS has the description o
Transforming extremely skewed distributions Try straight Box-Cox transform as per Box, G. E. P. and Cox, D. R. (1964), "An Analysis of Transformations," Journal of the Royal Statistical Society, Series B, 26, 211--234. SAS has the description of its loglikelihood function in Normalizing Transformations, which you can use to find the optimal $\lambda$ parameter, which is described in Atkinson, A. C. (1985), Plots, Transformations, and Regression, New York: Oxford University Press. It's very easy to implement it having the LL function, or if you have a stat package like SAS or MATLAB use their commands: it's boxcox command in MATLAB and PROC TRANSREG in SAS. Also, in R this is in the MASS package, function boxcox().
Transforming extremely skewed distributions Try straight Box-Cox transform as per Box, G. E. P. and Cox, D. R. (1964), "An Analysis of Transformations," Journal of the Royal Statistical Society, Series B, 26, 211--234. SAS has the description o
16,674
Transforming extremely skewed distributions
For positive skew (tail is on the positive end of the x axis), there are the square root transformation, the log transformation, and the inverse/reciprocal transformation (in order of increasing severity). Thus, if the log transformation is not sufficient, you can use the next level of transformation. Box Cox runs all transformations automatically so you can choose the best one.
Transforming extremely skewed distributions
For positive skew (tail is on the positive end of the x axis), there are the square root transformation, the log transformation, and the inverse/reciprocal transformation (in order of increasing sever
Transforming extremely skewed distributions For positive skew (tail is on the positive end of the x axis), there are the square root transformation, the log transformation, and the inverse/reciprocal transformation (in order of increasing severity). Thus, if the log transformation is not sufficient, you can use the next level of transformation. Box Cox runs all transformations automatically so you can choose the best one.
Transforming extremely skewed distributions For positive skew (tail is on the positive end of the x axis), there are the square root transformation, the log transformation, and the inverse/reciprocal transformation (in order of increasing sever
16,675
Transforming extremely skewed distributions
Most software suites will use Euler's number as the default log base, AKA: natural log. You can use a higher base number to rein in excessively right-skewed data. How you do it syntax-wise depends on the software you are using. If you need to get back out of you transformed values once estimations have been done, it might be a little easier to use this method because all you have to do is perform a exponential operator on your variable with whatever your log base was.
Transforming extremely skewed distributions
Most software suites will use Euler's number as the default log base, AKA: natural log. You can use a higher base number to rein in excessively right-skewed data. How you do it syntax-wise depends on
Transforming extremely skewed distributions Most software suites will use Euler's number as the default log base, AKA: natural log. You can use a higher base number to rein in excessively right-skewed data. How you do it syntax-wise depends on the software you are using. If you need to get back out of you transformed values once estimations have been done, it might be a little easier to use this method because all you have to do is perform a exponential operator on your variable with whatever your log base was.
Transforming extremely skewed distributions Most software suites will use Euler's number as the default log base, AKA: natural log. You can use a higher base number to rein in excessively right-skewed data. How you do it syntax-wise depends on
16,676
Cox model vs logistic regression
The problem with the Cox model is that it predicts nothing. The "intercept" (baseline hazard function) in Cox models is never actually estimated. Logistic regression can be used to predict the risk or probability for some event, in this case: whether or not a subject comes in to buy something on a specific month. The problem with the assumptions behind ordinary logistic regression is that you treat each person-month observation as independent, regardless of whether it was the same person or the same month in which observations occurred. This can be dangerous because some items are bought in two month intervals, so consecutive person by month observations are negatively correlated. Alternately, a customer can be retained or lost by good or bad experiences leading consecutive person by month observations are positively correlated. I think a good start to this prediction problem is taking the approach of forecasting where we can use previous information to inform our predictions about the next month's business. A simple start to this problem is adjusting for a lagged effect, or an indicator of whether a subject had arrived in the last month, as a predictor of whether they might arrive this month.
Cox model vs logistic regression
The problem with the Cox model is that it predicts nothing. The "intercept" (baseline hazard function) in Cox models is never actually estimated. Logistic regression can be used to predict the risk or
Cox model vs logistic regression The problem with the Cox model is that it predicts nothing. The "intercept" (baseline hazard function) in Cox models is never actually estimated. Logistic regression can be used to predict the risk or probability for some event, in this case: whether or not a subject comes in to buy something on a specific month. The problem with the assumptions behind ordinary logistic regression is that you treat each person-month observation as independent, regardless of whether it was the same person or the same month in which observations occurred. This can be dangerous because some items are bought in two month intervals, so consecutive person by month observations are negatively correlated. Alternately, a customer can be retained or lost by good or bad experiences leading consecutive person by month observations are positively correlated. I think a good start to this prediction problem is taking the approach of forecasting where we can use previous information to inform our predictions about the next month's business. A simple start to this problem is adjusting for a lagged effect, or an indicator of whether a subject had arrived in the last month, as a predictor of whether they might arrive this month.
Cox model vs logistic regression The problem with the Cox model is that it predicts nothing. The "intercept" (baseline hazard function) in Cox models is never actually estimated. Logistic regression can be used to predict the risk or
16,677
Cox model vs logistic regression
Let $T_j$ be the time that has elapsed from the time at which client $j$ starts buying until he stops. Survival analysis allows to compute probabilities like $\Pr(T_j > 3)$, i.e. the probability that client $j$ buys for at least $3$ months. Survival analysis takes into account the fact that each client has his own entry time into the study. The fact that the follow-up period varies across clients is therefore not a problem. Further, if client $j$ does not stop buying during the study period, then the last follow-up time is recorded and the data is considered right-censored. Survival analysis techniques are specifically designed to propertly handle censoring. Remark: here is a paper which shows that, under some constraints, both the logistic and the Cox model are linked.
Cox model vs logistic regression
Let $T_j$ be the time that has elapsed from the time at which client $j$ starts buying until he stops. Survival analysis allows to compute probabilities like $\Pr(T_j > 3)$, i.e. the probability that
Cox model vs logistic regression Let $T_j$ be the time that has elapsed from the time at which client $j$ starts buying until he stops. Survival analysis allows to compute probabilities like $\Pr(T_j > 3)$, i.e. the probability that client $j$ buys for at least $3$ months. Survival analysis takes into account the fact that each client has his own entry time into the study. The fact that the follow-up period varies across clients is therefore not a problem. Further, if client $j$ does not stop buying during the study period, then the last follow-up time is recorded and the data is considered right-censored. Survival analysis techniques are specifically designed to propertly handle censoring. Remark: here is a paper which shows that, under some constraints, both the logistic and the Cox model are linked.
Cox model vs logistic regression Let $T_j$ be the time that has elapsed from the time at which client $j$ starts buying until he stops. Survival analysis allows to compute probabilities like $\Pr(T_j > 3)$, i.e. the probability that
16,678
Cox model vs logistic regression
The marketing literature suggests a Pareto/NBD here or similar. You basically assume the purchase -- while they are purchasing -- follows a negative binomial distribution. But you have to model the time when the customer stops. That's the other part. Pete Fader and Bruce Hardie have some papers on this, along with Abe. There are several simpler approaches to the Pareto/NBD, even just counting Fader and Hardie's various papers. Do NOT use the simpler approach in which it is assumed the probability of stopping is constant at each point in time -- that means your heavier customers are more likely to drop out sooner. It's a simpler model to fit, but wrong. I haven't fit one of these in a while; sorry to be a bit nonspecific. Here's a reference to the Abe paper, which recasts this problem as a hierarchical Bayes. . If I was working in this area again, I think I would test out this approach.
Cox model vs logistic regression
The marketing literature suggests a Pareto/NBD here or similar. You basically assume the purchase -- while they are purchasing -- follows a negative binomial distribution. But you have to model the
Cox model vs logistic regression The marketing literature suggests a Pareto/NBD here or similar. You basically assume the purchase -- while they are purchasing -- follows a negative binomial distribution. But you have to model the time when the customer stops. That's the other part. Pete Fader and Bruce Hardie have some papers on this, along with Abe. There are several simpler approaches to the Pareto/NBD, even just counting Fader and Hardie's various papers. Do NOT use the simpler approach in which it is assumed the probability of stopping is constant at each point in time -- that means your heavier customers are more likely to drop out sooner. It's a simpler model to fit, but wrong. I haven't fit one of these in a while; sorry to be a bit nonspecific. Here's a reference to the Abe paper, which recasts this problem as a hierarchical Bayes. . If I was working in this area again, I think I would test out this approach.
Cox model vs logistic regression The marketing literature suggests a Pareto/NBD here or similar. You basically assume the purchase -- while they are purchasing -- follows a negative binomial distribution. But you have to model the
16,679
What does it indicate when the Spearman correlation is a definite amount less than Pearson?
The Spearman correlation is just the Pearson correlation using the ranks (order statistics) instead of the actual numeric values. The answer to your question is that they're not measuring the same thing. Pearson: linear trend, Spearman: monotonic trend. That the Pearson correlation is higher just means the linear correlation is larger than the rank correlation. This is probably due to influential observations in the tails of the distribution that have large influence relative to their ranked values. Tests of association using the Pearson correlation are of higher power when the linearity holds in the data.
What does it indicate when the Spearman correlation is a definite amount less than Pearson?
The Spearman correlation is just the Pearson correlation using the ranks (order statistics) instead of the actual numeric values. The answer to your question is that they're not measuring the same thi
What does it indicate when the Spearman correlation is a definite amount less than Pearson? The Spearman correlation is just the Pearson correlation using the ranks (order statistics) instead of the actual numeric values. The answer to your question is that they're not measuring the same thing. Pearson: linear trend, Spearman: monotonic trend. That the Pearson correlation is higher just means the linear correlation is larger than the rank correlation. This is probably due to influential observations in the tails of the distribution that have large influence relative to their ranked values. Tests of association using the Pearson correlation are of higher power when the linearity holds in the data.
What does it indicate when the Spearman correlation is a definite amount less than Pearson? The Spearman correlation is just the Pearson correlation using the ranks (order statistics) instead of the actual numeric values. The answer to your question is that they're not measuring the same thi
16,680
What does it indicate when the Spearman correlation is a definite amount less than Pearson?
The Pearson Correlation assumes several assumptions for it to be accurate: 1) Each variable is normally distributed; 2) Homoscedasticity, the variance of each variable remains constant; and 3) Linearity, meaning that a scatter plot depicting the relationship shows data points clustering symmetrically around the regression line. The Spearman Correlation is a nonparametric alternative to the Pearson one based on rank of the observations. The Spearman Correlation allows you to relax all three assumptions about your data set and derive correlations that are still reasonably accurate. What your data implies is that it probably breaks materially one or more of the mentioned assumptions materially so that the two correlations differ significantly. Given that you have a large gap between the two correlation you should investigate whether the variables of your data set are normally distributed, homoscedastic, and linear within a scatter plot. The above investigation will facilitate your decision on whether the Spearman or the Pearson correlation coefficient is the more representative one.
What does it indicate when the Spearman correlation is a definite amount less than Pearson?
The Pearson Correlation assumes several assumptions for it to be accurate: 1) Each variable is normally distributed; 2) Homoscedasticity, the variance of each variable remains constant; and 3) Lineari
What does it indicate when the Spearman correlation is a definite amount less than Pearson? The Pearson Correlation assumes several assumptions for it to be accurate: 1) Each variable is normally distributed; 2) Homoscedasticity, the variance of each variable remains constant; and 3) Linearity, meaning that a scatter plot depicting the relationship shows data points clustering symmetrically around the regression line. The Spearman Correlation is a nonparametric alternative to the Pearson one based on rank of the observations. The Spearman Correlation allows you to relax all three assumptions about your data set and derive correlations that are still reasonably accurate. What your data implies is that it probably breaks materially one or more of the mentioned assumptions materially so that the two correlations differ significantly. Given that you have a large gap between the two correlation you should investigate whether the variables of your data set are normally distributed, homoscedastic, and linear within a scatter plot. The above investigation will facilitate your decision on whether the Spearman or the Pearson correlation coefficient is the more representative one.
What does it indicate when the Spearman correlation is a definite amount less than Pearson? The Pearson Correlation assumes several assumptions for it to be accurate: 1) Each variable is normally distributed; 2) Homoscedasticity, the variance of each variable remains constant; and 3) Lineari
16,681
Does a logistic regression maximizing likelihood necessarily also maximize AUC over linear models?
It is not the case that $\beta_{MLE} = \beta_{AUC}$. To illustrate this, consider that AUC can written as $P(\hat y_1 > \hat y_0 | y_1 = 1, y_0 = 0)$ In otherwords, the ordering of the predictions is the only thing that affects AUC. This is not the case with the likelihood function. So as a mental exercise, suppose we had a single predictors and in our dataset, we don't see perfect separation (i.e., $\beta_{MLE}$ is finite). Now, if we simply take the value of the largest predictor and increase it by some small amount, we will change the likelihood of this solution, but it will not change the AUC, as the ordering should remain the same. Thus, if the old MLE maximized AUC, it will still maximize AUC after changing the predictor, but will no longer maximize the likelihood. Thus, at the very least, it is not the case that $\beta_{AUC}$ is not unique; any $\beta$ that preserves the ordering of the estimates achieves the exact same AUC. In general, since the AUC is sensitive to different aspects of the data, I would believe that we should be able to find a case where $\beta_{MLE}$ does not maximize $\beta_{AUC}$. In fact, I'd venture a guess that this happens with high probability. EDIT (moving comment into answer) The next step is to prove that the MLE doesn't necessarily maximize the AUC (which isn't proven yet). One can do this by taking something like predictors 1, 2, 3, 4, 5, 6, $x$ (with $x > 6$) with outcomes 0, 0, 0, 1, 1, 1, 0. Any positive value of $\beta$ will maximize the AUC (regardless of the value of $x$), but we can chose an $x$ large enough that the $\beta_{MLE} < 0$.
Does a logistic regression maximizing likelihood necessarily also maximize AUC over linear models?
It is not the case that $\beta_{MLE} = \beta_{AUC}$. To illustrate this, consider that AUC can written as $P(\hat y_1 > \hat y_0 | y_1 = 1, y_0 = 0)$ In otherwords, the ordering of the predictions is
Does a logistic regression maximizing likelihood necessarily also maximize AUC over linear models? It is not the case that $\beta_{MLE} = \beta_{AUC}$. To illustrate this, consider that AUC can written as $P(\hat y_1 > \hat y_0 | y_1 = 1, y_0 = 0)$ In otherwords, the ordering of the predictions is the only thing that affects AUC. This is not the case with the likelihood function. So as a mental exercise, suppose we had a single predictors and in our dataset, we don't see perfect separation (i.e., $\beta_{MLE}$ is finite). Now, if we simply take the value of the largest predictor and increase it by some small amount, we will change the likelihood of this solution, but it will not change the AUC, as the ordering should remain the same. Thus, if the old MLE maximized AUC, it will still maximize AUC after changing the predictor, but will no longer maximize the likelihood. Thus, at the very least, it is not the case that $\beta_{AUC}$ is not unique; any $\beta$ that preserves the ordering of the estimates achieves the exact same AUC. In general, since the AUC is sensitive to different aspects of the data, I would believe that we should be able to find a case where $\beta_{MLE}$ does not maximize $\beta_{AUC}$. In fact, I'd venture a guess that this happens with high probability. EDIT (moving comment into answer) The next step is to prove that the MLE doesn't necessarily maximize the AUC (which isn't proven yet). One can do this by taking something like predictors 1, 2, 3, 4, 5, 6, $x$ (with $x > 6$) with outcomes 0, 0, 0, 1, 1, 1, 0. Any positive value of $\beta$ will maximize the AUC (regardless of the value of $x$), but we can chose an $x$ large enough that the $\beta_{MLE} < 0$.
Does a logistic regression maximizing likelihood necessarily also maximize AUC over linear models? It is not the case that $\beta_{MLE} = \beta_{AUC}$. To illustrate this, consider that AUC can written as $P(\hat y_1 > \hat y_0 | y_1 = 1, y_0 = 0)$ In otherwords, the ordering of the predictions is
16,682
Should I use the cross validation score or the test score to evaluate a machine learning model?
First of all, if the cross validation results are actually not used to decide anything (no parameter tuning, no selection, nothing) then you don't gain anything by the test set you describe: your splitting in to training/test is subject to the same difficulties as you subsequent splitting of the training set into the surrogate training and cross validation surrogate test sets. Any data leakage (e.g. due to confounders you did not account for) happens to both. in addition, as you say, the 20 % test yset is smaller. Whether this is a problem or not depends largely on the absolute number of cases you have. If 20 % of your data are sufficient to yield test results with a suitable precision for your application at hand, then you are fine. That being said, selecting a model is part of the training of the final model. Thus, the selected model needs to undergo independent validation. In your case, this means: select according to your cross validation, e.g. model B (although you may want to look into more sophisticated selection rules that take instability into account). Then do an independent test of the selected model. That result is your validation (or better: verification) result for the final model. Here: 80 %. However, you can use an additional outer cross validation for that, avoiding the difficulty of having only few test cases for the final verification.
Should I use the cross validation score or the test score to evaluate a machine learning model?
First of all, if the cross validation results are actually not used to decide anything (no parameter tuning, no selection, nothing) then you don't gain anything by the test set you describe: your spl
Should I use the cross validation score or the test score to evaluate a machine learning model? First of all, if the cross validation results are actually not used to decide anything (no parameter tuning, no selection, nothing) then you don't gain anything by the test set you describe: your splitting in to training/test is subject to the same difficulties as you subsequent splitting of the training set into the surrogate training and cross validation surrogate test sets. Any data leakage (e.g. due to confounders you did not account for) happens to both. in addition, as you say, the 20 % test yset is smaller. Whether this is a problem or not depends largely on the absolute number of cases you have. If 20 % of your data are sufficient to yield test results with a suitable precision for your application at hand, then you are fine. That being said, selecting a model is part of the training of the final model. Thus, the selected model needs to undergo independent validation. In your case, this means: select according to your cross validation, e.g. model B (although you may want to look into more sophisticated selection rules that take instability into account). Then do an independent test of the selected model. That result is your validation (or better: verification) result for the final model. Here: 80 %. However, you can use an additional outer cross validation for that, avoiding the difficulty of having only few test cases for the final verification.
Should I use the cross validation score or the test score to evaluate a machine learning model? First of all, if the cross validation results are actually not used to decide anything (no parameter tuning, no selection, nothing) then you don't gain anything by the test set you describe: your spl
16,683
Should I use the cross validation score or the test score to evaluate a machine learning model?
However the cross-validation result is more representative because it represents the performance of the system on the 80% of the data instead of just the 20% of the training set. This is not the whole picture. Yes, the cross-validation error uses unseen ("out-of-bag") data. However, note that you are using the CV error in fitting your model and tuning (hyper-)parameters. And then the final model you are working with has seen these "unseen" data. Cross-validation is part of model training. CV errors are not indicative of out-of-sample performance. This would argue for using model A, which performs better out-of-sample. However... Note that now you are using your test set in selecting a model. Thus, for your final model, the test set is not unseen any more! Another thought experiment: assume you are fitting a huge amount of models to your data (maybe some of these models add random noise to your predictions?) and assess all of these models on your test set. Then one model will perform best on the test set. But if you then choose this model as your final model, its good performance on the test set may be due to chance alone. You may have overfit to the test set. Conclusion: test set performance is only then a guide to true out-of-sample performance if it is not used in selecting, tuning or "improving just a little bit" your final model. Moreover, if I change the split of my sets, the different test accuracies I get have a high variance but the average cross validation accuracy is more stable. High variance in test set performance is a red flag. It does seem like you are overfitting. You may simply have too little data for your model, and beyond some point, even cross-validation may not save you. Consider regularizing your model, or constraining it in some other way (e.g., using the one standard error rule). Also, accuracy is not a good evaluation measure.
Should I use the cross validation score or the test score to evaluate a machine learning model?
However the cross-validation result is more representative because it represents the performance of the system on the 80% of the data instead of just the 20% of the training set. This is not the whol
Should I use the cross validation score or the test score to evaluate a machine learning model? However the cross-validation result is more representative because it represents the performance of the system on the 80% of the data instead of just the 20% of the training set. This is not the whole picture. Yes, the cross-validation error uses unseen ("out-of-bag") data. However, note that you are using the CV error in fitting your model and tuning (hyper-)parameters. And then the final model you are working with has seen these "unseen" data. Cross-validation is part of model training. CV errors are not indicative of out-of-sample performance. This would argue for using model A, which performs better out-of-sample. However... Note that now you are using your test set in selecting a model. Thus, for your final model, the test set is not unseen any more! Another thought experiment: assume you are fitting a huge amount of models to your data (maybe some of these models add random noise to your predictions?) and assess all of these models on your test set. Then one model will perform best on the test set. But if you then choose this model as your final model, its good performance on the test set may be due to chance alone. You may have overfit to the test set. Conclusion: test set performance is only then a guide to true out-of-sample performance if it is not used in selecting, tuning or "improving just a little bit" your final model. Moreover, if I change the split of my sets, the different test accuracies I get have a high variance but the average cross validation accuracy is more stable. High variance in test set performance is a red flag. It does seem like you are overfitting. You may simply have too little data for your model, and beyond some point, even cross-validation may not save you. Consider regularizing your model, or constraining it in some other way (e.g., using the one standard error rule). Also, accuracy is not a good evaluation measure.
Should I use the cross validation score or the test score to evaluate a machine learning model? However the cross-validation result is more representative because it represents the performance of the system on the 80% of the data instead of just the 20% of the training set. This is not the whol
16,684
Should I use the cross validation score or the test score to evaluate a machine learning model?
What you are doing is creating test data at 20% of your total data set. However, the main purpose of Cross Validation Testing is to evaluate your models on different random samples loosing minimum information. It is also important to consider how you cross validate and create your test data, whether you stratify sample the data or straight split. I suggest using stratified sampling in both CV and test for the data to more representative. The information you present on the accuracy on two different models leads to conclusion that model A can be improved by using more data, it is seems to have underfitted and your model B has overfitted to your train data. These maybe due to the nature of the algorithms you have used, the features in your model, the regularisation you may have used or the sampling/splitting method you have used in the splits.
Should I use the cross validation score or the test score to evaluate a machine learning model?
What you are doing is creating test data at 20% of your total data set. However, the main purpose of Cross Validation Testing is to evaluate your models on different random samples loosing minimum inf
Should I use the cross validation score or the test score to evaluate a machine learning model? What you are doing is creating test data at 20% of your total data set. However, the main purpose of Cross Validation Testing is to evaluate your models on different random samples loosing minimum information. It is also important to consider how you cross validate and create your test data, whether you stratify sample the data or straight split. I suggest using stratified sampling in both CV and test for the data to more representative. The information you present on the accuracy on two different models leads to conclusion that model A can be improved by using more data, it is seems to have underfitted and your model B has overfitted to your train data. These maybe due to the nature of the algorithms you have used, the features in your model, the regularisation you may have used or the sampling/splitting method you have used in the splits.
Should I use the cross validation score or the test score to evaluate a machine learning model? What you are doing is creating test data at 20% of your total data set. However, the main purpose of Cross Validation Testing is to evaluate your models on different random samples loosing minimum inf
16,685
Bootstrap filter/ Particle filter algorithm(Understanding)
That is the transition density of the state ($x_t$), which is part of your model and therefore known. You do need to sample from it in the basic algorithm, but approximations are possible. $p(x_t|x_{t-1})$ is the proposal distribution in this case. It is used because the distribution $p(x_t|x_{0:t-1},y_{1:t})$ is generally not tractable. Yes, that's the observation density, which is also part of the model, and therefore known. Yes, that's what normalization means. The tilde is used to signify something like "preliminary": $\tilde{x}$ is $x$ before resampling, and $\tilde{w}$ is $w$ before renormalization. I would guess that it is done this way so that the notation matches up between variants of the algorithm that don't have a resampling step (i.e. $x$ is always the final estimate). The end goal of the bootstrap filter is to estimate the sequence of conditional distributions $p(x_t|y_{1:t})$ (the unobservable state at $t$, given all observations until $t$). Consider the simple model: $$X_t = X_{t-1} + \eta_t, \quad \eta_t \sim N(0,1)$$ $$X_0 \sim N(0,1)$$ $$Y_t = X_t + \varepsilon_t, \quad \varepsilon_t \sim N(0,1)$$ This is a random walk observed with noise (you only observe $Y$, not $X$). You can compute $p(X_t|Y_1, ..., Y_t)$ exactly with the Kalman filter, but we'll use the bootstrap filter at your request. We can restate the model in terms of the state transition distribution, the initial state distribution, and the observation distribution (in that order), which is more useful for the particle filter: $$X_t | X_{t-1} \sim N(X_{t-1},1)$$ $$X_0 \sim N(0,1)$$ $$Y_t | X_t \sim N(X_t,1)$$ Applying the algorithm: Initialization. We generate $N$ particles (independently) according to $X_0^{(i)} \sim N(0,1)$. We simulate each particle forward independently by generating $X_1^{(i)} | X_0^{(i)} \sim N(X_0^{(i)},1)$, for each $N$. We then compute the likelihood $\tilde{w}_t^{(i)} = \phi(y_t; x_t^{(i)},1)$, where $\phi(x; \mu, \sigma^2)$ is the normal density with mean $\mu$ and variance $\sigma^2$ (our observation density). We want to give more weight to particles which are more likely to produce the observation $y_t$ that we recorded. We normalize these weights so they sum to 1. We resample the particles according to these weights $w_t$. Note that a particle is a full path of $x$ (i.e. don't just resample the last point, it's the whole thing, which they denote as $x_{0:t}^{(i)}$). Go back to step 2, moving forward with the resampled version of the particles, until we've processed the whole series. An implementation in R follows: # Simulate some fake data set.seed(123) tau <- 100 x <- cumsum(rnorm(tau)) y <- x + rnorm(tau) # Begin particle filter N <- 1000 x.pf <- matrix(rep(NA,(tau+1)*N),nrow=tau+1) # 1. Initialize x.pf[1, ] <- rnorm(N) m <- rep(NA,tau) for (t in 2:(tau+1)) { # 2. Importance sampling step x.pf[t, ] <- x.pf[t-1,] + rnorm(N) #Likelihood w.tilde <- dnorm(y[t-1], mean=x.pf[t, ]) #Normalize w <- w.tilde/sum(w.tilde) # NOTE: This step isn't part of your description of the algorithm, but I'm going to compute the mean # of the particle distribution here to compare with the Kalman filter later. Note that this is done BEFORE resampling m[t-1] <- sum(w*x.pf[t,]) # 3. Resampling step s <- sample(1:N, size=N, replace=TRUE, prob=w) # Note: resample WHOLE path, not just x.pf[t, ] x.pf <- x.pf[, s] } plot(x) lines(m,col="red") # Let's do the Kalman filter to compare library(dlm) lines(dropFirst(dlmFilter(y, dlmModPoly(order=1))$m), col="blue") legend("topleft", legend = c("Actual x", "Particle filter (mean)", "Kalman filter"), col=c("black","red","blue"), lwd=1) The resulting graph: A useful tutorial is the one by Doucet and Johansen, see here.
Bootstrap filter/ Particle filter algorithm(Understanding)
That is the transition density of the state ($x_t$), which is part of your model and therefore known. You do need to sample from it in the basic algorithm, but approximations are possible. $p(x_t|x_{t
Bootstrap filter/ Particle filter algorithm(Understanding) That is the transition density of the state ($x_t$), which is part of your model and therefore known. You do need to sample from it in the basic algorithm, but approximations are possible. $p(x_t|x_{t-1})$ is the proposal distribution in this case. It is used because the distribution $p(x_t|x_{0:t-1},y_{1:t})$ is generally not tractable. Yes, that's the observation density, which is also part of the model, and therefore known. Yes, that's what normalization means. The tilde is used to signify something like "preliminary": $\tilde{x}$ is $x$ before resampling, and $\tilde{w}$ is $w$ before renormalization. I would guess that it is done this way so that the notation matches up between variants of the algorithm that don't have a resampling step (i.e. $x$ is always the final estimate). The end goal of the bootstrap filter is to estimate the sequence of conditional distributions $p(x_t|y_{1:t})$ (the unobservable state at $t$, given all observations until $t$). Consider the simple model: $$X_t = X_{t-1} + \eta_t, \quad \eta_t \sim N(0,1)$$ $$X_0 \sim N(0,1)$$ $$Y_t = X_t + \varepsilon_t, \quad \varepsilon_t \sim N(0,1)$$ This is a random walk observed with noise (you only observe $Y$, not $X$). You can compute $p(X_t|Y_1, ..., Y_t)$ exactly with the Kalman filter, but we'll use the bootstrap filter at your request. We can restate the model in terms of the state transition distribution, the initial state distribution, and the observation distribution (in that order), which is more useful for the particle filter: $$X_t | X_{t-1} \sim N(X_{t-1},1)$$ $$X_0 \sim N(0,1)$$ $$Y_t | X_t \sim N(X_t,1)$$ Applying the algorithm: Initialization. We generate $N$ particles (independently) according to $X_0^{(i)} \sim N(0,1)$. We simulate each particle forward independently by generating $X_1^{(i)} | X_0^{(i)} \sim N(X_0^{(i)},1)$, for each $N$. We then compute the likelihood $\tilde{w}_t^{(i)} = \phi(y_t; x_t^{(i)},1)$, where $\phi(x; \mu, \sigma^2)$ is the normal density with mean $\mu$ and variance $\sigma^2$ (our observation density). We want to give more weight to particles which are more likely to produce the observation $y_t$ that we recorded. We normalize these weights so they sum to 1. We resample the particles according to these weights $w_t$. Note that a particle is a full path of $x$ (i.e. don't just resample the last point, it's the whole thing, which they denote as $x_{0:t}^{(i)}$). Go back to step 2, moving forward with the resampled version of the particles, until we've processed the whole series. An implementation in R follows: # Simulate some fake data set.seed(123) tau <- 100 x <- cumsum(rnorm(tau)) y <- x + rnorm(tau) # Begin particle filter N <- 1000 x.pf <- matrix(rep(NA,(tau+1)*N),nrow=tau+1) # 1. Initialize x.pf[1, ] <- rnorm(N) m <- rep(NA,tau) for (t in 2:(tau+1)) { # 2. Importance sampling step x.pf[t, ] <- x.pf[t-1,] + rnorm(N) #Likelihood w.tilde <- dnorm(y[t-1], mean=x.pf[t, ]) #Normalize w <- w.tilde/sum(w.tilde) # NOTE: This step isn't part of your description of the algorithm, but I'm going to compute the mean # of the particle distribution here to compare with the Kalman filter later. Note that this is done BEFORE resampling m[t-1] <- sum(w*x.pf[t,]) # 3. Resampling step s <- sample(1:N, size=N, replace=TRUE, prob=w) # Note: resample WHOLE path, not just x.pf[t, ] x.pf <- x.pf[, s] } plot(x) lines(m,col="red") # Let's do the Kalman filter to compare library(dlm) lines(dropFirst(dlmFilter(y, dlmModPoly(order=1))$m), col="blue") legend("topleft", legend = c("Actual x", "Particle filter (mean)", "Kalman filter"), col=c("black","red","blue"), lwd=1) The resulting graph: A useful tutorial is the one by Doucet and Johansen, see here.
Bootstrap filter/ Particle filter algorithm(Understanding) That is the transition density of the state ($x_t$), which is part of your model and therefore known. You do need to sample from it in the basic algorithm, but approximations are possible. $p(x_t|x_{t
16,686
Should repeated cross-validation be used to assess predictive models?
The argument that the paper seems to be making appears strange to me. According to the paper, the goal of CV is to estimate $\alpha_2$, the expected predictive performance of the model on new data, given that the model was trained on the observed dataset $S$. When we conduct $k$-fold CV, we obtain an estimate $\hat A$ of this number. Because of the random partitioning of $S$ into $k$ folds, this is a random variable $\hat A \sim f(A)$ with mean $\mu_k$ and variance $\sigma^2_k$. In contrast, $n$-times-repeated CV yields an estimate with the same mean $\mu_k$ but smaller variance $\sigma^2_k/n$. Obviously, $\alpha_2\ne \mu_k$. This bias is something we have to accept. However, the expected error $\mathbb E\big[|\alpha_2-\hat A|^2\big]$ will be larger for smaller $n$, and will be the largest for $n=1$, at least under reasonable assumptions about $f(A)$, e.g. when $\hat A\mathrel{\dot\sim} \mathcal N(\mu_k,\sigma^2_k/n)$. In other words, repeated CV allows to get a more precise estimate of $\mu_k$ and it is a good thing because it gives a more precise estimate of $\alpha_2$. Therefore, repeated CV is strictly more precise than non-repeated CV. The authors do not argue with that! Instead they claim, based on the simulations, that reducing the variance [by repeating CV] is, in many cases, not very useful, and essentially a waste of computational resources. This just means that $\sigma^2_k$ in their simulations was pretty low; and indeed, the lowest sample size they used was $200$, which is probably big enough to yield small $\sigma^2_k$. (The difference in estimates obtained with non-repeated CV and 30-times-repeated CV is always small.) With smaller sample sizes one can expect larger between-repetitions variance. CAVEAT: Confidence intervals! Another point that the authors are making is that the reporting of confidence intervals [in repeated cross-validation] is misleading. It seems that they are referring to confidence intervals for the mean across CV repetitions. I fully agree that this is a meaningless thing to report! The more times CV is repeated, the smaller this CI will be, but nobody is interested in the CI around our estimate of $\mu_k$! We care about the CI around our estimate of $\alpha_2$. The authors also report CIs for the non-repeated CV, and it's not entirely clear to me how these CIs were constructed. I guess these are the CIs for the means across the $k$ folds. I would argue that these CIs are also pretty much meaningless! Take a look at one of their examples: the accuracy for adult dataset with NB algorithm and 200 sample size. They get 78.0% with non-repeated CV, CI (72.26, 83.74), 79.0% (77.21, 80.79) with 10-times-repeated CV, and 79.1% (78.07, 80.13) with 30-times-repeated CV. All of these CIs are useless, including the first one. The best estimate of $\mu_k$ is 79.1%. This corresponds to 158 successes out of 200. This yields 95% binomial confidence interval of (72.8, 84.5) -- broader even than the first one reported. If I wanted to report some CI, this is the one I would report. MORE GENERAL CAVEAT: variance of CV. You wrote that repeated CV has become a popular technique for reducing the variance of cross-validation. One should be very clear what one means by the "variance" of CV. Repeated CV reduces the variance of the estimate of $\mu_k$. Note that in case of leave-one-out CV (LOOCV), when $k=N$, this variance is equal to zero. Nevertheless, it is often said that LOOCV has actually the highest variance of all possible $k$-fold CVs. See e.g. here: Variance and bias in cross-validation: why does leave-one-out CV have higher variance? Why is that? This is because LOOCV has the highest variance as an estimate of $\alpha_1$ which is the expected predictive performance of the model on new data when built on a new dataset of the same size as $S$. This is a completely different issue.
Should repeated cross-validation be used to assess predictive models?
The argument that the paper seems to be making appears strange to me. According to the paper, the goal of CV is to estimate $\alpha_2$, the expected predictive performance of the model on new data, g
Should repeated cross-validation be used to assess predictive models? The argument that the paper seems to be making appears strange to me. According to the paper, the goal of CV is to estimate $\alpha_2$, the expected predictive performance of the model on new data, given that the model was trained on the observed dataset $S$. When we conduct $k$-fold CV, we obtain an estimate $\hat A$ of this number. Because of the random partitioning of $S$ into $k$ folds, this is a random variable $\hat A \sim f(A)$ with mean $\mu_k$ and variance $\sigma^2_k$. In contrast, $n$-times-repeated CV yields an estimate with the same mean $\mu_k$ but smaller variance $\sigma^2_k/n$. Obviously, $\alpha_2\ne \mu_k$. This bias is something we have to accept. However, the expected error $\mathbb E\big[|\alpha_2-\hat A|^2\big]$ will be larger for smaller $n$, and will be the largest for $n=1$, at least under reasonable assumptions about $f(A)$, e.g. when $\hat A\mathrel{\dot\sim} \mathcal N(\mu_k,\sigma^2_k/n)$. In other words, repeated CV allows to get a more precise estimate of $\mu_k$ and it is a good thing because it gives a more precise estimate of $\alpha_2$. Therefore, repeated CV is strictly more precise than non-repeated CV. The authors do not argue with that! Instead they claim, based on the simulations, that reducing the variance [by repeating CV] is, in many cases, not very useful, and essentially a waste of computational resources. This just means that $\sigma^2_k$ in their simulations was pretty low; and indeed, the lowest sample size they used was $200$, which is probably big enough to yield small $\sigma^2_k$. (The difference in estimates obtained with non-repeated CV and 30-times-repeated CV is always small.) With smaller sample sizes one can expect larger between-repetitions variance. CAVEAT: Confidence intervals! Another point that the authors are making is that the reporting of confidence intervals [in repeated cross-validation] is misleading. It seems that they are referring to confidence intervals for the mean across CV repetitions. I fully agree that this is a meaningless thing to report! The more times CV is repeated, the smaller this CI will be, but nobody is interested in the CI around our estimate of $\mu_k$! We care about the CI around our estimate of $\alpha_2$. The authors also report CIs for the non-repeated CV, and it's not entirely clear to me how these CIs were constructed. I guess these are the CIs for the means across the $k$ folds. I would argue that these CIs are also pretty much meaningless! Take a look at one of their examples: the accuracy for adult dataset with NB algorithm and 200 sample size. They get 78.0% with non-repeated CV, CI (72.26, 83.74), 79.0% (77.21, 80.79) with 10-times-repeated CV, and 79.1% (78.07, 80.13) with 30-times-repeated CV. All of these CIs are useless, including the first one. The best estimate of $\mu_k$ is 79.1%. This corresponds to 158 successes out of 200. This yields 95% binomial confidence interval of (72.8, 84.5) -- broader even than the first one reported. If I wanted to report some CI, this is the one I would report. MORE GENERAL CAVEAT: variance of CV. You wrote that repeated CV has become a popular technique for reducing the variance of cross-validation. One should be very clear what one means by the "variance" of CV. Repeated CV reduces the variance of the estimate of $\mu_k$. Note that in case of leave-one-out CV (LOOCV), when $k=N$, this variance is equal to zero. Nevertheless, it is often said that LOOCV has actually the highest variance of all possible $k$-fold CVs. See e.g. here: Variance and bias in cross-validation: why does leave-one-out CV have higher variance? Why is that? This is because LOOCV has the highest variance as an estimate of $\alpha_1$ which is the expected predictive performance of the model on new data when built on a new dataset of the same size as $S$. This is a completely different issue.
Should repeated cross-validation be used to assess predictive models? The argument that the paper seems to be making appears strange to me. According to the paper, the goal of CV is to estimate $\alpha_2$, the expected predictive performance of the model on new data, g
16,687
Resources for learning about multiple-target techniques?
Random forest handle it rather well, see Would a Random Forest with multiple outputs be possible/practical? or scikit learn's documentation. I guess GBM or any tree based method can be adapted in a similar fashion. More generally, when you run any learning algorithm minimizing a score, you usually work on minimizing $\sum_i(p_i-y_i)^2$ which is one-dimensional. But you can specify any target function. If you were working on (two-dimensional) position prediction, $\sum_i(\hat{y}_i-y_i)^2+(\hat{x}_i-x_i)^2$ would be a good metric. If you have mixed type output (classification and regression) then specifying the target function will probably require you to specify a target function that gives more weight to some targets than other: which scaling do you apply to continuous responses ? Which loss do you apply to miss-classifications? As for further academic reading, SVM Structured Learning's Wikipedia Simultaneously Leveraging Output and Task Structures for Multiple-Output Regression The Landmark Selection Method for Multiple Output Prediction (deals with high dimensional dependent variables)
Resources for learning about multiple-target techniques?
Random forest handle it rather well, see Would a Random Forest with multiple outputs be possible/practical? or scikit learn's documentation. I guess GBM or any tree based method can be adapted in a si
Resources for learning about multiple-target techniques? Random forest handle it rather well, see Would a Random Forest with multiple outputs be possible/practical? or scikit learn's documentation. I guess GBM or any tree based method can be adapted in a similar fashion. More generally, when you run any learning algorithm minimizing a score, you usually work on minimizing $\sum_i(p_i-y_i)^2$ which is one-dimensional. But you can specify any target function. If you were working on (two-dimensional) position prediction, $\sum_i(\hat{y}_i-y_i)^2+(\hat{x}_i-x_i)^2$ would be a good metric. If you have mixed type output (classification and regression) then specifying the target function will probably require you to specify a target function that gives more weight to some targets than other: which scaling do you apply to continuous responses ? Which loss do you apply to miss-classifications? As for further academic reading, SVM Structured Learning's Wikipedia Simultaneously Leveraging Output and Task Structures for Multiple-Output Regression The Landmark Selection Method for Multiple Output Prediction (deals with high dimensional dependent variables)
Resources for learning about multiple-target techniques? Random forest handle it rather well, see Would a Random Forest with multiple outputs be possible/practical? or scikit learn's documentation. I guess GBM or any tree based method can be adapted in a si
16,688
Resources for learning about multiple-target techniques?
This paper does a good job of describing the current methods, toolkits available, as well as datasets to test on. I happen to work on a commercial problem requiring multi-target regression, and I found that the Clus toolkit has a good blend of high performance and robustness The documentation is excellent The toolkit has several methods for both multi-target classification and regression It also support rule-based induction and clustering. The ensemble models (Bagging, RandomForest) that I used can be read and interpreted easily. Some of the newer methods (post 2012) have been implemented as an extension of the Mulan toolkit, here's the Github link. Although these methods such as Random Linear Target Combinations report better performance than ensemble models, I found that the toolkit not as mature as the Clus toolkit and hence didn't use them.
Resources for learning about multiple-target techniques?
This paper does a good job of describing the current methods, toolkits available, as well as datasets to test on. I happen to work on a commercial problem requiring multi-target regression, and I foun
Resources for learning about multiple-target techniques? This paper does a good job of describing the current methods, toolkits available, as well as datasets to test on. I happen to work on a commercial problem requiring multi-target regression, and I found that the Clus toolkit has a good blend of high performance and robustness The documentation is excellent The toolkit has several methods for both multi-target classification and regression It also support rule-based induction and clustering. The ensemble models (Bagging, RandomForest) that I used can be read and interpreted easily. Some of the newer methods (post 2012) have been implemented as an extension of the Mulan toolkit, here's the Github link. Although these methods such as Random Linear Target Combinations report better performance than ensemble models, I found that the toolkit not as mature as the Clus toolkit and hence didn't use them.
Resources for learning about multiple-target techniques? This paper does a good job of describing the current methods, toolkits available, as well as datasets to test on. I happen to work on a commercial problem requiring multi-target regression, and I foun
16,689
Resources for learning about multiple-target techniques?
A Bayesian take on this sort of problem: Bayesian non‐parametric models for spatially indexed data of mixed type. The multiple response element being handled by various normally distributed random vectors and link functions thereof. So that the complete response is a stack of a vector of normals, vector of counts and vector of bernoullis.
Resources for learning about multiple-target techniques?
A Bayesian take on this sort of problem: Bayesian non‐parametric models for spatially indexed data of mixed type. The multiple response element being handled by various normally distributed random vec
Resources for learning about multiple-target techniques? A Bayesian take on this sort of problem: Bayesian non‐parametric models for spatially indexed data of mixed type. The multiple response element being handled by various normally distributed random vectors and link functions thereof. So that the complete response is a stack of a vector of normals, vector of counts and vector of bernoullis.
Resources for learning about multiple-target techniques? A Bayesian take on this sort of problem: Bayesian non‐parametric models for spatially indexed data of mixed type. The multiple response element being handled by various normally distributed random vec
16,690
Is the machine learning community abusing "conditioned on" and "parametrized by"?
I think this is more about Bayesian/non-Bayesian statistics than machine learning vs.. statistics. In Bayesian statistics parameter are modelled as random variables, too. If you have a joint distribution for $X,\alpha$, $p(X \mid \alpha)$ is a conditional distribution, no matter what the physical interpretation of $X$ and $\alpha$. If one considers only fixed $\alpha$s or otherwise does not put a probability distribution over $\alpha$, the computations with $p(X; \alpha)$ are exactly the same as with $p(X \mid \alpha)$ with $p(\alpha)$. Furthermore, one can at any point decide to extend the model with fixed values of $\alpha$ to one where there is a prior distribution over $\alpha$. To me at least, it seems strange that the notation for the distribution-given-$\alpha$ should change at this point, wherefore some Bayesians prefer to use the conditioning notation even if one has not (yet?) bothered to define all parameters as random variables. Argument about whether one can write $p(X ; \alpha)$ as $p(X \mid \alpha)$ has also arisen in comments of Andrew Gelman's blog post Misunderstanding the $p$-value. For example, Larry Wasserman had the opinion that $\mid$ is not allowed when there is no conditioning-from-joint while Andrew Gelman had the opposite opinion.
Is the machine learning community abusing "conditioned on" and "parametrized by"?
I think this is more about Bayesian/non-Bayesian statistics than machine learning vs.. statistics. In Bayesian statistics parameter are modelled as random variables, too. If you have a joint distribut
Is the machine learning community abusing "conditioned on" and "parametrized by"? I think this is more about Bayesian/non-Bayesian statistics than machine learning vs.. statistics. In Bayesian statistics parameter are modelled as random variables, too. If you have a joint distribution for $X,\alpha$, $p(X \mid \alpha)$ is a conditional distribution, no matter what the physical interpretation of $X$ and $\alpha$. If one considers only fixed $\alpha$s or otherwise does not put a probability distribution over $\alpha$, the computations with $p(X; \alpha)$ are exactly the same as with $p(X \mid \alpha)$ with $p(\alpha)$. Furthermore, one can at any point decide to extend the model with fixed values of $\alpha$ to one where there is a prior distribution over $\alpha$. To me at least, it seems strange that the notation for the distribution-given-$\alpha$ should change at this point, wherefore some Bayesians prefer to use the conditioning notation even if one has not (yet?) bothered to define all parameters as random variables. Argument about whether one can write $p(X ; \alpha)$ as $p(X \mid \alpha)$ has also arisen in comments of Andrew Gelman's blog post Misunderstanding the $p$-value. For example, Larry Wasserman had the opinion that $\mid$ is not allowed when there is no conditioning-from-joint while Andrew Gelman had the opposite opinion.
Is the machine learning community abusing "conditioned on" and "parametrized by"? I think this is more about Bayesian/non-Bayesian statistics than machine learning vs.. statistics. In Bayesian statistics parameter are modelled as random variables, too. If you have a joint distribut
16,691
Linear combination of two dependent multivariate normal random variables
In that case, you have to write (with hopefully clear notations) $$ \left(\begin{matrix}X\\Y \end{matrix}\right) \sim \mathcal{N}\left[ \left(\begin{matrix}\mu_X\\\mu_Y\end{matrix}\right), \Sigma_{X,Y} \right] $$ (edited: assuming joint normality of $(X,Y)$) Then $$ AX+BY=\left(\begin{matrix}A& B \end{matrix}\right) \left(\begin{matrix}X\\Y \end{matrix}\right) $$ and $$ AX+BY+C \sim \mathcal{N}\left[ \left(\begin{matrix}A& B \end{matrix}\right) \left(\begin{matrix}\mu_X\\\mu_Y\end{matrix}\right) + C, \left(\begin{matrix}A & B \end{matrix}\right)\Sigma_{X,Y} \left(\begin{matrix}A^T \\ B^T \end{matrix}\right)\right] $$ i.e. $$ AX+BY+C \sim \mathcal{N}\left[A\mu_X + B\mu_Y +C, A\Sigma_{XX}A^T+B\Sigma_{XY}^TA^T+A\Sigma_{XY}B^T+B\Sigma_{YY}B^T \right] $$
Linear combination of two dependent multivariate normal random variables
In that case, you have to write (with hopefully clear notations) $$ \left(\begin{matrix}X\\Y \end{matrix}\right) \sim \mathcal{N}\left[ \left(\begin{matrix}\mu_X\\\mu_Y\end{matrix}\right), \Sigma_{X,
Linear combination of two dependent multivariate normal random variables In that case, you have to write (with hopefully clear notations) $$ \left(\begin{matrix}X\\Y \end{matrix}\right) \sim \mathcal{N}\left[ \left(\begin{matrix}\mu_X\\\mu_Y\end{matrix}\right), \Sigma_{X,Y} \right] $$ (edited: assuming joint normality of $(X,Y)$) Then $$ AX+BY=\left(\begin{matrix}A& B \end{matrix}\right) \left(\begin{matrix}X\\Y \end{matrix}\right) $$ and $$ AX+BY+C \sim \mathcal{N}\left[ \left(\begin{matrix}A& B \end{matrix}\right) \left(\begin{matrix}\mu_X\\\mu_Y\end{matrix}\right) + C, \left(\begin{matrix}A & B \end{matrix}\right)\Sigma_{X,Y} \left(\begin{matrix}A^T \\ B^T \end{matrix}\right)\right] $$ i.e. $$ AX+BY+C \sim \mathcal{N}\left[A\mu_X + B\mu_Y +C, A\Sigma_{XX}A^T+B\Sigma_{XY}^TA^T+A\Sigma_{XY}B^T+B\Sigma_{YY}B^T \right] $$
Linear combination of two dependent multivariate normal random variables In that case, you have to write (with hopefully clear notations) $$ \left(\begin{matrix}X\\Y \end{matrix}\right) \sim \mathcal{N}\left[ \left(\begin{matrix}\mu_X\\\mu_Y\end{matrix}\right), \Sigma_{X,
16,692
Linear combination of two dependent multivariate normal random variables
Your question does not have a unique answer as currently posed unless you assume that $X$and$Y$ are jointly normally distributed with covariance top right block $\Sigma_{XY}$. i think you do mean this because you say you have each covariance between X and Y. In this case we can write $W=(X^T,Y^T)^T$ which is also multivariate normal. then $Z$ is given in terms of $W$ as: $$Z=(A,B)W+C$$ Then you use your usual formula for linear combination. Note that the mean is unchanged but the covariance matrix has two extra terms added $A\Sigma_{XY}B^T+B\Sigma_{XY}^TA^T$
Linear combination of two dependent multivariate normal random variables
Your question does not have a unique answer as currently posed unless you assume that $X$and$Y$ are jointly normally distributed with covariance top right block $\Sigma_{XY}$. i think you do mean thi
Linear combination of two dependent multivariate normal random variables Your question does not have a unique answer as currently posed unless you assume that $X$and$Y$ are jointly normally distributed with covariance top right block $\Sigma_{XY}$. i think you do mean this because you say you have each covariance between X and Y. In this case we can write $W=(X^T,Y^T)^T$ which is also multivariate normal. then $Z$ is given in terms of $W$ as: $$Z=(A,B)W+C$$ Then you use your usual formula for linear combination. Note that the mean is unchanged but the covariance matrix has two extra terms added $A\Sigma_{XY}B^T+B\Sigma_{XY}^TA^T$
Linear combination of two dependent multivariate normal random variables Your question does not have a unique answer as currently posed unless you assume that $X$and$Y$ are jointly normally distributed with covariance top right block $\Sigma_{XY}$. i think you do mean thi
16,693
What is the statistical justification of interpolation?
Any form of function fitting, even nonparametric ones (that typically make assumptions on the smoothness of the curve involved), involves assumptions, and thus a leap of faith. The ancient solution of linear interpolation is one that 'just works' when the data you have is fine-grained 'enough' (if you look at a circle close enough, it looks flat as well - just ask Columbus), and was feasible even before the computer age (which is not the case for many modern day splines solutions). It makes sense to assume the belief that the function will 'continue in the same (i.e. linear) matter' between the two points, but there is no a priori reason for this (barring knowledge about the concepts at hand). It becomes quickly clear when you have three (or more) noncolinear points (like when you add the brown points above), that linear interpolation between each of them will soon involve sharp corners in each of those, which is typically unwanted. That is where the other options jump in. However, without further domain knowledge, there is no way to state with certainty that one solution is better than the other (for this, you would have to know what the value of the other points is, defeating the purpose of fitting the function in the first place). On the bright side, and maybe more relevant to your question, under 'regularity conditions' (read: assumptions: if we know that the function is e.g. smooth), both linear interpolation and the other popular solutions can be proven to be 'reasonable' approximations. Still: it requires assumptions, and for these, we typically do not have statistics.
What is the statistical justification of interpolation?
Any form of function fitting, even nonparametric ones (that typically make assumptions on the smoothness of the curve involved), involves assumptions, and thus a leap of faith. The ancient solution of
What is the statistical justification of interpolation? Any form of function fitting, even nonparametric ones (that typically make assumptions on the smoothness of the curve involved), involves assumptions, and thus a leap of faith. The ancient solution of linear interpolation is one that 'just works' when the data you have is fine-grained 'enough' (if you look at a circle close enough, it looks flat as well - just ask Columbus), and was feasible even before the computer age (which is not the case for many modern day splines solutions). It makes sense to assume the belief that the function will 'continue in the same (i.e. linear) matter' between the two points, but there is no a priori reason for this (barring knowledge about the concepts at hand). It becomes quickly clear when you have three (or more) noncolinear points (like when you add the brown points above), that linear interpolation between each of them will soon involve sharp corners in each of those, which is typically unwanted. That is where the other options jump in. However, without further domain knowledge, there is no way to state with certainty that one solution is better than the other (for this, you would have to know what the value of the other points is, defeating the purpose of fitting the function in the first place). On the bright side, and maybe more relevant to your question, under 'regularity conditions' (read: assumptions: if we know that the function is e.g. smooth), both linear interpolation and the other popular solutions can be proven to be 'reasonable' approximations. Still: it requires assumptions, and for these, we typically do not have statistics.
What is the statistical justification of interpolation? Any form of function fitting, even nonparametric ones (that typically make assumptions on the smoothness of the curve involved), involves assumptions, and thus a leap of faith. The ancient solution of
16,694
What is the statistical justification of interpolation?
You can work out the linear equation for the line of best fit (eg. y = 0.4554x + 0.7525 ) however this would only work if there was a labeled axis. However this would not give you the exact answer only the best fitting one in relation the other points.
What is the statistical justification of interpolation?
You can work out the linear equation for the line of best fit (eg. y = 0.4554x + 0.7525 ) however this would only work if there was a labeled axis. However this would not give you the exact answer onl
What is the statistical justification of interpolation? You can work out the linear equation for the line of best fit (eg. y = 0.4554x + 0.7525 ) however this would only work if there was a labeled axis. However this would not give you the exact answer only the best fitting one in relation the other points.
What is the statistical justification of interpolation? You can work out the linear equation for the line of best fit (eg. y = 0.4554x + 0.7525 ) however this would only work if there was a labeled axis. However this would not give you the exact answer onl
16,695
Intuitive explanation of stationarity
First of all, it is important to note that stationarity is a property of a process, not of a time series. You consider the ensemble of all time series generated by a process. If the statistical properties¹ of this ensemble (mean, variance, …) are constant over time, the process is called stationary. Strictly speaking, it is impossible to say whether a given time series was generated by a stationary process (however, with some assumptions, we can take a good guess). More intuitively, stationarity means that there are no distinguished points in time for your process (influencing the statistical properties of your observation). Whether this applies to a given process depends crucially on what you consider as fixed or variable for your process, i.e., what is contained in your ensemble. A typical cause of non-stationarity are time-dependent parameters – which allow to distinguish time points by the values of the parameters. Another cause are fixed initial conditions. Consider the following examples: The noise reaching my house from a single car passing at a given time is not a stationary process. E.g., the average amplitude² is highest when the car is directly next to my house. The noise reaching my house from street traffic in general is a stationary process, if we ignore the time dependency of the traffic intensity (e.g., less traffic at night or on weekends). There are no distinguished points in time anymore. While there may be strong fluctuations of individual time series, these vanish when I consider the ensemble of all realisations of the process. If I we include known impacts on traffic intensity, e.g., that there is less traffic at night, the process is non-stationary again: The average amplitude² varies with a daily rhythm. Every point in time is distinguished by the time of the day. The position of a single peppercorn in a pot of boiling water is a stationary process (ignoring the loss of water due to evaporation). There are no distinguished points in time. The position of a single peppercorn in a pot of boiling water dropped in the exact middle at $t=0$ is not a stationary process, as $t=0$ is a distinguished point in time. The average position of the peppercorn is always in the middle (assuming a symmetric pot without distinguished directions), but at $t=ε$ (with $ε$ small), we can be sure that the peppercorn is somewhere near the middle for every realisation of the process, while at a later time, it can also be closer to the border of the pot. So, the distribution of positions changes over time. To give a specific example, the standard deviation grows. The distribution quickly converges to the respective distributions of the previous example and if we only take a look at this process for $t>T$ with a sufficiently high $T$, we can neglect the non-stationarity and approximate it as a stationary process for all purposes – the impact of the initial condition has faded away. ¹ For practical purposes, this is sometimes reduced to the mean and the variance (weak stationarity), but I do not consider this helpful to understand the concept. Just ignore weak stationarity until you understood stationarity. ² Which is the mean of the volume, but the standard deviation of the actual sound signal (do not worry too much about this here).
Intuitive explanation of stationarity
First of all, it is important to note that stationarity is a property of a process, not of a time series. You consider the ensemble of all time series generated by a process. If the statistical proper
Intuitive explanation of stationarity First of all, it is important to note that stationarity is a property of a process, not of a time series. You consider the ensemble of all time series generated by a process. If the statistical properties¹ of this ensemble (mean, variance, …) are constant over time, the process is called stationary. Strictly speaking, it is impossible to say whether a given time series was generated by a stationary process (however, with some assumptions, we can take a good guess). More intuitively, stationarity means that there are no distinguished points in time for your process (influencing the statistical properties of your observation). Whether this applies to a given process depends crucially on what you consider as fixed or variable for your process, i.e., what is contained in your ensemble. A typical cause of non-stationarity are time-dependent parameters – which allow to distinguish time points by the values of the parameters. Another cause are fixed initial conditions. Consider the following examples: The noise reaching my house from a single car passing at a given time is not a stationary process. E.g., the average amplitude² is highest when the car is directly next to my house. The noise reaching my house from street traffic in general is a stationary process, if we ignore the time dependency of the traffic intensity (e.g., less traffic at night or on weekends). There are no distinguished points in time anymore. While there may be strong fluctuations of individual time series, these vanish when I consider the ensemble of all realisations of the process. If I we include known impacts on traffic intensity, e.g., that there is less traffic at night, the process is non-stationary again: The average amplitude² varies with a daily rhythm. Every point in time is distinguished by the time of the day. The position of a single peppercorn in a pot of boiling water is a stationary process (ignoring the loss of water due to evaporation). There are no distinguished points in time. The position of a single peppercorn in a pot of boiling water dropped in the exact middle at $t=0$ is not a stationary process, as $t=0$ is a distinguished point in time. The average position of the peppercorn is always in the middle (assuming a symmetric pot without distinguished directions), but at $t=ε$ (with $ε$ small), we can be sure that the peppercorn is somewhere near the middle for every realisation of the process, while at a later time, it can also be closer to the border of the pot. So, the distribution of positions changes over time. To give a specific example, the standard deviation grows. The distribution quickly converges to the respective distributions of the previous example and if we only take a look at this process for $t>T$ with a sufficiently high $T$, we can neglect the non-stationarity and approximate it as a stationary process for all purposes – the impact of the initial condition has faded away. ¹ For practical purposes, this is sometimes reduced to the mean and the variance (weak stationarity), but I do not consider this helpful to understand the concept. Just ignore weak stationarity until you understood stationarity. ² Which is the mean of the volume, but the standard deviation of the actual sound signal (do not worry too much about this here).
Intuitive explanation of stationarity First of all, it is important to note that stationarity is a property of a process, not of a time series. You consider the ensemble of all time series generated by a process. If the statistical proper
16,696
Intuitive explanation of stationarity
For clarity, I would add that any time series where the datapoints are normally distributed through time with a constant mean and variance is considered a strong stationary time series since given the mean and standard deviation the normal distribution will always have the same probability distribution curve (the inputs to the normal equation only depend on the mean and the standard deviation). This is not the case with a t-distribution, for example, where an input to the t-distribution equation is gamma which impacts the shape of the distribution curve despite a constant mean and constant standard deviation.
Intuitive explanation of stationarity
For clarity, I would add that any time series where the datapoints are normally distributed through time with a constant mean and variance is considered a strong stationary time series since given the
Intuitive explanation of stationarity For clarity, I would add that any time series where the datapoints are normally distributed through time with a constant mean and variance is considered a strong stationary time series since given the mean and standard deviation the normal distribution will always have the same probability distribution curve (the inputs to the normal equation only depend on the mean and the standard deviation). This is not the case with a t-distribution, for example, where an input to the t-distribution equation is gamma which impacts the shape of the distribution curve despite a constant mean and constant standard deviation.
Intuitive explanation of stationarity For clarity, I would add that any time series where the datapoints are normally distributed through time with a constant mean and variance is considered a strong stationary time series since given the
16,697
Change point analysis using R's nls()
(At first I thought it could be a problem resulting from the fact that max is not vectorized, but that's not true. It does make it a pain to work with changePoint, wherefore the following modification: changePoint <- function(x, b0, slope1, slope2, delta) { b0 + (x*slope1) + (sapply(x-delta, function (t) max(0, t)) * slope2) } This R-help mailing list post describes one way in which this error may result: the rhs of the formula is overparameterized, such that changing two parameters in tandem gives the same fit to the data. I can't see how that is true of your model, but maybe it is. In any case, you can write your own objective function and minimize it. The following function gives the squared error for data points (x,y) and a certain value of the parameters (the weird argument structure of the function is to account for how optim works): sqerror <- function (par, x, y) { sum((y - changePoint(x, par[1], par[2], par[3], par[4]))^2) } Then we say: optim(par = c(50, 0, 2, 48), fn = sqerror, x = x, y = data) And see: $par [1] 54.53436800 -0.09283594 2.07356459 48.00000006 Note that for my fake data (x <- 40:60; data <- changePoint(x, 50, 0, 2, 48) + rnorm(21, 0, 0.5)) there are lots of local maxima depending on the initial parameter values you give. I suppose if you wanted to take this seriously you'd call the optimizer many times with random initial parameters and examine the distribution of results.
Change point analysis using R's nls()
(At first I thought it could be a problem resulting from the fact that max is not vectorized, but that's not true. It does make it a pain to work with changePoint, wherefore the following modificatio
Change point analysis using R's nls() (At first I thought it could be a problem resulting from the fact that max is not vectorized, but that's not true. It does make it a pain to work with changePoint, wherefore the following modification: changePoint <- function(x, b0, slope1, slope2, delta) { b0 + (x*slope1) + (sapply(x-delta, function (t) max(0, t)) * slope2) } This R-help mailing list post describes one way in which this error may result: the rhs of the formula is overparameterized, such that changing two parameters in tandem gives the same fit to the data. I can't see how that is true of your model, but maybe it is. In any case, you can write your own objective function and minimize it. The following function gives the squared error for data points (x,y) and a certain value of the parameters (the weird argument structure of the function is to account for how optim works): sqerror <- function (par, x, y) { sum((y - changePoint(x, par[1], par[2], par[3], par[4]))^2) } Then we say: optim(par = c(50, 0, 2, 48), fn = sqerror, x = x, y = data) And see: $par [1] 54.53436800 -0.09283594 2.07356459 48.00000006 Note that for my fake data (x <- 40:60; data <- changePoint(x, 50, 0, 2, 48) + rnorm(21, 0, 0.5)) there are lots of local maxima depending on the initial parameter values you give. I suppose if you wanted to take this seriously you'd call the optimizer many times with random initial parameters and examine the distribution of results.
Change point analysis using R's nls() (At first I thought it could be a problem resulting from the fact that max is not vectorized, but that's not true. It does make it a pain to work with changePoint, wherefore the following modificatio
16,698
Change point analysis using R's nls()
Just wanted to add that you can do this with many other packages. If you want to get an estimate of uncertainty around the change point (something nls cannot do), try the mcp package. # Simulate the data df = data.frame(x = 1:100) df$y = c(rnorm(20, 50, 5), rnorm(80, 50 + 1.5*(df$x[21:100] - 20), 5)) # Fit the model model = list( y ~ 1, # Intercept ~ 0 + x # Joined slope ) library(mcp) fit = mcp(model, df) Let's plot it with a prediction interval (green line). The blue density is the posterior distribution for the change point location: # Plot it plot(fit, q_predict = T) You can inspect individual parameters in more detail using plot_pars(fit) and summary(fit).
Change point analysis using R's nls()
Just wanted to add that you can do this with many other packages. If you want to get an estimate of uncertainty around the change point (something nls cannot do), try the mcp package. # Simulate the d
Change point analysis using R's nls() Just wanted to add that you can do this with many other packages. If you want to get an estimate of uncertainty around the change point (something nls cannot do), try the mcp package. # Simulate the data df = data.frame(x = 1:100) df$y = c(rnorm(20, 50, 5), rnorm(80, 50 + 1.5*(df$x[21:100] - 20), 5)) # Fit the model model = list( y ~ 1, # Intercept ~ 0 + x # Joined slope ) library(mcp) fit = mcp(model, df) Let's plot it with a prediction interval (green line). The blue density is the posterior distribution for the change point location: # Plot it plot(fit, q_predict = T) You can inspect individual parameters in more detail using plot_pars(fit) and summary(fit).
Change point analysis using R's nls() Just wanted to add that you can do this with many other packages. If you want to get an estimate of uncertainty around the change point (something nls cannot do), try the mcp package. # Simulate the d
16,699
Hit and run MCMC
I didn't look at the paper you supplied, but let me have a go anyway: If you have a $p$-dimensional parameter space you can generate a random direction $d$ uniformly distributed on the surface of the unit sphere with x <- rnorm(p) d <- x/sqrt(sum(x^2)) (c.f. Wiki). Then, use this to generate proposals for $d$ for rejection sampling (assuming you can actually evaluate the distribution for $d$). Assuming you start in position $x$ and have accepted a $d$, generate a proposal $y$ with lambda <- r<SOMEDISTRIBUTION>(foo, bar) y <- x + lambda * d and do a Metropolis-Hastings-Step to decide whether to move to $y$ or not. Of course, how well this can work will depend on the distribution of $d$ and how expensive it is to (repeatedly) evaluate its density in the rejection sampling step, but since generating proposals for $d$ is cheap you may get away with it. Added for @csgillespie's benefit: From what I was able to gather by some googling, hit-and-run MCMC is useful primarily for fast mixing if you have a (multivariate) target that has arbitrary bounded but not necessarily connected support, because it enables you to move from any point in the support to any other in one step. More here and here.
Hit and run MCMC
I didn't look at the paper you supplied, but let me have a go anyway: If you have a $p$-dimensional parameter space you can generate a random direction $d$ uniformly distributed on the surface of the
Hit and run MCMC I didn't look at the paper you supplied, but let me have a go anyway: If you have a $p$-dimensional parameter space you can generate a random direction $d$ uniformly distributed on the surface of the unit sphere with x <- rnorm(p) d <- x/sqrt(sum(x^2)) (c.f. Wiki). Then, use this to generate proposals for $d$ for rejection sampling (assuming you can actually evaluate the distribution for $d$). Assuming you start in position $x$ and have accepted a $d$, generate a proposal $y$ with lambda <- r<SOMEDISTRIBUTION>(foo, bar) y <- x + lambda * d and do a Metropolis-Hastings-Step to decide whether to move to $y$ or not. Of course, how well this can work will depend on the distribution of $d$ and how expensive it is to (repeatedly) evaluate its density in the rejection sampling step, but since generating proposals for $d$ is cheap you may get away with it. Added for @csgillespie's benefit: From what I was able to gather by some googling, hit-and-run MCMC is useful primarily for fast mixing if you have a (multivariate) target that has arbitrary bounded but not necessarily connected support, because it enables you to move from any point in the support to any other in one step. More here and here.
Hit and run MCMC I didn't look at the paper you supplied, but let me have a go anyway: If you have a $p$-dimensional parameter space you can generate a random direction $d$ uniformly distributed on the surface of the
16,700
Hit and run MCMC
I came across your question when I was looking for the original reference for Hit-and-Run. Thanks for that! I just put together a proof-of-concept implementation of hit-and-run for PyMC at the end of this recent blog.
Hit and run MCMC
I came across your question when I was looking for the original reference for Hit-and-Run. Thanks for that! I just put together a proof-of-concept implementation of hit-and-run for PyMC at the end o
Hit and run MCMC I came across your question when I was looking for the original reference for Hit-and-Run. Thanks for that! I just put together a proof-of-concept implementation of hit-and-run for PyMC at the end of this recent blog.
Hit and run MCMC I came across your question when I was looking for the original reference for Hit-and-Run. Thanks for that! I just put together a proof-of-concept implementation of hit-and-run for PyMC at the end o