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
15,601
What is/are the "mechanical" difference between multiple linear regression with lags and time series?
Why create a whole new method, i.e., time series (ARIMA), instead of using multiple linear regression and adding lagged variables to it (with the order of lags determined using ACF and PACF)? One immediate point is that a linear regression only works with observed variables while ARIMA incorporates unobserved variables in the moving average part; thus, ARIMA is more flexible, or more general, in a way. AR model can be seen as a linear regression model and its coefficients can be estimated using OLS; $\hat\beta_{OLS}=(X'X)^{-1}X'y$ where $X$ consists of lags of the dependent variable that are observed. Meanwhile, MA or ARMA models do not fit into the OLS framework since some of the variables, namely the lagged error terms, are unobserved, and hence the OLS estimator is infeasible. one G-M assumption is that the independent variables should be normally distributed? or just the dependent variable conditional to the independent ones? The normality assumption is sometimes invoked for model errors, not for the independent variables. However, normality is required neither for the consistency and efficiency of the OLS estimator nor for the Gauss-Markov theorem to hold. Wikipedia article on the Gauss-Markov theorem states explicitly that "The errors do not need to be normal". multicollinearity between variables may (obviously) arise, so estimates would be wrong. A high degree of multicollinearity means inflated variance of the OLS estimator. However, the OLS estimator is still BLUE as long as the multicollinearity is not perfect. Thus your statement does not look right. It is obvious that even with lagged variables OLS problems arise and it is not efficient nor correct, but when using maximum likelihood, do these problems persist? An AR model can be estimated using both OLS and ML; both of these methods give consistent estimators. MA and ARMA models cannot be estimated by OLS, so ML is the main choice; again, it is consistent. The other interesting property is efficiency, and here I am not completely sure (but clearly the information should be available somewhere as the question is pretty standard). I would try commenting on "correctness", but I am not sure what you mean by that.
What is/are the "mechanical" difference between multiple linear regression with lags and time series
Why create a whole new method, i.e., time series (ARIMA), instead of using multiple linear regression and adding lagged variables to it (with the order of lags determined using ACF and PACF)? One imm
What is/are the "mechanical" difference between multiple linear regression with lags and time series? Why create a whole new method, i.e., time series (ARIMA), instead of using multiple linear regression and adding lagged variables to it (with the order of lags determined using ACF and PACF)? One immediate point is that a linear regression only works with observed variables while ARIMA incorporates unobserved variables in the moving average part; thus, ARIMA is more flexible, or more general, in a way. AR model can be seen as a linear regression model and its coefficients can be estimated using OLS; $\hat\beta_{OLS}=(X'X)^{-1}X'y$ where $X$ consists of lags of the dependent variable that are observed. Meanwhile, MA or ARMA models do not fit into the OLS framework since some of the variables, namely the lagged error terms, are unobserved, and hence the OLS estimator is infeasible. one G-M assumption is that the independent variables should be normally distributed? or just the dependent variable conditional to the independent ones? The normality assumption is sometimes invoked for model errors, not for the independent variables. However, normality is required neither for the consistency and efficiency of the OLS estimator nor for the Gauss-Markov theorem to hold. Wikipedia article on the Gauss-Markov theorem states explicitly that "The errors do not need to be normal". multicollinearity between variables may (obviously) arise, so estimates would be wrong. A high degree of multicollinearity means inflated variance of the OLS estimator. However, the OLS estimator is still BLUE as long as the multicollinearity is not perfect. Thus your statement does not look right. It is obvious that even with lagged variables OLS problems arise and it is not efficient nor correct, but when using maximum likelihood, do these problems persist? An AR model can be estimated using both OLS and ML; both of these methods give consistent estimators. MA and ARMA models cannot be estimated by OLS, so ML is the main choice; again, it is consistent. The other interesting property is efficiency, and here I am not completely sure (but clearly the information should be available somewhere as the question is pretty standard). I would try commenting on "correctness", but I am not sure what you mean by that.
What is/are the "mechanical" difference between multiple linear regression with lags and time series Why create a whole new method, i.e., time series (ARIMA), instead of using multiple linear regression and adding lagged variables to it (with the order of lags determined using ACF and PACF)? One imm
15,602
What is/are the "mechanical" difference between multiple linear regression with lags and time series?
That's a great question. The real difference between ARIMA models and multiple linear regression lies in your error structure. You can manipulate the independent variables in a multiple linear regression model so that they fit your time series data, which is what @IrishStat is saying. However, after that, you need to incorporate ARIMA errors into your multiple regression model to get correct coefficient and test results. A great free book on this is: https://www.otexts.org/fpp/9/1. I've linked the section that discusses combining ARIMA and multiple regression models.
What is/are the "mechanical" difference between multiple linear regression with lags and time series
That's a great question. The real difference between ARIMA models and multiple linear regression lies in your error structure. You can manipulate the independent variables in a multiple linear regress
What is/are the "mechanical" difference between multiple linear regression with lags and time series? That's a great question. The real difference between ARIMA models and multiple linear regression lies in your error structure. You can manipulate the independent variables in a multiple linear regression model so that they fit your time series data, which is what @IrishStat is saying. However, after that, you need to incorporate ARIMA errors into your multiple regression model to get correct coefficient and test results. A great free book on this is: https://www.otexts.org/fpp/9/1. I've linked the section that discusses combining ARIMA and multiple regression models.
What is/are the "mechanical" difference between multiple linear regression with lags and time series That's a great question. The real difference between ARIMA models and multiple linear regression lies in your error structure. You can manipulate the independent variables in a multiple linear regress
15,603
What is/are the "mechanical" difference between multiple linear regression with lags and time series?
Good question, I actually have built both in my day job as a Data Scientist. Time series models are easy to build (forecast package in R lets you build one in less in 5 seconds), the same or more accurate than regression models, etc. Generally, one should always build time series, then regression. There are Philosophical implications of time series as well, if you can predict without knowing anything, then what does that mean? My take on Darlington. 1) "Regression is far more flexible and powerful, producing better models. This point is developed in numerous spots throughout the work." No, quite the opposite. Regression models make far more assumptions than time series models. The fewer the assumptions, the more likely the ability to withstand the earthquake (regime change). Furthermore, time series models respond faster to sudden shifts. 2) "Regression is far easier to master than ARIMA, at least for those already familiar with the use of regression in other areas." This is circular reasoning. 3) "Regression uses a "closed" computational algorithm that is essentially guaranteed to yield results if at all possible, while ARIMA and many other methods use iterative algorithms that often fail to reach a solution. I have often seen the ARIMA method "hang up" on data that gave the regression method no problem." Regression gives you an answer, but is it the right answer? If I build linear regression and machine learning models and they all come to the same conclusion, what does it mean? So in summary, yes regression and time series can both answer the same question and technically, time series is technically regression (albeit auto-regression). Time series models are less complex and therefore more robust than regression models. If you think about specialization, then TS models specialize in forecasting whereas regression specialize in understanding. It boils down to whether you want to explain or predict.
What is/are the "mechanical" difference between multiple linear regression with lags and time series
Good question, I actually have built both in my day job as a Data Scientist. Time series models are easy to build (forecast package in R lets you build one in less in 5 seconds), the same or more accu
What is/are the "mechanical" difference between multiple linear regression with lags and time series? Good question, I actually have built both in my day job as a Data Scientist. Time series models are easy to build (forecast package in R lets you build one in less in 5 seconds), the same or more accurate than regression models, etc. Generally, one should always build time series, then regression. There are Philosophical implications of time series as well, if you can predict without knowing anything, then what does that mean? My take on Darlington. 1) "Regression is far more flexible and powerful, producing better models. This point is developed in numerous spots throughout the work." No, quite the opposite. Regression models make far more assumptions than time series models. The fewer the assumptions, the more likely the ability to withstand the earthquake (regime change). Furthermore, time series models respond faster to sudden shifts. 2) "Regression is far easier to master than ARIMA, at least for those already familiar with the use of regression in other areas." This is circular reasoning. 3) "Regression uses a "closed" computational algorithm that is essentially guaranteed to yield results if at all possible, while ARIMA and many other methods use iterative algorithms that often fail to reach a solution. I have often seen the ARIMA method "hang up" on data that gave the regression method no problem." Regression gives you an answer, but is it the right answer? If I build linear regression and machine learning models and they all come to the same conclusion, what does it mean? So in summary, yes regression and time series can both answer the same question and technically, time series is technically regression (albeit auto-regression). Time series models are less complex and therefore more robust than regression models. If you think about specialization, then TS models specialize in forecasting whereas regression specialize in understanding. It boils down to whether you want to explain or predict.
What is/are the "mechanical" difference between multiple linear regression with lags and time series Good question, I actually have built both in my day job as a Data Scientist. Time series models are easy to build (forecast package in R lets you build one in less in 5 seconds), the same or more accu
15,604
What is/are the "mechanical" difference between multiple linear regression with lags and time series?
In think the deepest difference between transfer functions and multipe linear regression (in its usual use) lies in their objectives, multiple regressions is oriented to find the main causal observable determinants of the dependent variable while transfer functions just want to forecasts the effect on a dependent variable of the variation of a specific exogenous variable...In summary, multiple regression is oriented to exhaustive explanation and transfer function to forecasting very specific effects...
What is/are the "mechanical" difference between multiple linear regression with lags and time series
In think the deepest difference between transfer functions and multipe linear regression (in its usual use) lies in their objectives, multiple regressions is oriented to find the main causal observabl
What is/are the "mechanical" difference between multiple linear regression with lags and time series? In think the deepest difference between transfer functions and multipe linear regression (in its usual use) lies in their objectives, multiple regressions is oriented to find the main causal observable determinants of the dependent variable while transfer functions just want to forecasts the effect on a dependent variable of the variation of a specific exogenous variable...In summary, multiple regression is oriented to exhaustive explanation and transfer function to forecasting very specific effects...
What is/are the "mechanical" difference between multiple linear regression with lags and time series In think the deepest difference between transfer functions and multipe linear regression (in its usual use) lies in their objectives, multiple regressions is oriented to find the main causal observabl
15,605
Can we use categorical independent variable in discriminant analysis?
Discriminant analysis assumes a multivariate normal distribution because what we usually consider to be predictors are really a multivariate dependent variable, and the grouping variable is considered to be a predictor. This means that categorical variables that are to be treated as predictors in the sense you wish are not handled well. This is one reason that many, including myself, consider discriminant analysis to have been made obsolete by logistic regression. Logistic regression makes no distributional assumptions of any kind, on either the left hand or the right hand side of the model. Logistic regression is a direct probability model and doesn't require one to use Bayes' rule to convert results to probabilities as does discriminant analysis.
Can we use categorical independent variable in discriminant analysis?
Discriminant analysis assumes a multivariate normal distribution because what we usually consider to be predictors are really a multivariate dependent variable, and the grouping variable is considered
Can we use categorical independent variable in discriminant analysis? Discriminant analysis assumes a multivariate normal distribution because what we usually consider to be predictors are really a multivariate dependent variable, and the grouping variable is considered to be a predictor. This means that categorical variables that are to be treated as predictors in the sense you wish are not handled well. This is one reason that many, including myself, consider discriminant analysis to have been made obsolete by logistic regression. Logistic regression makes no distributional assumptions of any kind, on either the left hand or the right hand side of the model. Logistic regression is a direct probability model and doesn't require one to use Bayes' rule to convert results to probabilities as does discriminant analysis.
Can we use categorical independent variable in discriminant analysis? Discriminant analysis assumes a multivariate normal distribution because what we usually consider to be predictors are really a multivariate dependent variable, and the grouping variable is considered
15,606
Can we use categorical independent variable in discriminant analysis?
The short answer is rather no than yes. One preliminary note. It is difficult to say whether the variables which produce discriminant functions out of themselves should be called "independent" or "dependent". LDA is basically a specific case of Canonical correlation analysis, and therefore it is ambidirectional. It can be seen as MANOVA (with the class variable as the independent factor) or, when the class is dichotomous, as a linear regression of the class as the dependent variable. It is not quite legal therefore to always oppose LDA with one-directional regressions such as logistic one. LDA assumes that the variables (those you called "independent") come from multivariate normal distribution, hence - all them continuous. This assumption is important for (1) classification stage of LDA and (2) testing significance of the discriminants produced at the extraction stage. The extracting of the discriminants itself does not need the assumption. However LDA is quite robust to the violation of the assumption which is seen sometimes as a warranty to do it on binary data. In fact, some people do it. Canonical correlations (of which LDA is a specific case) can be done where both sets consist of binary or even dummy binary variables. Once again, there is no problem with the extraction of the latent functions; the problems with such application potentially arise when p-values or classifying objects are invoked. From binary/ordinal variables one might compute tetrachoric/polychoric correlations and submit it to LDA (if the program allows to input correlation matrices in place of data); but then computation of discriminant scores on case level will be problematic. A more flexible approach would be to turn categorical (ordinal, nominal) variables into continuous by optimal scaling/quantification. Nonlinear canonical correlation analysis (OVERALS). It will do it under the task to maximize canonical correlations between the two sides (the class variable and the categorical "predictors"). You may then try LDA with the transformed variables. (Multinomial or binary) logistic regression may be another alternative to LDA.
Can we use categorical independent variable in discriminant analysis?
The short answer is rather no than yes. One preliminary note. It is difficult to say whether the variables which produce discriminant functions out of themselves should be called "independent" or "dep
Can we use categorical independent variable in discriminant analysis? The short answer is rather no than yes. One preliminary note. It is difficult to say whether the variables which produce discriminant functions out of themselves should be called "independent" or "dependent". LDA is basically a specific case of Canonical correlation analysis, and therefore it is ambidirectional. It can be seen as MANOVA (with the class variable as the independent factor) or, when the class is dichotomous, as a linear regression of the class as the dependent variable. It is not quite legal therefore to always oppose LDA with one-directional regressions such as logistic one. LDA assumes that the variables (those you called "independent") come from multivariate normal distribution, hence - all them continuous. This assumption is important for (1) classification stage of LDA and (2) testing significance of the discriminants produced at the extraction stage. The extracting of the discriminants itself does not need the assumption. However LDA is quite robust to the violation of the assumption which is seen sometimes as a warranty to do it on binary data. In fact, some people do it. Canonical correlations (of which LDA is a specific case) can be done where both sets consist of binary or even dummy binary variables. Once again, there is no problem with the extraction of the latent functions; the problems with such application potentially arise when p-values or classifying objects are invoked. From binary/ordinal variables one might compute tetrachoric/polychoric correlations and submit it to LDA (if the program allows to input correlation matrices in place of data); but then computation of discriminant scores on case level will be problematic. A more flexible approach would be to turn categorical (ordinal, nominal) variables into continuous by optimal scaling/quantification. Nonlinear canonical correlation analysis (OVERALS). It will do it under the task to maximize canonical correlations between the two sides (the class variable and the categorical "predictors"). You may then try LDA with the transformed variables. (Multinomial or binary) logistic regression may be another alternative to LDA.
Can we use categorical independent variable in discriminant analysis? The short answer is rather no than yes. One preliminary note. It is difficult to say whether the variables which produce discriminant functions out of themselves should be called "independent" or "dep
15,607
When doing a t-test for the significance of a regression coefficient, why is the number of degrees of freedom $n-p-1$?
You lose one degree of freedom for each estimated mean parameter. For an ordinary t-test that's 1 (the mean). For regression, each predictor costs you a degree of freedom. The extra one is for the intercept. More specifically, the degrees of freedom come from the denominator in the t-test, which is based on the residual sum of squares -- there are $n-p-1$ degrees of freedom in the residual sums of squares.
When doing a t-test for the significance of a regression coefficient, why is the number of degrees o
You lose one degree of freedom for each estimated mean parameter. For an ordinary t-test that's 1 (the mean). For regression, each predictor costs you a degree of freedom. The extra one is for the int
When doing a t-test for the significance of a regression coefficient, why is the number of degrees of freedom $n-p-1$? You lose one degree of freedom for each estimated mean parameter. For an ordinary t-test that's 1 (the mean). For regression, each predictor costs you a degree of freedom. The extra one is for the intercept. More specifically, the degrees of freedom come from the denominator in the t-test, which is based on the residual sum of squares -- there are $n-p-1$ degrees of freedom in the residual sums of squares.
When doing a t-test for the significance of a regression coefficient, why is the number of degrees o You lose one degree of freedom for each estimated mean parameter. For an ordinary t-test that's 1 (the mean). For regression, each predictor costs you a degree of freedom. The extra one is for the int
15,608
When doing a t-test for the significance of a regression coefficient, why is the number of degrees of freedom $n-p-1$?
This is not true in general. The number of degrees of freedom of t-test depends on a specific model. They're talking about linear regression. So, t-test for an estimator has $n-p-1$ degrees of freedom where $p$ is number of explanatory parameters in the model.
When doing a t-test for the significance of a regression coefficient, why is the number of degrees o
This is not true in general. The number of degrees of freedom of t-test depends on a specific model. They're talking about linear regression. So, t-test for an estimator has $n-p-1$ degrees of freedom
When doing a t-test for the significance of a regression coefficient, why is the number of degrees of freedom $n-p-1$? This is not true in general. The number of degrees of freedom of t-test depends on a specific model. They're talking about linear regression. So, t-test for an estimator has $n-p-1$ degrees of freedom where $p$ is number of explanatory parameters in the model.
When doing a t-test for the significance of a regression coefficient, why is the number of degrees o This is not true in general. The number of degrees of freedom of t-test depends on a specific model. They're talking about linear regression. So, t-test for an estimator has $n-p-1$ degrees of freedom
15,609
When doing a t-test for the significance of a regression coefficient, why is the number of degrees of freedom $n-p-1$?
Degrees of freedom is the number of independent values or quantities which can be assigned to a statistical distribution. So in this case its n−p−1 because: n is number of training samples. p is number of predictors. 1 is for intercept.
When doing a t-test for the significance of a regression coefficient, why is the number of degrees o
Degrees of freedom is the number of independent values or quantities which can be assigned to a statistical distribution. So in this case its n−p−1 because: n is number of training samples. p is numbe
When doing a t-test for the significance of a regression coefficient, why is the number of degrees of freedom $n-p-1$? Degrees of freedom is the number of independent values or quantities which can be assigned to a statistical distribution. So in this case its n−p−1 because: n is number of training samples. p is number of predictors. 1 is for intercept.
When doing a t-test for the significance of a regression coefficient, why is the number of degrees o Degrees of freedom is the number of independent values or quantities which can be assigned to a statistical distribution. So in this case its n−p−1 because: n is number of training samples. p is numbe
15,610
Overdispersion in logistic regression
A binomial random variable with $N$ trials and probability of success $p$ can take more than two values. The binomial random variable represents the number of successes in those $N$ trials, and can in fact take $N+1$ different values ($0,1,2,3,...,N$). So if the variance of that distribution is greater than too be expected under the binomial assumptions (perhaps there are excess zeros for instance), that is a case of overdispersion. Overdispersion does not make sense for a Bernoulli random variable ($N = 1$) In the context of a logistic regression curve, you can consider a "small slice", or grouping, through a narrow range of predictor value to be a realization of a binomial experiment (maybe we have 10 points in the slice with a certain number of successes and failures). Even though we do not truly have multiple trials at each predictor value and we are looking at proportions instead of raw counts, we would still expect the proportion of each of these "slices" to be close to the curve. If these "slices" have a tendency to be far away from the curve, there is too much variability in the distribution. So by grouping the observations, you create realizations of binomial random variables rather than looking at the 0/1 data individually. The Example below is from another question on this site. Lets say the blue lines represents the expected proportion over the range of predictor variables. The blue cells indicate observed instances (in this case schools). This provides a graphical representation of how overdispersion may look. Note that there are flaws with interpreting the cells of the graph below, but it provides an idea of how overdispersion can manifest itself.
Overdispersion in logistic regression
A binomial random variable with $N$ trials and probability of success $p$ can take more than two values. The binomial random variable represents the number of successes in those $N$ trials, and can i
Overdispersion in logistic regression A binomial random variable with $N$ trials and probability of success $p$ can take more than two values. The binomial random variable represents the number of successes in those $N$ trials, and can in fact take $N+1$ different values ($0,1,2,3,...,N$). So if the variance of that distribution is greater than too be expected under the binomial assumptions (perhaps there are excess zeros for instance), that is a case of overdispersion. Overdispersion does not make sense for a Bernoulli random variable ($N = 1$) In the context of a logistic regression curve, you can consider a "small slice", or grouping, through a narrow range of predictor value to be a realization of a binomial experiment (maybe we have 10 points in the slice with a certain number of successes and failures). Even though we do not truly have multiple trials at each predictor value and we are looking at proportions instead of raw counts, we would still expect the proportion of each of these "slices" to be close to the curve. If these "slices" have a tendency to be far away from the curve, there is too much variability in the distribution. So by grouping the observations, you create realizations of binomial random variables rather than looking at the 0/1 data individually. The Example below is from another question on this site. Lets say the blue lines represents the expected proportion over the range of predictor variables. The blue cells indicate observed instances (in this case schools). This provides a graphical representation of how overdispersion may look. Note that there are flaws with interpreting the cells of the graph below, but it provides an idea of how overdispersion can manifest itself.
Overdispersion in logistic regression A binomial random variable with $N$ trials and probability of success $p$ can take more than two values. The binomial random variable represents the number of successes in those $N$ trials, and can i
15,611
Overdispersion in logistic regression
As already noted by others, overdispersion doesn't apply in the case of a Bernoulli (0/1) variable, since in that case, the mean necessarily determines the variance. In the context of logistic regression, this means that if your outcome is binary, you can't estimate a dispersion parameter. (N.B. This does not mean that you can ignore potential correlation between observations just because your outcome is binary!) If, on the other hand, your outcome is a set of proportions, then you can estimate a dispersion parameter (which, although often greater than one, can also be less than one) by dividing the Pearson chi-squared statistic (or the deviance) by the residual degrees of freedom. Remember, logistic regression with a purely binary outcome is just a special case of the more general logistic regression model in which the binomial index can exceed one (and can vary across observations). Thus, the question of whether you're fitting a logistic regression model or not is unrelated to the question of whether your data are overdispersed.
Overdispersion in logistic regression
As already noted by others, overdispersion doesn't apply in the case of a Bernoulli (0/1) variable, since in that case, the mean necessarily determines the variance. In the context of logistic regres
Overdispersion in logistic regression As already noted by others, overdispersion doesn't apply in the case of a Bernoulli (0/1) variable, since in that case, the mean necessarily determines the variance. In the context of logistic regression, this means that if your outcome is binary, you can't estimate a dispersion parameter. (N.B. This does not mean that you can ignore potential correlation between observations just because your outcome is binary!) If, on the other hand, your outcome is a set of proportions, then you can estimate a dispersion parameter (which, although often greater than one, can also be less than one) by dividing the Pearson chi-squared statistic (or the deviance) by the residual degrees of freedom. Remember, logistic regression with a purely binary outcome is just a special case of the more general logistic regression model in which the binomial index can exceed one (and can vary across observations). Thus, the question of whether you're fitting a logistic regression model or not is unrelated to the question of whether your data are overdispersed.
Overdispersion in logistic regression As already noted by others, overdispersion doesn't apply in the case of a Bernoulli (0/1) variable, since in that case, the mean necessarily determines the variance. In the context of logistic regres
15,612
Performing PCA with only a distance matrix
Update: I entirely removed my original answer, because it was based on a confusion between Euclidean distances and scalar products. This is a new version of my answer. Apologies. If by pairwise distances you mean Euclidean distances, then yes, there is a way to perform PCA and to find principal components. I describe the algorithm in my answer to the following question: What's the difference between principal components analysis and multidimensional scaling? Very briefly, the matrix of Euclidean distances can be converted into a centered Gram matrix, which can be directly used to perform PCA via eigendecomposition. This procedure is known as [classical] multidimensional scaling (MDS). If your pairwise distances are not Euclidean, then you cannot perform PCA, but still can perform MDS, which is not going to be equivalent to PCA anymore. However, in this situation MDS is likely to be even better for your purposes.
Performing PCA with only a distance matrix
Update: I entirely removed my original answer, because it was based on a confusion between Euclidean distances and scalar products. This is a new version of my answer. Apologies. If by pairwise distan
Performing PCA with only a distance matrix Update: I entirely removed my original answer, because it was based on a confusion between Euclidean distances and scalar products. This is a new version of my answer. Apologies. If by pairwise distances you mean Euclidean distances, then yes, there is a way to perform PCA and to find principal components. I describe the algorithm in my answer to the following question: What's the difference between principal components analysis and multidimensional scaling? Very briefly, the matrix of Euclidean distances can be converted into a centered Gram matrix, which can be directly used to perform PCA via eigendecomposition. This procedure is known as [classical] multidimensional scaling (MDS). If your pairwise distances are not Euclidean, then you cannot perform PCA, but still can perform MDS, which is not going to be equivalent to PCA anymore. However, in this situation MDS is likely to be even better for your purposes.
Performing PCA with only a distance matrix Update: I entirely removed my original answer, because it was based on a confusion between Euclidean distances and scalar products. This is a new version of my answer. Apologies. If by pairwise distan
15,613
Performing PCA with only a distance matrix
PCA with a distance matrix exists, and it is called Multi-dimensional scaling (MDS). You can learn more on wikipedia or in this book. You can do it in R with mds function cmdscale. For a sample x, you can check that prcomp(x) and cmdscale(dist(x)) give the same result (where prcomp does PCA and dist just computes euclidian distances between elements of x)
Performing PCA with only a distance matrix
PCA with a distance matrix exists, and it is called Multi-dimensional scaling (MDS). You can learn more on wikipedia or in this book. You can do it in R with mds function cmdscale. For a sample x, you
Performing PCA with only a distance matrix PCA with a distance matrix exists, and it is called Multi-dimensional scaling (MDS). You can learn more on wikipedia or in this book. You can do it in R with mds function cmdscale. For a sample x, you can check that prcomp(x) and cmdscale(dist(x)) give the same result (where prcomp does PCA and dist just computes euclidian distances between elements of x)
Performing PCA with only a distance matrix PCA with a distance matrix exists, and it is called Multi-dimensional scaling (MDS). You can learn more on wikipedia or in this book. You can do it in R with mds function cmdscale. For a sample x, you
15,614
Performing PCA with only a distance matrix
This looks like a problem that spectral clustering could be applied to. Since you have the pairwise distance matrix, you can define a fully connected graph where each node has N connections, corresponding to its distance from every other node in the graph. From this, you can compute the graph Laplacian (if this sounds scary, don't worry--it's an easy computation) and then take eigenvectors of the smallest eigenvalues (this is where it differs from PCA). If you take 3 eigenvectors, for example, you will then have an Nx3 matrix. In this space, the points should (hopefully) be well-separated because of some neat graph theory which suggests that this is an optimal cut for maximizing flow (or distance, in this case) between clusters. From there, you could use a k-means or similar algorithm to cluster in 3-space. I recommend checking out this awesome walkthrough for more insight: http://arxiv.org/abs/0711.0189
Performing PCA with only a distance matrix
This looks like a problem that spectral clustering could be applied to. Since you have the pairwise distance matrix, you can define a fully connected graph where each node has N connections, correspon
Performing PCA with only a distance matrix This looks like a problem that spectral clustering could be applied to. Since you have the pairwise distance matrix, you can define a fully connected graph where each node has N connections, corresponding to its distance from every other node in the graph. From this, you can compute the graph Laplacian (if this sounds scary, don't worry--it's an easy computation) and then take eigenvectors of the smallest eigenvalues (this is where it differs from PCA). If you take 3 eigenvectors, for example, you will then have an Nx3 matrix. In this space, the points should (hopefully) be well-separated because of some neat graph theory which suggests that this is an optimal cut for maximizing flow (or distance, in this case) between clusters. From there, you could use a k-means or similar algorithm to cluster in 3-space. I recommend checking out this awesome walkthrough for more insight: http://arxiv.org/abs/0711.0189
Performing PCA with only a distance matrix This looks like a problem that spectral clustering could be applied to. Since you have the pairwise distance matrix, you can define a fully connected graph where each node has N connections, correspon
15,615
Performing PCA with only a distance matrix
The pairwise distances also form a square matrix just like the co-variance matrix. PCA is just SVD (http://en.wikipedia.org/wiki/Singular_value_decomposition) applied to the co-variance matrix. You should still be able to do dimension reduction using SVD on your data. I'm not exactly sure how to interpret your output but it is definitely something to try. You could use clustering methods such as k-means or hierarchical clustering. Also take a look at other dimension reduction techniques such as multidimensional scaling. What are you trying to get out of your clusters?
Performing PCA with only a distance matrix
The pairwise distances also form a square matrix just like the co-variance matrix. PCA is just SVD (http://en.wikipedia.org/wiki/Singular_value_decomposition) applied to the co-variance matrix. You s
Performing PCA with only a distance matrix The pairwise distances also form a square matrix just like the co-variance matrix. PCA is just SVD (http://en.wikipedia.org/wiki/Singular_value_decomposition) applied to the co-variance matrix. You should still be able to do dimension reduction using SVD on your data. I'm not exactly sure how to interpret your output but it is definitely something to try. You could use clustering methods such as k-means or hierarchical clustering. Also take a look at other dimension reduction techniques such as multidimensional scaling. What are you trying to get out of your clusters?
Performing PCA with only a distance matrix The pairwise distances also form a square matrix just like the co-variance matrix. PCA is just SVD (http://en.wikipedia.org/wiki/Singular_value_decomposition) applied to the co-variance matrix. You s
15,616
Understanding Metropolis-Hastings with asymmetric proposal distribution
The bibliography states that if q is a symmetric distribution the ratio q(x|y)/q(y|x) becomes 1 and the algorithm is called Metropolis. Is that correct? Yes, this is correct. The Metropolis algorithm is a special case of the MH algorithm. What about "Random Walk" Metropolis(-Hastings)? How does it differ from the other two? In a random walk, the proposal distribution is re-centered after each step at the value last generated by the chain. Generally, in a random walk the proposal distribution is gaussian, in which case this random walk satisfies the symmetry requirement and the algorithm is metropolis. I suppose you could perform a "pseudo" random walk with an asymmetric distribution which would cause the proposals too drift in the opposite direction of the skew (a left skewed distribution would favor proposals toward the right). I'm not sure why you would do this, but you could and it would be a metropolis hastings algorithm (i.e. require the additional ratio term). How does it differ from the other two? In a non-random walk algorithm, the proposal distributions are fixed. In the random walk variant, the center of the proposal distribution changes at each iteration. What if the proposal distribution is a Poisson distribution? Then you need to use MH instead of just metropolis. Presumably this would be to sample a discrete distribution, otherwise you wouldn't want to use a discrete function to generate your proposals. In any event, if the sampling distribution is truncated or you have prior knowledge of its skew, you probably want to use an asymmetric sampling distribution and therefore need to use metropolis-hastings. Could someone give me a simple code (C, python, R, pseudo-code or whatever you prefer) example? Here's metropolis: Metropolis <- function(F_sample # distribution we want to sample , F_prop # proposal distribution , I=1e5 # iterations ){ y = rep(NA,T) y[1] = 0 # starting location for random walk accepted = c(1) for(t in 2:I) { #y.prop <- rnorm(1, y[t-1], sqrt(sigma2) ) # random walk proposal y.prop <- F_prop(y[t-1]) # implementation assumes a random walk. # discard this input for a fixed proposal distribution # We work with the log-likelihoods for numeric stability. logR = sum(log(F_sample(y.prop))) - sum(log(F_sample(y[t-1]))) R = exp(logR) u <- runif(1) ## uniform variable to determine acceptance if(u < R){ ## accept the new value y[t] = y.prop accepted = c(accepted,1) } else{ y[t] = y[t-1] ## reject the new value accepted = c(accepted,0) } } return(list(y, accepted)) } Let's try using this to sample a bimodal distribution. First, let's see what happens if we use a random walk for our propsal: set.seed(100) test = function(x){dnorm(x,-5,1)+dnorm(x,7,3)} # random walk response1 <- Metropolis(F_sample = test ,F_prop = function(x){rnorm(1, x, sqrt(0.5) )} ,I=1e5 ) y_trace1 = response1[[1]]; accpt_1 = response1[[2]] mean(accpt_1) # acceptance rate without considering burn-in # 0.85585 not bad # looks about how we'd expect plot(density(y_trace1)) abline(v=-5);abline(v=7) # Highlight the approximate modes of the true distribution Now let's try sampling using a fixed proposal distribution and see what happens: response2 <- Metropolis(F_sample = test ,F_prop = function(x){rnorm(1, -5, sqrt(0.5) )} ,I=1e5 ) y_trace2 = response2[[1]]; accpt_2 = response2[[2]] mean(accpt_2) # .871, not bad This looks ok at first, but if we take a look at the posterior density... plot(density(y_trace2)) we'll see that it's completely stuck at a local maximum. This isn't entirely surprising since we actually centered our proposal distribution there. Same thing happens if we center this on the other mode: response2b <- Metropolis(F_sample = test ,F_prop = function(x){rnorm(1, 7, sqrt(10) )} ,I=1e5 ) plot(density(response2b[[1]])) We can try dropping our proposal between the two modes, but we'll need to set the variance really high to have a chance at exploring either of them response3 <- Metropolis(F_sample = test ,F_prop = function(x){rnorm(1, -2, sqrt(10) )} ,I=1e5 ) y_trace3 = response3[[1]]; accpt_3 = response3[[2]] mean(accpt_3) # .3958! Notice how the choice of the center of our proposal distribution has a significant impact on the acceptance rate of our sampler. plot(density(y_trace3)) plot(y_trace3) # we really need to set the variance pretty high to catch # the mode at +7. We're still just barely exploring it We still get stuck in the closer of the two modes. Let's try dropping this directly between the two modes. response4 <- Metropolis(F_sample = test ,F_prop = function(x){rnorm(1, 1, sqrt(10) )} ,I=1e5 ) y_trace4 = response4[[1]]; accpt_4 = response4[[2]] plot(density(y_trace1)) lines(density(y_trace4), col='red') Finally, we're getting closer to what we were looking for. Theoretically, if we let the sampler run long enough we can get a representative sample out of any of these proposal distributions, but the random walk produced a usable sample very quickly, and we had to take advantage of our knowledge of how the posterior was supposed to look to tune the fixed sampling distributions to produce a usable result (which, truth be told, we don't quite have yet in y_trace4). I'll try to update with an example of metropolis hastings later. You should be able to see fairly easily how to modify the above code to produce a metropolis hastings algorithm (hint: you just need to add the supplemental ratio into the logR calculation).
Understanding Metropolis-Hastings with asymmetric proposal distribution
The bibliography states that if q is a symmetric distribution the ratio q(x|y)/q(y|x) becomes 1 and the algorithm is called Metropolis. Is that correct? Yes, this is correct. The Metropolis algorith
Understanding Metropolis-Hastings with asymmetric proposal distribution The bibliography states that if q is a symmetric distribution the ratio q(x|y)/q(y|x) becomes 1 and the algorithm is called Metropolis. Is that correct? Yes, this is correct. The Metropolis algorithm is a special case of the MH algorithm. What about "Random Walk" Metropolis(-Hastings)? How does it differ from the other two? In a random walk, the proposal distribution is re-centered after each step at the value last generated by the chain. Generally, in a random walk the proposal distribution is gaussian, in which case this random walk satisfies the symmetry requirement and the algorithm is metropolis. I suppose you could perform a "pseudo" random walk with an asymmetric distribution which would cause the proposals too drift in the opposite direction of the skew (a left skewed distribution would favor proposals toward the right). I'm not sure why you would do this, but you could and it would be a metropolis hastings algorithm (i.e. require the additional ratio term). How does it differ from the other two? In a non-random walk algorithm, the proposal distributions are fixed. In the random walk variant, the center of the proposal distribution changes at each iteration. What if the proposal distribution is a Poisson distribution? Then you need to use MH instead of just metropolis. Presumably this would be to sample a discrete distribution, otherwise you wouldn't want to use a discrete function to generate your proposals. In any event, if the sampling distribution is truncated or you have prior knowledge of its skew, you probably want to use an asymmetric sampling distribution and therefore need to use metropolis-hastings. Could someone give me a simple code (C, python, R, pseudo-code or whatever you prefer) example? Here's metropolis: Metropolis <- function(F_sample # distribution we want to sample , F_prop # proposal distribution , I=1e5 # iterations ){ y = rep(NA,T) y[1] = 0 # starting location for random walk accepted = c(1) for(t in 2:I) { #y.prop <- rnorm(1, y[t-1], sqrt(sigma2) ) # random walk proposal y.prop <- F_prop(y[t-1]) # implementation assumes a random walk. # discard this input for a fixed proposal distribution # We work with the log-likelihoods for numeric stability. logR = sum(log(F_sample(y.prop))) - sum(log(F_sample(y[t-1]))) R = exp(logR) u <- runif(1) ## uniform variable to determine acceptance if(u < R){ ## accept the new value y[t] = y.prop accepted = c(accepted,1) } else{ y[t] = y[t-1] ## reject the new value accepted = c(accepted,0) } } return(list(y, accepted)) } Let's try using this to sample a bimodal distribution. First, let's see what happens if we use a random walk for our propsal: set.seed(100) test = function(x){dnorm(x,-5,1)+dnorm(x,7,3)} # random walk response1 <- Metropolis(F_sample = test ,F_prop = function(x){rnorm(1, x, sqrt(0.5) )} ,I=1e5 ) y_trace1 = response1[[1]]; accpt_1 = response1[[2]] mean(accpt_1) # acceptance rate without considering burn-in # 0.85585 not bad # looks about how we'd expect plot(density(y_trace1)) abline(v=-5);abline(v=7) # Highlight the approximate modes of the true distribution Now let's try sampling using a fixed proposal distribution and see what happens: response2 <- Metropolis(F_sample = test ,F_prop = function(x){rnorm(1, -5, sqrt(0.5) )} ,I=1e5 ) y_trace2 = response2[[1]]; accpt_2 = response2[[2]] mean(accpt_2) # .871, not bad This looks ok at first, but if we take a look at the posterior density... plot(density(y_trace2)) we'll see that it's completely stuck at a local maximum. This isn't entirely surprising since we actually centered our proposal distribution there. Same thing happens if we center this on the other mode: response2b <- Metropolis(F_sample = test ,F_prop = function(x){rnorm(1, 7, sqrt(10) )} ,I=1e5 ) plot(density(response2b[[1]])) We can try dropping our proposal between the two modes, but we'll need to set the variance really high to have a chance at exploring either of them response3 <- Metropolis(F_sample = test ,F_prop = function(x){rnorm(1, -2, sqrt(10) )} ,I=1e5 ) y_trace3 = response3[[1]]; accpt_3 = response3[[2]] mean(accpt_3) # .3958! Notice how the choice of the center of our proposal distribution has a significant impact on the acceptance rate of our sampler. plot(density(y_trace3)) plot(y_trace3) # we really need to set the variance pretty high to catch # the mode at +7. We're still just barely exploring it We still get stuck in the closer of the two modes. Let's try dropping this directly between the two modes. response4 <- Metropolis(F_sample = test ,F_prop = function(x){rnorm(1, 1, sqrt(10) )} ,I=1e5 ) y_trace4 = response4[[1]]; accpt_4 = response4[[2]] plot(density(y_trace1)) lines(density(y_trace4), col='red') Finally, we're getting closer to what we were looking for. Theoretically, if we let the sampler run long enough we can get a representative sample out of any of these proposal distributions, but the random walk produced a usable sample very quickly, and we had to take advantage of our knowledge of how the posterior was supposed to look to tune the fixed sampling distributions to produce a usable result (which, truth be told, we don't quite have yet in y_trace4). I'll try to update with an example of metropolis hastings later. You should be able to see fairly easily how to modify the above code to produce a metropolis hastings algorithm (hint: you just need to add the supplemental ratio into the logR calculation).
Understanding Metropolis-Hastings with asymmetric proposal distribution The bibliography states that if q is a symmetric distribution the ratio q(x|y)/q(y|x) becomes 1 and the algorithm is called Metropolis. Is that correct? Yes, this is correct. The Metropolis algorith
15,617
Generate normally distributed random numbers with non positive-definite covariance matrix
Solution Method A: If C is not symmetric, then symmetrize it. D <-- $0.5(C + C^T)$ Add a multiple of the Identity matrix to the symmetrized C sufficient to make it positive definite with whatever margin, m, is desired, i.e., such that smallest eigenvalue of new matrix has minimum eigenvalue = m. Specifically, D <-- $D + (m - min(eigenvalue(D)))I$, where I is the identity matrix. D contains the desired positive definite covariance matrix. In MATLAB, the code would be D = 0.5 * (C + C'); D = D + (m - min(eig(CD)) * eye(size(D)); Solution Method B: Formulate and solve a Convex SDP (Semidefinite Program) to find the nearest matrix D to C according to the frobenius norm of their difference, such that D is positive definite, having specified minimum eigenvalue m. Using CVX under MATLAB, the code would be: n = size(C,1); cvx_begin variable D(n,n) minimize(norm(D-C,'fro')) D -m *eye(n) == semidefinite(n) cvx_end Comparison of Solution Methods: Apart from symmetrizing the initial matrix, solution method A adjusts (increases) only the diagonal elements by some common amount, and leaves the off-diagonal elements unchanged. Solution method B finds the nearest (to the original matrix) positive definite matrix having the specified minimum eigenvalue, in the sense of minimum frobenius norm of the difference of the positive definite matrix D and the original matrix C, which is based on the sums of squared differences of all elements of D - C, to include the off-diagonal elements. So by adjusting off-diagonal elements, it may reduce the amount by which diagonal elements need to be increased, and diagoanl elements are not necessarily all increased by the same amount.
Generate normally distributed random numbers with non positive-definite covariance matrix
Solution Method A: If C is not symmetric, then symmetrize it. D <-- $0.5(C + C^T)$ Add a multiple of the Identity matrix to the symmetrized C sufficient to make it positive definite with whatever mar
Generate normally distributed random numbers with non positive-definite covariance matrix Solution Method A: If C is not symmetric, then symmetrize it. D <-- $0.5(C + C^T)$ Add a multiple of the Identity matrix to the symmetrized C sufficient to make it positive definite with whatever margin, m, is desired, i.e., such that smallest eigenvalue of new matrix has minimum eigenvalue = m. Specifically, D <-- $D + (m - min(eigenvalue(D)))I$, where I is the identity matrix. D contains the desired positive definite covariance matrix. In MATLAB, the code would be D = 0.5 * (C + C'); D = D + (m - min(eig(CD)) * eye(size(D)); Solution Method B: Formulate and solve a Convex SDP (Semidefinite Program) to find the nearest matrix D to C according to the frobenius norm of their difference, such that D is positive definite, having specified minimum eigenvalue m. Using CVX under MATLAB, the code would be: n = size(C,1); cvx_begin variable D(n,n) minimize(norm(D-C,'fro')) D -m *eye(n) == semidefinite(n) cvx_end Comparison of Solution Methods: Apart from symmetrizing the initial matrix, solution method A adjusts (increases) only the diagonal elements by some common amount, and leaves the off-diagonal elements unchanged. Solution method B finds the nearest (to the original matrix) positive definite matrix having the specified minimum eigenvalue, in the sense of minimum frobenius norm of the difference of the positive definite matrix D and the original matrix C, which is based on the sums of squared differences of all elements of D - C, to include the off-diagonal elements. So by adjusting off-diagonal elements, it may reduce the amount by which diagonal elements need to be increased, and diagoanl elements are not necessarily all increased by the same amount.
Generate normally distributed random numbers with non positive-definite covariance matrix Solution Method A: If C is not symmetric, then symmetrize it. D <-- $0.5(C + C^T)$ Add a multiple of the Identity matrix to the symmetrized C sufficient to make it positive definite with whatever mar
15,618
Generate normally distributed random numbers with non positive-definite covariance matrix
The question concerns how to generate random variates from a multivariate Normal distribution with a (possibly) singular covariance matrix $\mathbb{C}$. This answer explains one way that will work for any covariance matrix. It provides an R implementation that tests its accuracy. Algebraic analysis of the covariance matrix Because $\mathbb{C}$ is a covariance matrix, it necessarily is symmetric and positive-semidefinite. To complete the background information, let $\mu$ be the vector of desired means. Because $\mathbb{C}$ is symmetric, its Singular Value Decomposition (SVD) and its eigendecomposition will automatically have the form $$\mathbb{C} = \mathbb{V\, D^2\, V^\prime}$$ for some orthogonal matrix $\mathbb{V}$ and diagonal matrix $\mathbb{D}^2$. In general the diagonal elements of $\mathbb{D}^2$ are nonnegative (implying they all have real square roots: choose the positive ones to form the diagonal matrix $\mathbb{D}$). The information we have about $\mathbb{C}$ says that one or more of those diagonal elements are zero--but that won't affect any of the subsequent operations, nor will it prevent the SVD from being computed. Generating multivariate random values Let $X$ have a standard multivariate Normal distribution: each component has zero mean, unit variance, and all covariances are zero: its covariance matrix is the identity $\mathbb{I}$. Then the random variable $Y=\mathbb{VD}X$ has covariance matrix $$\operatorname{Cov}(Y) = \mathbb{E}(Y Y^\prime) = \mathbb{E}(\mathbb{V D}X\, X^\prime \mathbb{D^\prime V^\prime}) = \mathbb{V D}\mathbb{E}(X X^\prime)\mathbb{D V^\prime} = \mathbb{V D I D V^\prime} = \mathbb{V D^2 V^\prime} = \mathbb{C}.$$ Consequently the random variable $\mu + \mathbb{Y}$ has a multivariate Normal distribution with mean $\mu$ and covariance matrix $\mathbb{C}$. Computation and Example code The following R code generates a covariance matrix of given dimensions and rank, analyzes it with the SVD (or, in commented-out code, with an eigendecomposition), uses that analysis to generate a specified number of realizations of $Y$ (with mean vector $0$), and then compares the covariance matrix of those data to the intended covariance matrix both numerically and graphically. As shown, it generates $10,000$ realizations where the dimension of $Y$ is $100$ and the rank of $C$ is $50$. The output is rank L2 5.000000e+01 8.846689e-05 That is, the rank of the data is also $50$ and the covariance matrix as estimated from the data is within distance $8\times 10^{-5}$ of $C$--which is close. As a more detailed check, the coefficients of $C$ are plotted against those of its estimate. They all lie close to the line of equality: The code exactly parallels the preceding analysis and so should be self-explanatory (even to non-R users, who might emulate it in their favorite application environment). One thing it reveals is the need for caution when using floating-point algorithms: the entries of $\mathbb{D}^2$ can easily be negative (but tiny) due to imprecision. Such entries need to be zeroed out before computing the square root to find $\mathbb{D}$ itself. n <- 100 # Dimension rank <- 50 n.values <- 1e4 # Number of random vectors to generate set.seed(17) # # Create an indefinite covariance matrix. # r <- min(rank, n)+1 X <- matrix(rnorm(r*n), r) C <- cov(X) # # Analyze C preparatory to generating random values. # `zapsmall` removes zeros that, due to floating point imprecision, might # have been rendered as tiny negative values. # s <- svd(C) V <- s$v D <- sqrt(zapsmall(diag(s$d))) # s <- eigen(C) # V <- s$vectors # D <- sqrt(zapsmall(diag(s$values))) # # Generate random values. # X <- (V %*% D) %*% matrix(rnorm(n*n.values), n) # # Verify their covariance has the desired rank and is close to `C`. # s <- svd(Sigma <- cov(t(X))) (c(rank=sum(zapsmall(s$d) > 0), L2=sqrt(mean(Sigma - C)^2))) plot(as.vector(C), as.vector(Sigma), col="#00000040", xlab="Intended Covariances", ylab="Estimated Covariances") abline(c(0,1), col="Gray")
Generate normally distributed random numbers with non positive-definite covariance matrix
The question concerns how to generate random variates from a multivariate Normal distribution with a (possibly) singular covariance matrix $\mathbb{C}$. This answer explains one way that will work fo
Generate normally distributed random numbers with non positive-definite covariance matrix The question concerns how to generate random variates from a multivariate Normal distribution with a (possibly) singular covariance matrix $\mathbb{C}$. This answer explains one way that will work for any covariance matrix. It provides an R implementation that tests its accuracy. Algebraic analysis of the covariance matrix Because $\mathbb{C}$ is a covariance matrix, it necessarily is symmetric and positive-semidefinite. To complete the background information, let $\mu$ be the vector of desired means. Because $\mathbb{C}$ is symmetric, its Singular Value Decomposition (SVD) and its eigendecomposition will automatically have the form $$\mathbb{C} = \mathbb{V\, D^2\, V^\prime}$$ for some orthogonal matrix $\mathbb{V}$ and diagonal matrix $\mathbb{D}^2$. In general the diagonal elements of $\mathbb{D}^2$ are nonnegative (implying they all have real square roots: choose the positive ones to form the diagonal matrix $\mathbb{D}$). The information we have about $\mathbb{C}$ says that one or more of those diagonal elements are zero--but that won't affect any of the subsequent operations, nor will it prevent the SVD from being computed. Generating multivariate random values Let $X$ have a standard multivariate Normal distribution: each component has zero mean, unit variance, and all covariances are zero: its covariance matrix is the identity $\mathbb{I}$. Then the random variable $Y=\mathbb{VD}X$ has covariance matrix $$\operatorname{Cov}(Y) = \mathbb{E}(Y Y^\prime) = \mathbb{E}(\mathbb{V D}X\, X^\prime \mathbb{D^\prime V^\prime}) = \mathbb{V D}\mathbb{E}(X X^\prime)\mathbb{D V^\prime} = \mathbb{V D I D V^\prime} = \mathbb{V D^2 V^\prime} = \mathbb{C}.$$ Consequently the random variable $\mu + \mathbb{Y}$ has a multivariate Normal distribution with mean $\mu$ and covariance matrix $\mathbb{C}$. Computation and Example code The following R code generates a covariance matrix of given dimensions and rank, analyzes it with the SVD (or, in commented-out code, with an eigendecomposition), uses that analysis to generate a specified number of realizations of $Y$ (with mean vector $0$), and then compares the covariance matrix of those data to the intended covariance matrix both numerically and graphically. As shown, it generates $10,000$ realizations where the dimension of $Y$ is $100$ and the rank of $C$ is $50$. The output is rank L2 5.000000e+01 8.846689e-05 That is, the rank of the data is also $50$ and the covariance matrix as estimated from the data is within distance $8\times 10^{-5}$ of $C$--which is close. As a more detailed check, the coefficients of $C$ are plotted against those of its estimate. They all lie close to the line of equality: The code exactly parallels the preceding analysis and so should be self-explanatory (even to non-R users, who might emulate it in their favorite application environment). One thing it reveals is the need for caution when using floating-point algorithms: the entries of $\mathbb{D}^2$ can easily be negative (but tiny) due to imprecision. Such entries need to be zeroed out before computing the square root to find $\mathbb{D}$ itself. n <- 100 # Dimension rank <- 50 n.values <- 1e4 # Number of random vectors to generate set.seed(17) # # Create an indefinite covariance matrix. # r <- min(rank, n)+1 X <- matrix(rnorm(r*n), r) C <- cov(X) # # Analyze C preparatory to generating random values. # `zapsmall` removes zeros that, due to floating point imprecision, might # have been rendered as tiny negative values. # s <- svd(C) V <- s$v D <- sqrt(zapsmall(diag(s$d))) # s <- eigen(C) # V <- s$vectors # D <- sqrt(zapsmall(diag(s$values))) # # Generate random values. # X <- (V %*% D) %*% matrix(rnorm(n*n.values), n) # # Verify their covariance has the desired rank and is close to `C`. # s <- svd(Sigma <- cov(t(X))) (c(rank=sum(zapsmall(s$d) > 0), L2=sqrt(mean(Sigma - C)^2))) plot(as.vector(C), as.vector(Sigma), col="#00000040", xlab="Intended Covariances", ylab="Estimated Covariances") abline(c(0,1), col="Gray")
Generate normally distributed random numbers with non positive-definite covariance matrix The question concerns how to generate random variates from a multivariate Normal distribution with a (possibly) singular covariance matrix $\mathbb{C}$. This answer explains one way that will work fo
15,619
Generate normally distributed random numbers with non positive-definite covariance matrix
One way would be to compute the matrix from an eigenvalue decomposition. Now I'll admit I don't know too much of the Math behind these processes but from my research it seems fruitful to look at this help file: http://stat.ethz.ch/R-manual/R-patched/library/Matrix/html/chol.html and some other related commands in R. Also, check out 'nearPD' in the Matrix package. Sorry I couldn't be of more help but I hope my searching around can help push you in the right direction.
Generate normally distributed random numbers with non positive-definite covariance matrix
One way would be to compute the matrix from an eigenvalue decomposition. Now I'll admit I don't know too much of the Math behind these processes but from my research it seems fruitful to look at this
Generate normally distributed random numbers with non positive-definite covariance matrix One way would be to compute the matrix from an eigenvalue decomposition. Now I'll admit I don't know too much of the Math behind these processes but from my research it seems fruitful to look at this help file: http://stat.ethz.ch/R-manual/R-patched/library/Matrix/html/chol.html and some other related commands in R. Also, check out 'nearPD' in the Matrix package. Sorry I couldn't be of more help but I hope my searching around can help push you in the right direction.
Generate normally distributed random numbers with non positive-definite covariance matrix One way would be to compute the matrix from an eigenvalue decomposition. Now I'll admit I don't know too much of the Math behind these processes but from my research it seems fruitful to look at this
15,620
Generate normally distributed random numbers with non positive-definite covariance matrix
I would begin by thinking about the model you are estimating. If a covariance matrix is not positive semi-definite, it may indicate that you have a colinearity problem in your variables which would indicate a problem with the model and should not necessarily be solved by numerical methods. If the matrix is not positive semidefinite for numerical reasons, then there some solutions which can be read about here
Generate normally distributed random numbers with non positive-definite covariance matrix
I would begin by thinking about the model you are estimating. If a covariance matrix is not positive semi-definite, it may indicate that you have a colinearity problem in your variables which would i
Generate normally distributed random numbers with non positive-definite covariance matrix I would begin by thinking about the model you are estimating. If a covariance matrix is not positive semi-definite, it may indicate that you have a colinearity problem in your variables which would indicate a problem with the model and should not necessarily be solved by numerical methods. If the matrix is not positive semidefinite for numerical reasons, then there some solutions which can be read about here
Generate normally distributed random numbers with non positive-definite covariance matrix I would begin by thinking about the model you are estimating. If a covariance matrix is not positive semi-definite, it may indicate that you have a colinearity problem in your variables which would i
15,621
Generate normally distributed random numbers with non positive-definite covariance matrix
You can get the results from the nearPD function in the Matrix package in R. This will give you a real valued matrix back. library(Matrix) A <- matrix(1, 3,3); A[1,3] <- A[3,1] <- 0 n.A <- nearPD(A, corr=T, do2eigen=FALSE) n.A$mat # 3 x 3 Matrix of class "dpoMatrix" # [,1] [,2] [,3] # [1,] 1.0000000 0.7606899 0.1572981 # [2,] 0.7606899 1.0000000 0.7606899 # [3,] 0.1572981 0.7606899 1.0000000
Generate normally distributed random numbers with non positive-definite covariance matrix
You can get the results from the nearPD function in the Matrix package in R. This will give you a real valued matrix back. library(Matrix) A <- matrix(1, 3,3); A[1,3] <- A[3,1] <- 0 n.A <- nearPD(A, c
Generate normally distributed random numbers with non positive-definite covariance matrix You can get the results from the nearPD function in the Matrix package in R. This will give you a real valued matrix back. library(Matrix) A <- matrix(1, 3,3); A[1,3] <- A[3,1] <- 0 n.A <- nearPD(A, corr=T, do2eigen=FALSE) n.A$mat # 3 x 3 Matrix of class "dpoMatrix" # [,1] [,2] [,3] # [1,] 1.0000000 0.7606899 0.1572981 # [2,] 0.7606899 1.0000000 0.7606899 # [3,] 0.1572981 0.7606899 1.0000000
Generate normally distributed random numbers with non positive-definite covariance matrix You can get the results from the nearPD function in the Matrix package in R. This will give you a real valued matrix back. library(Matrix) A <- matrix(1, 3,3); A[1,3] <- A[3,1] <- 0 n.A <- nearPD(A, c
15,622
What is the variance of the maximum of a sample?
For any $n$ random variables $X_i$ , the best general bound is $\newcommand{\Var}{\mathrm{Var}}\Var(\max X_i) \le \sum_i \Var(X_i)$ as stated in the original question. Here is a proof sketch: If X,Y are IID then $E[(X-Y)^2] =2\Var(X)$. Given a vector of possibly dependent variables $(X_1,\ldots ,X_n)$, let $(Y_1,\ldots ,Y_n)$ be an independent vector with the same joint distribution. For any $r>0$, we have by the union bound that $P[ |\max_i X_i-\max_i Y_i|^2 >r] \le \sum_i P[ | X_i-Y_i|^2 >r]$, and integrating this $dr$ from $0$ to $\infty$ yields the claimed inequality. If $X_i$ are IID indicators of events of probability $\epsilon$, then $\max X_i$ is an indicator of an event of probability $n\epsilon+O(n^2 \epsilon^2)$. Fixing $n$ and letting $\epsilon$ tend to zero, we get $\Var(X_i)=\epsilon-\epsilon^2$ and $\Var(\max_i X_i)= n\epsilon +O(n^2\epsilon^2)$.
What is the variance of the maximum of a sample?
For any $n$ random variables $X_i$ , the best general bound is $\newcommand{\Var}{\mathrm{Var}}\Var(\max X_i) \le \sum_i \Var(X_i)$ as stated in the original question. Here is a proof sketch: If X,Y
What is the variance of the maximum of a sample? For any $n$ random variables $X_i$ , the best general bound is $\newcommand{\Var}{\mathrm{Var}}\Var(\max X_i) \le \sum_i \Var(X_i)$ as stated in the original question. Here is a proof sketch: If X,Y are IID then $E[(X-Y)^2] =2\Var(X)$. Given a vector of possibly dependent variables $(X_1,\ldots ,X_n)$, let $(Y_1,\ldots ,Y_n)$ be an independent vector with the same joint distribution. For any $r>0$, we have by the union bound that $P[ |\max_i X_i-\max_i Y_i|^2 >r] \le \sum_i P[ | X_i-Y_i|^2 >r]$, and integrating this $dr$ from $0$ to $\infty$ yields the claimed inequality. If $X_i$ are IID indicators of events of probability $\epsilon$, then $\max X_i$ is an indicator of an event of probability $n\epsilon+O(n^2 \epsilon^2)$. Fixing $n$ and letting $\epsilon$ tend to zero, we get $\Var(X_i)=\epsilon-\epsilon^2$ and $\Var(\max_i X_i)= n\epsilon +O(n^2\epsilon^2)$.
What is the variance of the maximum of a sample? For any $n$ random variables $X_i$ , the best general bound is $\newcommand{\Var}{\mathrm{Var}}\Var(\max X_i) \le \sum_i \Var(X_i)$ as stated in the original question. Here is a proof sketch: If X,Y
15,623
What is the variance of the maximum of a sample?
A question on MathOverflow is related to this question. For IID random variables, the $k$th highest is called an order statistic. Even for IID Bernoulli random variables, the variance of any order statistic other than the median can be greater than the variance of the population. For example, if $X_i$ is $1$ with probability $1/10$ and $0$ with probability $9/10$ and $M=10$, then the maximum is $1$ with probability $\approx 1- 1/e$, so the variance of the population is $0.09$ while the variance of the maximum is about $0.23$. Here are two papers on the variances of order statistics: Yang, H. (1982) "On the variances of median and some other order statistics." Bull. Inst. Math. Acad. Sinica, 10(2) pp. 197-204 Papadatos, N. (1995) "Maximum variance of order statistics." Ann. Inst. Statist. Math., 47(1) pp. 185-193 I believe the upper bound on the variance of the maximum in the second paper is $M\sigma^2$. They point out that equality can't occur, but any lower value can occur for IID Bernoulli random variables.
What is the variance of the maximum of a sample?
A question on MathOverflow is related to this question. For IID random variables, the $k$th highest is called an order statistic. Even for IID Bernoulli random variables, the variance of any order st
What is the variance of the maximum of a sample? A question on MathOverflow is related to this question. For IID random variables, the $k$th highest is called an order statistic. Even for IID Bernoulli random variables, the variance of any order statistic other than the median can be greater than the variance of the population. For example, if $X_i$ is $1$ with probability $1/10$ and $0$ with probability $9/10$ and $M=10$, then the maximum is $1$ with probability $\approx 1- 1/e$, so the variance of the population is $0.09$ while the variance of the maximum is about $0.23$. Here are two papers on the variances of order statistics: Yang, H. (1982) "On the variances of median and some other order statistics." Bull. Inst. Math. Acad. Sinica, 10(2) pp. 197-204 Papadatos, N. (1995) "Maximum variance of order statistics." Ann. Inst. Statist. Math., 47(1) pp. 185-193 I believe the upper bound on the variance of the maximum in the second paper is $M\sigma^2$. They point out that equality can't occur, but any lower value can occur for IID Bernoulli random variables.
What is the variance of the maximum of a sample? A question on MathOverflow is related to this question. For IID random variables, the $k$th highest is called an order statistic. Even for IID Bernoulli random variables, the variance of any order st
15,624
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models?
There is a nice and reasonably recent discussion of this problem here: Christian P. Robert Multimodality and label switching: a discussion. Workshop on mixtures, ICMS March 3, 2010. Essentially, there are several standard strategies, and each has pros and cons. The most obvious thing to do is to formulate the prior in such a way as to ensure there is only one posterior mode (eg. order the means of the mixuture components), but this turns out to have a strange effect on the posterior, and therefore isn't generally used. Next is to ignore the problem during sampling, and then post-process the output to re-label the components to keep the labels consistent. This is easy to implement and seems to work OK. The more sophisticated approaches re-label on-line, either by keeping a single mode, or deliberately randomly permuting the labels to ensure mixing over multiple modes. I quite like the latter approach, but this still leaves the problem of how to summarise the output meaningfully. However, I see that as a separate problem.
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models
There is a nice and reasonably recent discussion of this problem here: Christian P. Robert Multimodality and label switching: a discussion. Workshop on mixtures, ICMS March 3, 2010. Essentially, t
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models? There is a nice and reasonably recent discussion of this problem here: Christian P. Robert Multimodality and label switching: a discussion. Workshop on mixtures, ICMS March 3, 2010. Essentially, there are several standard strategies, and each has pros and cons. The most obvious thing to do is to formulate the prior in such a way as to ensure there is only one posterior mode (eg. order the means of the mixuture components), but this turns out to have a strange effect on the posterior, and therefore isn't generally used. Next is to ignore the problem during sampling, and then post-process the output to re-label the components to keep the labels consistent. This is easy to implement and seems to work OK. The more sophisticated approaches re-label on-line, either by keeping a single mode, or deliberately randomly permuting the labels to ensure mixing over multiple modes. I quite like the latter approach, but this still leaves the problem of how to summarise the output meaningfully. However, I see that as a separate problem.
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models There is a nice and reasonably recent discussion of this problem here: Christian P. Robert Multimodality and label switching: a discussion. Workshop on mixtures, ICMS March 3, 2010. Essentially, t
15,625
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models?
Gilles Celeux also worked on the problem of label switching, e.g. G. Celeux, Bayesian inference for Mixture: the label switching problem. Proceedings Compstat 98, pp. 227-232, Physica-Verlag (1998). As a complement to @darrenjw's fine answer, here are two online papers that reviewed alternative strategies: Jasra et al., Markov Chain Monte Carlo Methods and the Label Switching Problem in Bayesian Mixture Modelling Sperrin et al., Probabilistic relabelling strategies for the label switching problem in Bayesian mixture models
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models
Gilles Celeux also worked on the problem of label switching, e.g. G. Celeux, Bayesian inference for Mixture: the label switching problem. Proceedings Compstat 98, pp. 227-232, Physica-Verlag (1998).
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models? Gilles Celeux also worked on the problem of label switching, e.g. G. Celeux, Bayesian inference for Mixture: the label switching problem. Proceedings Compstat 98, pp. 227-232, Physica-Verlag (1998). As a complement to @darrenjw's fine answer, here are two online papers that reviewed alternative strategies: Jasra et al., Markov Chain Monte Carlo Methods and the Label Switching Problem in Bayesian Mixture Modelling Sperrin et al., Probabilistic relabelling strategies for the label switching problem in Bayesian mixture models
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models Gilles Celeux also worked on the problem of label switching, e.g. G. Celeux, Bayesian inference for Mixture: the label switching problem. Proceedings Compstat 98, pp. 227-232, Physica-Verlag (1998).
15,626
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models?
With the R-Package "label.switching" (https://cran.r-project.org/web/packages/label.switching/index.html), the following algorithms can be compared: ECR algorithm (default version), ECR algorithm (two iterative versions), PRA algorithm, Stephens’ algorithm, Artificial Identifiability Constraint (AIC), Data-Based relabelling and a probabilistic relabelling algorithm (SJW). With the function permute.mcmc() the labels in the mcmc chains can be relablled for parameters that differ between mixture components or latent classes.
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models
With the R-Package "label.switching" (https://cran.r-project.org/web/packages/label.switching/index.html), the following algorithms can be compared: ECR algorithm (default version), ECR algorithm (two
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models? With the R-Package "label.switching" (https://cran.r-project.org/web/packages/label.switching/index.html), the following algorithms can be compared: ECR algorithm (default version), ECR algorithm (two iterative versions), PRA algorithm, Stephens’ algorithm, Artificial Identifiability Constraint (AIC), Data-Based relabelling and a probabilistic relabelling algorithm (SJW). With the function permute.mcmc() the labels in the mcmc chains can be relablled for parameters that differ between mixture components or latent classes.
Is there a standard method to deal with label switching problem in MCMC estimation of mixture models With the R-Package "label.switching" (https://cran.r-project.org/web/packages/label.switching/index.html), the following algorithms can be compared: ECR algorithm (default version), ECR algorithm (two
15,627
Purpose of Dirichlet noise in the AlphaZero paper
Question 1 is straightforward, here $\alpha$ is a vector of repetitions of the given value. (As answered by Max S.) Question 2 is more interesting: The Dirichlet distribution has the following interpretation relevant in this context: When $\alpha$ is the observed vector of outcome-counts drawn from some (unknown) categorical distribution with outcome probabilities $\pi$, then $Dir(\alpha)(\pi)$ is the likelihood that $Cat(\pi)$ is the actual underlying distribution given you observed $\alpha$ as the counts. (This is basically the definition of a dual distribution.) Now P(s,a) estimates the probability that a good player would play a in s, that is the parameters of his categorical distribution, which AlphaZero wants to learn. So $Dir(\alpha)$ would sample reasonable estimates for $pi=$P(s,a) if we observed a good player play moves $\alpha$-times. But if some $\alpha_i=0$, then all $\pi\sim Dir(\alpha)$ have $\pi_i=0$, preventing exploration. By adding the noise they assume that they have observed every move being played some small number of times $\alpha$ (here chosen 0.3, 0.15, 0.03). As for how they got the constants, my guess is that they assume to have observed ~10 random plays in every game: In chess, $Dir(0.3)$ assumes that you have seen each move played 0.3 times. Given that there are ~35 moves available according to Allis, the authors assume you have seen ~10 random moves in every node. In Go, if we assume ~270 legal moves on average (3/4 of 361 board positions), we see an equivalent to observing ~8 random moves. (I do not have the data for Shogi.)
Purpose of Dirichlet noise in the AlphaZero paper
Question 1 is straightforward, here $\alpha$ is a vector of repetitions of the given value. (As answered by Max S.) Question 2 is more interesting: The Dirichlet distribution has the following interpr
Purpose of Dirichlet noise in the AlphaZero paper Question 1 is straightforward, here $\alpha$ is a vector of repetitions of the given value. (As answered by Max S.) Question 2 is more interesting: The Dirichlet distribution has the following interpretation relevant in this context: When $\alpha$ is the observed vector of outcome-counts drawn from some (unknown) categorical distribution with outcome probabilities $\pi$, then $Dir(\alpha)(\pi)$ is the likelihood that $Cat(\pi)$ is the actual underlying distribution given you observed $\alpha$ as the counts. (This is basically the definition of a dual distribution.) Now P(s,a) estimates the probability that a good player would play a in s, that is the parameters of his categorical distribution, which AlphaZero wants to learn. So $Dir(\alpha)$ would sample reasonable estimates for $pi=$P(s,a) if we observed a good player play moves $\alpha$-times. But if some $\alpha_i=0$, then all $\pi\sim Dir(\alpha)$ have $\pi_i=0$, preventing exploration. By adding the noise they assume that they have observed every move being played some small number of times $\alpha$ (here chosen 0.3, 0.15, 0.03). As for how they got the constants, my guess is that they assume to have observed ~10 random plays in every game: In chess, $Dir(0.3)$ assumes that you have seen each move played 0.3 times. Given that there are ~35 moves available according to Allis, the authors assume you have seen ~10 random moves in every node. In Go, if we assume ~270 legal moves on average (3/4 of 361 board positions), we see an equivalent to observing ~8 random moves. (I do not have the data for Shogi.)
Purpose of Dirichlet noise in the AlphaZero paper Question 1 is straightforward, here $\alpha$ is a vector of repetitions of the given value. (As answered by Max S.) Question 2 is more interesting: The Dirichlet distribution has the following interpr
15,628
Purpose of Dirichlet noise in the AlphaZero paper
For question number 1 the answer is yes, $\alpha$ is a vector, but in this case all values are the same. According to wikipedia this is called a symmetric Dirichlet distribution, and is used when "there is no prior knowledge favoring one component over another". In this case this means that you don't want to add more noise to any particular component. For question 2, samples drawn from a Dirichlet distribution have the property that the elements will sum to 1. I assume they're using this to ensure that after adding the noise, and the elements will still sum to 1.
Purpose of Dirichlet noise in the AlphaZero paper
For question number 1 the answer is yes, $\alpha$ is a vector, but in this case all values are the same. According to wikipedia this is called a symmetric Dirichlet distribution, and is used when "the
Purpose of Dirichlet noise in the AlphaZero paper For question number 1 the answer is yes, $\alpha$ is a vector, but in this case all values are the same. According to wikipedia this is called a symmetric Dirichlet distribution, and is used when "there is no prior knowledge favoring one component over another". In this case this means that you don't want to add more noise to any particular component. For question 2, samples drawn from a Dirichlet distribution have the property that the elements will sum to 1. I assume they're using this to ensure that after adding the noise, and the elements will still sum to 1.
Purpose of Dirichlet noise in the AlphaZero paper For question number 1 the answer is yes, $\alpha$ is a vector, but in this case all values are the same. According to wikipedia this is called a symmetric Dirichlet distribution, and is used when "the
15,629
Layman's explanation of censoring in survival analysis
Censoring is often described in comparison with truncation. Nice description of the two processes is provided by Gelman et al (2005, p. 235): Truncated data differs from censored data that no count of observations beyond truncation point is available. With censoring the values of observations beyond the truncation point are lost, but their number is observed. Censoring or truncation can occur for values above some level (right-censoring), below some level (left-censoring), or both. Below you can find example of standard normal distribution that is censored at point $2.0$ (middle) or truncated at $2.0$ (right). If sample is truncated we have no data beyond the truncation point, with censored sample values above the truncation point are "rounded" to the boundary value, so they are over-represented in your sample. Intuitive example of censoring is that you ask your respondents about their age, but record it only up to some value and all the ages above this value, say 60 years, are recorded as "60+". This leads to having precise information for non-censored values and no information about censored values. Not so typical, real-life example of censoring was observed in Polish matura exam scores that caught pretty much attention on the internet. The exam is taken at the end of high school and students must pass it in order to be able to apply for higher education. Can you guess from the plot below what is the minimal amount of points that students need to get to pass the exam? Not surprisingly, the "gap" in otherwise normal distribution can be easily "filled in" if you take an appropriate fraction of the over-represented scores just above the censoring boundry. In case of survival analysis censoring occurs when we have some information about individual survival time, but we don’t know the survival time exactly (Kleinbaum and Klein, 2005, p. 5). For example, you treat patients with some drug and observe them until end your study, but you have no knowledge what happens to them after study finishes (were there any relapses or side effects?), the only thing that you know is that they "survived" at least until end of the study. Below you can find example of data generated from Weibull distribution modeled using Kaplan–Meier estimator. Blue curve marks model estimated on the full dataset, in the middle plot you can see censored sample and model estimated on censored data (red curve), on right you see truncated sample and model estimated on such sample (red curve). As you can see, missing data (truncation) has a significant impact on estimates, but censoring can be easily managed using standard survival analysis models. This does not mean that you cannot analyze truncated samples, but in such cases you have to use models for missing data that try to "guess" the unknown information. Kleinbaum, D.G. and Klein, M. (2005). Survival Analysis: A Self-Learning Text. Springer. Gelman, A., Carlin, J.B., Stern, H.S., and Rubin, D.B. (2005). Bayesian Data Analysis. Chapman & Hall/CRC.
Layman's explanation of censoring in survival analysis
Censoring is often described in comparison with truncation. Nice description of the two processes is provided by Gelman et al (2005, p. 235): Truncated data differs from censored data that no count o
Layman's explanation of censoring in survival analysis Censoring is often described in comparison with truncation. Nice description of the two processes is provided by Gelman et al (2005, p. 235): Truncated data differs from censored data that no count of observations beyond truncation point is available. With censoring the values of observations beyond the truncation point are lost, but their number is observed. Censoring or truncation can occur for values above some level (right-censoring), below some level (left-censoring), or both. Below you can find example of standard normal distribution that is censored at point $2.0$ (middle) or truncated at $2.0$ (right). If sample is truncated we have no data beyond the truncation point, with censored sample values above the truncation point are "rounded" to the boundary value, so they are over-represented in your sample. Intuitive example of censoring is that you ask your respondents about their age, but record it only up to some value and all the ages above this value, say 60 years, are recorded as "60+". This leads to having precise information for non-censored values and no information about censored values. Not so typical, real-life example of censoring was observed in Polish matura exam scores that caught pretty much attention on the internet. The exam is taken at the end of high school and students must pass it in order to be able to apply for higher education. Can you guess from the plot below what is the minimal amount of points that students need to get to pass the exam? Not surprisingly, the "gap" in otherwise normal distribution can be easily "filled in" if you take an appropriate fraction of the over-represented scores just above the censoring boundry. In case of survival analysis censoring occurs when we have some information about individual survival time, but we don’t know the survival time exactly (Kleinbaum and Klein, 2005, p. 5). For example, you treat patients with some drug and observe them until end your study, but you have no knowledge what happens to them after study finishes (were there any relapses or side effects?), the only thing that you know is that they "survived" at least until end of the study. Below you can find example of data generated from Weibull distribution modeled using Kaplan–Meier estimator. Blue curve marks model estimated on the full dataset, in the middle plot you can see censored sample and model estimated on censored data (red curve), on right you see truncated sample and model estimated on such sample (red curve). As you can see, missing data (truncation) has a significant impact on estimates, but censoring can be easily managed using standard survival analysis models. This does not mean that you cannot analyze truncated samples, but in such cases you have to use models for missing data that try to "guess" the unknown information. Kleinbaum, D.G. and Klein, M. (2005). Survival Analysis: A Self-Learning Text. Springer. Gelman, A., Carlin, J.B., Stern, H.S., and Rubin, D.B. (2005). Bayesian Data Analysis. Chapman & Hall/CRC.
Layman's explanation of censoring in survival analysis Censoring is often described in comparison with truncation. Nice description of the two processes is provided by Gelman et al (2005, p. 235): Truncated data differs from censored data that no count o
15,630
Layman's explanation of censoring in survival analysis
Censoring is central to survival analysis. The basic idea is that information is censored, it is invisible to you. Simply explained, a censored distribution of life times is obtained if you record the life times before everyone in the sample has died. If you think of time moving "rightwards" on the X-axis, this can be called right-censoring. There are also other types: left-censoring and window-censoring. See e.g. Allison's 1984 text on Event History Analysis, published by Sage for an instructive introduction. Example: If you are calculating divorce rates in population, you only want to include individuals who are at risk of divorcing (that is, they are married). If people end their marriage for reasons other than divorce (bereavement, annulment) then you want to censor them. They are no longer at risk of divorce. Your Kaplan-Meier estimates (and plots) should not include censored observations after the time point when they are censored, but should include them up until that time point.
Layman's explanation of censoring in survival analysis
Censoring is central to survival analysis. The basic idea is that information is censored, it is invisible to you. Simply explained, a censored distribution of life times is obtained if you record the
Layman's explanation of censoring in survival analysis Censoring is central to survival analysis. The basic idea is that information is censored, it is invisible to you. Simply explained, a censored distribution of life times is obtained if you record the life times before everyone in the sample has died. If you think of time moving "rightwards" on the X-axis, this can be called right-censoring. There are also other types: left-censoring and window-censoring. See e.g. Allison's 1984 text on Event History Analysis, published by Sage for an instructive introduction. Example: If you are calculating divorce rates in population, you only want to include individuals who are at risk of divorcing (that is, they are married). If people end their marriage for reasons other than divorce (bereavement, annulment) then you want to censor them. They are no longer at risk of divorce. Your Kaplan-Meier estimates (and plots) should not include censored observations after the time point when they are censored, but should include them up until that time point.
Layman's explanation of censoring in survival analysis Censoring is central to survival analysis. The basic idea is that information is censored, it is invisible to you. Simply explained, a censored distribution of life times is obtained if you record the
15,631
Confidence intervals vs. standard deviation
There are two things here : The "2 sigma rule" where sigma refers to standard deviation is a way to construct tolerance intervals for normally distributed data, not confidence intervals (see this link to learn about the difference). Said shortly, tolerance intervals refer to the distribution inside the population, whereas confidence intervals refer to a degree of certainty regarding an estimation. In case you meant standard error instead of standard deviation (which is what I understood at first), then the "2 sigma rule" gives a 95% confidence interval if your data are normally distributed (for example, if the conditions of the Central Limit Theorem apply and your sample size is great enough).
Confidence intervals vs. standard deviation
There are two things here : The "2 sigma rule" where sigma refers to standard deviation is a way to construct tolerance intervals for normally distributed data, not confidence intervals (see this lin
Confidence intervals vs. standard deviation There are two things here : The "2 sigma rule" where sigma refers to standard deviation is a way to construct tolerance intervals for normally distributed data, not confidence intervals (see this link to learn about the difference). Said shortly, tolerance intervals refer to the distribution inside the population, whereas confidence intervals refer to a degree of certainty regarding an estimation. In case you meant standard error instead of standard deviation (which is what I understood at first), then the "2 sigma rule" gives a 95% confidence interval if your data are normally distributed (for example, if the conditions of the Central Limit Theorem apply and your sample size is great enough).
Confidence intervals vs. standard deviation There are two things here : The "2 sigma rule" where sigma refers to standard deviation is a way to construct tolerance intervals for normally distributed data, not confidence intervals (see this lin
15,632
Confidence intervals vs. standard deviation
May be, it will be easier to explain, to avoid confusion. Standard deviation: With probability about 95% we will find every new sample in interval (x_mean - 2 * sigma; x_mean + 2 * sigma) what says us where to expect the location of new samples. Confidence interval: With probability of f.e. 95% the real x_mean value will be found in the interval (x_mean - x_ci; x_mean + x_ci) which shows us quality of the measurements. "x_ci" and "2 * sigma" are two different values, because of corresponding to two different expectations. x_ci = t * sigma / sqrt(n), where t is a multiplier according to the used theory.
Confidence intervals vs. standard deviation
May be, it will be easier to explain, to avoid confusion. Standard deviation: With probability about 95% we will find every new sample in interval (x_mean - 2 * sigma; x_mean + 2 * sigma) what says us
Confidence intervals vs. standard deviation May be, it will be easier to explain, to avoid confusion. Standard deviation: With probability about 95% we will find every new sample in interval (x_mean - 2 * sigma; x_mean + 2 * sigma) what says us where to expect the location of new samples. Confidence interval: With probability of f.e. 95% the real x_mean value will be found in the interval (x_mean - x_ci; x_mean + x_ci) which shows us quality of the measurements. "x_ci" and "2 * sigma" are two different values, because of corresponding to two different expectations. x_ci = t * sigma / sqrt(n), where t is a multiplier according to the used theory.
Confidence intervals vs. standard deviation May be, it will be easier to explain, to avoid confusion. Standard deviation: With probability about 95% we will find every new sample in interval (x_mean - 2 * sigma; x_mean + 2 * sigma) what says us
15,633
Confidence intervals vs. standard deviation
This equation relies on the assumption that the errors are Gaussian. Also, the factor of 2 in front of the SE(β1) term will vary slightly depending on the number of observations n in the linear regression. To be precise, rather than the number 2, the equation should contain the 97.5 % quantile of a t-distribution with n−2 degrees of freedom.
Confidence intervals vs. standard deviation
This equation relies on the assumption that the errors are Gaussian. Also, the factor of 2 in front of the SE(β1) term will vary slightly depending on the number of observations n in the linear regres
Confidence intervals vs. standard deviation This equation relies on the assumption that the errors are Gaussian. Also, the factor of 2 in front of the SE(β1) term will vary slightly depending on the number of observations n in the linear regression. To be precise, rather than the number 2, the equation should contain the 97.5 % quantile of a t-distribution with n−2 degrees of freedom.
Confidence intervals vs. standard deviation This equation relies on the assumption that the errors are Gaussian. Also, the factor of 2 in front of the SE(β1) term will vary slightly depending on the number of observations n in the linear regres
15,634
Why is optimizing a mixture of Gaussian directly computationally hard?
First, GMM is a particular algorithm for clustering, where you try to find the optimal labelling of your $n$ observations. Having $k$ possible classes, it means that there are $k^n$ possible labellings of your training data. This becomes already huge for moderate values of $k$ and $n$. Second, the functional you are trying to minimize is not convex, and together with the size of your problem, makes it very hard. I only know that k-means (GMM can be seen as a soft version of kmeans) is NP-hard. But I am not aware of whether it has been proved for GMM as well. To see that the problem is not convex, consider the one dimensional case: $$ L = \log \left(e^{-({x}/{\sigma_{1}})^2} + e^{-({x}/{\sigma_{2}})^2}\right) $$ and check that you cannot guarantee that $\frac{d^2L}{dx^2} > 0$ for all x. Having a non-convex problem means that you can get stuck in local minima. In general, you do not have the strong warranties you have in convex optimization, and searching for a solution is also much harder.
Why is optimizing a mixture of Gaussian directly computationally hard?
First, GMM is a particular algorithm for clustering, where you try to find the optimal labelling of your $n$ observations. Having $k$ possible classes, it means that there are $k^n$ possible labelling
Why is optimizing a mixture of Gaussian directly computationally hard? First, GMM is a particular algorithm for clustering, where you try to find the optimal labelling of your $n$ observations. Having $k$ possible classes, it means that there are $k^n$ possible labellings of your training data. This becomes already huge for moderate values of $k$ and $n$. Second, the functional you are trying to minimize is not convex, and together with the size of your problem, makes it very hard. I only know that k-means (GMM can be seen as a soft version of kmeans) is NP-hard. But I am not aware of whether it has been proved for GMM as well. To see that the problem is not convex, consider the one dimensional case: $$ L = \log \left(e^{-({x}/{\sigma_{1}})^2} + e^{-({x}/{\sigma_{2}})^2}\right) $$ and check that you cannot guarantee that $\frac{d^2L}{dx^2} > 0$ for all x. Having a non-convex problem means that you can get stuck in local minima. In general, you do not have the strong warranties you have in convex optimization, and searching for a solution is also much harder.
Why is optimizing a mixture of Gaussian directly computationally hard? First, GMM is a particular algorithm for clustering, where you try to find the optimal labelling of your $n$ observations. Having $k$ possible classes, it means that there are $k^n$ possible labelling
15,635
Why is optimizing a mixture of Gaussian directly computationally hard?
In addition to juampa's points, let me signal those difficulties: The function $l(\theta|S_n)$ is unbounded, so the true maximum is $+\infty$ and corresponds to $\hat\mu^{(i)}=x_1$ (for instance) and $\hat\sigma_i=0$. A true maximiser should therefore end up with this solution, which is not useful for estimation purposes. Even without considering the $k^n$ terms in the decomposition of the product of sums as a sum of products in $l(\theta|S_n)$, the function to be maximised in $\theta$ is highly multi-modal (in addition to being non-convex) hence a challenge for numerical methods. EM acknowledges the difficulty by converging to a local mode or saddle point and requiring multiple runs. As shown on taken from my book. An additional remark: without calling the EM algorithm, one may use a standard optimisation algorithm (like Newton-Raphson) one parameter at a time, that is, iterate find $\theta_1^\prime=\arg\max_{\theta_1} l(\theta|S_n)$ find $\theta_2^\prime=\arg\max_{\theta_2} l(\theta_1^\prime,\theta_{-1}|S_n)$ ... find $\theta_v^\prime=\arg\max_{\theta_v} l(\theta_{-v}^\prime,\theta_v|S_n)$ if there are $v$ parameters and each step should increase the value of the target function $l(\theta|S_n)$, but this scheme will at best end up in the same mode as the EM algorithm.
Why is optimizing a mixture of Gaussian directly computationally hard?
In addition to juampa's points, let me signal those difficulties: The function $l(\theta|S_n)$ is unbounded, so the true maximum is $+\infty$ and corresponds to $\hat\mu^{(i)}=x_1$ (for instance) and
Why is optimizing a mixture of Gaussian directly computationally hard? In addition to juampa's points, let me signal those difficulties: The function $l(\theta|S_n)$ is unbounded, so the true maximum is $+\infty$ and corresponds to $\hat\mu^{(i)}=x_1$ (for instance) and $\hat\sigma_i=0$. A true maximiser should therefore end up with this solution, which is not useful for estimation purposes. Even without considering the $k^n$ terms in the decomposition of the product of sums as a sum of products in $l(\theta|S_n)$, the function to be maximised in $\theta$ is highly multi-modal (in addition to being non-convex) hence a challenge for numerical methods. EM acknowledges the difficulty by converging to a local mode or saddle point and requiring multiple runs. As shown on taken from my book. An additional remark: without calling the EM algorithm, one may use a standard optimisation algorithm (like Newton-Raphson) one parameter at a time, that is, iterate find $\theta_1^\prime=\arg\max_{\theta_1} l(\theta|S_n)$ find $\theta_2^\prime=\arg\max_{\theta_2} l(\theta_1^\prime,\theta_{-1}|S_n)$ ... find $\theta_v^\prime=\arg\max_{\theta_v} l(\theta_{-v}^\prime,\theta_v|S_n)$ if there are $v$ parameters and each step should increase the value of the target function $l(\theta|S_n)$, but this scheme will at best end up in the same mode as the EM algorithm.
Why is optimizing a mixture of Gaussian directly computationally hard? In addition to juampa's points, let me signal those difficulties: The function $l(\theta|S_n)$ is unbounded, so the true maximum is $+\infty$ and corresponds to $\hat\mu^{(i)}=x_1$ (for instance) and
15,636
Check memoryless property of a Markov chain
I wonder if the following would give a valid Pearson $\chi^2$ test for proportions as follows. Estimate the one-step transition probabilities -- you've done that. Obtain the two-step model probabilities: $$ \hat p_{U,V} = {\rm Prob}[X_{i+2}=U|X_i=V] = \sum_{W\in\{A,B,C,D\}} {\rm Prob}[X_{i+2}=U|X_{i+1}=W]{\rm Prob}[X_{i+1}=W|X_i=V] $$ Obtain the two-step empirical probabilities $$\tilde p_{U,V} = \frac{\sum_i \# X_i = V, X_{i+2} = U}{\sum_i \# X_i = V}$$ Form Pearson test statistic $$T_V = \# \{X_i = V\} \sum_U \frac{(\hat p_{U,V} - \tilde p_{U,V})^2}{\hat p_{U,V}}, \quad T=T_A + T_B + T_C + T_D$$ It is tempting for me to think that each $T_U \sim \chi^2_3$, so that the total $T\sim \chi^2_{12}$. However, I am not entirely sure of that, and would appreciate your thoughts on this. I am not likewise not co sertain about whether one needs to be paranoid about independence, and would want to split the sample in halves to estimate $\hat p$ and $\bar p$.
Check memoryless property of a Markov chain
I wonder if the following would give a valid Pearson $\chi^2$ test for proportions as follows. Estimate the one-step transition probabilities -- you've done that. Obtain the two-step model probabilit
Check memoryless property of a Markov chain I wonder if the following would give a valid Pearson $\chi^2$ test for proportions as follows. Estimate the one-step transition probabilities -- you've done that. Obtain the two-step model probabilities: $$ \hat p_{U,V} = {\rm Prob}[X_{i+2}=U|X_i=V] = \sum_{W\in\{A,B,C,D\}} {\rm Prob}[X_{i+2}=U|X_{i+1}=W]{\rm Prob}[X_{i+1}=W|X_i=V] $$ Obtain the two-step empirical probabilities $$\tilde p_{U,V} = \frac{\sum_i \# X_i = V, X_{i+2} = U}{\sum_i \# X_i = V}$$ Form Pearson test statistic $$T_V = \# \{X_i = V\} \sum_U \frac{(\hat p_{U,V} - \tilde p_{U,V})^2}{\hat p_{U,V}}, \quad T=T_A + T_B + T_C + T_D$$ It is tempting for me to think that each $T_U \sim \chi^2_3$, so that the total $T\sim \chi^2_{12}$. However, I am not entirely sure of that, and would appreciate your thoughts on this. I am not likewise not co sertain about whether one needs to be paranoid about independence, and would want to split the sample in halves to estimate $\hat p$ and $\bar p$.
Check memoryless property of a Markov chain I wonder if the following would give a valid Pearson $\chi^2$ test for proportions as follows. Estimate the one-step transition probabilities -- you've done that. Obtain the two-step model probabilit
15,637
Check memoryless property of a Markov chain
Markov property might be hard to test directly. But it might be enough to fit a model which assumes Markov property and then test whether the model holds. It may turn out that the fitted model is a good approximation which is useful for you in practice, and you need not to be concerned whether Markov property really holds or not. The parallel can be drawn to the linear regression. The usual practice is not to test whether linearity holds, but whether linear model is a useful approximation.
Check memoryless property of a Markov chain
Markov property might be hard to test directly. But it might be enough to fit a model which assumes Markov property and then test whether the model holds. It may turn out that the fitted model is a go
Check memoryless property of a Markov chain Markov property might be hard to test directly. But it might be enough to fit a model which assumes Markov property and then test whether the model holds. It may turn out that the fitted model is a good approximation which is useful for you in practice, and you need not to be concerned whether Markov property really holds or not. The parallel can be drawn to the linear regression. The usual practice is not to test whether linearity holds, but whether linear model is a useful approximation.
Check memoryless property of a Markov chain Markov property might be hard to test directly. But it might be enough to fit a model which assumes Markov property and then test whether the model holds. It may turn out that the fitted model is a go
15,638
Check memoryless property of a Markov chain
To concretize the suggestion of the previous reply, you first want to estimate the Markov probabilities - assuming it's Markov. See the reply here Estimating Markov Chain Probabilities You should get a 4 x 4 matrix based on the proportion of transitions from state A to A, A to B, etc. Call this matrix $M$. $M^2$ should then be the two-step transition matrix: A to A in 2 steps, and so on. You can then test if your observed 2 step transition matrix is similar to $M^2$. Since you have a lot of data for the number of states, you could estimate $M$ from one half of the data and test $M^2$ using the other half - you are testing observed frequencies against theoretical probabilities of a multinomial. That should give you an idea of how far off you are. Another possibility would be to see if the basic state proportions: proportion time spent in A, time spent in B, matches the eigenvector of the unit eigenvalue of M. If your series has reached some sort of steady state, the proportion of time in each state should tend to that limit.
Check memoryless property of a Markov chain
To concretize the suggestion of the previous reply, you first want to estimate the Markov probabilities - assuming it's Markov. See the reply here Estimating Markov Chain Probabilities You should get
Check memoryless property of a Markov chain To concretize the suggestion of the previous reply, you first want to estimate the Markov probabilities - assuming it's Markov. See the reply here Estimating Markov Chain Probabilities You should get a 4 x 4 matrix based on the proportion of transitions from state A to A, A to B, etc. Call this matrix $M$. $M^2$ should then be the two-step transition matrix: A to A in 2 steps, and so on. You can then test if your observed 2 step transition matrix is similar to $M^2$. Since you have a lot of data for the number of states, you could estimate $M$ from one half of the data and test $M^2$ using the other half - you are testing observed frequencies against theoretical probabilities of a multinomial. That should give you an idea of how far off you are. Another possibility would be to see if the basic state proportions: proportion time spent in A, time spent in B, matches the eigenvector of the unit eigenvalue of M. If your series has reached some sort of steady state, the proportion of time in each state should tend to that limit.
Check memoryless property of a Markov chain To concretize the suggestion of the previous reply, you first want to estimate the Markov probabilities - assuming it's Markov. See the reply here Estimating Markov Chain Probabilities You should get
15,639
Check memoryless property of a Markov chain
Beyond Markov Property (MP), a further property is Time Homogeneity (TH): $X_t$ can be Markov but with its transition matrix $\mathbf{P}(t)$ depending on time $t$. E.g., it may depend on the weekday at $t$ if observations are daily, and then a dependence $X_t$ on $X_{t-7}$ conditional on $X_{t-1}$ may be diagnosed if TH is unduly assumed. Assuming TH holds, a possible check for MP is testing that $X_t$ is independent from $X_{t-2}$ conditional on $X_{t-1}$, as Michael Chernick and StasK suggested. This can be done by using a test for contingency table. We can build the $n$ contingency tables of $X_t$ and $X_{t-2}$ conditional on $\{X_{t-1} = x_j\}$ for the $n$ possible values $x_j$, and test for independence. This can also be done using $X_{t-\ell}$ with $\ell > 1$ in place of $X_{t-2}$. In R, contingency tables or arrays are easily produced thanks to the factor facility and the functions apply, sweep. The idea above can also be exploited graphically. Packages ggplot2 or lattice easily provide conditional plots to compare conditional distributions $p(X_t \vert X_{t-1}=x_j, X_{t-2} = x_i)$. For instance setting $i$ as row index and $j$ as column index in trellis should under MP lead to similar distributions within a column. The chap. 5 of the book The statistical analysis of stochastic processes in time by J.K Lindsey contains other ideas for checking assumptions. [## simulates a MC with transition matrix in 'trans', starting from 'ini' simMC <- function(trans, ini = 1, N) { X <- rep(NA, N) Pcum <- t(apply(trans, 1, cumsum)) X[1] <- ini for (t in 2:N) { U <- runif(1) X[t] <- findInterval(U, Pcum[X[t-1], ]) + 1 } X } set.seed(1234) ## transition matrix P <- matrix(c(0.1, 0.1, 0.1, 0.7, 0.1, 0.1, 0.6, 0.2, 0.1, 0.3, 0.2, 0.4, 0.2, 0.2, 0.3, 0.3), nrow = 4, ncol = 4, byrow = TRUE) N <- 2000 X <- simMC(trans = P, ini = 1, N = N) ## it is better to work with factors X <- as.factor(X) levels(X) <- LETTERS[1:4] ## table transitions and normalize each row Phat <- table(X[1:(N-1)], X[2:N]) Phat <- sweep(x = Phat, MARGIN = 1, STATS = apply(Phat, 1, sum), FUN = "/") ## explicit dimnames dimnames(Phat) <- lapply(list("X(t-1)=" ,"X(t)="), paste, sep = "", levels(as.factor(X))) ## transition 3-fold contingency array P3 <- table(X[1:(N-2)], X[2:(N-1)], X[3:N]) dimnames(P3) <- lapply(list("X(t-2)=", "X(t-1)=" ,"X(t)="), paste, sep = "", levels(as.factor(X))) ## apply ONE indendence test fisher.test(P3[ , 1, ], simulate.p.value = TRUE) ## plot conditional distr. library(lattice) X3 <- data.frame(X = X[3:N], lag1X = X[2:(N-1)], lag2X = X[1:(N-2)]) histogram( ~ X | lag1X + lag2X, data = X3, col = "SteelBlue3") ]
Check memoryless property of a Markov chain
Beyond Markov Property (MP), a further property is Time Homogeneity (TH): $X_t$ can be Markov but with its transition matrix $\mathbf{P}(t)$ depending on time $t$. E.g., it may depend on the weekday a
Check memoryless property of a Markov chain Beyond Markov Property (MP), a further property is Time Homogeneity (TH): $X_t$ can be Markov but with its transition matrix $\mathbf{P}(t)$ depending on time $t$. E.g., it may depend on the weekday at $t$ if observations are daily, and then a dependence $X_t$ on $X_{t-7}$ conditional on $X_{t-1}$ may be diagnosed if TH is unduly assumed. Assuming TH holds, a possible check for MP is testing that $X_t$ is independent from $X_{t-2}$ conditional on $X_{t-1}$, as Michael Chernick and StasK suggested. This can be done by using a test for contingency table. We can build the $n$ contingency tables of $X_t$ and $X_{t-2}$ conditional on $\{X_{t-1} = x_j\}$ for the $n$ possible values $x_j$, and test for independence. This can also be done using $X_{t-\ell}$ with $\ell > 1$ in place of $X_{t-2}$. In R, contingency tables or arrays are easily produced thanks to the factor facility and the functions apply, sweep. The idea above can also be exploited graphically. Packages ggplot2 or lattice easily provide conditional plots to compare conditional distributions $p(X_t \vert X_{t-1}=x_j, X_{t-2} = x_i)$. For instance setting $i$ as row index and $j$ as column index in trellis should under MP lead to similar distributions within a column. The chap. 5 of the book The statistical analysis of stochastic processes in time by J.K Lindsey contains other ideas for checking assumptions. [## simulates a MC with transition matrix in 'trans', starting from 'ini' simMC <- function(trans, ini = 1, N) { X <- rep(NA, N) Pcum <- t(apply(trans, 1, cumsum)) X[1] <- ini for (t in 2:N) { U <- runif(1) X[t] <- findInterval(U, Pcum[X[t-1], ]) + 1 } X } set.seed(1234) ## transition matrix P <- matrix(c(0.1, 0.1, 0.1, 0.7, 0.1, 0.1, 0.6, 0.2, 0.1, 0.3, 0.2, 0.4, 0.2, 0.2, 0.3, 0.3), nrow = 4, ncol = 4, byrow = TRUE) N <- 2000 X <- simMC(trans = P, ini = 1, N = N) ## it is better to work with factors X <- as.factor(X) levels(X) <- LETTERS[1:4] ## table transitions and normalize each row Phat <- table(X[1:(N-1)], X[2:N]) Phat <- sweep(x = Phat, MARGIN = 1, STATS = apply(Phat, 1, sum), FUN = "/") ## explicit dimnames dimnames(Phat) <- lapply(list("X(t-1)=" ,"X(t)="), paste, sep = "", levels(as.factor(X))) ## transition 3-fold contingency array P3 <- table(X[1:(N-2)], X[2:(N-1)], X[3:N]) dimnames(P3) <- lapply(list("X(t-2)=", "X(t-1)=" ,"X(t)="), paste, sep = "", levels(as.factor(X))) ## apply ONE indendence test fisher.test(P3[ , 1, ], simulate.p.value = TRUE) ## plot conditional distr. library(lattice) X3 <- data.frame(X = X[3:N], lag1X = X[2:(N-1)], lag2X = X[1:(N-2)]) histogram( ~ X | lag1X + lag2X, data = X3, col = "SteelBlue3") ]
Check memoryless property of a Markov chain Beyond Markov Property (MP), a further property is Time Homogeneity (TH): $X_t$ can be Markov but with its transition matrix $\mathbf{P}(t)$ depending on time $t$. E.g., it may depend on the weekday a
15,640
Check memoryless property of a Markov chain
I think placida and mpiktas have both given very thoughtful and excellent approaches. I am answering because I just want to add that one could construct a test to see if $P(X_i=x|X_{i-1}=y)$ is different from $P(X_i=x|X_{i-1}=y \text{ and } X_{i-2}=z)$. I would pick values for $x$, $y$ and $z$ for which there are a large number of cases where the transition from $z$ to $y$ to $x$ occurs. Compute sample estimates for both probabilities. Then test for difference in proportions. The difficult aspect of this is to get the variances of the two estimates under the null hypothesis that say the proportions are equal and the chain is stationary and Markov. In that case under the null hypothesis if we just look at all 2 stage transitions and compare them to their corresponding three stage transitions but only include outcomes where these sets of paired outcomes are separate by at least 2 time points then the sequence of joint outcomes where success is defined as a $z$ to $y$ to $x$ transition and all other two stage transitions to $x$ as failures represent a set of independent Bernoulli trials under the null hypothesis. The same would work for defining all $y$ to $x$ transitions as successes and other one stage transitions to $x$ as failures. Then the test statistic would be the difference between these estimated proportions. The complication to the standard comparison of the Bernoulli sequences is that they are correlated. But you could do a bootstrap test of binomial proportions in this case. The other possibility is to construct a two by two table of the two stage and three stage paired outcomes where $0$ is failure and $1$ is success and the cell frequencies are counts for the pairs $(0,0)$, $(0,1)$, $(1,0)$ and $(1,1)$ where the first component is the two stage outcome and the second is the corresponding three stage outcome. You can then apply McNemar's test to the table.
Check memoryless property of a Markov chain
I think placida and mpiktas have both given very thoughtful and excellent approaches. I am answering because I just want to add that one could construct a test to see if $P(X_i=x|X_{i-1}=y)$ is differ
Check memoryless property of a Markov chain I think placida and mpiktas have both given very thoughtful and excellent approaches. I am answering because I just want to add that one could construct a test to see if $P(X_i=x|X_{i-1}=y)$ is different from $P(X_i=x|X_{i-1}=y \text{ and } X_{i-2}=z)$. I would pick values for $x$, $y$ and $z$ for which there are a large number of cases where the transition from $z$ to $y$ to $x$ occurs. Compute sample estimates for both probabilities. Then test for difference in proportions. The difficult aspect of this is to get the variances of the two estimates under the null hypothesis that say the proportions are equal and the chain is stationary and Markov. In that case under the null hypothesis if we just look at all 2 stage transitions and compare them to their corresponding three stage transitions but only include outcomes where these sets of paired outcomes are separate by at least 2 time points then the sequence of joint outcomes where success is defined as a $z$ to $y$ to $x$ transition and all other two stage transitions to $x$ as failures represent a set of independent Bernoulli trials under the null hypothesis. The same would work for defining all $y$ to $x$ transitions as successes and other one stage transitions to $x$ as failures. Then the test statistic would be the difference between these estimated proportions. The complication to the standard comparison of the Bernoulli sequences is that they are correlated. But you could do a bootstrap test of binomial proportions in this case. The other possibility is to construct a two by two table of the two stage and three stage paired outcomes where $0$ is failure and $1$ is success and the cell frequencies are counts for the pairs $(0,0)$, $(0,1)$, $(1,0)$ and $(1,1)$ where the first component is the two stage outcome and the second is the corresponding three stage outcome. You can then apply McNemar's test to the table.
Check memoryless property of a Markov chain I think placida and mpiktas have both given very thoughtful and excellent approaches. I am answering because I just want to add that one could construct a test to see if $P(X_i=x|X_{i-1}=y)$ is differ
15,641
Check memoryless property of a Markov chain
You could bin the data into evenly spaced intervals, then compute the unbiased sample variances of subsets $\{X_{n+1}:X_n=x_1,X_{n-k}=x_2\}$. By the law of total variance, $$\mathrm{Var}[E(X_{n+1}|X_n,X_{n-k})|X_n] = \mathrm{Var}[X_{n+1}|X_n]-E(\mathrm{Var}[X_{n+1}|X_n])$$ The LHS, if it is almost zero, provides evidence that the transition probabilities do not depend on $X_{n-k}$, though it is clearly a weaker statement: e.g., let $X_{n+1}\sim N(X_n,X_{n-1})$. Taking the expected value of both sides of the above equation, the RHS can be computed from the sample variances (i.e., replacing expected values with averages). If the expected value of the variance is zero then the variance is 0 almost always.
Check memoryless property of a Markov chain
You could bin the data into evenly spaced intervals, then compute the unbiased sample variances of subsets $\{X_{n+1}:X_n=x_1,X_{n-k}=x_2\}$. By the law of total variance, $$\mathrm{Var}[E(X_{n+1}|X_n
Check memoryless property of a Markov chain You could bin the data into evenly spaced intervals, then compute the unbiased sample variances of subsets $\{X_{n+1}:X_n=x_1,X_{n-k}=x_2\}$. By the law of total variance, $$\mathrm{Var}[E(X_{n+1}|X_n,X_{n-k})|X_n] = \mathrm{Var}[X_{n+1}|X_n]-E(\mathrm{Var}[X_{n+1}|X_n])$$ The LHS, if it is almost zero, provides evidence that the transition probabilities do not depend on $X_{n-k}$, though it is clearly a weaker statement: e.g., let $X_{n+1}\sim N(X_n,X_{n-1})$. Taking the expected value of both sides of the above equation, the RHS can be computed from the sample variances (i.e., replacing expected values with averages). If the expected value of the variance is zero then the variance is 0 almost always.
Check memoryless property of a Markov chain You could bin the data into evenly spaced intervals, then compute the unbiased sample variances of subsets $\{X_{n+1}:X_n=x_1,X_{n-k}=x_2\}$. By the law of total variance, $$\mathrm{Var}[E(X_{n+1}|X_n
15,642
How to minimize residual sum of squares of an exponential fit?
A (negative) exponential law takes the form $y=-\exp(-x)$. When you allow for changes of units in the $x$ and $y$ values, though, say to $y = \alpha y' + \beta$ and $x = \gamma x' + \delta$, then the law will be expressed as $$\alpha y' + \beta = y = -\exp(-x) = -\exp(-\gamma x' - \delta),$$ which algebraically is equivalent to $$y' = \frac{-1}{\alpha} \exp(-\gamma x' - \delta) - \beta = a\left(1 - u\exp(-b x')\right)$$ using three parameters $a = -\beta/\alpha$, $u = 1/(\beta\exp(\delta))$, and $b = \gamma$. We can recognize $a$ as a scale parameter for $y$, $b$ as a scale parameter for $x$, and $u$ as deriving from a location parameter for $x$. As a rule of thumb, these parameters can be identified at a glance from the plot: The parameter $a$ is the value of the horizontal asymptote, a little less than $2000$. The parameter $u$ is the relative amount the curve rises from the origin to its horizontal asymptote. Here, the the rise therefore is a little less than $2000 - 937$; relatively, that's about $0.55$ of the asymptote. Because $\exp(-3) \approx 0.05$, when $x$ equals three times the value of $1/b$ the curve should have risen to about $1-0.05$ or $95\%$ of its total. $95\%$ of the rise from $937$ to almost $2000$ places us around $1950$; scanning across the plot indicates this took $20$ to $25$ days. Let's call it $24$ for simplicity, whence $b \approx 3/24 = 0.125$. (This $95\%$ method to eyeball an exponential scale is standard in some fields that use exponential plots a lot.) Let's see what this looks like: plot(Days, Emissions) curve((y = 2000 * (1 - 0.56 * exp(-0.125*x))), add = T) Not bad for a start! (Even despite typing 0.56 in place of 0.55, which was a crude approximation anyway.) We can polish it with nls: fit <- nls(Emissions ~ a * (1- u * exp(-b*Days)), start=list(a=2000, b=1/8, u=0.55)) beta <- coefficients(fit) plot(Days, Emissions) curve((y = beta["a"] * (1 - beta["u"] * exp(-beta["b"]*x))), add = T, col="Green", lwd=2) The output of nls contains extensive information about parameter uncertainty. E.g., a simple summary provides standard errors of estimates: > summary(fit) Parameters: Estimate Std. Error t value Pr(>|t|) a 1.969e+03 1.317e+01 149.51 2.54e-10 *** b 1.603e-01 1.022e-02 15.69 1.91e-05 *** u 6.091e-01 1.613e-02 37.75 2.46e-07 *** We can read and work with the entire covariance matrix of the estimates, which is useful for estimating simultaneous confidence intervals (at least for large datasets): > vcov(fit) a b u a 173.38613624 -8.720531e-02 -2.602935e-02 b -0.08720531 1.044004e-04 9.442374e-05 u -0.02602935 9.442374e-05 2.603217e-04 nls supports profile plots for the parameters, giving more detailed information about their uncertainty: > plot(profile(fit)) Here is one of the three output plots showing variation in $a$: E.g., a t-value of $2$ corresponds roughly to a 95% two-sided confidence interval; this plot places its endpoints around $1945$ and $1995$.
How to minimize residual sum of squares of an exponential fit?
A (negative) exponential law takes the form $y=-\exp(-x)$. When you allow for changes of units in the $x$ and $y$ values, though, say to $y = \alpha y' + \beta$ and $x = \gamma x' + \delta$, then the
How to minimize residual sum of squares of an exponential fit? A (negative) exponential law takes the form $y=-\exp(-x)$. When you allow for changes of units in the $x$ and $y$ values, though, say to $y = \alpha y' + \beta$ and $x = \gamma x' + \delta$, then the law will be expressed as $$\alpha y' + \beta = y = -\exp(-x) = -\exp(-\gamma x' - \delta),$$ which algebraically is equivalent to $$y' = \frac{-1}{\alpha} \exp(-\gamma x' - \delta) - \beta = a\left(1 - u\exp(-b x')\right)$$ using three parameters $a = -\beta/\alpha$, $u = 1/(\beta\exp(\delta))$, and $b = \gamma$. We can recognize $a$ as a scale parameter for $y$, $b$ as a scale parameter for $x$, and $u$ as deriving from a location parameter for $x$. As a rule of thumb, these parameters can be identified at a glance from the plot: The parameter $a$ is the value of the horizontal asymptote, a little less than $2000$. The parameter $u$ is the relative amount the curve rises from the origin to its horizontal asymptote. Here, the the rise therefore is a little less than $2000 - 937$; relatively, that's about $0.55$ of the asymptote. Because $\exp(-3) \approx 0.05$, when $x$ equals three times the value of $1/b$ the curve should have risen to about $1-0.05$ or $95\%$ of its total. $95\%$ of the rise from $937$ to almost $2000$ places us around $1950$; scanning across the plot indicates this took $20$ to $25$ days. Let's call it $24$ for simplicity, whence $b \approx 3/24 = 0.125$. (This $95\%$ method to eyeball an exponential scale is standard in some fields that use exponential plots a lot.) Let's see what this looks like: plot(Days, Emissions) curve((y = 2000 * (1 - 0.56 * exp(-0.125*x))), add = T) Not bad for a start! (Even despite typing 0.56 in place of 0.55, which was a crude approximation anyway.) We can polish it with nls: fit <- nls(Emissions ~ a * (1- u * exp(-b*Days)), start=list(a=2000, b=1/8, u=0.55)) beta <- coefficients(fit) plot(Days, Emissions) curve((y = beta["a"] * (1 - beta["u"] * exp(-beta["b"]*x))), add = T, col="Green", lwd=2) The output of nls contains extensive information about parameter uncertainty. E.g., a simple summary provides standard errors of estimates: > summary(fit) Parameters: Estimate Std. Error t value Pr(>|t|) a 1.969e+03 1.317e+01 149.51 2.54e-10 *** b 1.603e-01 1.022e-02 15.69 1.91e-05 *** u 6.091e-01 1.613e-02 37.75 2.46e-07 *** We can read and work with the entire covariance matrix of the estimates, which is useful for estimating simultaneous confidence intervals (at least for large datasets): > vcov(fit) a b u a 173.38613624 -8.720531e-02 -2.602935e-02 b -0.08720531 1.044004e-04 9.442374e-05 u -0.02602935 9.442374e-05 2.603217e-04 nls supports profile plots for the parameters, giving more detailed information about their uncertainty: > plot(profile(fit)) Here is one of the three output plots showing variation in $a$: E.g., a t-value of $2$ corresponds roughly to a 95% two-sided confidence interval; this plot places its endpoints around $1945$ and $1995$.
How to minimize residual sum of squares of an exponential fit? A (negative) exponential law takes the form $y=-\exp(-x)$. When you allow for changes of units in the $x$ and $y$ values, though, say to $y = \alpha y' + \beta$ and $x = \gamma x' + \delta$, then the
15,643
Best way to perform multiclass SVM
There are a lot of methods for multi-class classification. Two classic options, which are not SVM-specific are: One-vs-all (OVA) classification: Suppose you have classes A, B, C, and D. Instead of doing a four way classification, train up four binary classifiers: A vs. not-A, B vs. not-B, C vs. not-C, and D vs. not-D. Then, pick either the positive class that's "best" (e.g., furtherest from the margin across all four runs). If none of the classifications are positive (i.e., they're all not-X), pick the "opposite" of class that's worst (e.g., closest to the margin). All-vs-All: Train all possible pairs of classifications. Rank the classes by some factor (e.g., # of times selected), and pick the best. Which works best has been contentious: Duan and Keerthi have an empirical study that suggests a specific all-vs-all method, while Rifkin and Klautau argue for a one-vs-all scheme. There are even schemes where one learns error-correcting codes describing the class labels, instead of the labels themselves. Good luck! Edit: What you really want, particularly for OVA, is the posterior probability of each class. For some methods, like Naive Bayes, that's trivial to get out. SVMs typically don't give you probabilities, but there are ways to compute them. See John Platt's 1999 paper "Probabilistic Outputs for Support Vector Machines..."
Best way to perform multiclass SVM
There are a lot of methods for multi-class classification. Two classic options, which are not SVM-specific are: One-vs-all (OVA) classification: Suppose you have classes A, B, C, and D. Instead of do
Best way to perform multiclass SVM There are a lot of methods for multi-class classification. Two classic options, which are not SVM-specific are: One-vs-all (OVA) classification: Suppose you have classes A, B, C, and D. Instead of doing a four way classification, train up four binary classifiers: A vs. not-A, B vs. not-B, C vs. not-C, and D vs. not-D. Then, pick either the positive class that's "best" (e.g., furtherest from the margin across all four runs). If none of the classifications are positive (i.e., they're all not-X), pick the "opposite" of class that's worst (e.g., closest to the margin). All-vs-All: Train all possible pairs of classifications. Rank the classes by some factor (e.g., # of times selected), and pick the best. Which works best has been contentious: Duan and Keerthi have an empirical study that suggests a specific all-vs-all method, while Rifkin and Klautau argue for a one-vs-all scheme. There are even schemes where one learns error-correcting codes describing the class labels, instead of the labels themselves. Good luck! Edit: What you really want, particularly for OVA, is the posterior probability of each class. For some methods, like Naive Bayes, that's trivial to get out. SVMs typically don't give you probabilities, but there are ways to compute them. See John Platt's 1999 paper "Probabilistic Outputs for Support Vector Machines..."
Best way to perform multiclass SVM There are a lot of methods for multi-class classification. Two classic options, which are not SVM-specific are: One-vs-all (OVA) classification: Suppose you have classes A, B, C, and D. Instead of do
15,644
Best way to perform multiclass SVM
Let me add that there is work on extending SVMs to multiple classes (as opposed to the methods Matt Krause describes that are decomposition into several binary classification tasks). One important work is: On the Algorithmic Implementation of Multiclass Kernel-based Vector Machine
Best way to perform multiclass SVM
Let me add that there is work on extending SVMs to multiple classes (as opposed to the methods Matt Krause describes that are decomposition into several binary classification tasks). One important wor
Best way to perform multiclass SVM Let me add that there is work on extending SVMs to multiple classes (as opposed to the methods Matt Krause describes that are decomposition into several binary classification tasks). One important work is: On the Algorithmic Implementation of Multiclass Kernel-based Vector Machine
Best way to perform multiclass SVM Let me add that there is work on extending SVMs to multiple classes (as opposed to the methods Matt Krause describes that are decomposition into several binary classification tasks). One important wor
15,645
Name of mean absolute error analogue to Brier score?
Answer seems to be: no, because MAE doesn't lead to a proper scoring rule. See Loss Functions for Binary Class Probability Estimation and Classification: Structure and Applications where the MAE is discussed under "Counterexamples of proper scoring rules".
Name of mean absolute error analogue to Brier score?
Answer seems to be: no, because MAE doesn't lead to a proper scoring rule. See Loss Functions for Binary Class Probability Estimation and Classification: Structure and Applications where the MAE is di
Name of mean absolute error analogue to Brier score? Answer seems to be: no, because MAE doesn't lead to a proper scoring rule. See Loss Functions for Binary Class Probability Estimation and Classification: Structure and Applications where the MAE is discussed under "Counterexamples of proper scoring rules".
Name of mean absolute error analogue to Brier score? Answer seems to be: no, because MAE doesn't lead to a proper scoring rule. See Loss Functions for Binary Class Probability Estimation and Classification: Structure and Applications where the MAE is di
15,646
Plotting sparklines in R
I initially managed to produce something approaching your original picture with some quick and dirty R code (see this gist), until I discovered that the sparkTable package should do this very much better, provided you are willing to use $\LaTeX$. (In the meantime, it has also been pointed out by @Bernd!) Here is an example, from help(sparkEPS): It should not be too difficult to arrange this the way you want.
Plotting sparklines in R
I initially managed to produce something approaching your original picture with some quick and dirty R code (see this gist), until I discovered that the sparkTable package should do this very much bet
Plotting sparklines in R I initially managed to produce something approaching your original picture with some quick and dirty R code (see this gist), until I discovered that the sparkTable package should do this very much better, provided you are willing to use $\LaTeX$. (In the meantime, it has also been pointed out by @Bernd!) Here is an example, from help(sparkEPS): It should not be too difficult to arrange this the way you want.
Plotting sparklines in R I initially managed to produce something approaching your original picture with some quick and dirty R code (see this gist), until I discovered that the sparkTable package should do this very much bet
15,647
Fitting an Orthogonal Grid to Noisy Points
Because the streets are on an irregular orthogonal grid, the Fourier Transform solutions--although clever--will likely fail. The following approach exploits two ideas: Using the Hough transform to identify sets of points that tend to line up. Exploiting the assumed orthogonality of the grid to augment the data. The link explains and illustrates the Hough transform and the Mathematica code I am using. Here is the gist of it, as extracted from the second paragraph: ... the Hough transform depicts sets of lines. A line in the plane can be parameterized by its slope, $x,$ and its distance, $y,$ from a fixed origin. A point in this $x,y$ coordinate system thereby designates a single line. Each point in the original plot determines a pencil of lines passing through that point: this pencil appears as a curve in the Hough transform. When features in the original plot fall along a common line, or near enough to one, then the collections of curves they produce in the Hough transform tend to have a common intersection corresponding to that common line. By finding these points of greatest intensity in the Hough transform, we can read off good solutions to the original problem. Please refer to the rest of that post for further explanation and code. Here, I'll simply take you through the workflow with your example (the dots in the left image). Import the image and crop it. img = Import["https://i.stack.imgur.com/uAjLw.jpg"] i = ColorNegate[Binarize[img]]; crop2 = ImageCrop[ImageTake[i, {25, 700}, {1, 1050}], 940]; Combine the image with its 90 degree rotation. (Optionally, combine it with all three rotations at 90, 180, and 270 degrees.) I also downsample it for speed and because coarsening the resolution is a crude kind of windowed smooth that helps identify points that line up. Various forms of additional smoothing will appear further below without comment. The amount of smoothing is a matter of trial and error but good results are quickly found. crop3 = ImageResize[crop2, 80]; (* crop3 = ImageAdd[crop3, ImageRotate[crop3]]; *) crop3=ImageAdd[crop3, ImageRotate[crop3, \[Pi]]] Notice how much more clearly the orthogonal geometry of the street intersections comes through in this combined image. [Edit: I made a mistake here. The commented-out line performs the 90 degree rotation; the final line rotates by 180 degrees. I intended to comment out the last line only. The result of this error is to produce an inferior solution--the one shown below--but it still illustrates the ideas, so I have left the figures as is.] Compute the Hough transform. hough2 = Radon[crop3, Method -> "Hough"] // ImageAdjust Smooth the Hough transform to help detect peaks. blur = ImageAdjust[Blur[ImageAdjust[hough2, {1, 0}], 5]] Identify the "morphological components" (isolated high points). comp = MorphologicalComponents[blur, 0.85] // Colorize Find the angles associated with component centroids. width = ImageDimensions[blur][[1]]; slopes = Module[{x, y, z}, ComponentMeasurements[comp, "Centroid"] /. Rule[x_, {y_, z_}] :> Round[((y - 1/2)/(width - 1)) 180., 0.1] ] {101., 93.4, 7.1, 93.4, 101.} The output varies a little depending on choices made previously, but the variation is consistent with the amount of noise apparent in the original image. Rotate the original to make the grid appear isothetic (parallel to the coordinate axes). j = ImageRotate[crop2, -slopes[[1]] / 180 * \[Pi]]; ImageResize[j, 150] Smooth row and column sums to plot the marginal distributions of intensity. "Streets" run left to right; "avenues" run straight up and down. ListPlot[ListConvolve[{1,2,3,2,1}, (Plus @@ #)& /@ ImageData[j]], Joined->True, PlotRange-> {Full, Full}, PlotLabel->"Streets"] You can post-process the locations of the peaks to identify the coordinates of the "street" centerlines. The values along the horizontal axis are pixels indexing the cropped image I have been using. Here is a plot for the transpose of the image data (the code is essentially the same): Standard errors for these location estimates can also be obtained from the half-widths of the peaks in these "spectra." At this juncture we have obtained the angle of the street grid and locations of all identifiable streets and avenues in the image. Further processing will depend on the data structures you need and what you intend to do with this information. I consider this to be a great result, because it has succeeded in identifying the numbers of streets and avenues and estimating the resulting $1+4+6=11$ parameters with appropriate precision from just $17$ rather uncertain point locations. This method still works without the second idea (of combining the image with rotated versions of itself), when it can identify gridlines on a non-orthogonal street system, but it requires more data to achieve the same level of precision.
Fitting an Orthogonal Grid to Noisy Points
Because the streets are on an irregular orthogonal grid, the Fourier Transform solutions--although clever--will likely fail. The following approach exploits two ideas: Using the Hough transform to i
Fitting an Orthogonal Grid to Noisy Points Because the streets are on an irregular orthogonal grid, the Fourier Transform solutions--although clever--will likely fail. The following approach exploits two ideas: Using the Hough transform to identify sets of points that tend to line up. Exploiting the assumed orthogonality of the grid to augment the data. The link explains and illustrates the Hough transform and the Mathematica code I am using. Here is the gist of it, as extracted from the second paragraph: ... the Hough transform depicts sets of lines. A line in the plane can be parameterized by its slope, $x,$ and its distance, $y,$ from a fixed origin. A point in this $x,y$ coordinate system thereby designates a single line. Each point in the original plot determines a pencil of lines passing through that point: this pencil appears as a curve in the Hough transform. When features in the original plot fall along a common line, or near enough to one, then the collections of curves they produce in the Hough transform tend to have a common intersection corresponding to that common line. By finding these points of greatest intensity in the Hough transform, we can read off good solutions to the original problem. Please refer to the rest of that post for further explanation and code. Here, I'll simply take you through the workflow with your example (the dots in the left image). Import the image and crop it. img = Import["https://i.stack.imgur.com/uAjLw.jpg"] i = ColorNegate[Binarize[img]]; crop2 = ImageCrop[ImageTake[i, {25, 700}, {1, 1050}], 940]; Combine the image with its 90 degree rotation. (Optionally, combine it with all three rotations at 90, 180, and 270 degrees.) I also downsample it for speed and because coarsening the resolution is a crude kind of windowed smooth that helps identify points that line up. Various forms of additional smoothing will appear further below without comment. The amount of smoothing is a matter of trial and error but good results are quickly found. crop3 = ImageResize[crop2, 80]; (* crop3 = ImageAdd[crop3, ImageRotate[crop3]]; *) crop3=ImageAdd[crop3, ImageRotate[crop3, \[Pi]]] Notice how much more clearly the orthogonal geometry of the street intersections comes through in this combined image. [Edit: I made a mistake here. The commented-out line performs the 90 degree rotation; the final line rotates by 180 degrees. I intended to comment out the last line only. The result of this error is to produce an inferior solution--the one shown below--but it still illustrates the ideas, so I have left the figures as is.] Compute the Hough transform. hough2 = Radon[crop3, Method -> "Hough"] // ImageAdjust Smooth the Hough transform to help detect peaks. blur = ImageAdjust[Blur[ImageAdjust[hough2, {1, 0}], 5]] Identify the "morphological components" (isolated high points). comp = MorphologicalComponents[blur, 0.85] // Colorize Find the angles associated with component centroids. width = ImageDimensions[blur][[1]]; slopes = Module[{x, y, z}, ComponentMeasurements[comp, "Centroid"] /. Rule[x_, {y_, z_}] :> Round[((y - 1/2)/(width - 1)) 180., 0.1] ] {101., 93.4, 7.1, 93.4, 101.} The output varies a little depending on choices made previously, but the variation is consistent with the amount of noise apparent in the original image. Rotate the original to make the grid appear isothetic (parallel to the coordinate axes). j = ImageRotate[crop2, -slopes[[1]] / 180 * \[Pi]]; ImageResize[j, 150] Smooth row and column sums to plot the marginal distributions of intensity. "Streets" run left to right; "avenues" run straight up and down. ListPlot[ListConvolve[{1,2,3,2,1}, (Plus @@ #)& /@ ImageData[j]], Joined->True, PlotRange-> {Full, Full}, PlotLabel->"Streets"] You can post-process the locations of the peaks to identify the coordinates of the "street" centerlines. The values along the horizontal axis are pixels indexing the cropped image I have been using. Here is a plot for the transpose of the image data (the code is essentially the same): Standard errors for these location estimates can also be obtained from the half-widths of the peaks in these "spectra." At this juncture we have obtained the angle of the street grid and locations of all identifiable streets and avenues in the image. Further processing will depend on the data structures you need and what you intend to do with this information. I consider this to be a great result, because it has succeeded in identifying the numbers of streets and avenues and estimating the resulting $1+4+6=11$ parameters with appropriate precision from just $17$ rather uncertain point locations. This method still works without the second idea (of combining the image with rotated versions of itself), when it can identify gridlines on a non-orthogonal street system, but it requires more data to achieve the same level of precision.
Fitting an Orthogonal Grid to Noisy Points Because the streets are on an irregular orthogonal grid, the Fourier Transform solutions--although clever--will likely fail. The following approach exploits two ideas: Using the Hough transform to i
15,648
Fitting an Orthogonal Grid to Noisy Points
How about this approach: Your grid can be described by seven parameters: Consider the lower left rectangle in your grid. You need five parameters to describe the four corners of this rectangle, and two parameters for the number of rectangles in both directions. Next, you design a cost function that takes as input those seven parameters and your data (the points) and computes for each of your data points the squared distance to the nearest grid point. The sum of those squared distances would be returned as cost. Finally, you might want to add an extra term to penalize the grid vertices count: Imagine a grid with extremely many vertices, then there would be a vertex near any of your data points, reducing the cost to almost zero, but that is probably not what you want. Finally, find the minimum of your cost function and the belonging seven parameters, e.g. with the R function optim, if you cannot find anything more appropriate.
Fitting an Orthogonal Grid to Noisy Points
How about this approach: Your grid can be described by seven parameters: Consider the lower left rectangle in your grid. You need five parameters to describe the four corners of this rectangle, and tw
Fitting an Orthogonal Grid to Noisy Points How about this approach: Your grid can be described by seven parameters: Consider the lower left rectangle in your grid. You need five parameters to describe the four corners of this rectangle, and two parameters for the number of rectangles in both directions. Next, you design a cost function that takes as input those seven parameters and your data (the points) and computes for each of your data points the squared distance to the nearest grid point. The sum of those squared distances would be returned as cost. Finally, you might want to add an extra term to penalize the grid vertices count: Imagine a grid with extremely many vertices, then there would be a vertex near any of your data points, reducing the cost to almost zero, but that is probably not what you want. Finally, find the minimum of your cost function and the belonging seven parameters, e.g. with the R function optim, if you cannot find anything more appropriate.
Fitting an Orthogonal Grid to Noisy Points How about this approach: Your grid can be described by seven parameters: Consider the lower left rectangle in your grid. You need five parameters to describe the four corners of this rectangle, and tw
15,649
Fitting an Orthogonal Grid to Noisy Points
This answer is not a complete answer to the exact question but I leave it as it does explain some principles and works well in another related situation. This answer is based on the assumption that the grid is regular (equal distance between grid lines). In the solution this assumption is necessary when we apply the fit with a sine wave to detect the clusters of points. The advantage of working with this assumption is that it works well for large and sparse matrices. (but of course it only works of the grid is truly regular). An example is the image below that is made with by turning the problem below a bit more difficult by having the standard deviation of the noise at 20% of the distance between 30 by 20 grid lines and by having only 10% sampled points per grid point. The principle of the answer still stands. It is based on finding the clusters in a rotated image (one could use other methods than the sine wave applied here) and find the correct rotation by an optimisation. The disadvantage is that the optimisation requires a lot of computation. Performing clustering at different angles. The advantage is that the method works without assumptions. An example of such assumption. If the envelope of your grid points is forming a rectangle (this is not clear from your description as you say that points are missing), then you could quickly find an initial starting point by minimising the size of the smallest enveloping rectangle around the points, which is easy to find using the minimum and maximum coordinates after rotation) This method is similar to the method with the Haugh transform that Whuber describes. The image below shows how it is similar. We rotate the image and compute the x and y-coordinates. Those are plotted in the image as function of the angle. The trick is to find the angle where the points are most strongly clustered around single centers (which depict the grid lines). With the Haugh transform this is done by looking for points with high contrast/density. The method below does this a bit less efficient by making a seperate computation for every seperate angle. The image also shows how it is much easier to detect the optimal angle by looking for the smallest bandwidth of the coordinates. In the case that a fitting is performed by computing the grid and a cost function based on distances, then a trick to speed up would be to rotate the points and find the distances to a rectangle with fixed orientation, instead of rotating the rectangle and finding the distances to the points. In this way you do not need to find a nearest neighbour among $N \times M$ grid points, and only look at distance to the $N+M$ grid lines. The squared distance of the distance to the grid point is the sum of the squared distance to the grid lines. So a part of the algorithm could be something like Rotate the grid points with some angle $\theta$ Fit horizontal and vertical grid lines seperately to $x$ and $y$ coordinates of the points. This just needs to take into account the distance and offset-position of the grid lines. The number of grid lines (size of the square) you do not to worry about. Consider at this moment the grid to be infinitely large. I did a quick search but could not find anything. I imagine that there should be some standard algorithms/functions doing this, e.g. some Gaussian kernel that is convoluted with a regular grid. Otherwise if you do it yourself, then you might use an autocorrelation function to find an initial estimate for the distance between grid lines. You could also fit a Gaussian kernel with some number of points (for which there are many programs available), and use the fitted points to figure out the grid. In the code example below we fit a sine wave such that the following function is maximized $$\sum_{k=1}^n \sin\left(\text{offset}+2 \pi \frac{x_k}{\lambda} \right)$$ the advantage of the sine wave is that it allows simple algebraic computations to find the optimal $\lambda$ and $\text{offset}$. After reading the answer by Dan Piponi, I realize that this is effectively computing a Fourier transform. Compute some cost function using the distances of the points to the vertical and horizontal grid lines (possibly the sine wave cost function of the previous paragraph could be used, but I imagine that using something else, like squared distance, might result in less variance of the error). In the example below we rescale and shift the points again such that we get grid lines at $x=0,1,2,\dots$ and we can use round off function to easily compute the distance. Then you repeat the above with different values of $\theta$ to find the optimum for that parameter In the above graph there is a clear minimum at -5 degrees, which is how the data was generated. One remaining problem is that for different angles there are also minima and these are due to the tendency of adding more grid lines than the true model (overfitting). You need some way to limit the total amount of grid lines. For this you need prior information. The fit above is an improvement from the code below. It is using the scaling to add a penalty for adding too many grid lines (this will scale the image more strongly and increase the distances). Instead of computing the distance as ### compute distance distance[k] = sum((ttx-round(ttx))^2*modx$l_max^2) + sum((tty-round(tty))^2*mody$l_max^2) } the above image uses ### compute distance distance[k] = sum((ttx-round(ttx))^2) + sum((tty-round(tty))^2) } And the distance is computed in the scaled frame (where grid line distance are standardized to be 1) instead of multiplying with l_max to scale back to the original. So the distance is relative to the grid line distance. Example r-code: ### settings set.seed(1) nx = 10 ny = 10 theta = 5*2*pi/360 dx = 1.5 dy = 1.5 sigma_x = 0.1 sigma_y = 0.1 p_sel = 0.7 ### generate data kx = rep(1:nx,each=ny) - (nx+1)/2+0.3 ky = rep(1:ny,times=nx) - (ny+1)/2 x = kx*dx + rnorm(nx*ny,0,sigma_x) y = ky*dy + rnorm(nx*ny,0,sigma_y) rx = cos(theta)*x-sin(theta)*y ry = sin(theta)*x+cos(theta)*y sel = which(rbinom(nx*ny,1,p_sel) == 1) sx = rx[sel] sy = ry[sel] plot(sx,sy, main = "original data") ### example of rotated data alpha = -6*2*pi/360 tx = cos(alpha)*sx-sin(alpha)*sy ty = sin(alpha)*sx+cos(alpha)*sy plot(tx,ty, main = "rotated data") ### function to find a regular grid for 1d data ### fitting by maximizing a sine wave ### we search for the offset of the wave and the wave length fitpoints = function(s,lmd_range, plt = TRUE) { ### initial search for wavelength cost = sapply(lmd_range, function(z) sum(sin(s/z*2*pi))^2 + sum(cos(s/z*2*pi))^2 ) l_max = lmd_range[which.max(cost)] if(plt) { plot(lmd_range, cost, type = "l", main = "find optimal lambda \n distance between lines") } ### given optimal wave length ### search for offset ### ### this makes use of the linear sum of cosine and sine waves ### sin(x+b) = cos(b)sin(x) + sin(b)cos(x) ss = sum(sin(s/l_max*2*pi)) sc = sum(cos(s/l_max*2*pi)) M = matrix(c(ss,sc,sc,-ss),2,byrow=TRUE) factor = solve(M) %*% c(sqrt(ss^2+sc^2),0) xs = seq(min(s),max(s),0.01) if(plt) { plot(xs, factor[1] * sin(xs/l_max*2*pi) + factor[2] * cos(xs/l_max*2*pi), type="l", main = "sine wave with highest values for points") points(s, factor[1] * sin(s/l_max*2*pi) + factor[2] * cos(s/l_max*2*pi), pch = 19) } angle = Arg(complex(real=factor[1],imaginary=factor[2])) offset = -angle/2/pi*l_max+0.25*l_max ### return result return(list(l_max = l_max, offset = offset)) } modx = fitpoints(tx,seq(0.25, 5, 0.01)) mody = fitpoints(ty,seq(0.25, 5, 0.01), plt = 0) ttx = (tx-modx$offset)/modx$l_max tty = (ty-mody$offset)/mody$l_max plot(ttx,tty, pch = 21, main = "rescaled and shifted data \n ready to get distance to lines by using roundoff function") for (i in -30:30) { lines(c(i,i),c(-100,100),lty=2) lines(c(-100,100),c(i,i),lty=2) } ### find optimal angle angle_range = seq(-20,10,0.2)*2*pi/360 distance = angle_range*0 ### create an empty vector for (k in 1:length(angle_range)) { alpha = angle_range[k] ### rotate tx = cos(alpha)*sx-sin(alpha)*sy ty = sin(alpha)*sx+cos(alpha)*sy ### optimize lines modx = fitpoints(tx,seq(0.5, 5, 0.01), plt = 0) mody = fitpoints(ty,seq(0.5, 5, 0.01), plt = 0) ### shift and rescale ttx = (tx-modx$offset)/modx$l_max tty = (ty-mody$offset)/mody$l_max ### compute distance distance[k] = sum((ttx-round(ttx))^2*modx$l_max^2) + sum((tty-round(tty))^2*mody$l_max^2) } plot(angle_range*360/2/pi, distance, type = 'l' , main = "distance for grids fitted with different rotation") points(angle_range*360/2/pi, distance, pch = 19) Sidenote: The above does not compute a beginning or end of the rectangle. However, after finding $\theta$ and the grid lines, you can find out easily where the rectangle ends and starts (I would not place the end and start of the rectangle in the optimisation, these parameters do not change the cost function and just slow down the fitting).
Fitting an Orthogonal Grid to Noisy Points
This answer is not a complete answer to the exact question but I leave it as it does explain some principles and works well in another related situation. This answer is based on the assumption that t
Fitting an Orthogonal Grid to Noisy Points This answer is not a complete answer to the exact question but I leave it as it does explain some principles and works well in another related situation. This answer is based on the assumption that the grid is regular (equal distance between grid lines). In the solution this assumption is necessary when we apply the fit with a sine wave to detect the clusters of points. The advantage of working with this assumption is that it works well for large and sparse matrices. (but of course it only works of the grid is truly regular). An example is the image below that is made with by turning the problem below a bit more difficult by having the standard deviation of the noise at 20% of the distance between 30 by 20 grid lines and by having only 10% sampled points per grid point. The principle of the answer still stands. It is based on finding the clusters in a rotated image (one could use other methods than the sine wave applied here) and find the correct rotation by an optimisation. The disadvantage is that the optimisation requires a lot of computation. Performing clustering at different angles. The advantage is that the method works without assumptions. An example of such assumption. If the envelope of your grid points is forming a rectangle (this is not clear from your description as you say that points are missing), then you could quickly find an initial starting point by minimising the size of the smallest enveloping rectangle around the points, which is easy to find using the minimum and maximum coordinates after rotation) This method is similar to the method with the Haugh transform that Whuber describes. The image below shows how it is similar. We rotate the image and compute the x and y-coordinates. Those are plotted in the image as function of the angle. The trick is to find the angle where the points are most strongly clustered around single centers (which depict the grid lines). With the Haugh transform this is done by looking for points with high contrast/density. The method below does this a bit less efficient by making a seperate computation for every seperate angle. The image also shows how it is much easier to detect the optimal angle by looking for the smallest bandwidth of the coordinates. In the case that a fitting is performed by computing the grid and a cost function based on distances, then a trick to speed up would be to rotate the points and find the distances to a rectangle with fixed orientation, instead of rotating the rectangle and finding the distances to the points. In this way you do not need to find a nearest neighbour among $N \times M$ grid points, and only look at distance to the $N+M$ grid lines. The squared distance of the distance to the grid point is the sum of the squared distance to the grid lines. So a part of the algorithm could be something like Rotate the grid points with some angle $\theta$ Fit horizontal and vertical grid lines seperately to $x$ and $y$ coordinates of the points. This just needs to take into account the distance and offset-position of the grid lines. The number of grid lines (size of the square) you do not to worry about. Consider at this moment the grid to be infinitely large. I did a quick search but could not find anything. I imagine that there should be some standard algorithms/functions doing this, e.g. some Gaussian kernel that is convoluted with a regular grid. Otherwise if you do it yourself, then you might use an autocorrelation function to find an initial estimate for the distance between grid lines. You could also fit a Gaussian kernel with some number of points (for which there are many programs available), and use the fitted points to figure out the grid. In the code example below we fit a sine wave such that the following function is maximized $$\sum_{k=1}^n \sin\left(\text{offset}+2 \pi \frac{x_k}{\lambda} \right)$$ the advantage of the sine wave is that it allows simple algebraic computations to find the optimal $\lambda$ and $\text{offset}$. After reading the answer by Dan Piponi, I realize that this is effectively computing a Fourier transform. Compute some cost function using the distances of the points to the vertical and horizontal grid lines (possibly the sine wave cost function of the previous paragraph could be used, but I imagine that using something else, like squared distance, might result in less variance of the error). In the example below we rescale and shift the points again such that we get grid lines at $x=0,1,2,\dots$ and we can use round off function to easily compute the distance. Then you repeat the above with different values of $\theta$ to find the optimum for that parameter In the above graph there is a clear minimum at -5 degrees, which is how the data was generated. One remaining problem is that for different angles there are also minima and these are due to the tendency of adding more grid lines than the true model (overfitting). You need some way to limit the total amount of grid lines. For this you need prior information. The fit above is an improvement from the code below. It is using the scaling to add a penalty for adding too many grid lines (this will scale the image more strongly and increase the distances). Instead of computing the distance as ### compute distance distance[k] = sum((ttx-round(ttx))^2*modx$l_max^2) + sum((tty-round(tty))^2*mody$l_max^2) } the above image uses ### compute distance distance[k] = sum((ttx-round(ttx))^2) + sum((tty-round(tty))^2) } And the distance is computed in the scaled frame (where grid line distance are standardized to be 1) instead of multiplying with l_max to scale back to the original. So the distance is relative to the grid line distance. Example r-code: ### settings set.seed(1) nx = 10 ny = 10 theta = 5*2*pi/360 dx = 1.5 dy = 1.5 sigma_x = 0.1 sigma_y = 0.1 p_sel = 0.7 ### generate data kx = rep(1:nx,each=ny) - (nx+1)/2+0.3 ky = rep(1:ny,times=nx) - (ny+1)/2 x = kx*dx + rnorm(nx*ny,0,sigma_x) y = ky*dy + rnorm(nx*ny,0,sigma_y) rx = cos(theta)*x-sin(theta)*y ry = sin(theta)*x+cos(theta)*y sel = which(rbinom(nx*ny,1,p_sel) == 1) sx = rx[sel] sy = ry[sel] plot(sx,sy, main = "original data") ### example of rotated data alpha = -6*2*pi/360 tx = cos(alpha)*sx-sin(alpha)*sy ty = sin(alpha)*sx+cos(alpha)*sy plot(tx,ty, main = "rotated data") ### function to find a regular grid for 1d data ### fitting by maximizing a sine wave ### we search for the offset of the wave and the wave length fitpoints = function(s,lmd_range, plt = TRUE) { ### initial search for wavelength cost = sapply(lmd_range, function(z) sum(sin(s/z*2*pi))^2 + sum(cos(s/z*2*pi))^2 ) l_max = lmd_range[which.max(cost)] if(plt) { plot(lmd_range, cost, type = "l", main = "find optimal lambda \n distance between lines") } ### given optimal wave length ### search for offset ### ### this makes use of the linear sum of cosine and sine waves ### sin(x+b) = cos(b)sin(x) + sin(b)cos(x) ss = sum(sin(s/l_max*2*pi)) sc = sum(cos(s/l_max*2*pi)) M = matrix(c(ss,sc,sc,-ss),2,byrow=TRUE) factor = solve(M) %*% c(sqrt(ss^2+sc^2),0) xs = seq(min(s),max(s),0.01) if(plt) { plot(xs, factor[1] * sin(xs/l_max*2*pi) + factor[2] * cos(xs/l_max*2*pi), type="l", main = "sine wave with highest values for points") points(s, factor[1] * sin(s/l_max*2*pi) + factor[2] * cos(s/l_max*2*pi), pch = 19) } angle = Arg(complex(real=factor[1],imaginary=factor[2])) offset = -angle/2/pi*l_max+0.25*l_max ### return result return(list(l_max = l_max, offset = offset)) } modx = fitpoints(tx,seq(0.25, 5, 0.01)) mody = fitpoints(ty,seq(0.25, 5, 0.01), plt = 0) ttx = (tx-modx$offset)/modx$l_max tty = (ty-mody$offset)/mody$l_max plot(ttx,tty, pch = 21, main = "rescaled and shifted data \n ready to get distance to lines by using roundoff function") for (i in -30:30) { lines(c(i,i),c(-100,100),lty=2) lines(c(-100,100),c(i,i),lty=2) } ### find optimal angle angle_range = seq(-20,10,0.2)*2*pi/360 distance = angle_range*0 ### create an empty vector for (k in 1:length(angle_range)) { alpha = angle_range[k] ### rotate tx = cos(alpha)*sx-sin(alpha)*sy ty = sin(alpha)*sx+cos(alpha)*sy ### optimize lines modx = fitpoints(tx,seq(0.5, 5, 0.01), plt = 0) mody = fitpoints(ty,seq(0.5, 5, 0.01), plt = 0) ### shift and rescale ttx = (tx-modx$offset)/modx$l_max tty = (ty-mody$offset)/mody$l_max ### compute distance distance[k] = sum((ttx-round(ttx))^2*modx$l_max^2) + sum((tty-round(tty))^2*mody$l_max^2) } plot(angle_range*360/2/pi, distance, type = 'l' , main = "distance for grids fitted with different rotation") points(angle_range*360/2/pi, distance, pch = 19) Sidenote: The above does not compute a beginning or end of the rectangle. However, after finding $\theta$ and the grid lines, you can find out easily where the rectangle ends and starts (I would not place the end and start of the rectangle in the optimisation, these parameters do not change the cost function and just slow down the fitting).
Fitting an Orthogonal Grid to Noisy Points This answer is not a complete answer to the exact question but I leave it as it does explain some principles and works well in another related situation. This answer is based on the assumption that t
15,650
Fitting an Orthogonal Grid to Noisy Points
We can turn the problem of finding the points in a noisy grid into the problem of finding the peaks of a smooth function, which can be much easier. If your points are $p_i$, define the function $f$ of 2D vector $k$ by $f(k)=|\sum_{i=1}^n\exp(i k\cdot p_i)|$. For your example set of points you'll get the function whose "heat map" looks like (You can think of this as the Fourier transform of the function defined by placing Dirac deltas at the points.) There's a 3x3 grid of (bright white) local maxima in the middle with 0 at the centre that form a parallelogram. The vectors giving the midpoint of the right side and the top side give a pair of vectors, call them $g$ and $h$. In this case we have roughly $g=(0.039,0.006)$ and $h=(-0.005,0.039)$. These define the "reciprocal" lattice to the one you want. You can get the original lattice by taking the inverse of the matrix whose rows are $g$ and $h$ and scaling by $2\pi$. Here's some Mathematica code that plots the original points along side the points in the new perfectly regular lattice This doesn't give you the 'phase' of the points so you'll have to slide the lattice around until it fits. Both the problem of finding bright peaks and sliding around a fixed lattice to get a fit are easier than the original problem. So this may make things easier for you. On the negative side: this method is robust up to a certain amount of noise/deformation and then it quickly falls apart so you need to start with your worst examples and see if this approach can handle them. For example, I chose not to use this method for finding grid-points in a lens calibration method because even though the image looked grid-like, there was no actual regular grid that fit over the entire image due to the lens distortion. If it's ambiguous which peaks to use you can, of course, write code that tries more than one pair of vector candidates. Update: I think you don't need to do any shifting yourself. We can use the phase of the sum of the exponentials to extract the shift. Again, here is some Mathematica code:
Fitting an Orthogonal Grid to Noisy Points
We can turn the problem of finding the points in a noisy grid into the problem of finding the peaks of a smooth function, which can be much easier. If your points are $p_i$, define the function $f$ of
Fitting an Orthogonal Grid to Noisy Points We can turn the problem of finding the points in a noisy grid into the problem of finding the peaks of a smooth function, which can be much easier. If your points are $p_i$, define the function $f$ of 2D vector $k$ by $f(k)=|\sum_{i=1}^n\exp(i k\cdot p_i)|$. For your example set of points you'll get the function whose "heat map" looks like (You can think of this as the Fourier transform of the function defined by placing Dirac deltas at the points.) There's a 3x3 grid of (bright white) local maxima in the middle with 0 at the centre that form a parallelogram. The vectors giving the midpoint of the right side and the top side give a pair of vectors, call them $g$ and $h$. In this case we have roughly $g=(0.039,0.006)$ and $h=(-0.005,0.039)$. These define the "reciprocal" lattice to the one you want. You can get the original lattice by taking the inverse of the matrix whose rows are $g$ and $h$ and scaling by $2\pi$. Here's some Mathematica code that plots the original points along side the points in the new perfectly regular lattice This doesn't give you the 'phase' of the points so you'll have to slide the lattice around until it fits. Both the problem of finding bright peaks and sliding around a fixed lattice to get a fit are easier than the original problem. So this may make things easier for you. On the negative side: this method is robust up to a certain amount of noise/deformation and then it quickly falls apart so you need to start with your worst examples and see if this approach can handle them. For example, I chose not to use this method for finding grid-points in a lens calibration method because even though the image looked grid-like, there was no actual regular grid that fit over the entire image due to the lens distortion. If it's ambiguous which peaks to use you can, of course, write code that tries more than one pair of vector candidates. Update: I think you don't need to do any shifting yourself. We can use the phase of the sum of the exponentials to extract the shift. Again, here is some Mathematica code:
Fitting an Orthogonal Grid to Noisy Points We can turn the problem of finding the points in a noisy grid into the problem of finding the peaks of a smooth function, which can be much easier. If your points are $p_i$, define the function $f$ of
15,651
Fitting an Orthogonal Grid to Noisy Points
As an adjustable approach, you could try Rotate all the points by a fixed angle (around the origin or centre of mass, whatever suits). Project the rotated points to the x-axis and y-axis. This is just the x-values and y-values of the rotated points. Use k-means or a method of clustering points on a 1d line. K-means lets you specify the number of clusters, which here will correspond to the number of parallel lines in the non-uniform grid. The centres of the clusters says where the grid lines should go. Rotate the grid lines backwards by the same angle to line them up with the original points. With this approach you can explicitly set the number of grid lines in each direction. If searching for a solution, the parameters to adjust are reduced to a float, and two integers (the fixed angle, the number of vertical lines, and the number of horizontal lines). Here is an example solution from some hasty code. I eyeballed the angle and number of lines each way. import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans def fit_grid_to_points( points, angle: float, vertical_lines: int, horizontal_lines: int ): rotated_xs, rotated_ys = rotate_points(points, angle) x_centres = find_centres(rotated_xs, vertical_lines) y_centres = find_centres(rotated_ys, horizontal_lines) # Rotate the centres back. Match up with the original alignment. x_centre_points = np.hstack((x_centres, np.zeros_like(x_centres))).T y_centre_points = np.hstack((np.zeros_like(y_centres), y_centres)).T rotated_back_x_centres = rotate_points(x_centre_points, -angle) rotated_back_y_centres = rotate_points(y_centre_points, -angle) return rotated_back_x_centres, rotated_back_y_centres def main(): pts = np.array( [ (104, 131), (240, 136), (580, 183), (88, 234), (396, 277), (199, 431), (367, 451), (534, 464), (29, 554), (171, 627), (342, 628), (493, 638), (10, 739), (144, 747), (138, 927), (472, 966), ] ).T angle = -0.14 # radians vertical_lines, horizontal_lines = 4, 6 res_xs, res_ys = fit_grid_to_points(pts, angle, vertical_lines, horizontal_lines) display_found_grid(pts, res_xs, res_ys, angle, vertical_lines, horizontal_lines) def find_centres(values, number_of_centres: int): kmeans = KMeans(n_clusters=number_of_centres) # Reshape because this needs a dummy dimension. kmeans.fit(values.reshape(-1, 1)) return np.array(kmeans.cluster_centers_) def rotate_points(points, angle): """Rotate the points around the origin by `angle` radians. Modified from https://stackoverflow.com/questions/34372480/rotate-point-about-another-point-in-degrees-python """ xs, ys = points[0, :], points[1, :] rotated_xs = np.cos(angle) * xs - np.sin(angle) * ys rotated_ys = np.sin(angle) * xs + np.cos(angle) * ys return rotated_xs, rotated_ys def display_found_grid(points, res_xs, res_ys, angle, vertical_lines, horizontal_lines): xs, ys = points[0, :], points[1, :] plt.scatter(xs, ys) for x_centre in np.array(res_xs).T: plt.axline(x_centre, slope=1 / angle, color="black", alpha=0.6) for y_centre in np.array(res_ys).T: plt.axline(y_centre, slope=-angle, color="black", alpha=0.6) plt.title( f"Fitting a non-uniform ({horizontal_lines}x{vertical_lines}) grid to points\n" + f"using a fixed angle of: {angle:0.3} (radians)" ) plt.show() if __name__ == "__main__": main() The quality of the solution will depend on the clustering algorithm. Here I used kmeans as a quick fix. A more carefully chosen algorithm might be smarter about ensuring minimum distances between clusters which will guarantee the lines aren't pushed too close.
Fitting an Orthogonal Grid to Noisy Points
As an adjustable approach, you could try Rotate all the points by a fixed angle (around the origin or centre of mass, whatever suits). Project the rotated points to the x-axis and y-axis. This is jus
Fitting an Orthogonal Grid to Noisy Points As an adjustable approach, you could try Rotate all the points by a fixed angle (around the origin or centre of mass, whatever suits). Project the rotated points to the x-axis and y-axis. This is just the x-values and y-values of the rotated points. Use k-means or a method of clustering points on a 1d line. K-means lets you specify the number of clusters, which here will correspond to the number of parallel lines in the non-uniform grid. The centres of the clusters says where the grid lines should go. Rotate the grid lines backwards by the same angle to line them up with the original points. With this approach you can explicitly set the number of grid lines in each direction. If searching for a solution, the parameters to adjust are reduced to a float, and two integers (the fixed angle, the number of vertical lines, and the number of horizontal lines). Here is an example solution from some hasty code. I eyeballed the angle and number of lines each way. import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans def fit_grid_to_points( points, angle: float, vertical_lines: int, horizontal_lines: int ): rotated_xs, rotated_ys = rotate_points(points, angle) x_centres = find_centres(rotated_xs, vertical_lines) y_centres = find_centres(rotated_ys, horizontal_lines) # Rotate the centres back. Match up with the original alignment. x_centre_points = np.hstack((x_centres, np.zeros_like(x_centres))).T y_centre_points = np.hstack((np.zeros_like(y_centres), y_centres)).T rotated_back_x_centres = rotate_points(x_centre_points, -angle) rotated_back_y_centres = rotate_points(y_centre_points, -angle) return rotated_back_x_centres, rotated_back_y_centres def main(): pts = np.array( [ (104, 131), (240, 136), (580, 183), (88, 234), (396, 277), (199, 431), (367, 451), (534, 464), (29, 554), (171, 627), (342, 628), (493, 638), (10, 739), (144, 747), (138, 927), (472, 966), ] ).T angle = -0.14 # radians vertical_lines, horizontal_lines = 4, 6 res_xs, res_ys = fit_grid_to_points(pts, angle, vertical_lines, horizontal_lines) display_found_grid(pts, res_xs, res_ys, angle, vertical_lines, horizontal_lines) def find_centres(values, number_of_centres: int): kmeans = KMeans(n_clusters=number_of_centres) # Reshape because this needs a dummy dimension. kmeans.fit(values.reshape(-1, 1)) return np.array(kmeans.cluster_centers_) def rotate_points(points, angle): """Rotate the points around the origin by `angle` radians. Modified from https://stackoverflow.com/questions/34372480/rotate-point-about-another-point-in-degrees-python """ xs, ys = points[0, :], points[1, :] rotated_xs = np.cos(angle) * xs - np.sin(angle) * ys rotated_ys = np.sin(angle) * xs + np.cos(angle) * ys return rotated_xs, rotated_ys def display_found_grid(points, res_xs, res_ys, angle, vertical_lines, horizontal_lines): xs, ys = points[0, :], points[1, :] plt.scatter(xs, ys) for x_centre in np.array(res_xs).T: plt.axline(x_centre, slope=1 / angle, color="black", alpha=0.6) for y_centre in np.array(res_ys).T: plt.axline(y_centre, slope=-angle, color="black", alpha=0.6) plt.title( f"Fitting a non-uniform ({horizontal_lines}x{vertical_lines}) grid to points\n" + f"using a fixed angle of: {angle:0.3} (radians)" ) plt.show() if __name__ == "__main__": main() The quality of the solution will depend on the clustering algorithm. Here I used kmeans as a quick fix. A more carefully chosen algorithm might be smarter about ensuring minimum distances between clusters which will guarantee the lines aren't pushed too close.
Fitting an Orthogonal Grid to Noisy Points As an adjustable approach, you could try Rotate all the points by a fixed angle (around the origin or centre of mass, whatever suits). Project the rotated points to the x-axis and y-axis. This is jus
15,652
Suppose $Y_1, \dots, Y_n \overset{\text{iid}}{\sim} \text{Exp}(1)$. Show $\sum_{i=1}^{n}(Y_i - Y_{(1)}) \sim \text{Gamma}(n-1, 1)$
The proof is given in the Mother of All Random Generation Books, Devroye's Non-uniform Random Variate Generation, on p.211 (and it is a very elegant one!): Theorem 2.3 (Sukhatme, 1937) If we define $E_{(0)}=0$ then the normalised exponential spacings $$(n-i+1)(E_{(i)}-E_{(i-1)})$$ derived from the order statistics $E_{(1)}\le\ldots\le E_{(n)}$ of an i.i.d. exponential sample of size $n$ are themselves i.i.d. exponential variables Proof. Since \begin{align*} \sum_{i=1}^n e_i &= \sum_{i=1}^n e_{(i)} =\sum_{i=1}^n \sum_{j=1}^i(e_{(j)}-e_{(j-1)})\\ &=\sum_{j=1}^n \sum_{i=j}^n(e_{(j)}-e_{(j-1)}) =\sum_{j=1}^n (n-j+1)(e_{(j)}-e_{(j-1)}) \end{align*} the joint density of the order statistic $(E_{(1)},\ldots,E_{(n)})$ writes as $$f(\mathbf{e})=n!\,\exp\left\{-\sum_{i=1}^ne_{(i)}\right\}=n!\,\exp\left\{-\sum_{i=1}^n (n-i+1)(e_{(i)}-e_{(i-1)})\right\}$$ Setting $Y_i=(E_{(i)}-E_{(i-1)})$, the change of variables from $(E_{(1)},\ldots,E_{(n)})$ to $(Y_1,\ldots,Y_n)$ has a constant Jacobian [incidentally equal to $1/n!$ but this does not need to be computed] and hence the density of $(Y_1,\ldots,Y_n)$ is proportional to $$\exp\left\{-\sum_{i=1}^n y_i \right\}$$ which establishes the result. Q.E.D. An alternative suggested to me by Gérard Letac is to check that $$(E_{(1)},\ldots,E_{(n)})$$has the same distribution as$$\left(\frac{E_1}{n},\frac{E_1}{n}+\frac{E_2}{n-1},\ldots,\frac{E_1}{n}+\frac{E_2}{n-1}+\ldots+\frac{E_n}{1}\right)$$ (by virtue of the memoryless property), which makes the derivation of $$\sum_{k=1}^n(E_k-E_{(1)})\sim \sum_{k=1}^{n-1}E_k$$ straightforward.
Suppose $Y_1, \dots, Y_n \overset{\text{iid}}{\sim} \text{Exp}(1)$. Show $\sum_{i=1}^{n}(Y_i - Y_{(1
The proof is given in the Mother of All Random Generation Books, Devroye's Non-uniform Random Variate Generation, on p.211 (and it is a very elegant one!): Theorem 2.3 (Sukhatme, 1937) If we define $
Suppose $Y_1, \dots, Y_n \overset{\text{iid}}{\sim} \text{Exp}(1)$. Show $\sum_{i=1}^{n}(Y_i - Y_{(1)}) \sim \text{Gamma}(n-1, 1)$ The proof is given in the Mother of All Random Generation Books, Devroye's Non-uniform Random Variate Generation, on p.211 (and it is a very elegant one!): Theorem 2.3 (Sukhatme, 1937) If we define $E_{(0)}=0$ then the normalised exponential spacings $$(n-i+1)(E_{(i)}-E_{(i-1)})$$ derived from the order statistics $E_{(1)}\le\ldots\le E_{(n)}$ of an i.i.d. exponential sample of size $n$ are themselves i.i.d. exponential variables Proof. Since \begin{align*} \sum_{i=1}^n e_i &= \sum_{i=1}^n e_{(i)} =\sum_{i=1}^n \sum_{j=1}^i(e_{(j)}-e_{(j-1)})\\ &=\sum_{j=1}^n \sum_{i=j}^n(e_{(j)}-e_{(j-1)}) =\sum_{j=1}^n (n-j+1)(e_{(j)}-e_{(j-1)}) \end{align*} the joint density of the order statistic $(E_{(1)},\ldots,E_{(n)})$ writes as $$f(\mathbf{e})=n!\,\exp\left\{-\sum_{i=1}^ne_{(i)}\right\}=n!\,\exp\left\{-\sum_{i=1}^n (n-i+1)(e_{(i)}-e_{(i-1)})\right\}$$ Setting $Y_i=(E_{(i)}-E_{(i-1)})$, the change of variables from $(E_{(1)},\ldots,E_{(n)})$ to $(Y_1,\ldots,Y_n)$ has a constant Jacobian [incidentally equal to $1/n!$ but this does not need to be computed] and hence the density of $(Y_1,\ldots,Y_n)$ is proportional to $$\exp\left\{-\sum_{i=1}^n y_i \right\}$$ which establishes the result. Q.E.D. An alternative suggested to me by Gérard Letac is to check that $$(E_{(1)},\ldots,E_{(n)})$$has the same distribution as$$\left(\frac{E_1}{n},\frac{E_1}{n}+\frac{E_2}{n-1},\ldots,\frac{E_1}{n}+\frac{E_2}{n-1}+\ldots+\frac{E_n}{1}\right)$$ (by virtue of the memoryless property), which makes the derivation of $$\sum_{k=1}^n(E_k-E_{(1)})\sim \sum_{k=1}^{n-1}E_k$$ straightforward.
Suppose $Y_1, \dots, Y_n \overset{\text{iid}}{\sim} \text{Exp}(1)$. Show $\sum_{i=1}^{n}(Y_i - Y_{(1 The proof is given in the Mother of All Random Generation Books, Devroye's Non-uniform Random Variate Generation, on p.211 (and it is a very elegant one!): Theorem 2.3 (Sukhatme, 1937) If we define $
15,653
Suppose $Y_1, \dots, Y_n \overset{\text{iid}}{\sim} \text{Exp}(1)$. Show $\sum_{i=1}^{n}(Y_i - Y_{(1)}) \sim \text{Gamma}(n-1, 1)$
I lay out here what has been suggested in comments by @jbowman. Let a constant $a\geq 0$. Let $Y_i$ follow an $\text{Exp(1)}$ and consider $Z_i = Y_i-a$. Then $$\Pr(Z_i\leq z_i \mid Y_i \geq a) = \Pr(Y_i-a\leq z_i \mid Y_i \geq a)$$ $$\implies \Pr(Y_i\leq z_i+a \mid Y_i \geq a) = \frac {\Pr(Y_i\leq z_i+a,Y_i \geq a)}{1-\Pr(Y_i\leq a)}$$ $$\implies \frac {\Pr(a\leq Y_i\leq z_i+a)}{1-\Pr(Y_i\leq a)} = \frac {1-e^{-z_i-a}-1+e^{-a}}{e^{-a}}=1-e^{-z_i} $$ which is the distribution function of $\text{Exp(1)}$. Let's describe this: the probability that an $\text{Exp(1)}$ r.v. will fall in a specific interval (the numerator in the last line), given that it will exceed the interval's lower bound (the denominator), depends only on the length of the interval and not on where this interval is placed on the real line. This is an incarnation of the "memorylessness" property of the Exponential distribution, here in a more general setting, free of time-interpretations (and it holds for the Exponential distribution in general) Now, by conditioning on $\{Y_i \geq a\}$ we force $Z_i$ to be non-negative, and crucially, the obtained result holds $\forall a\in \mathbb R^+$. So we can state the following: If $Y_i\sim \text{Exp(1)}$, then $\forall Q\geq 0 : Z_i = Y_i-Q \geq 0$ $\implies$ $Z_i\sim \text{Exp(1)}$. Can we find a $Q\geq 0$ that is free to take all non-negative real values and for which the required inequality always holds (almost surely)? If we can, then we can dispense with the conditioning argument. And indeed we can. It is the minimum-order statistic, $Q=Y_{(1)}$, $\Pr(Y_i \geq Y_{(1)})=1$. So we have obtained $$Y_i\sim \text{Exp(1)} \implies Y_i-Y_{(1)} \sim \text{Exp(1)}$$ This means that $$\Pr(Y_i-Y_{(1)} \leq y_i-y_{(1)}) = \Pr(Y_i \leq y_i)$$ So if the probabilistic structure of $Y_i$ remains unchanged if we subtract the minimum order statistic, it follows that the random variables $Z_i=Y_i-Y_{(1)}$ and $Z_j=Y_j-Y_{(1)}$ where $Y_i, Y_j$ independent, are also independent since the possible link between them, $Y_{(1)}$ does not have an effect on the probabilistic structure. Then the sum $\sum_{i=1}^{n}(Y_i - Y_{(1)})$ contains $n-1$ $\text{Exp(1)}$ i.i.d. random variables (and a zero), and so $$\sum_{i=1}^{n}(Y_i - Y_{(1)}) \sim \text{Gamma}(n-1, 1)$$
Suppose $Y_1, \dots, Y_n \overset{\text{iid}}{\sim} \text{Exp}(1)$. Show $\sum_{i=1}^{n}(Y_i - Y_{(1
I lay out here what has been suggested in comments by @jbowman. Let a constant $a\geq 0$. Let $Y_i$ follow an $\text{Exp(1)}$ and consider $Z_i = Y_i-a$. Then $$\Pr(Z_i\leq z_i \mid Y_i \geq a) =
Suppose $Y_1, \dots, Y_n \overset{\text{iid}}{\sim} \text{Exp}(1)$. Show $\sum_{i=1}^{n}(Y_i - Y_{(1)}) \sim \text{Gamma}(n-1, 1)$ I lay out here what has been suggested in comments by @jbowman. Let a constant $a\geq 0$. Let $Y_i$ follow an $\text{Exp(1)}$ and consider $Z_i = Y_i-a$. Then $$\Pr(Z_i\leq z_i \mid Y_i \geq a) = \Pr(Y_i-a\leq z_i \mid Y_i \geq a)$$ $$\implies \Pr(Y_i\leq z_i+a \mid Y_i \geq a) = \frac {\Pr(Y_i\leq z_i+a,Y_i \geq a)}{1-\Pr(Y_i\leq a)}$$ $$\implies \frac {\Pr(a\leq Y_i\leq z_i+a)}{1-\Pr(Y_i\leq a)} = \frac {1-e^{-z_i-a}-1+e^{-a}}{e^{-a}}=1-e^{-z_i} $$ which is the distribution function of $\text{Exp(1)}$. Let's describe this: the probability that an $\text{Exp(1)}$ r.v. will fall in a specific interval (the numerator in the last line), given that it will exceed the interval's lower bound (the denominator), depends only on the length of the interval and not on where this interval is placed on the real line. This is an incarnation of the "memorylessness" property of the Exponential distribution, here in a more general setting, free of time-interpretations (and it holds for the Exponential distribution in general) Now, by conditioning on $\{Y_i \geq a\}$ we force $Z_i$ to be non-negative, and crucially, the obtained result holds $\forall a\in \mathbb R^+$. So we can state the following: If $Y_i\sim \text{Exp(1)}$, then $\forall Q\geq 0 : Z_i = Y_i-Q \geq 0$ $\implies$ $Z_i\sim \text{Exp(1)}$. Can we find a $Q\geq 0$ that is free to take all non-negative real values and for which the required inequality always holds (almost surely)? If we can, then we can dispense with the conditioning argument. And indeed we can. It is the minimum-order statistic, $Q=Y_{(1)}$, $\Pr(Y_i \geq Y_{(1)})=1$. So we have obtained $$Y_i\sim \text{Exp(1)} \implies Y_i-Y_{(1)} \sim \text{Exp(1)}$$ This means that $$\Pr(Y_i-Y_{(1)} \leq y_i-y_{(1)}) = \Pr(Y_i \leq y_i)$$ So if the probabilistic structure of $Y_i$ remains unchanged if we subtract the minimum order statistic, it follows that the random variables $Z_i=Y_i-Y_{(1)}$ and $Z_j=Y_j-Y_{(1)}$ where $Y_i, Y_j$ independent, are also independent since the possible link between them, $Y_{(1)}$ does not have an effect on the probabilistic structure. Then the sum $\sum_{i=1}^{n}(Y_i - Y_{(1)})$ contains $n-1$ $\text{Exp(1)}$ i.i.d. random variables (and a zero), and so $$\sum_{i=1}^{n}(Y_i - Y_{(1)}) \sim \text{Gamma}(n-1, 1)$$
Suppose $Y_1, \dots, Y_n \overset{\text{iid}}{\sim} \text{Exp}(1)$. Show $\sum_{i=1}^{n}(Y_i - Y_{(1 I lay out here what has been suggested in comments by @jbowman. Let a constant $a\geq 0$. Let $Y_i$ follow an $\text{Exp(1)}$ and consider $Z_i = Y_i-a$. Then $$\Pr(Z_i\leq z_i \mid Y_i \geq a) =
15,654
simulating random samples with a given MLE
One option would be to use a constrained HMC variant as described in A Family of MCMC Methods on Implicitly Defined Manifolds by Brubaker et al (1). This requires that we can express the condition that the maximum-likelihood estimate of the location parameter is equal to some fixed $\mu_0$ as some implicitly defined (and differentiable) holonomic constraint $c\left(\lbrace x_i \rbrace_{i=1}^N\right) = 0$. We can then simulate a constrained Hamiltonian dynamic subject to this constraint, and accept / reject within a Metropolis-Hastings step as in standard HMC. The negative log-likelihood is $$ \mathcal{L} = -\sum_{i=1}^N \left[ \log f(x_i \,|\, \mu) \right] = 3 \sum_{i=1}^N \left[ \log\left(1 + \frac{(x_i - \mu)^2}{5}\right)\right] + \text{constant} $$ which has first and second order partial derivatives with respect to the location parameter $\mu$ $$ \frac{\partial \mathcal{L}}{\partial \mu} = 3 \sum_{i=1}^N \left[ \frac{2(\mu - x_i)}{5 + (\mu - x_i)^2}\right] \quad\text{and}\quad \frac{\partial^2 \mathcal{L}}{\partial \mu^2} = 6 \sum_{i=1}^N \left[\frac{5 - (\mu - x_i)^2}{\left(5 + (\mu - x_i)^2\right)^2}\right]. $$ A maximum-likelihood estimate of $\mu_0$ is then implicitly defined as a solution to $$ c = \sum_{i=1}^N \left[ \frac{2(\mu_0 - x_i)}{5 + (\mu_0 - x_i)^2}\right] = 0 \quad\text{subject to}\quad \sum_{i=1}^N \left[\frac{5 - (\mu_0 - x_i)^2}{\left(5 + (\mu_0 - x_i)^2\right)^2}\right] > 0. $$ I am not sure if there are any results suggesting there will be a unique MLE for $\mu$ for given $\lbrace x_i \rbrace_{i=1}^N$ - the density is not log-concave in $\mu$ so it doesn't seem trivial to guarantee this. If there is a single unique solution the above implicitly defines a connected $N - 1$ dimensional manifold embedded in $\mathbb{R}^N$ corresponding to the set of $\lbrace x_i \rbrace_{i=1}^N$ with MLE for $\mu$ equal to $\mu_0$. If there are multiple solutions then the manifold may consist of multiple non-connected components some of which may correspond to minima in the likelihood function. In this case we would need to have some additional mechanism for moving between the non-connected components (as the simulated dynamic will generally remain confined to a single component) and check the second-order condition and reject a move if it corresponds to moving to a minima in the likelihood. If we use $\boldsymbol{x}$ to denote the vector $\left[ x_1 \dots x_N\right]^{\rm T}$ and introduce a conjugate momentum state $\boldsymbol{p}$ with mass matrix $\mathbf{M}$ and a Lagrange multiplier $\lambda$ for the scalar constraint $c(\boldsymbol{x})$ then the solution to system of ODEs $$ \frac{{\rm d}\boldsymbol{x}}{{\rm d}t} = \mathbf{M}^{-1}\boldsymbol{p}, \quad \frac{{\rm d}\boldsymbol{p}}{{\rm d}t} = -\frac{\partial \mathcal{L}}{\partial \mathbf{x}} - \lambda \frac{\partial c}{\partial \boldsymbol{x}} \quad\text{subject to}\quad c(\boldsymbol{x}) = 0 \quad\text{and}\quad \frac{\partial c}{\partial \boldsymbol{x}}\mathbf{M}^{-1}\boldsymbol{p} = 0 $$ given initial condition $\boldsymbol{x}(0) = \boldsymbol{x}_0,~\boldsymbol{p}(0) = \boldsymbol{p}_0$ with $c(\boldsymbol{x}_0) = 0$ and $\left.\frac{\partial c}{\partial \boldsymbol{x}}\right|_{\boldsymbol{x}_0}\,\mathbf{M}^{-1}\boldsymbol{p}_0 = 0$, defines a constrained Hamiltonian dynamic which remains confined to the constraint manifold, is time reversible and exactly conserves the Hamiltonian and the manifold volume element. If we use a symplectic integrator for constrained Hamiltonian systems such as SHAKE (2) or RATTLE (3), which exactly maintain the constraint at each timestep by solving for the Lagrange multiplier, we can simulate the exact dynamic forward $L$ discrete timesteps $\delta t$ from some initial constraint satisfying $\boldsymbol{x},\,\boldsymbol{p}$ and accept the proposed new state pair $\boldsymbol{x}',\,\boldsymbol{p}'$ with probability $$ \min\left\lbrace 1, \,\exp\left[ \mathcal{L}(\boldsymbol{x}) - \mathcal{L}(\boldsymbol{x}') + \frac{1}{2}\boldsymbol{p}^{\rm T}\mathbf{M}^{-1}\boldsymbol{p} - \frac{1}{2}\boldsymbol{p}'^{\rm T}\mathbf{M}^{-1}\boldsymbol{p}'\right] \right\rbrace. $$ If we interleave these dynamics updates with partial / full resampling of the momenta from their Gaussian marginal (restricted to the linear subspace defined by $\frac{\partial c}{\partial \boldsymbol{x}}\mathbf{M}^{-1}\boldsymbol{p} = 0$) then modulo the possiblity of there being multiple non-connected constraint manifold components, the overall MCMC dynamic should be ergodic and the configuration state samples $\boldsymbol{x}$ will coverge in distribution to the target density restricted to the constraint manifold. To see how constrained HMC performed for the case here I ran the geodesic integrator based constrained HMC implementation described in (4) and available on Github here (full disclosure: I am an author of (4) and owner of the Github repository), which uses a variation of the 'geodesic-BAOAB' integrator scheme proposed in (5) without the stochastic Ornstein-Uhlenbeck step. In my experience this geodesic integration scheme is generally a bit easier to tune than the RATTLE scheme used in (1) due the extra flexibility of using multiple smaller inner steps for the geodesic motion on the constraint manifold. An IPython notebook generating the results is available here. I used $N=3$, $\mu=1$ and $\mu_0=2$. An initial $\boldsymbol{x}$ corresponding to a MLE of $\mu_0$ was found by Newton's method (with the second order derivative checked to ensure a maxima of the likelihood was found). I ran a constrained dynamic with $\delta t = 0.5$, $L=5$ interleaved with full momentum refreshals for 1000 updates. The plot below shows the resulting traces on the three $\boldsymbol{x}$ components and the corresponding values of the first and second order derivatives of the negative log-likelihood are shown below from which it can be seen that we are at a maximum of the log-likelihood for all sampled $\boldsymbol{x}$. Although it is not readily apparent from the individual trace plots, the sampled $\boldsymbol{x}$ lie on a 2D non-linear manifold embedded in $\mathbb{R}^3$ - the animation below shows the samples in 3D Depending on the interpretation of the constraint it may also be necessary to adjust the target density by some Jacobian factor as described in (4). In particular if we want results consistent with the $\epsilon \to 0$ limit of using an ABC like approach to approximately maintain the constraint by proposing unconstrained moves in $\mathbb{R}^N$ and accepting if $|c(\boldsymbol{x})| < \epsilon$, then we need to multiply the target density by $\sqrt{\frac{\partial c}{\partial \boldsymbol{x}}^{\rm \scriptscriptstyle T}\frac{\partial c}{\partial \boldsymbol{x}}}$. In the above example I did not include this adjustment so the samples are from the original target density restricted to the constraint manifold. References M. A. Brubaker, M. Salzmann, and R. Urtasun. A family of MCMC methods on implicitly defined manifolds. In Proceedings of the 15th International Conference on Artificial Intelligence and Statistics, 2012. http://www.cs.toronto.edu/~mbrubake/projects/AISTATS12.pdf J.-P. Ryckaert, G. Ciccotti, and H. J. Berendsen. Numerical integration of the Cartesian equations of motion of a system with constraints: molecular dynamics of n-alkanes. Journal of Computational Physics, 1977. http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.399.6868 H. C. Andersen. RATTLE: A "velocity" version of the SHAKE algorithm for molecular dynamics calculations. Journal of Computational Physics, 1983. http://www.sciencedirect.com/science/article/pii/0021999183900141 M. M. Graham and A. J. Storkey. Asymptotically exact inference in likelihood-free models. arXiv pre-print arXiv:1605.07826v3, 2016. https://arxiv.org/abs/1605.07826 B. Leimkuhler and C. Matthews. Efficient molecular dynamics using geodesic integration and solvent–solute splitting. Proc. R. Soc. A. Vol. 472. No. 2189. The Royal Society, 2016. http://rspa.royalsocietypublishing.org/content/472/2189/20160138.abstract
simulating random samples with a given MLE
One option would be to use a constrained HMC variant as described in A Family of MCMC Methods on Implicitly Defined Manifolds by Brubaker et al (1). This requires that we can express the condition tha
simulating random samples with a given MLE One option would be to use a constrained HMC variant as described in A Family of MCMC Methods on Implicitly Defined Manifolds by Brubaker et al (1). This requires that we can express the condition that the maximum-likelihood estimate of the location parameter is equal to some fixed $\mu_0$ as some implicitly defined (and differentiable) holonomic constraint $c\left(\lbrace x_i \rbrace_{i=1}^N\right) = 0$. We can then simulate a constrained Hamiltonian dynamic subject to this constraint, and accept / reject within a Metropolis-Hastings step as in standard HMC. The negative log-likelihood is $$ \mathcal{L} = -\sum_{i=1}^N \left[ \log f(x_i \,|\, \mu) \right] = 3 \sum_{i=1}^N \left[ \log\left(1 + \frac{(x_i - \mu)^2}{5}\right)\right] + \text{constant} $$ which has first and second order partial derivatives with respect to the location parameter $\mu$ $$ \frac{\partial \mathcal{L}}{\partial \mu} = 3 \sum_{i=1}^N \left[ \frac{2(\mu - x_i)}{5 + (\mu - x_i)^2}\right] \quad\text{and}\quad \frac{\partial^2 \mathcal{L}}{\partial \mu^2} = 6 \sum_{i=1}^N \left[\frac{5 - (\mu - x_i)^2}{\left(5 + (\mu - x_i)^2\right)^2}\right]. $$ A maximum-likelihood estimate of $\mu_0$ is then implicitly defined as a solution to $$ c = \sum_{i=1}^N \left[ \frac{2(\mu_0 - x_i)}{5 + (\mu_0 - x_i)^2}\right] = 0 \quad\text{subject to}\quad \sum_{i=1}^N \left[\frac{5 - (\mu_0 - x_i)^2}{\left(5 + (\mu_0 - x_i)^2\right)^2}\right] > 0. $$ I am not sure if there are any results suggesting there will be a unique MLE for $\mu$ for given $\lbrace x_i \rbrace_{i=1}^N$ - the density is not log-concave in $\mu$ so it doesn't seem trivial to guarantee this. If there is a single unique solution the above implicitly defines a connected $N - 1$ dimensional manifold embedded in $\mathbb{R}^N$ corresponding to the set of $\lbrace x_i \rbrace_{i=1}^N$ with MLE for $\mu$ equal to $\mu_0$. If there are multiple solutions then the manifold may consist of multiple non-connected components some of which may correspond to minima in the likelihood function. In this case we would need to have some additional mechanism for moving between the non-connected components (as the simulated dynamic will generally remain confined to a single component) and check the second-order condition and reject a move if it corresponds to moving to a minima in the likelihood. If we use $\boldsymbol{x}$ to denote the vector $\left[ x_1 \dots x_N\right]^{\rm T}$ and introduce a conjugate momentum state $\boldsymbol{p}$ with mass matrix $\mathbf{M}$ and a Lagrange multiplier $\lambda$ for the scalar constraint $c(\boldsymbol{x})$ then the solution to system of ODEs $$ \frac{{\rm d}\boldsymbol{x}}{{\rm d}t} = \mathbf{M}^{-1}\boldsymbol{p}, \quad \frac{{\rm d}\boldsymbol{p}}{{\rm d}t} = -\frac{\partial \mathcal{L}}{\partial \mathbf{x}} - \lambda \frac{\partial c}{\partial \boldsymbol{x}} \quad\text{subject to}\quad c(\boldsymbol{x}) = 0 \quad\text{and}\quad \frac{\partial c}{\partial \boldsymbol{x}}\mathbf{M}^{-1}\boldsymbol{p} = 0 $$ given initial condition $\boldsymbol{x}(0) = \boldsymbol{x}_0,~\boldsymbol{p}(0) = \boldsymbol{p}_0$ with $c(\boldsymbol{x}_0) = 0$ and $\left.\frac{\partial c}{\partial \boldsymbol{x}}\right|_{\boldsymbol{x}_0}\,\mathbf{M}^{-1}\boldsymbol{p}_0 = 0$, defines a constrained Hamiltonian dynamic which remains confined to the constraint manifold, is time reversible and exactly conserves the Hamiltonian and the manifold volume element. If we use a symplectic integrator for constrained Hamiltonian systems such as SHAKE (2) or RATTLE (3), which exactly maintain the constraint at each timestep by solving for the Lagrange multiplier, we can simulate the exact dynamic forward $L$ discrete timesteps $\delta t$ from some initial constraint satisfying $\boldsymbol{x},\,\boldsymbol{p}$ and accept the proposed new state pair $\boldsymbol{x}',\,\boldsymbol{p}'$ with probability $$ \min\left\lbrace 1, \,\exp\left[ \mathcal{L}(\boldsymbol{x}) - \mathcal{L}(\boldsymbol{x}') + \frac{1}{2}\boldsymbol{p}^{\rm T}\mathbf{M}^{-1}\boldsymbol{p} - \frac{1}{2}\boldsymbol{p}'^{\rm T}\mathbf{M}^{-1}\boldsymbol{p}'\right] \right\rbrace. $$ If we interleave these dynamics updates with partial / full resampling of the momenta from their Gaussian marginal (restricted to the linear subspace defined by $\frac{\partial c}{\partial \boldsymbol{x}}\mathbf{M}^{-1}\boldsymbol{p} = 0$) then modulo the possiblity of there being multiple non-connected constraint manifold components, the overall MCMC dynamic should be ergodic and the configuration state samples $\boldsymbol{x}$ will coverge in distribution to the target density restricted to the constraint manifold. To see how constrained HMC performed for the case here I ran the geodesic integrator based constrained HMC implementation described in (4) and available on Github here (full disclosure: I am an author of (4) and owner of the Github repository), which uses a variation of the 'geodesic-BAOAB' integrator scheme proposed in (5) without the stochastic Ornstein-Uhlenbeck step. In my experience this geodesic integration scheme is generally a bit easier to tune than the RATTLE scheme used in (1) due the extra flexibility of using multiple smaller inner steps for the geodesic motion on the constraint manifold. An IPython notebook generating the results is available here. I used $N=3$, $\mu=1$ and $\mu_0=2$. An initial $\boldsymbol{x}$ corresponding to a MLE of $\mu_0$ was found by Newton's method (with the second order derivative checked to ensure a maxima of the likelihood was found). I ran a constrained dynamic with $\delta t = 0.5$, $L=5$ interleaved with full momentum refreshals for 1000 updates. The plot below shows the resulting traces on the three $\boldsymbol{x}$ components and the corresponding values of the first and second order derivatives of the negative log-likelihood are shown below from which it can be seen that we are at a maximum of the log-likelihood for all sampled $\boldsymbol{x}$. Although it is not readily apparent from the individual trace plots, the sampled $\boldsymbol{x}$ lie on a 2D non-linear manifold embedded in $\mathbb{R}^3$ - the animation below shows the samples in 3D Depending on the interpretation of the constraint it may also be necessary to adjust the target density by some Jacobian factor as described in (4). In particular if we want results consistent with the $\epsilon \to 0$ limit of using an ABC like approach to approximately maintain the constraint by proposing unconstrained moves in $\mathbb{R}^N$ and accepting if $|c(\boldsymbol{x})| < \epsilon$, then we need to multiply the target density by $\sqrt{\frac{\partial c}{\partial \boldsymbol{x}}^{\rm \scriptscriptstyle T}\frac{\partial c}{\partial \boldsymbol{x}}}$. In the above example I did not include this adjustment so the samples are from the original target density restricted to the constraint manifold. References M. A. Brubaker, M. Salzmann, and R. Urtasun. A family of MCMC methods on implicitly defined manifolds. In Proceedings of the 15th International Conference on Artificial Intelligence and Statistics, 2012. http://www.cs.toronto.edu/~mbrubake/projects/AISTATS12.pdf J.-P. Ryckaert, G. Ciccotti, and H. J. Berendsen. Numerical integration of the Cartesian equations of motion of a system with constraints: molecular dynamics of n-alkanes. Journal of Computational Physics, 1977. http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.399.6868 H. C. Andersen. RATTLE: A "velocity" version of the SHAKE algorithm for molecular dynamics calculations. Journal of Computational Physics, 1983. http://www.sciencedirect.com/science/article/pii/0021999183900141 M. M. Graham and A. J. Storkey. Asymptotically exact inference in likelihood-free models. arXiv pre-print arXiv:1605.07826v3, 2016. https://arxiv.org/abs/1605.07826 B. Leimkuhler and C. Matthews. Efficient molecular dynamics using geodesic integration and solvent–solute splitting. Proc. R. Soc. A. Vol. 472. No. 2189. The Royal Society, 2016. http://rspa.royalsocietypublishing.org/content/472/2189/20160138.abstract
simulating random samples with a given MLE One option would be to use a constrained HMC variant as described in A Family of MCMC Methods on Implicitly Defined Manifolds by Brubaker et al (1). This requires that we can express the condition tha
15,655
Why can't ridge regression provide better interpretability than LASSO?
If you order 1 million ridge-shrunk, scaled, but non-zero features, you will have to make some kind of decision: you will look at the n best predictors, but what is n? The LASSO solves this problem in a principled, objective way, because for every step on the path (and often, you'd settle on one point via e.g. cross validation), there are only m coefficients which are non-zero. Very often, you will train models on some data and then later apply it to some data not yet collected. For example, you could fit your model on 50.000.000 emails and then use that model on every new email. True, you will fit it on the full feature set for the first 50.000.000 mails, but for every following email, you will deal with a much sparser and faster, and much more memory efficient, model. You also won't even need to collect the information for the dropped features, which may be hugely helpful if the features are expensive to extract, e.g. via genotyping. Another perspective on the L1/L2 problem exposed by e.g. Andrew Gelman is that you often have some intuition what your problem may be like. In some circumstances, it is possible that reality is truly sparse. Maybe you have measured millions of genes, but it is plausible that only 30.000 of them actually determine dopamine metabolism. In such a situation, L1 arguably fits the problem better. In other cases, reality may be dense. For example, in psychology, "everything correlates (to some degree) with everything" (Paul Meehl). Preferences for apples vs. oranges probably does correlate with political leanings somehow - and even with IQ. Regularization might still make sense here, but true zero effects should be rare, so L2 might be more appropriate.
Why can't ridge regression provide better interpretability than LASSO?
If you order 1 million ridge-shrunk, scaled, but non-zero features, you will have to make some kind of decision: you will look at the n best predictors, but what is n? The LASSO solves this problem in
Why can't ridge regression provide better interpretability than LASSO? If you order 1 million ridge-shrunk, scaled, but non-zero features, you will have to make some kind of decision: you will look at the n best predictors, but what is n? The LASSO solves this problem in a principled, objective way, because for every step on the path (and often, you'd settle on one point via e.g. cross validation), there are only m coefficients which are non-zero. Very often, you will train models on some data and then later apply it to some data not yet collected. For example, you could fit your model on 50.000.000 emails and then use that model on every new email. True, you will fit it on the full feature set for the first 50.000.000 mails, but for every following email, you will deal with a much sparser and faster, and much more memory efficient, model. You also won't even need to collect the information for the dropped features, which may be hugely helpful if the features are expensive to extract, e.g. via genotyping. Another perspective on the L1/L2 problem exposed by e.g. Andrew Gelman is that you often have some intuition what your problem may be like. In some circumstances, it is possible that reality is truly sparse. Maybe you have measured millions of genes, but it is plausible that only 30.000 of them actually determine dopamine metabolism. In such a situation, L1 arguably fits the problem better. In other cases, reality may be dense. For example, in psychology, "everything correlates (to some degree) with everything" (Paul Meehl). Preferences for apples vs. oranges probably does correlate with political leanings somehow - and even with IQ. Regularization might still make sense here, but true zero effects should be rare, so L2 might be more appropriate.
Why can't ridge regression provide better interpretability than LASSO? If you order 1 million ridge-shrunk, scaled, but non-zero features, you will have to make some kind of decision: you will look at the n best predictors, but what is n? The LASSO solves this problem in
15,656
Why can't ridge regression provide better interpretability than LASSO?
Interpretability decreases if the target is dependent on lot of features. It increases if we can reduce the number of features as well maintain the accuracy. Ridge regularization does not have the ability to reduce number of features. But Lasso has the ability. How this happens is explained visually in the following link: Click Article on Towards Data Science
Why can't ridge regression provide better interpretability than LASSO?
Interpretability decreases if the target is dependent on lot of features. It increases if we can reduce the number of features as well maintain the accuracy. Ridge regularization does not have the abi
Why can't ridge regression provide better interpretability than LASSO? Interpretability decreases if the target is dependent on lot of features. It increases if we can reduce the number of features as well maintain the accuracy. Ridge regularization does not have the ability to reduce number of features. But Lasso has the ability. How this happens is explained visually in the following link: Click Article on Towards Data Science
Why can't ridge regression provide better interpretability than LASSO? Interpretability decreases if the target is dependent on lot of features. It increases if we can reduce the number of features as well maintain the accuracy. Ridge regularization does not have the abi
15,657
Why should one use EM vs. say, Gradient Descent with MLE?
I think there's some crossed wires here. The MLE, as referred to in the statistical literature, is the Maximum Likelihood Estimate. This is an estimator. The EM algorithm is, as the name implies, an algorithm which is often used to compute the MLE. These are apples and oranges. When the MLE is not in closed form, a commonly used algorithm for finding this is the Newton-Raphson algorithm, which may be what you are referring to when you state "can also be solved with MLE". In many problems, this algorithm works great; for "vanilla" problems, it's typically hard to beat. However, there are plenty of problems where it fails, such as mixture models. My experience with various computational problems has been that while the EM algorithm is not always the fastest choice, it's often the easiest for a variety of reasons. Many times with novel models, the first algorithm used to find the MLE will be an EM algorithm. Then, several years later, researchers may find that a significantly more complicated algorithm is significantly faster. But these algorithms are non-trival. Additionally, I speculate that much of the popularity of the EM-algorithm is the statistical flavor of it, helping statisticians feel differentiated from numerical analysts.
Why should one use EM vs. say, Gradient Descent with MLE?
I think there's some crossed wires here. The MLE, as referred to in the statistical literature, is the Maximum Likelihood Estimate. This is an estimator. The EM algorithm is, as the name implies, an a
Why should one use EM vs. say, Gradient Descent with MLE? I think there's some crossed wires here. The MLE, as referred to in the statistical literature, is the Maximum Likelihood Estimate. This is an estimator. The EM algorithm is, as the name implies, an algorithm which is often used to compute the MLE. These are apples and oranges. When the MLE is not in closed form, a commonly used algorithm for finding this is the Newton-Raphson algorithm, which may be what you are referring to when you state "can also be solved with MLE". In many problems, this algorithm works great; for "vanilla" problems, it's typically hard to beat. However, there are plenty of problems where it fails, such as mixture models. My experience with various computational problems has been that while the EM algorithm is not always the fastest choice, it's often the easiest for a variety of reasons. Many times with novel models, the first algorithm used to find the MLE will be an EM algorithm. Then, several years later, researchers may find that a significantly more complicated algorithm is significantly faster. But these algorithms are non-trival. Additionally, I speculate that much of the popularity of the EM-algorithm is the statistical flavor of it, helping statisticians feel differentiated from numerical analysts.
Why should one use EM vs. say, Gradient Descent with MLE? I think there's some crossed wires here. The MLE, as referred to in the statistical literature, is the Maximum Likelihood Estimate. This is an estimator. The EM algorithm is, as the name implies, an a
15,658
What is the problem with post-hoc testing?
"You know, the most amazing thing happened to me tonight. I was coming here, on the way to the lecture, and I came in through the parking lot. And you won't believe what happened. I saw a car with the license plate ARW 357. Can you imagine? Of all the millions of license plates in the state, what was the chance that I would see that particular one tonight? Amazing!" Richard Feynman I feel that I am not in position to explain the deep technical aspects of this problem. However I think many of them can be reduced to an intuition. In the first set up you start with some hypothesis which you verify on new data (from the designed experiment). Studying the sales figures can lead you to a very crafted well-designed experiment, where you really can decide how strong your answer should be (statistical power, p-values, sample size, and other many stuff). In the second set up first of all is that you decide nothing about the strength of the answer. This is one problem. The second problem is that extracting the hypothesis from the same sample used for tests, will increase in a very uncontrollable way the chances that random patterns are interpreted as valuable information. What you do is to notice something (that white cars are in great number) and ask yourself if this is significant. The point is that you selected only a notable fact visible on that sample, discarding other hypotheses. Doing that you created favourable conditions for some hypothesis, and you break the assumptions of most apriori statistical tests. It is not scientific to behave like you did not know about this leak, and pretend that it is an experiment with all its assumptions, when it is not true. It is scientific in this case to use post hoc analysis to formulate a hypothesis and design a brand new experiment in order to test it.
What is the problem with post-hoc testing?
"You know, the most amazing thing happened to me tonight. I was coming here, on the way to the lecture, and I came in through the parking lot. And you won't believe what happened. I saw a car with the
What is the problem with post-hoc testing? "You know, the most amazing thing happened to me tonight. I was coming here, on the way to the lecture, and I came in through the parking lot. And you won't believe what happened. I saw a car with the license plate ARW 357. Can you imagine? Of all the millions of license plates in the state, what was the chance that I would see that particular one tonight? Amazing!" Richard Feynman I feel that I am not in position to explain the deep technical aspects of this problem. However I think many of them can be reduced to an intuition. In the first set up you start with some hypothesis which you verify on new data (from the designed experiment). Studying the sales figures can lead you to a very crafted well-designed experiment, where you really can decide how strong your answer should be (statistical power, p-values, sample size, and other many stuff). In the second set up first of all is that you decide nothing about the strength of the answer. This is one problem. The second problem is that extracting the hypothesis from the same sample used for tests, will increase in a very uncontrollable way the chances that random patterns are interpreted as valuable information. What you do is to notice something (that white cars are in great number) and ask yourself if this is significant. The point is that you selected only a notable fact visible on that sample, discarding other hypotheses. Doing that you created favourable conditions for some hypothesis, and you break the assumptions of most apriori statistical tests. It is not scientific to behave like you did not know about this leak, and pretend that it is an experiment with all its assumptions, when it is not true. It is scientific in this case to use post hoc analysis to formulate a hypothesis and design a brand new experiment in order to test it.
What is the problem with post-hoc testing? "You know, the most amazing thing happened to me tonight. I was coming here, on the way to the lecture, and I came in through the parking lot. And you won't believe what happened. I saw a car with the
15,659
What is the problem with post-hoc testing?
If you first collect data and then construct a theory based on the data, you are in danger of fitting a story to your observations. The problem is that we humans are extremely good at writing stories. Put another way: any data can be "explained" by a story, if the story is just convoluted enough. This process provides for nice anecdotes. However, there is no reason why it should explain reality and/or provide good predictions. You need to set up and validate a model for that. xkcd notes that this phenomenon pervades sports "commentary": Related is the phenomenon of pareidolia: seeing patterns where none exist. See, for instance, the "Face" people saw in earlier satellite imagery of Mars: Plus, as you collect more data, you need to be careful you don't tweak your story in ever more bizarre ways to make it "continue" to "explain" your observations:
What is the problem with post-hoc testing?
If you first collect data and then construct a theory based on the data, you are in danger of fitting a story to your observations. The problem is that we humans are extremely good at writing stories.
What is the problem with post-hoc testing? If you first collect data and then construct a theory based on the data, you are in danger of fitting a story to your observations. The problem is that we humans are extremely good at writing stories. Put another way: any data can be "explained" by a story, if the story is just convoluted enough. This process provides for nice anecdotes. However, there is no reason why it should explain reality and/or provide good predictions. You need to set up and validate a model for that. xkcd notes that this phenomenon pervades sports "commentary": Related is the phenomenon of pareidolia: seeing patterns where none exist. See, for instance, the "Face" people saw in earlier satellite imagery of Mars: Plus, as you collect more data, you need to be careful you don't tweak your story in ever more bizarre ways to make it "continue" to "explain" your observations:
What is the problem with post-hoc testing? If you first collect data and then construct a theory based on the data, you are in danger of fitting a story to your observations. The problem is that we humans are extremely good at writing stories.
15,660
What is the problem with post-hoc testing?
Science operates by forming hypotheses (which are of course are motivated by experience), making predictions based on those hypotheses and then testing them. Would it make sense to observe something in the past, generalize this observation into a theory, but then treat the past itself as a kind of retroactive experiment that automatically validates the theory? No, because the whole question was how well your theory generalizes, not whether or not it worked once in the past. This is why testing hypotheses suggested by the data is considered bad science.
What is the problem with post-hoc testing?
Science operates by forming hypotheses (which are of course are motivated by experience), making predictions based on those hypotheses and then testing them. Would it make sense to observe something
What is the problem with post-hoc testing? Science operates by forming hypotheses (which are of course are motivated by experience), making predictions based on those hypotheses and then testing them. Would it make sense to observe something in the past, generalize this observation into a theory, but then treat the past itself as a kind of retroactive experiment that automatically validates the theory? No, because the whole question was how well your theory generalizes, not whether or not it worked once in the past. This is why testing hypotheses suggested by the data is considered bad science.
What is the problem with post-hoc testing? Science operates by forming hypotheses (which are of course are motivated by experience), making predictions based on those hypotheses and then testing them. Would it make sense to observe something
15,661
What is the problem with post-hoc testing?
Your professor and the other answers are right that post-hoc analysis have problems. However, you are also right that a lot of good science comes from post-hoc analysis. The key point is that properly designed experiments should be preferred and that post-hoc analysis should be dealt with caution and with special tools to prevent missing spurious artefacts by actual discoveries. Wikipedia article on false discovery rate may give an insight on the problem. Just to give a couple of examples: If we take biometric measures on the whole world population of cattle we can conclude that cattle have two nostrils. That is in fact a post-hoc analysis, but most of biology, volcanology or history has been built this way. The reason we don't dismiss the fact that cattle have two nostrils is the evidence in favour of it being so overwhelming. We take data from calves born in previous year in a given cattle farm. We realise that in every Tuesday under the full moon more than 50% of new born calves were female - except for public holidays in that country or winter Tuesdays. If we had previously made the hypothesis that those kinds of days produced more female calves, we could do an hypothesis test and accept (or reject) that hypothesis. However, if we take in account that it is just a post-hoc analysis, evidence won't be enough to reject an spurious phenomenon. There is an often cited article that ironically dismisses all evidence of parachutes being useful as anecdotal - which is just a particularly bad class of evidence based on post-hoc analysis. And to use a good example used by Stephan Kolassa's answer: a few dark spots resembling a face in Mars can be rejected as pareidolia, but something reproducing the Last Supper by Leonardo Da Vinci to the tinniest detail couldn't.
What is the problem with post-hoc testing?
Your professor and the other answers are right that post-hoc analysis have problems. However, you are also right that a lot of good science comes from post-hoc analysis. The key point is that properly
What is the problem with post-hoc testing? Your professor and the other answers are right that post-hoc analysis have problems. However, you are also right that a lot of good science comes from post-hoc analysis. The key point is that properly designed experiments should be preferred and that post-hoc analysis should be dealt with caution and with special tools to prevent missing spurious artefacts by actual discoveries. Wikipedia article on false discovery rate may give an insight on the problem. Just to give a couple of examples: If we take biometric measures on the whole world population of cattle we can conclude that cattle have two nostrils. That is in fact a post-hoc analysis, but most of biology, volcanology or history has been built this way. The reason we don't dismiss the fact that cattle have two nostrils is the evidence in favour of it being so overwhelming. We take data from calves born in previous year in a given cattle farm. We realise that in every Tuesday under the full moon more than 50% of new born calves were female - except for public holidays in that country or winter Tuesdays. If we had previously made the hypothesis that those kinds of days produced more female calves, we could do an hypothesis test and accept (or reject) that hypothesis. However, if we take in account that it is just a post-hoc analysis, evidence won't be enough to reject an spurious phenomenon. There is an often cited article that ironically dismisses all evidence of parachutes being useful as anecdotal - which is just a particularly bad class of evidence based on post-hoc analysis. And to use a good example used by Stephan Kolassa's answer: a few dark spots resembling a face in Mars can be rejected as pareidolia, but something reproducing the Last Supper by Leonardo Da Vinci to the tinniest detail couldn't.
What is the problem with post-hoc testing? Your professor and the other answers are right that post-hoc analysis have problems. However, you are also right that a lot of good science comes from post-hoc analysis. The key point is that properly
15,662
What is the problem with post-hoc testing?
If you don't have a theory backing your propositions, then even if your proposition is validated, it could be through coincidence and does not prove anything. For example, I find that I do potty when the sun rises and have been doing that for the past 10 years - based on this data, a post-hoc analysis tells me that there is a relationship between my doing potty and the sun rising, whereas what exists is merely a coincidence. The sun doesn't rise because you do potty or vice-versa. Life is full of coincidences. Theory backed propositions eliminates such coincidences or pseudo-relationships.
What is the problem with post-hoc testing?
If you don't have a theory backing your propositions, then even if your proposition is validated, it could be through coincidence and does not prove anything. For example, I find that I do potty when
What is the problem with post-hoc testing? If you don't have a theory backing your propositions, then even if your proposition is validated, it could be through coincidence and does not prove anything. For example, I find that I do potty when the sun rises and have been doing that for the past 10 years - based on this data, a post-hoc analysis tells me that there is a relationship between my doing potty and the sun rising, whereas what exists is merely a coincidence. The sun doesn't rise because you do potty or vice-versa. Life is full of coincidences. Theory backed propositions eliminates such coincidences or pseudo-relationships.
What is the problem with post-hoc testing? If you don't have a theory backing your propositions, then even if your proposition is validated, it could be through coincidence and does not prove anything. For example, I find that I do potty when
15,663
What is the problem with post-hoc testing?
Here is an intuition that you may find useful. If you are bored and count cars, you still have to remember that what you see is the result of some random process. In particular, the cars could have been different colors. Therefore if you form the hypothesis that the most frequent color is white, if may be because it actually is but it could also be that the most frequent color is red but, on that particular experiment, the most frequent was white (which is always possible). Now, if you do post-hoc, you will test for white being the most frequent and, given that the data suggested that very hypothesis, you may well conclude that white is the most frequent... At least, the data will never contradict the (post-hoc) hypothesis.
What is the problem with post-hoc testing?
Here is an intuition that you may find useful. If you are bored and count cars, you still have to remember that what you see is the result of some random process. In particular, the cars could have be
What is the problem with post-hoc testing? Here is an intuition that you may find useful. If you are bored and count cars, you still have to remember that what you see is the result of some random process. In particular, the cars could have been different colors. Therefore if you form the hypothesis that the most frequent color is white, if may be because it actually is but it could also be that the most frequent color is red but, on that particular experiment, the most frequent was white (which is always possible). Now, if you do post-hoc, you will test for white being the most frequent and, given that the data suggested that very hypothesis, you may well conclude that white is the most frequent... At least, the data will never contradict the (post-hoc) hypothesis.
What is the problem with post-hoc testing? Here is an intuition that you may find useful. If you are bored and count cars, you still have to remember that what you see is the result of some random process. In particular, the cars could have be
15,664
Real examples of Correlation confused with Causation
For many years large observational epidemiological studies interpreted by researchers using Bradford Hill-style heuristic criteria for inferring causation asserted evidence that hormone replacement therapy (HRT) in females decreased risk of coronary heart disease, and it was only after two large scale randomized trials demonstrated the opposite, that clinical understanding and clinical recommendations regarding HRT changed. This a classic cautionary tale in contemporary epidemiology that you can read about in textbooks (e.g., Leon Gordis' Epidemiology), and on the Wikipedia article on David Hume's classic maxim. That said, The Bradford Hill criteria have not been understood as the state of the art for a good while now, with counterfactual causal inference (a la Judea Pearl, Jamie Robbins, Sander Greenland, and others) being the really heavy lifter. It is possible to make reasonably strong causal inferences without conducting randomized experiments, using, for example, instrumental variables, Mendelian randomization, etc. (which is good for science, since we cannot conduct randomized experiments on much, if not most, of the universe).
Real examples of Correlation confused with Causation
For many years large observational epidemiological studies interpreted by researchers using Bradford Hill-style heuristic criteria for inferring causation asserted evidence that hormone replacement th
Real examples of Correlation confused with Causation For many years large observational epidemiological studies interpreted by researchers using Bradford Hill-style heuristic criteria for inferring causation asserted evidence that hormone replacement therapy (HRT) in females decreased risk of coronary heart disease, and it was only after two large scale randomized trials demonstrated the opposite, that clinical understanding and clinical recommendations regarding HRT changed. This a classic cautionary tale in contemporary epidemiology that you can read about in textbooks (e.g., Leon Gordis' Epidemiology), and on the Wikipedia article on David Hume's classic maxim. That said, The Bradford Hill criteria have not been understood as the state of the art for a good while now, with counterfactual causal inference (a la Judea Pearl, Jamie Robbins, Sander Greenland, and others) being the really heavy lifter. It is possible to make reasonably strong causal inferences without conducting randomized experiments, using, for example, instrumental variables, Mendelian randomization, etc. (which is good for science, since we cannot conduct randomized experiments on much, if not most, of the universe).
Real examples of Correlation confused with Causation For many years large observational epidemiological studies interpreted by researchers using Bradford Hill-style heuristic criteria for inferring causation asserted evidence that hormone replacement th
15,665
Real examples of Correlation confused with Causation
Not the most glamorous topic, but Nora T. Gedgaudas (Ch. 18) summarizes very nicely the turnaround in findings about fiber's role in preventing colon cancer. Fiber, widely thought for 25 years to be an important preventative factor (based on correlation), was shown through the 16-year, 88,000-subject Nurses' Study to be merely a correlate of other factors that mattered. These included the consumption of fruits and vegetables high in certain nutrients (which decrease risk) and of red meat and especially processed red meat (which increase risk). The author notes that the myth "seems to doggedly persist, nonetheless," even among doctors. As so often happens, once word of a pattern gets out, it's very difficult to eradicate the idea.
Real examples of Correlation confused with Causation
Not the most glamorous topic, but Nora T. Gedgaudas (Ch. 18) summarizes very nicely the turnaround in findings about fiber's role in preventing colon cancer. Fiber, widely thought for 25 years to be
Real examples of Correlation confused with Causation Not the most glamorous topic, but Nora T. Gedgaudas (Ch. 18) summarizes very nicely the turnaround in findings about fiber's role in preventing colon cancer. Fiber, widely thought for 25 years to be an important preventative factor (based on correlation), was shown through the 16-year, 88,000-subject Nurses' Study to be merely a correlate of other factors that mattered. These included the consumption of fruits and vegetables high in certain nutrients (which decrease risk) and of red meat and especially processed red meat (which increase risk). The author notes that the myth "seems to doggedly persist, nonetheless," even among doctors. As so often happens, once word of a pattern gets out, it's very difficult to eradicate the idea.
Real examples of Correlation confused with Causation Not the most glamorous topic, but Nora T. Gedgaudas (Ch. 18) summarizes very nicely the turnaround in findings about fiber's role in preventing colon cancer. Fiber, widely thought for 25 years to be
15,666
Real examples of Correlation confused with Causation
Pellagra According to this book chapter, pellagra, a disease characterized by dizziness, lethargy, running sores, vomiting, and severe diarrhea that had reached epidemic proportions in the US South by the early 1900s, was widely attributed to an unknown pathogen on the basis of a correlation with unsanitary living conditions. Dr. Joseph Goldberger was instrumental in showing experimentally that the disease was, in fact, caused by a poor diet, which (along with unsanitary living conditions) stemmed from widespread poverty in the postbellum South. His work was largely ignored until the late 1930s, when researchers finally proved that the disease was caused by a lack of niacin. Ocular Literacy Training From the same source - a correlation between reading (in)ability and erratic eye movements during reading was taken as evidence of a causal relationship in the wrong direction, and "eye movement training programs" were implemented to improve literacy. These were ineffective, and later work showed that causality runs in the opposite direction; reading difficulties lead to the regressions and fixations observed in poor readers.
Real examples of Correlation confused with Causation
Pellagra According to this book chapter, pellagra, a disease characterized by dizziness, lethargy, running sores, vomiting, and severe diarrhea that had reached epidemic proportions in the US South by
Real examples of Correlation confused with Causation Pellagra According to this book chapter, pellagra, a disease characterized by dizziness, lethargy, running sores, vomiting, and severe diarrhea that had reached epidemic proportions in the US South by the early 1900s, was widely attributed to an unknown pathogen on the basis of a correlation with unsanitary living conditions. Dr. Joseph Goldberger was instrumental in showing experimentally that the disease was, in fact, caused by a poor diet, which (along with unsanitary living conditions) stemmed from widespread poverty in the postbellum South. His work was largely ignored until the late 1930s, when researchers finally proved that the disease was caused by a lack of niacin. Ocular Literacy Training From the same source - a correlation between reading (in)ability and erratic eye movements during reading was taken as evidence of a causal relationship in the wrong direction, and "eye movement training programs" were implemented to improve literacy. These were ineffective, and later work showed that causality runs in the opposite direction; reading difficulties lead to the regressions and fixations observed in poor readers.
Real examples of Correlation confused with Causation Pellagra According to this book chapter, pellagra, a disease characterized by dizziness, lethargy, running sores, vomiting, and severe diarrhea that had reached epidemic proportions in the US South by
15,667
How to perform a bootstrap test to compare the means of two samples?
I would just do a regular bootstrap test: compute the t-statistic in your data and store it change the data such that the null-hypothesis is true. In this case, subtract the mean in group 1 for group 1 and add the overall mean, and do the same for group 2, that way the means in both group will be the overall mean. Take bootstrap samples from this dataset, probably in the order of 20,000. compute the t-statistic in each of these bootstrap samples. The distribution of these t-statistics is the bootstrap estimate of the sampling distribution of the t-statistic in your skewed data if the null-hypothesis is true. The proportion of bootstrap t-statistics that is larger than or equal to your observed t-statistic is your estimate of the $p$-value. You can do a bit better by looking at $($the number of bootstrap t-statistics that are larger than or equal to the observed t-statistic $+1)$ divided by $($the number of bootstrap samples $+1)$. However, the difference is going to be small when the number of bootstrap samples is large. You can read more on that in: Chapter 4 of A.C. Davison and D.V. Hinkley (1997) Bootstrap Methods and their Application. Cambridge: Cambridge University Press. Chapter 16 of Bradley Efron and Robert J. Tibshirani (1993) An Introduction to the Bootstrap. Boca Raton: Chapman & Hall/CRC. Wikipedia entry on bootstrap hypothesis testing.
How to perform a bootstrap test to compare the means of two samples?
I would just do a regular bootstrap test: compute the t-statistic in your data and store it change the data such that the null-hypothesis is true. In this case, subtract the mean in group 1 for group
How to perform a bootstrap test to compare the means of two samples? I would just do a regular bootstrap test: compute the t-statistic in your data and store it change the data such that the null-hypothesis is true. In this case, subtract the mean in group 1 for group 1 and add the overall mean, and do the same for group 2, that way the means in both group will be the overall mean. Take bootstrap samples from this dataset, probably in the order of 20,000. compute the t-statistic in each of these bootstrap samples. The distribution of these t-statistics is the bootstrap estimate of the sampling distribution of the t-statistic in your skewed data if the null-hypothesis is true. The proportion of bootstrap t-statistics that is larger than or equal to your observed t-statistic is your estimate of the $p$-value. You can do a bit better by looking at $($the number of bootstrap t-statistics that are larger than or equal to the observed t-statistic $+1)$ divided by $($the number of bootstrap samples $+1)$. However, the difference is going to be small when the number of bootstrap samples is large. You can read more on that in: Chapter 4 of A.C. Davison and D.V. Hinkley (1997) Bootstrap Methods and their Application. Cambridge: Cambridge University Press. Chapter 16 of Bradley Efron and Robert J. Tibshirani (1993) An Introduction to the Bootstrap. Boca Raton: Chapman & Hall/CRC. Wikipedia entry on bootstrap hypothesis testing.
How to perform a bootstrap test to compare the means of two samples? I would just do a regular bootstrap test: compute the t-statistic in your data and store it change the data such that the null-hypothesis is true. In this case, subtract the mean in group 1 for group
15,668
How to scale new observations for making predictions when the model was fitted with scaled data?
The short answer to your question is, yes - that expression for scaled.new is correct (except you wanted sd instead of std). It may be worth noting that scale has optional arguments which you could use: scaled.new <- scale(new, center = mean(data), scale = sd(data)) Also, the object returned by scale (scaled.data) has attributes holding the numeric centering and scalings used (if any), which you could use: scaled.new <- scale(new, attr(scaled.data, "scaled:center"), attr(scaled.data, "scaled:scale")) The advantage of that appears when the original data has more than one column, so there are multiple means and/or standard deviations to consider.
How to scale new observations for making predictions when the model was fitted with scaled data?
The short answer to your question is, yes - that expression for scaled.new is correct (except you wanted sd instead of std). It may be worth noting that scale has optional arguments which you could us
How to scale new observations for making predictions when the model was fitted with scaled data? The short answer to your question is, yes - that expression for scaled.new is correct (except you wanted sd instead of std). It may be worth noting that scale has optional arguments which you could use: scaled.new <- scale(new, center = mean(data), scale = sd(data)) Also, the object returned by scale (scaled.data) has attributes holding the numeric centering and scalings used (if any), which you could use: scaled.new <- scale(new, attr(scaled.data, "scaled:center"), attr(scaled.data, "scaled:scale")) The advantage of that appears when the original data has more than one column, so there are multiple means and/or standard deviations to consider.
How to scale new observations for making predictions when the model was fitted with scaled data? The short answer to your question is, yes - that expression for scaled.new is correct (except you wanted sd instead of std). It may be worth noting that scale has optional arguments which you could us
15,669
How to scale new observations for making predictions when the model was fitted with scaled data?
There are now simpler ways to do this. For example, the preprocess function of the caret package library(caret) preproc <- preProcess(data, method = c("center", "scale") scaled.new <- predict(preproc, newdata = new) or scale_by in the standardize package or using the receipes package library(recipes); library(dplyr) rec <- recipe(~ ., data) %>% step_normalize(all_numeric()) %>% prep() scaled.new <- rec %>% bake(new)
How to scale new observations for making predictions when the model was fitted with scaled data?
There are now simpler ways to do this. For example, the preprocess function of the caret package library(caret) preproc <- preProcess(data, method = c("center", "scale") scaled.new <- predict(preproc,
How to scale new observations for making predictions when the model was fitted with scaled data? There are now simpler ways to do this. For example, the preprocess function of the caret package library(caret) preproc <- preProcess(data, method = c("center", "scale") scaled.new <- predict(preproc, newdata = new) or scale_by in the standardize package or using the receipes package library(recipes); library(dplyr) rec <- recipe(~ ., data) %>% step_normalize(all_numeric()) %>% prep() scaled.new <- rec %>% bake(new)
How to scale new observations for making predictions when the model was fitted with scaled data? There are now simpler ways to do this. For example, the preprocess function of the caret package library(caret) preproc <- preProcess(data, method = c("center", "scale") scaled.new <- predict(preproc,
15,670
Impact of data-based bin boundaries on a chi-square goodness of fit test?
The basic results of chi-square goodness-of-fit testing can be understood hierarchically. Level 0. The classical Pearson's chi-square test statistic for testing a multinomial sample against a fixed probability vector $p$ is $$ X^2(p) = \sum_{i=1}^k \frac{(X^{(n)}_i - n p_i)^2}{n p_i} \stackrel{d}{\to} \chi_{k-1}^2 \>, $$ where $X_i^{(n)}$ denotes the number of outcomes in the $i$th cell out of a sample of size $n$. This can be fruitfully viewed as the squared norm of the vector $\mathbf Y_n = (Y_1^{(n)},\ldots,Y_k^{(n)})$ where $Y_i^{(n)} = (X_i^{(n)} - n p_i)/\sqrt{n p_i}$ which, by the multivariate central limit theorem converges in distribution as $$ \mathbf Y_n \stackrel{d}{\to} \mathcal N(0, \mathbf I - \sqrt{p}\sqrt{p}^T) \>. $$ From this we see that $X^2 = \|\mathbf Y_n\|^2 \to \chi^2_{k-1}$ since $\mathbf I - \sqrt{p}\sqrt{p}^T$ is idempotent of rank $k-1$. Level 1. At the next level of the hierarchy, we consider composite hypotheses with multinomial samples. Since the exact $p$ of interest is unknown under the null hypothesis, we have to estimate it. If the null hypothesis is composite and composed of a linear subspace of dimension $m$, then maximum likelihood estimates (or other efficient estimators) of the $p_i$ can be used as "plug-in" estimators. Then, the statistic $$ X^2_1 = \sum_{i=1}^k \frac{(X^{(n)}_i - n \hat{p}_i)^2}{n \hat{p}_i} \stackrel{d}{\to} \chi_{k-m - 1}^2 \>, $$ under the null hypothesis. Level 2. Consider the case of goodness of fit testing of a parametric model where the cells are fixed and known in advance: For example, we have a sample from an exponential distribution with rate $\lambda$ and from this we produce a multinomial sample by binning over $k$ cells, then the above result still holds provided that we use efficient estimates (e.g., MLEs) of the bin probabilities themselves using only the observed frequencies. If the number of parameters for the distribution is $m$ (e.g., $m = 1$ in the exponential case), then $$ X^2_2 = \sum_{i=1}^k \frac{(X^{(n)}_i - n \hat{p}_i)^2}{n \hat{p}_i} \stackrel{d}{\to} \chi_{k-m - 1}^2 \>, $$ where here $\hat{p}_i$ can be taken to be the MLEs of the cell probabilities of the fixed, known cells corresponding to the given distribution of interest. Level 3. But, wait! If we have a sample $Z_1,\ldots,Z_n \sim F_\lambda$, why shouldn't we estimate $\lambda$ efficiently first, and then use a chi-square statistic with our fixed, known cells? Well, we can, but in general we no longer get a chi-square distribution for the corresponding chi-square statistic. In fact, Chernoff and Lehmann (1954) showed that using MLEs to estimate the parameters and then plugging them back in to get estimates of the cell probabilities results in a non-chi-square distribution, in general. Under suitable regularity conditions, the distribution is (stochastically) between a $\chi_{k-m-1}^2$ and a $\chi_{k-1}^2$ random variable, with the distribution depending on the parameters. Untuitively, this means that the limiting distribution of $\mathbf Y_n$ is $\mathcal N(0, \mathbf I - \sqrt{p_\lambda}\sqrt{p_\lambda}^T - \mathbf A(\lambda))$. We haven't even talked about random cell boundaries yet, and we're already in a bit of a tight spot! There are two ways out: One is to retreat back to Level 2, or at the very least not use efficient estimators (like MLEs) of the underlying parameters $\lambda$. The second approach is to try to undo the effects of $\mathbf A(\lambda)$ in such a way as to recover a chi-square distribution. There are several ways of going the latter route. They basically amount to premultiplying $\mathbf Y_n$ by the "right" matrix $\mathbf B(\hat{\lambda})$. Then, the quadratic form $$ \mathbf Y_n^T \mathbf B^T \mathbf B \mathbf Y_n \stackrel{d}{\to} \chi_{k-1}^2 \>, $$ where $k$ is the number of cells. Examples are the Rao–Robson–Nikulin statistic and the Dzhaparidze–Nikulin statistic. Level 4. Random cells. In the case of random cells, under certain regularity conditions, we end up in the same situation as in Level 3 if we take the route of modifying the Pearson chi-square statistic. Location-scale families, in particular, behave very nicely. One common approach is to take our $k$ cells each to have probability $1/k$, nominally. So, our random cells are intervals of the form $\hat{I}_j = \hat \mu + \hat\sigma I_{0,j}$ where $I_{0,j} = [F^{-1}((j-1)/k), F^{-1}(j/k))$. This result has been further extended to the case where the number of random cells grows with the sample size. References A W. van der Vaart (1998), Asymptotic Statistics, Cambridge University Press. Chapter 17: Chi-Square Tests. H. Chernoff and E. L. Lehmann (1954), The use of maximum likelihood estimates in $\chi^2$ tests for goodness of fit, Ann. Math. Statist., vol. 25, no. 3, 579–586. F. C. Drost (1989), Generalized chi-square goodness-of-fit tests for location-scale models when the number of classes tends to infinity, Ann. Stat, vol. 17, no. 3, 1285–1300. M. S. Nikulin, M.S. (1973), Chi-square test for continuous distribution with shift and scale parameters, Theory of Probability and its Application, vol. 19, no. 3, 559–568. K. O. Dzaparidze and M. S. Nikulin (1973), On a modification of the standard statistics of Pearson, Theory of Probability and its Application, vol. 19, no. 4, 851–853. K. C. Rao and D. S. Robson (1974), A chi-square statistic for goodness of fit tests within exponential family, Comm. Statist., vol 3., no. 12, 1139–1153. N. Balakrishnan, V. Voinov and M. S. Nikulin (2013), Chi-Squared Goodness of Fit Tests With Applications, Academic Press.
Impact of data-based bin boundaries on a chi-square goodness of fit test?
The basic results of chi-square goodness-of-fit testing can be understood hierarchically. Level 0. The classical Pearson's chi-square test statistic for testing a multinomial sample against a fixed pr
Impact of data-based bin boundaries on a chi-square goodness of fit test? The basic results of chi-square goodness-of-fit testing can be understood hierarchically. Level 0. The classical Pearson's chi-square test statistic for testing a multinomial sample against a fixed probability vector $p$ is $$ X^2(p) = \sum_{i=1}^k \frac{(X^{(n)}_i - n p_i)^2}{n p_i} \stackrel{d}{\to} \chi_{k-1}^2 \>, $$ where $X_i^{(n)}$ denotes the number of outcomes in the $i$th cell out of a sample of size $n$. This can be fruitfully viewed as the squared norm of the vector $\mathbf Y_n = (Y_1^{(n)},\ldots,Y_k^{(n)})$ where $Y_i^{(n)} = (X_i^{(n)} - n p_i)/\sqrt{n p_i}$ which, by the multivariate central limit theorem converges in distribution as $$ \mathbf Y_n \stackrel{d}{\to} \mathcal N(0, \mathbf I - \sqrt{p}\sqrt{p}^T) \>. $$ From this we see that $X^2 = \|\mathbf Y_n\|^2 \to \chi^2_{k-1}$ since $\mathbf I - \sqrt{p}\sqrt{p}^T$ is idempotent of rank $k-1$. Level 1. At the next level of the hierarchy, we consider composite hypotheses with multinomial samples. Since the exact $p$ of interest is unknown under the null hypothesis, we have to estimate it. If the null hypothesis is composite and composed of a linear subspace of dimension $m$, then maximum likelihood estimates (or other efficient estimators) of the $p_i$ can be used as "plug-in" estimators. Then, the statistic $$ X^2_1 = \sum_{i=1}^k \frac{(X^{(n)}_i - n \hat{p}_i)^2}{n \hat{p}_i} \stackrel{d}{\to} \chi_{k-m - 1}^2 \>, $$ under the null hypothesis. Level 2. Consider the case of goodness of fit testing of a parametric model where the cells are fixed and known in advance: For example, we have a sample from an exponential distribution with rate $\lambda$ and from this we produce a multinomial sample by binning over $k$ cells, then the above result still holds provided that we use efficient estimates (e.g., MLEs) of the bin probabilities themselves using only the observed frequencies. If the number of parameters for the distribution is $m$ (e.g., $m = 1$ in the exponential case), then $$ X^2_2 = \sum_{i=1}^k \frac{(X^{(n)}_i - n \hat{p}_i)^2}{n \hat{p}_i} \stackrel{d}{\to} \chi_{k-m - 1}^2 \>, $$ where here $\hat{p}_i$ can be taken to be the MLEs of the cell probabilities of the fixed, known cells corresponding to the given distribution of interest. Level 3. But, wait! If we have a sample $Z_1,\ldots,Z_n \sim F_\lambda$, why shouldn't we estimate $\lambda$ efficiently first, and then use a chi-square statistic with our fixed, known cells? Well, we can, but in general we no longer get a chi-square distribution for the corresponding chi-square statistic. In fact, Chernoff and Lehmann (1954) showed that using MLEs to estimate the parameters and then plugging them back in to get estimates of the cell probabilities results in a non-chi-square distribution, in general. Under suitable regularity conditions, the distribution is (stochastically) between a $\chi_{k-m-1}^2$ and a $\chi_{k-1}^2$ random variable, with the distribution depending on the parameters. Untuitively, this means that the limiting distribution of $\mathbf Y_n$ is $\mathcal N(0, \mathbf I - \sqrt{p_\lambda}\sqrt{p_\lambda}^T - \mathbf A(\lambda))$. We haven't even talked about random cell boundaries yet, and we're already in a bit of a tight spot! There are two ways out: One is to retreat back to Level 2, or at the very least not use efficient estimators (like MLEs) of the underlying parameters $\lambda$. The second approach is to try to undo the effects of $\mathbf A(\lambda)$ in such a way as to recover a chi-square distribution. There are several ways of going the latter route. They basically amount to premultiplying $\mathbf Y_n$ by the "right" matrix $\mathbf B(\hat{\lambda})$. Then, the quadratic form $$ \mathbf Y_n^T \mathbf B^T \mathbf B \mathbf Y_n \stackrel{d}{\to} \chi_{k-1}^2 \>, $$ where $k$ is the number of cells. Examples are the Rao–Robson–Nikulin statistic and the Dzhaparidze–Nikulin statistic. Level 4. Random cells. In the case of random cells, under certain regularity conditions, we end up in the same situation as in Level 3 if we take the route of modifying the Pearson chi-square statistic. Location-scale families, in particular, behave very nicely. One common approach is to take our $k$ cells each to have probability $1/k$, nominally. So, our random cells are intervals of the form $\hat{I}_j = \hat \mu + \hat\sigma I_{0,j}$ where $I_{0,j} = [F^{-1}((j-1)/k), F^{-1}(j/k))$. This result has been further extended to the case where the number of random cells grows with the sample size. References A W. van der Vaart (1998), Asymptotic Statistics, Cambridge University Press. Chapter 17: Chi-Square Tests. H. Chernoff and E. L. Lehmann (1954), The use of maximum likelihood estimates in $\chi^2$ tests for goodness of fit, Ann. Math. Statist., vol. 25, no. 3, 579–586. F. C. Drost (1989), Generalized chi-square goodness-of-fit tests for location-scale models when the number of classes tends to infinity, Ann. Stat, vol. 17, no. 3, 1285–1300. M. S. Nikulin, M.S. (1973), Chi-square test for continuous distribution with shift and scale parameters, Theory of Probability and its Application, vol. 19, no. 3, 559–568. K. O. Dzaparidze and M. S. Nikulin (1973), On a modification of the standard statistics of Pearson, Theory of Probability and its Application, vol. 19, no. 4, 851–853. K. C. Rao and D. S. Robson (1974), A chi-square statistic for goodness of fit tests within exponential family, Comm. Statist., vol 3., no. 12, 1139–1153. N. Balakrishnan, V. Voinov and M. S. Nikulin (2013), Chi-Squared Goodness of Fit Tests With Applications, Academic Press.
Impact of data-based bin boundaries on a chi-square goodness of fit test? The basic results of chi-square goodness-of-fit testing can be understood hierarchically. Level 0. The classical Pearson's chi-square test statistic for testing a multinomial sample against a fixed pr
15,671
Impact of data-based bin boundaries on a chi-square goodness of fit test?
I've found at least partial answers to my question, below. (I'd still like to give someone that bonus, so any further information appreciated.) Moore (1971) said that Roy (1956) and Watson (1957,58,59) showed that when the cell boundaries for a chi-square statistic are functions of best asymptotic normal estimated parameter values, then under certain conditions, the asymptotic null distribution of the chi-square statistic is still that of a sum of a $\chi^2_{k-p-1}$ and a weighted sum of $p$ $\chi^2_1$ variables (for $k$ cells, $p$ parameters) where the weights are between 0 and 1 (making the cdf of the distribution between that of a $\chi^2_{k-p}$ and a $\chi^2_{k}$, as alluded to in my question for the distribution when using ML estimation), and the weights on those last $p$ terms are unaffected by that estimation. References Moore D.S. (1971), A Chi-Square Statistic with Random Cell Boundaries, Ann. Math. Stat., Vol 42, No 1, 147–156. Roy A.R. (1956), On $\chi^2$ statistics with variable intervals, Technical Report No. 1, Dept of Statistics, Stanford University. Watson, G.S. (1957), The $\chi^2$ goodness-of-fit test for normal distributions, Biometrika, 44, 336–348. Watson, G.S. (1958), On $\chi^2$ goodness-of-fit tests for continuous distributions, J. Royal Statist. Soc. B, 20, 44–61. Watson, G.S. (1959), Some recent results in $\chi^2$ goodness-of- fit tests, Biometrics, 15, 440-468
Impact of data-based bin boundaries on a chi-square goodness of fit test?
I've found at least partial answers to my question, below. (I'd still like to give someone that bonus, so any further information appreciated.) Moore (1971) said that Roy (1956) and Watson (1957,58,59
Impact of data-based bin boundaries on a chi-square goodness of fit test? I've found at least partial answers to my question, below. (I'd still like to give someone that bonus, so any further information appreciated.) Moore (1971) said that Roy (1956) and Watson (1957,58,59) showed that when the cell boundaries for a chi-square statistic are functions of best asymptotic normal estimated parameter values, then under certain conditions, the asymptotic null distribution of the chi-square statistic is still that of a sum of a $\chi^2_{k-p-1}$ and a weighted sum of $p$ $\chi^2_1$ variables (for $k$ cells, $p$ parameters) where the weights are between 0 and 1 (making the cdf of the distribution between that of a $\chi^2_{k-p}$ and a $\chi^2_{k}$, as alluded to in my question for the distribution when using ML estimation), and the weights on those last $p$ terms are unaffected by that estimation. References Moore D.S. (1971), A Chi-Square Statistic with Random Cell Boundaries, Ann. Math. Stat., Vol 42, No 1, 147–156. Roy A.R. (1956), On $\chi^2$ statistics with variable intervals, Technical Report No. 1, Dept of Statistics, Stanford University. Watson, G.S. (1957), The $\chi^2$ goodness-of-fit test for normal distributions, Biometrika, 44, 336–348. Watson, G.S. (1958), On $\chi^2$ goodness-of-fit tests for continuous distributions, J. Royal Statist. Soc. B, 20, 44–61. Watson, G.S. (1959), Some recent results in $\chi^2$ goodness-of- fit tests, Biometrics, 15, 440-468
Impact of data-based bin boundaries on a chi-square goodness of fit test? I've found at least partial answers to my question, below. (I'd still like to give someone that bonus, so any further information appreciated.) Moore (1971) said that Roy (1956) and Watson (1957,58,59
15,672
Periods in history of statistics
These recent papers by Stigler, where he argues (convincingly I believe) for the types of periods you seem to have in mind. Stigler, Stephen M. 2010. Darwin, Galton and the statistical enlightenment. Journal of the Royal Statistical Society: Series A 173(3):469-482. Stigler, Stephen M. 2012. Studies in the history of probability and statistics, L: Karl Pearson and the Rule of Three. Biometrika 99(1): 1-14.
Periods in history of statistics
These recent papers by Stigler, where he argues (convincingly I believe) for the types of periods you seem to have in mind. Stigler, Stephen M. 2010. Darwin, Galton and the statistical enlightenme
Periods in history of statistics These recent papers by Stigler, where he argues (convincingly I believe) for the types of periods you seem to have in mind. Stigler, Stephen M. 2010. Darwin, Galton and the statistical enlightenment. Journal of the Royal Statistical Society: Series A 173(3):469-482. Stigler, Stephen M. 2012. Studies in the history of probability and statistics, L: Karl Pearson and the Rule of Three. Biometrika 99(1): 1-14.
Periods in history of statistics These recent papers by Stigler, where he argues (convincingly I believe) for the types of periods you seem to have in mind. Stigler, Stephen M. 2010. Darwin, Galton and the statistical enlightenme
15,673
Periods in history of statistics
I think that "periods" in history are closely related to people and their developments. Of course one can expect "waves" in Toffler's sense, but even those waves are related to persons. Anyway, wikipedia has an article in this regard.
Periods in history of statistics
I think that "periods" in history are closely related to people and their developments. Of course one can expect "waves" in Toffler's sense, but even those waves are related to persons. Anyway, wikip
Periods in history of statistics I think that "periods" in history are closely related to people and their developments. Of course one can expect "waves" in Toffler's sense, but even those waves are related to persons. Anyway, wikipedia has an article in this regard.
Periods in history of statistics I think that "periods" in history are closely related to people and their developments. Of course one can expect "waves" in Toffler's sense, but even those waves are related to persons. Anyway, wikip
15,674
Periods in history of statistics
According to the webpage titled "Materials for the History of Statistics" by the Department of Mathematics at the University of York, a major text on this subject is: Oscar Sheynin, Theory of Probability: A Historical Essay (published by NG Verlag 2005, ISBN 3-938417-15-3) The book is packed full of names, dates, ideas, and references. It's probably a good contender for what you're looking for. In the Preface to the book, the author tells us that: The book is intended for those interested in the history of mathematics or statistics and more or less acquainted with the latter. It will also be useful for statisticians. He then goes on to give a short outline of the book: I describe the origin of the notions of randomness and subjective or logical probability in antiquity, discuss how laymen comprehended the main notions of the theory of probability, dwell on the birth of political arithmetic and study the history of the theory proper. I also trace the development of statistics and its penetration into natural sciences as well as the history of the mathematical treatment of observations (Ptolemy, Al-Biruni, Kepler, the classical error theory). I stop at the axiomatization of probability and at the birth of the real mathematical statistics, i.e., at Kolmogorov and Fisher. The author appears to be active at making revisions to the book, so it would be worth visiting his website to see the latest available version of the book and his other related publications.
Periods in history of statistics
According to the webpage titled "Materials for the History of Statistics" by the Department of Mathematics at the University of York, a major text on this subject is: Oscar Sheynin, Theory of Probabil
Periods in history of statistics According to the webpage titled "Materials for the History of Statistics" by the Department of Mathematics at the University of York, a major text on this subject is: Oscar Sheynin, Theory of Probability: A Historical Essay (published by NG Verlag 2005, ISBN 3-938417-15-3) The book is packed full of names, dates, ideas, and references. It's probably a good contender for what you're looking for. In the Preface to the book, the author tells us that: The book is intended for those interested in the history of mathematics or statistics and more or less acquainted with the latter. It will also be useful for statisticians. He then goes on to give a short outline of the book: I describe the origin of the notions of randomness and subjective or logical probability in antiquity, discuss how laymen comprehended the main notions of the theory of probability, dwell on the birth of political arithmetic and study the history of the theory proper. I also trace the development of statistics and its penetration into natural sciences as well as the history of the mathematical treatment of observations (Ptolemy, Al-Biruni, Kepler, the classical error theory). I stop at the axiomatization of probability and at the birth of the real mathematical statistics, i.e., at Kolmogorov and Fisher. The author appears to be active at making revisions to the book, so it would be worth visiting his website to see the latest available version of the book and his other related publications.
Periods in history of statistics According to the webpage titled "Materials for the History of Statistics" by the Department of Mathematics at the University of York, a major text on this subject is: Oscar Sheynin, Theory of Probabil
15,675
Correlation of log-normal random variables
I assume that $X_1\sim N(0,\sigma_1^2)$ and $X_2\sim N(0,\sigma_2^2)$. Denote $Z_i=\exp(\sqrt{T}X_i)$. Then \begin{align} \log(Z_i)\sim N(0,T\sigma_i^2) \end{align} so $Z_i$ are log-normal. Thus \begin{align} EZ_i&=\exp\left(\frac{T\sigma_i^2}{2}\right)\\ var(Z_i)&=(\exp(T\sigma_i^2)-1)\exp(T\sigma_i^2) \end{align} and \begin{align} EY_i&=a_i\exp(\mu_iT)EZ_i\\ var(Y_i)&=a_i^2\exp(2\mu_iT)var(Z_i) \end{align} Then using the formula for m.g.f of multivariate normal we have \begin{align} EY_1Y_2&=a_1a_2\exp((\mu_1+\mu_2)T)E\exp(\sqrt{T}X_1+\sqrt{T}X_2)\\ &=a_1a_2\exp((\mu_1+\mu_2)T)\exp\left(\frac{1}{2}T(\sigma_1^2+2\rho\sigma_1\sigma_2+\sigma_2^2)\right) \end{align} So \begin{align} cov(Y_1,Y_2)&=EY_1Y_2-EY_1EY_2\\ &=a_1a_2\exp((\mu_1+\mu_2)T)\exp\left(\frac{T}{2}(\sigma_1^2+\sigma_2^2)\right)(\exp(\rho\sigma_1\sigma_2T)-1) \end{align} Now the correlation of $Y_1$ and $Y_2$ is covariance divided by square roots of variances: \begin{align} \rho_{Y_1Y_2}=\frac{\exp(\rho\sigma_1\sigma_2T)-1}{\sqrt{\left(\exp(\sigma_1^2T)-1\right)\left(\exp(\sigma_2^2T)-1\right)}} \end{align}
Correlation of log-normal random variables
I assume that $X_1\sim N(0,\sigma_1^2)$ and $X_2\sim N(0,\sigma_2^2)$. Denote $Z_i=\exp(\sqrt{T}X_i)$. Then \begin{align} \log(Z_i)\sim N(0,T\sigma_i^2) \end{align} so $Z_i$ are log-normal. Thus \beg
Correlation of log-normal random variables I assume that $X_1\sim N(0,\sigma_1^2)$ and $X_2\sim N(0,\sigma_2^2)$. Denote $Z_i=\exp(\sqrt{T}X_i)$. Then \begin{align} \log(Z_i)\sim N(0,T\sigma_i^2) \end{align} so $Z_i$ are log-normal. Thus \begin{align} EZ_i&=\exp\left(\frac{T\sigma_i^2}{2}\right)\\ var(Z_i)&=(\exp(T\sigma_i^2)-1)\exp(T\sigma_i^2) \end{align} and \begin{align} EY_i&=a_i\exp(\mu_iT)EZ_i\\ var(Y_i)&=a_i^2\exp(2\mu_iT)var(Z_i) \end{align} Then using the formula for m.g.f of multivariate normal we have \begin{align} EY_1Y_2&=a_1a_2\exp((\mu_1+\mu_2)T)E\exp(\sqrt{T}X_1+\sqrt{T}X_2)\\ &=a_1a_2\exp((\mu_1+\mu_2)T)\exp\left(\frac{1}{2}T(\sigma_1^2+2\rho\sigma_1\sigma_2+\sigma_2^2)\right) \end{align} So \begin{align} cov(Y_1,Y_2)&=EY_1Y_2-EY_1EY_2\\ &=a_1a_2\exp((\mu_1+\mu_2)T)\exp\left(\frac{T}{2}(\sigma_1^2+\sigma_2^2)\right)(\exp(\rho\sigma_1\sigma_2T)-1) \end{align} Now the correlation of $Y_1$ and $Y_2$ is covariance divided by square roots of variances: \begin{align} \rho_{Y_1Y_2}=\frac{\exp(\rho\sigma_1\sigma_2T)-1}{\sqrt{\left(\exp(\sigma_1^2T)-1\right)\left(\exp(\sigma_2^2T)-1\right)}} \end{align}
Correlation of log-normal random variables I assume that $X_1\sim N(0,\sigma_1^2)$ and $X_2\sim N(0,\sigma_2^2)$. Denote $Z_i=\exp(\sqrt{T}X_i)$. Then \begin{align} \log(Z_i)\sim N(0,T\sigma_i^2) \end{align} so $Z_i$ are log-normal. Thus \beg
15,676
Data partitioning for spatial data
After watching the video, I have become more confident that this application is more like "data reproduction", where a random partitioning is OK, rather than "data prediction". To me, you justify your choice of using random CV for spatial ML models too much with "if I use it for data reproduction, it is ok". The overarching goal of fitting a model is to make predictions on unseen data. The overarching goal of a performance assessment of a model is to have a generalizable overview of its performance in all kind of prediction scenarios. Because there is only a limited amount of data available, one tries to make the best out of it by estimating a performance via CV. Prediction scenarios in spatial modeling always come with the fact that the prediction set is spatially distant to the training data (with a varying degree of distance). And when this happens, you just lie to yourself with a model performance estimated via non-spatial (NSP) CV. If you justify your choice of using a random CV in a spatial model scenario with "I just want to reproduce the data" than you do not need to conduct a CV at all / estimate the performance. In this case, you can fit the model and try to interpret it (if this is possible). A spatial CV with a random partitioning is sometimes very similar to training and testing your model on the same data (i.e. train on "train" and test on "train") because both sets are highly similar due to the chosen partitioning. Remember that the partitioning was freely chosen by you here, most likely because it is the most popular scheme in ML. While it is perfectly fine for non-spatial data (because there is no such things as spatial relations), it is in fact just completely unsuited for spatial data. There is no problem in reporting a less good performance of a model. And due to the availability of dedicated partitioning strategies for spatial data (at least in R, see 1, 2, 3) there is also no excuse that no method was available to easily apply it (even though the non-availabilty of implementations in programming languages should never be a justification to use non-valid ones). I cannot think of a valid reason why one would even just start trying to justify the correctness of non-spatial partitioning methods in certain scenarios with the potential goal of reporting it in a scientific study/report. Trying to do so feels like "cheating on purpose" to me for the sake of better performance values. We are on a long way making the spatial modeling community aware of the need to use spatial partitioning methods for CV. I want to ensure that people coming across this question here understand that using random CV is not a choice under certain circumstances and that its results are completely invalid for any kind of reporting. The same applies for optimizing hyperparameters: If you do this with CV and use random partitioning, you are in danger of selecting non-optimal parameters for the performance estimation in the outer loop. While the differences of using spatial/non-spatial CV for tuning might not be as high as the ones for the performance estimation, they just introduce another potential bias into your study design (Schratz et al. 2019).
Data partitioning for spatial data
After watching the video, I have become more confident that this application is more like "data reproduction", where a random partitioning is OK, rather than "data prediction". To me, you justify
Data partitioning for spatial data After watching the video, I have become more confident that this application is more like "data reproduction", where a random partitioning is OK, rather than "data prediction". To me, you justify your choice of using random CV for spatial ML models too much with "if I use it for data reproduction, it is ok". The overarching goal of fitting a model is to make predictions on unseen data. The overarching goal of a performance assessment of a model is to have a generalizable overview of its performance in all kind of prediction scenarios. Because there is only a limited amount of data available, one tries to make the best out of it by estimating a performance via CV. Prediction scenarios in spatial modeling always come with the fact that the prediction set is spatially distant to the training data (with a varying degree of distance). And when this happens, you just lie to yourself with a model performance estimated via non-spatial (NSP) CV. If you justify your choice of using a random CV in a spatial model scenario with "I just want to reproduce the data" than you do not need to conduct a CV at all / estimate the performance. In this case, you can fit the model and try to interpret it (if this is possible). A spatial CV with a random partitioning is sometimes very similar to training and testing your model on the same data (i.e. train on "train" and test on "train") because both sets are highly similar due to the chosen partitioning. Remember that the partitioning was freely chosen by you here, most likely because it is the most popular scheme in ML. While it is perfectly fine for non-spatial data (because there is no such things as spatial relations), it is in fact just completely unsuited for spatial data. There is no problem in reporting a less good performance of a model. And due to the availability of dedicated partitioning strategies for spatial data (at least in R, see 1, 2, 3) there is also no excuse that no method was available to easily apply it (even though the non-availabilty of implementations in programming languages should never be a justification to use non-valid ones). I cannot think of a valid reason why one would even just start trying to justify the correctness of non-spatial partitioning methods in certain scenarios with the potential goal of reporting it in a scientific study/report. Trying to do so feels like "cheating on purpose" to me for the sake of better performance values. We are on a long way making the spatial modeling community aware of the need to use spatial partitioning methods for CV. I want to ensure that people coming across this question here understand that using random CV is not a choice under certain circumstances and that its results are completely invalid for any kind of reporting. The same applies for optimizing hyperparameters: If you do this with CV and use random partitioning, you are in danger of selecting non-optimal parameters for the performance estimation in the outer loop. While the differences of using spatial/non-spatial CV for tuning might not be as high as the ones for the performance estimation, they just introduce another potential bias into your study design (Schratz et al. 2019).
Data partitioning for spatial data After watching the video, I have become more confident that this application is more like "data reproduction", where a random partitioning is OK, rather than "data prediction". To me, you justify
15,677
Data partitioning for spatial data
Nice question, and I fully agree with Roozbeh. Spatial cross validation is relevant when you have spatial autocorrelation in your training data that usually occur when your data are clustered in space. If you want to know how well your model is able to generalize (i.e. make predictions beyond training locations), you will need to assess this by a kind of spatial validation. But following up Roozbeh’s warning: even if you’re not interested in making spatial predictions but “only” in variable importance, you should be careful with spatial dependencies. If the data are not independent, the “default” variable importance tells you the importance of the variables to “reproduce” the training data. Variables like latitude and longitude are, if your data are clustered, for sure highly suitable as predictors for reproducing training data. But that doesn’t mean they have any relevance for explaining spatial patters. If you want to know if the variable is relevant for an independent location, you probably should asses the “spatial variable importance”. We implemented a method for this in the R package “CAST” (j.envsoft.2017.12.001), and the idea is described in the paper Roozbeh mentioned as well (j.ecolmodel.2019.108815).
Data partitioning for spatial data
Nice question, and I fully agree with Roozbeh. Spatial cross validation is relevant when you have spatial autocorrelation in your training data that usually occur when your data are clustered in space
Data partitioning for spatial data Nice question, and I fully agree with Roozbeh. Spatial cross validation is relevant when you have spatial autocorrelation in your training data that usually occur when your data are clustered in space. If you want to know how well your model is able to generalize (i.e. make predictions beyond training locations), you will need to assess this by a kind of spatial validation. But following up Roozbeh’s warning: even if you’re not interested in making spatial predictions but “only” in variable importance, you should be careful with spatial dependencies. If the data are not independent, the “default” variable importance tells you the importance of the variables to “reproduce” the training data. Variables like latitude and longitude are, if your data are clustered, for sure highly suitable as predictors for reproducing training data. But that doesn’t mean they have any relevance for explaining spatial patters. If you want to know if the variable is relevant for an independent location, you probably should asses the “spatial variable importance”. We implemented a method for this in the R package “CAST” (j.envsoft.2017.12.001), and the idea is described in the paper Roozbeh mentioned as well (j.ecolmodel.2019.108815).
Data partitioning for spatial data Nice question, and I fully agree with Roozbeh. Spatial cross validation is relevant when you have spatial autocorrelation in your training data that usually occur when your data are clustered in space
15,678
Data partitioning for spatial data
Very interesting question! The importance of spatial/block cross-validation comes to play when you think your performance might be affected by spatial autocorrelation. This totally depends on the purpose of your study. If you are interested to assess the performance of your models for only those specific locations or new locations that are within the same proximity, the conventional random CV might still be a reasonable option. In general, the purpose of these kinds of modelling is to come up with a model that not only have a good performance but also generalise well. Because we want the result of our model to be true for our data and will be still reasonable in general (or for other data sets or locations). In this case, spatial autocorrelation can lead to inflated confidence in your model results. I just give a warning here as you are using spatial coordinates as the predictor, the model might give you a wrong sense of high importance for these variables when you are using random CV, check out Meyer et al., 2019 Ecological Modelling as a good example for this. Cheers, Roozbeh Valavi
Data partitioning for spatial data
Very interesting question! The importance of spatial/block cross-validation comes to play when you think your performance might be affected by spatial autocorrelation. This totally depends on the purp
Data partitioning for spatial data Very interesting question! The importance of spatial/block cross-validation comes to play when you think your performance might be affected by spatial autocorrelation. This totally depends on the purpose of your study. If you are interested to assess the performance of your models for only those specific locations or new locations that are within the same proximity, the conventional random CV might still be a reasonable option. In general, the purpose of these kinds of modelling is to come up with a model that not only have a good performance but also generalise well. Because we want the result of our model to be true for our data and will be still reasonable in general (or for other data sets or locations). In this case, spatial autocorrelation can lead to inflated confidence in your model results. I just give a warning here as you are using spatial coordinates as the predictor, the model might give you a wrong sense of high importance for these variables when you are using random CV, check out Meyer et al., 2019 Ecological Modelling as a good example for this. Cheers, Roozbeh Valavi
Data partitioning for spatial data Very interesting question! The importance of spatial/block cross-validation comes to play when you think your performance might be affected by spatial autocorrelation. This totally depends on the purp
15,679
How to measure the statistical "distance" between two frequency distributions?
You may be interested in the Earth mover's distance, also known as the Wasserstein metric. It is implemented in R (look at the emdist package) and in Python. We also have a number of threads on it. The EMD works for both continuous and discrete distributions. The emdist package for R works on discrete distributions. The advantage over something like a $\chi^2$ statistic is that the EMD yields interpretable results. Picture your distribution as mounds of earth, then the EMD tells you how much earth you would need to transport how far to turn one distribution into the other. Put another way: two distributions (1,0,0) and (0,1,0) should be "more similar" than (1,0,0) and (0,0,1). The EMD will recognize this and assign a smaller distance to the first pair than to the second. The $\chi^2$ statistic will assign the same distance to both pairs, because it has no notion of an ordering in the distribution entries.
How to measure the statistical "distance" between two frequency distributions?
You may be interested in the Earth mover's distance, also known as the Wasserstein metric. It is implemented in R (look at the emdist package) and in Python. We also have a number of threads on it. Th
How to measure the statistical "distance" between two frequency distributions? You may be interested in the Earth mover's distance, also known as the Wasserstein metric. It is implemented in R (look at the emdist package) and in Python. We also have a number of threads on it. The EMD works for both continuous and discrete distributions. The emdist package for R works on discrete distributions. The advantage over something like a $\chi^2$ statistic is that the EMD yields interpretable results. Picture your distribution as mounds of earth, then the EMD tells you how much earth you would need to transport how far to turn one distribution into the other. Put another way: two distributions (1,0,0) and (0,1,0) should be "more similar" than (1,0,0) and (0,0,1). The EMD will recognize this and assign a smaller distance to the first pair than to the second. The $\chi^2$ statistic will assign the same distance to both pairs, because it has no notion of an ordering in the distribution entries.
How to measure the statistical "distance" between two frequency distributions? You may be interested in the Earth mover's distance, also known as the Wasserstein metric. It is implemented in R (look at the emdist package) and in Python. We also have a number of threads on it. Th
15,680
How to measure the statistical "distance" between two frequency distributions?
If you randomly sample an individual from each of the two distributions, you can calculate a difference between them. If you repeat this (with replacement) a number of times, you can generate a distribution of differences that contains all the information you are after. You can plot this distribution and characterize it with any summary statistics you desire - means, medians, etc.
How to measure the statistical "distance" between two frequency distributions?
If you randomly sample an individual from each of the two distributions, you can calculate a difference between them. If you repeat this (with replacement) a number of times, you can generate a distri
How to measure the statistical "distance" between two frequency distributions? If you randomly sample an individual from each of the two distributions, you can calculate a difference between them. If you repeat this (with replacement) a number of times, you can generate a distribution of differences that contains all the information you are after. You can plot this distribution and characterize it with any summary statistics you desire - means, medians, etc.
How to measure the statistical "distance" between two frequency distributions? If you randomly sample an individual from each of the two distributions, you can calculate a difference between them. If you repeat this (with replacement) a number of times, you can generate a distri
15,681
How to measure the statistical "distance" between two frequency distributions?
One of the metric is Hellinger distance between two distributions which are characterised by means and standard deviations. The application can be found in the following article. https://www.sciencedirect.com/science/article/pii/S1568494615005104
How to measure the statistical "distance" between two frequency distributions?
One of the metric is Hellinger distance between two distributions which are characterised by means and standard deviations. The application can be found in the following article. https://www.sciencedi
How to measure the statistical "distance" between two frequency distributions? One of the metric is Hellinger distance between two distributions which are characterised by means and standard deviations. The application can be found in the following article. https://www.sciencedirect.com/science/article/pii/S1568494615005104
How to measure the statistical "distance" between two frequency distributions? One of the metric is Hellinger distance between two distributions which are characterised by means and standard deviations. The application can be found in the following article. https://www.sciencedi
15,682
How does a Bayesian update his belief when something with probability 0 happened?
Any posterior probability is valid in this case This is an interesting question, which gets into the territory of the foundations of probability. There are a few possible approaches here, but for reasons that I will elaborate on soon, the approach I favour is to give a broader definition of conditional probability that is analogous to its definition when dealing with continuous random variables. (Details of this method are shown below.) In this particular case, this leads to the conclusion that the Bayesian can hold any posterior belief about $X$, and this yields a coherent set of beliefs (notwithstanding that they have observed an event that they believe to have probability zero). The advantage of this approach is that it gives a well-defined posterior distribution, and allows the Bayesian to update their beliefs conditional on observing an event that was stipulated to occur with probability zero. The posterior is updated essentially arbitrarily (any posterior probability is equally coherent), but that flexibility is unsurprising given what has occurred. In this case, different Bayesians with the same prior beliefs could legitimately come to different posterior conclusions, owing to the fact that they have all observed an event with zero probability a priori. Conditional probability for continuous random variables: When we are dealing with continuous random variables, the conditional probability function is defined through the Radon-Nikodym derivative, and essentially just requires the function to satisfies the law of joint probability. If $X$ and $E$ were continuous random variables (rather than discrete events) in a probability space $(\Omega, \mathscr{G}, P)$ then we would define the conditional probability function $p(x|e)$ as any non-negative measureable function that satisfies the integral equation: $$p(x) = \int \limits_\mathscr{E} p(x|e) \ dP(e) \quad \quad \quad \text{for all } x \in \mathscr{X} \in \mathscr{G}.$$ Since $p(x)$ is also defined via the Radon-Nikodym derivative, this implicitly means that $p(x|e)$ can be any non-negative measureable function that satisfies the integral equation: $$\mathbb{P}(X \in \mathcal{A}) = \int \limits_\mathcal{A} \int \limits_\mathscr{E} p(x|e) \ dP(e) \ dx \quad \quad \quad \text{for all } \mathcal{A} \in \mathscr{G}.$$ This gives a non-unique solution for the conditional probability function, though in practice, every solution is "almost surely" equivalent (i.e., they differ only on a set of outcomes with probability zero) so there is no problem with the non-uniqueness. Defining conditional probability for discrete events: The standard definition for conditional probability for discrete events is the well-known ratio formula, where the denominator is the probability of the conditioning event. Obviously, in the case where the conditioning event has zero probability, this object is undefined. The obvious solution here is to broaden the definition in a manner that is analogous to the method used in the continuous case. That is, we define the conditional probability pair $\mathbb{P}(X|E)$ and $\mathbb{P}(X|\bar{E})$ as any pair of values between zero and one that satisfy the equation: $$\mathbb{P}(X) = \mathbb{P}(X|E) \times \mathbb{P}(E) + \mathbb{P}(X|\bar{E}) \times (1-\mathbb{P}(E)).$$ In the case stipulated in the question we have the prior belief $\mathbb{P}(X) = 1$ and the sampling distribution $\mathbb{P}(E|X) = 0$, which leads to $\mathbb{P}(E) = 0$. Substituting these values into the above equation gives: $$1 = \mathbb{P}(X|E) \times 0 + \mathbb{P}(X|\bar{E}) \times 1.$$ We can see that this equation is satisfied by taking $\mathbb{P}(X|\bar{E}) = 1$ and any $0 \leqslant \mathbb{P}(X|E) \leqslant 1$. Thus, the (posterior) conditional probability $\mathbb{P}(X|E)$ may coherently be any value between zero and one. When we say that this is "coherent" we simply mean that the posterior probability is not inconsistent with the other stipulated probabilities in the problem (i.e., the prior and sampling probabilities). Why this approach makes the most sense: It is entirely possible that a Bayesian analysis could involve observation of a discrete event that has zero probability stipulated in the prior distribution. For example, in a standard model of coin-flipping, we stipulate a Bernoulli distribution for the heads/tails outcome, but it is possible that the coin could come to rest on its edge (thus being neither heads or tails). Brains should not explode in this case, and thus it is incumbent on Bayesian reasoning to have a well-defined way of proceeding in this case. The major advantage of the approach I have outlined is that it always leads to at least one allowable value for the posterior probability (i.e., the posterior probability is well-defined). The posterior probability is not uniquely defined, but that is a natural offshoot of the fact that there are several values that are equally coherent with the zero-probability sampling observation. This approach means that the Bayesian is free to stipulate any posterior probability, and this is as coherent as any other. (Bear in mind that when we say "coherent" here, we are talking about coherence with a prior belief that stipulated zero probability for a discrete event that actually happened, so coherence with that is not a high bar!) There is another major benefit to this approach, which is that it allows the Bayesian to update his or her beliefs in response to observing an event that had zero sampling probablity under the prior, and in particular, the Bayesian can now revise his or her beliefs so that they no longer ascribe zero probability to this event. In the example you give, the Bayesian had a prior belief that $X$ is true almost surely, buy then observed an event with zero sampling probability conditional on this event. Now the Bayesian is free to update his or her belief to a posterior probabilty for $X$ that is not one (and so a corresponding posterior probability for $\bar{X}$ that is not zero). So, in essence, the Bayesian can now say "Oh shit! That was a silly prior! Let me update my belief in that event so that it no longer occurs almost surely!" Moreover, this is not some ad hoc change, but a legitimate "coherent" updating done under Bayes' theorem.
How does a Bayesian update his belief when something with probability 0 happened?
Any posterior probability is valid in this case This is an interesting question, which gets into the territory of the foundations of probability. There are a few possible approaches here, but for rea
How does a Bayesian update his belief when something with probability 0 happened? Any posterior probability is valid in this case This is an interesting question, which gets into the territory of the foundations of probability. There are a few possible approaches here, but for reasons that I will elaborate on soon, the approach I favour is to give a broader definition of conditional probability that is analogous to its definition when dealing with continuous random variables. (Details of this method are shown below.) In this particular case, this leads to the conclusion that the Bayesian can hold any posterior belief about $X$, and this yields a coherent set of beliefs (notwithstanding that they have observed an event that they believe to have probability zero). The advantage of this approach is that it gives a well-defined posterior distribution, and allows the Bayesian to update their beliefs conditional on observing an event that was stipulated to occur with probability zero. The posterior is updated essentially arbitrarily (any posterior probability is equally coherent), but that flexibility is unsurprising given what has occurred. In this case, different Bayesians with the same prior beliefs could legitimately come to different posterior conclusions, owing to the fact that they have all observed an event with zero probability a priori. Conditional probability for continuous random variables: When we are dealing with continuous random variables, the conditional probability function is defined through the Radon-Nikodym derivative, and essentially just requires the function to satisfies the law of joint probability. If $X$ and $E$ were continuous random variables (rather than discrete events) in a probability space $(\Omega, \mathscr{G}, P)$ then we would define the conditional probability function $p(x|e)$ as any non-negative measureable function that satisfies the integral equation: $$p(x) = \int \limits_\mathscr{E} p(x|e) \ dP(e) \quad \quad \quad \text{for all } x \in \mathscr{X} \in \mathscr{G}.$$ Since $p(x)$ is also defined via the Radon-Nikodym derivative, this implicitly means that $p(x|e)$ can be any non-negative measureable function that satisfies the integral equation: $$\mathbb{P}(X \in \mathcal{A}) = \int \limits_\mathcal{A} \int \limits_\mathscr{E} p(x|e) \ dP(e) \ dx \quad \quad \quad \text{for all } \mathcal{A} \in \mathscr{G}.$$ This gives a non-unique solution for the conditional probability function, though in practice, every solution is "almost surely" equivalent (i.e., they differ only on a set of outcomes with probability zero) so there is no problem with the non-uniqueness. Defining conditional probability for discrete events: The standard definition for conditional probability for discrete events is the well-known ratio formula, where the denominator is the probability of the conditioning event. Obviously, in the case where the conditioning event has zero probability, this object is undefined. The obvious solution here is to broaden the definition in a manner that is analogous to the method used in the continuous case. That is, we define the conditional probability pair $\mathbb{P}(X|E)$ and $\mathbb{P}(X|\bar{E})$ as any pair of values between zero and one that satisfy the equation: $$\mathbb{P}(X) = \mathbb{P}(X|E) \times \mathbb{P}(E) + \mathbb{P}(X|\bar{E}) \times (1-\mathbb{P}(E)).$$ In the case stipulated in the question we have the prior belief $\mathbb{P}(X) = 1$ and the sampling distribution $\mathbb{P}(E|X) = 0$, which leads to $\mathbb{P}(E) = 0$. Substituting these values into the above equation gives: $$1 = \mathbb{P}(X|E) \times 0 + \mathbb{P}(X|\bar{E}) \times 1.$$ We can see that this equation is satisfied by taking $\mathbb{P}(X|\bar{E}) = 1$ and any $0 \leqslant \mathbb{P}(X|E) \leqslant 1$. Thus, the (posterior) conditional probability $\mathbb{P}(X|E)$ may coherently be any value between zero and one. When we say that this is "coherent" we simply mean that the posterior probability is not inconsistent with the other stipulated probabilities in the problem (i.e., the prior and sampling probabilities). Why this approach makes the most sense: It is entirely possible that a Bayesian analysis could involve observation of a discrete event that has zero probability stipulated in the prior distribution. For example, in a standard model of coin-flipping, we stipulate a Bernoulli distribution for the heads/tails outcome, but it is possible that the coin could come to rest on its edge (thus being neither heads or tails). Brains should not explode in this case, and thus it is incumbent on Bayesian reasoning to have a well-defined way of proceeding in this case. The major advantage of the approach I have outlined is that it always leads to at least one allowable value for the posterior probability (i.e., the posterior probability is well-defined). The posterior probability is not uniquely defined, but that is a natural offshoot of the fact that there are several values that are equally coherent with the zero-probability sampling observation. This approach means that the Bayesian is free to stipulate any posterior probability, and this is as coherent as any other. (Bear in mind that when we say "coherent" here, we are talking about coherence with a prior belief that stipulated zero probability for a discrete event that actually happened, so coherence with that is not a high bar!) There is another major benefit to this approach, which is that it allows the Bayesian to update his or her beliefs in response to observing an event that had zero sampling probablity under the prior, and in particular, the Bayesian can now revise his or her beliefs so that they no longer ascribe zero probability to this event. In the example you give, the Bayesian had a prior belief that $X$ is true almost surely, buy then observed an event with zero sampling probability conditional on this event. Now the Bayesian is free to update his or her belief to a posterior probabilty for $X$ that is not one (and so a corresponding posterior probability for $\bar{X}$ that is not zero). So, in essence, the Bayesian can now say "Oh shit! That was a silly prior! Let me update my belief in that event so that it no longer occurs almost surely!" Moreover, this is not some ad hoc change, but a legitimate "coherent" updating done under Bayes' theorem.
How does a Bayesian update his belief when something with probability 0 happened? Any posterior probability is valid in this case This is an interesting question, which gets into the territory of the foundations of probability. There are a few possible approaches here, but for rea
15,683
How does a Bayesian update his belief when something with probability 0 happened?
This is related to field of logic. in particular, a false statement implies all other statements, true or false. In your scenario $X$ is a false statement.This means we can write $X\implies S$ for any other proposition $S$. For example, we have $X\implies E$ (it implies tails) and also $X\implies E^c$ (it implies not tails as well)! This is consistent with Ben's solution as well (set the posterior to any value you want). Obviously this not really useful in applications though. For I am quite confident of not needing any mathematical framework for making up whatever results I want. What it does mean, is that one should not include known false statements into their prior probabilities. This is just the same as one shouldn't use false statements about the data. In terms of dealing with "black swan" type of issues, we can deal with this conceptually by assigning some tiny, but nonzero chance that our "working assumptions" are wrong. If you call this statement $A_w$ as "my working assumptions are correct", and set it's prior equal to $p(A_w)=1-\epsilon$. There are some impossible situations under the working assumption, which means that the likelihood $p(d\in D_{impossible}|A_w)=0$ for some values of the "data" $d$ that exist in the "impossible" region $D_{impossible}$ when the working assumptions hold. Call this event $Q:=d\in D_{impossible}$. This also means that $p(Q^c|A_w)=1-p(Q|A_w)=1$. We assume that $p(Q|A_w^c)=\delta>0$ (ie "impossible" data is possible if the working assumption is wrong). And finally that $p(Q^c|A_w^c)=1-p(Q|A_w^c)=1-\delta$. Now we have two scenarios. The first is that the data is "normal" (meaning $Q^c$ is true) $$p(A_w|Q^c)= \frac{p(A_w)p(Q^c|A_w)}{p(A_w)p(Q^c|A_w)+p(A_w^c)p(Q^c|A_w^c)}= \frac{1-\epsilon}{1-\epsilon+\epsilon(1-\delta)}=\frac{1-\epsilon}{1-\delta \epsilon} > 1-\epsilon$$ The second is that the data is "impossible" (meaning $Q$ is true) $$p(A_w|Q)= \frac{p(A_w)p(Q|A_w)}{p(A_w)p(Q|A_w)+p(A_w^c)p(Q|A_w^c)}=\frac{0}{0+\epsilon\delta}=0.$$ Now hopefully this very clearly shows that if your assumptions are satisfied, and you already had a very high prior probability, the posterior is at least as high (and often higher). So whatever value for $\epsilon$ you use to represent "basically impossible" before seeing the data, you should use a value that is smaller after seeing the predictions confirmed. When doing calculations, assuming $p(A_w|Q^c)=1$ won't lead you astray. So you "absorb" $A_w,Q^c$ into the prior information Now, what about when the impossible thing happens? Well then you need to unpack and change your likelihood and prior according to what was wrong with your assumption.
How does a Bayesian update his belief when something with probability 0 happened?
This is related to field of logic. in particular, a false statement implies all other statements, true or false. In your scenario $X$ is a false statement.This means we can write $X\implies S$ for any
How does a Bayesian update his belief when something with probability 0 happened? This is related to field of logic. in particular, a false statement implies all other statements, true or false. In your scenario $X$ is a false statement.This means we can write $X\implies S$ for any other proposition $S$. For example, we have $X\implies E$ (it implies tails) and also $X\implies E^c$ (it implies not tails as well)! This is consistent with Ben's solution as well (set the posterior to any value you want). Obviously this not really useful in applications though. For I am quite confident of not needing any mathematical framework for making up whatever results I want. What it does mean, is that one should not include known false statements into their prior probabilities. This is just the same as one shouldn't use false statements about the data. In terms of dealing with "black swan" type of issues, we can deal with this conceptually by assigning some tiny, but nonzero chance that our "working assumptions" are wrong. If you call this statement $A_w$ as "my working assumptions are correct", and set it's prior equal to $p(A_w)=1-\epsilon$. There are some impossible situations under the working assumption, which means that the likelihood $p(d\in D_{impossible}|A_w)=0$ for some values of the "data" $d$ that exist in the "impossible" region $D_{impossible}$ when the working assumptions hold. Call this event $Q:=d\in D_{impossible}$. This also means that $p(Q^c|A_w)=1-p(Q|A_w)=1$. We assume that $p(Q|A_w^c)=\delta>0$ (ie "impossible" data is possible if the working assumption is wrong). And finally that $p(Q^c|A_w^c)=1-p(Q|A_w^c)=1-\delta$. Now we have two scenarios. The first is that the data is "normal" (meaning $Q^c$ is true) $$p(A_w|Q^c)= \frac{p(A_w)p(Q^c|A_w)}{p(A_w)p(Q^c|A_w)+p(A_w^c)p(Q^c|A_w^c)}= \frac{1-\epsilon}{1-\epsilon+\epsilon(1-\delta)}=\frac{1-\epsilon}{1-\delta \epsilon} > 1-\epsilon$$ The second is that the data is "impossible" (meaning $Q$ is true) $$p(A_w|Q)= \frac{p(A_w)p(Q|A_w)}{p(A_w)p(Q|A_w)+p(A_w^c)p(Q|A_w^c)}=\frac{0}{0+\epsilon\delta}=0.$$ Now hopefully this very clearly shows that if your assumptions are satisfied, and you already had a very high prior probability, the posterior is at least as high (and often higher). So whatever value for $\epsilon$ you use to represent "basically impossible" before seeing the data, you should use a value that is smaller after seeing the predictions confirmed. When doing calculations, assuming $p(A_w|Q^c)=1$ won't lead you astray. So you "absorb" $A_w,Q^c$ into the prior information Now, what about when the impossible thing happens? Well then you need to unpack and change your likelihood and prior according to what was wrong with your assumption.
How does a Bayesian update his belief when something with probability 0 happened? This is related to field of logic. in particular, a false statement implies all other statements, true or false. In your scenario $X$ is a false statement.This means we can write $X\implies S$ for any
15,684
How does a Bayesian update his belief when something with probability 0 happened?
There's an implicit assumption in all reasoning, Bayesian or otherwise, that we know everything that could happen and accounted for it. If something happens which is impossible under the model, it just means that that assumption is false. The principled thing to do is to go back and expand the model, and start over. At least in a Bayesian framework, this process is relatively easy to formalize -- instead of inference within a single model, one would do inference in a set of models. At some point, our human ability to nest models within models must run out. Even with automated help (i.e. computers or whatever), there must be an upper limit to the complexity of the "mother of all models". I don't have any idea what to do in that circumstance, but we are certainly very far away from that, when we're working with typical parametric models found in applications.
How does a Bayesian update his belief when something with probability 0 happened?
There's an implicit assumption in all reasoning, Bayesian or otherwise, that we know everything that could happen and accounted for it. If something happens which is impossible under the model, it jus
How does a Bayesian update his belief when something with probability 0 happened? There's an implicit assumption in all reasoning, Bayesian or otherwise, that we know everything that could happen and accounted for it. If something happens which is impossible under the model, it just means that that assumption is false. The principled thing to do is to go back and expand the model, and start over. At least in a Bayesian framework, this process is relatively easy to formalize -- instead of inference within a single model, one would do inference in a set of models. At some point, our human ability to nest models within models must run out. Even with automated help (i.e. computers or whatever), there must be an upper limit to the complexity of the "mother of all models". I don't have any idea what to do in that circumstance, but we are certainly very far away from that, when we're working with typical parametric models found in applications.
How does a Bayesian update his belief when something with probability 0 happened? There's an implicit assumption in all reasoning, Bayesian or otherwise, that we know everything that could happen and accounted for it. If something happens which is impossible under the model, it jus
15,685
Accuracy vs. area under the ROC curve
It's indeed possible. The key is to remember that the accuracy is highly affected by class imbalance. E.g., in your case, you have more negative samples than positive samples, since when the FPR ($=\frac{FP}{FP+TN}$) is close to 0, and TPR (= $\frac{TP}{TP+FN}$) is 0.5, your accuracy ($= \frac{TP+TN}{TP+FN+FP+TN}$) is still very high. To put it otherwise, since you have many more negative samples, if the classifier predicts 0 all the time, it will still get a high accuracy with FPR and TPR close to 0. What you call optimum threshold setting (the point closest to point (0, 1)) is just one of many definitions for optimal threshold: it doesn't necessarily optimize the accuracy.
Accuracy vs. area under the ROC curve
It's indeed possible. The key is to remember that the accuracy is highly affected by class imbalance. E.g., in your case, you have more negative samples than positive samples, since when the FPR ($=\f
Accuracy vs. area under the ROC curve It's indeed possible. The key is to remember that the accuracy is highly affected by class imbalance. E.g., in your case, you have more negative samples than positive samples, since when the FPR ($=\frac{FP}{FP+TN}$) is close to 0, and TPR (= $\frac{TP}{TP+FN}$) is 0.5, your accuracy ($= \frac{TP+TN}{TP+FN+FP+TN}$) is still very high. To put it otherwise, since you have many more negative samples, if the classifier predicts 0 all the time, it will still get a high accuracy with FPR and TPR close to 0. What you call optimum threshold setting (the point closest to point (0, 1)) is just one of many definitions for optimal threshold: it doesn't necessarily optimize the accuracy.
Accuracy vs. area under the ROC curve It's indeed possible. The key is to remember that the accuracy is highly affected by class imbalance. E.g., in your case, you have more negative samples than positive samples, since when the FPR ($=\f
15,686
Accuracy vs. area under the ROC curve
Okay, remember the relation between the $FPR$ (False Positive Rate), $TPR$ (True Positive Rate) and $ACC$ (Accuracy): $$TPR = \frac{\sum \text{True positive}}{\sum \text{Positive cases}}$$ $$FPR = \frac{\sum \text{False positive}}{\sum \text{Negative cases}}$$ $$ACC = \frac{TPR \cdot \sum \text{Positive cases} + (1-FPR) \cdot \sum \text{Negative cases}}{\sum \text{Positive cases} + \sum \text{Negative cases}}$$ So, $ACC$ can be represented as a weighted average of $TPR$ and $FPR$. If the number of negatives and positives is the same: $$ACC = \frac{TPR + 1 - FPR}{2}$$ But what if $N_- \gg N_+$? Then: $$ACC(N_- \gg N_+) \approx 1-FPR$$ So, in this case, maximal $ACC$ occurs at minimal $FPR$ See this example, negatives outnumber positives 1000:1. data = c(rnorm(10L), rnorm(10000L)+1) lab = c(rep(1, 10L), rep(-1, 10000L)) plot(data, lab, col = lab + 3) tresh = c(-10, data[lab == 1], 10) do.call(function(x) abline(v = x, col = "gray"), list(tresh)) pred = lapply(tresh, function (x) ifelse(data <= x, 1, -1)) res = data.frame( acc = sapply(pred, function(x) sum(x == lab)/length(lab)), tpr = sapply(pred, function(x) sum(lab == x & x == 1)/sum(lab == 1)), fpr = sapply(pred, function(x) sum(lab != x & x == 1)/sum(lab != 1)) ) res[order(res$acc),] #> res[order(res$acc),] # acc tpr fpr #12 0.000999001 1.0 1.0000 #11 0.189110889 1.0 0.8117 #9 0.500099900 0.9 0.5003 #2 0.757742258 0.8 0.2423 #5 0.763136863 0.7 0.2368 #4 0.792007992 0.6 0.2078 #10 0.807292707 0.5 0.1924 #3 0.884215784 0.4 0.1153 #7 0.890709291 0.3 0.1087 #6 0.903096903 0.2 0.0962 #8 0.971428571 0.1 0.0277 #1 0.999000999 0.0 0.0000 See, when fpr is 0 acc is maximum. And here's the ROC, with accuracy annotated. plot(sort(res$fpr), sort(res$tpr), type = "S", ylab = "TPR", xlab = "FPR") text(sort(res$fpr), sort(res$tpr), pos = 4L, lab = round(res$acc[order(res$fpr)], 3L)) abline(a = 0, b = 1) abline(a = 1, b = -1) The $AUC$ is 1-sum(res$fpr[-12]*0.1) #[1] 0.74608 The bottom line is that you can optimize accuracy in a way resulting in a bogus model (tpr = 0 in my example). That's because accuracy is not a good metric, dichotomization of the result should be left to the decision-maker. The optimal threshold is said to be the $TPR = 1-FPR$ line because that way both errors have equal weight, even if accuracy is not optimal. When you have imbalanced classes, optimizing accuracy can be trivial (e.g. predict everyone as the majority class). Another thing, you can't translate most $AUC$ measures to an accuracy estimate like that; see these questions: Area under curve of ROC vs. overall accuracy Accuracy and area under ROC curve (AUC) And most important of all: Why is AUC higher for a classifier that is less accurate than for one that is more accurate?
Accuracy vs. area under the ROC curve
Okay, remember the relation between the $FPR$ (False Positive Rate), $TPR$ (True Positive Rate) and $ACC$ (Accuracy): $$TPR = \frac{\sum \text{True positive}}{\sum \text{Positive cases}}$$ $$FPR = \fr
Accuracy vs. area under the ROC curve Okay, remember the relation between the $FPR$ (False Positive Rate), $TPR$ (True Positive Rate) and $ACC$ (Accuracy): $$TPR = \frac{\sum \text{True positive}}{\sum \text{Positive cases}}$$ $$FPR = \frac{\sum \text{False positive}}{\sum \text{Negative cases}}$$ $$ACC = \frac{TPR \cdot \sum \text{Positive cases} + (1-FPR) \cdot \sum \text{Negative cases}}{\sum \text{Positive cases} + \sum \text{Negative cases}}$$ So, $ACC$ can be represented as a weighted average of $TPR$ and $FPR$. If the number of negatives and positives is the same: $$ACC = \frac{TPR + 1 - FPR}{2}$$ But what if $N_- \gg N_+$? Then: $$ACC(N_- \gg N_+) \approx 1-FPR$$ So, in this case, maximal $ACC$ occurs at minimal $FPR$ See this example, negatives outnumber positives 1000:1. data = c(rnorm(10L), rnorm(10000L)+1) lab = c(rep(1, 10L), rep(-1, 10000L)) plot(data, lab, col = lab + 3) tresh = c(-10, data[lab == 1], 10) do.call(function(x) abline(v = x, col = "gray"), list(tresh)) pred = lapply(tresh, function (x) ifelse(data <= x, 1, -1)) res = data.frame( acc = sapply(pred, function(x) sum(x == lab)/length(lab)), tpr = sapply(pred, function(x) sum(lab == x & x == 1)/sum(lab == 1)), fpr = sapply(pred, function(x) sum(lab != x & x == 1)/sum(lab != 1)) ) res[order(res$acc),] #> res[order(res$acc),] # acc tpr fpr #12 0.000999001 1.0 1.0000 #11 0.189110889 1.0 0.8117 #9 0.500099900 0.9 0.5003 #2 0.757742258 0.8 0.2423 #5 0.763136863 0.7 0.2368 #4 0.792007992 0.6 0.2078 #10 0.807292707 0.5 0.1924 #3 0.884215784 0.4 0.1153 #7 0.890709291 0.3 0.1087 #6 0.903096903 0.2 0.0962 #8 0.971428571 0.1 0.0277 #1 0.999000999 0.0 0.0000 See, when fpr is 0 acc is maximum. And here's the ROC, with accuracy annotated. plot(sort(res$fpr), sort(res$tpr), type = "S", ylab = "TPR", xlab = "FPR") text(sort(res$fpr), sort(res$tpr), pos = 4L, lab = round(res$acc[order(res$fpr)], 3L)) abline(a = 0, b = 1) abline(a = 1, b = -1) The $AUC$ is 1-sum(res$fpr[-12]*0.1) #[1] 0.74608 The bottom line is that you can optimize accuracy in a way resulting in a bogus model (tpr = 0 in my example). That's because accuracy is not a good metric, dichotomization of the result should be left to the decision-maker. The optimal threshold is said to be the $TPR = 1-FPR$ line because that way both errors have equal weight, even if accuracy is not optimal. When you have imbalanced classes, optimizing accuracy can be trivial (e.g. predict everyone as the majority class). Another thing, you can't translate most $AUC$ measures to an accuracy estimate like that; see these questions: Area under curve of ROC vs. overall accuracy Accuracy and area under ROC curve (AUC) And most important of all: Why is AUC higher for a classifier that is less accurate than for one that is more accurate?
Accuracy vs. area under the ROC curve Okay, remember the relation between the $FPR$ (False Positive Rate), $TPR$ (True Positive Rate) and $ACC$ (Accuracy): $$TPR = \frac{\sum \text{True positive}}{\sum \text{Positive cases}}$$ $$FPR = \fr
15,687
Is variance a more fundamental concept than standard deviation?
Robert's and Bey's answers do give part of the story (i.e. moments tend to be regarded as basic properties of distributions, and conventionally standard deviation is defined in terms of the second central moment rather than the other way around), but the extent to which those things are really fundamental depends partly on what we mean by the term. There would be no insurmountable problem, for example, if our conventions went the other way -- there's nothing stopping us conventionally defining some other sequence of quantities in place of the usual moments, say $E[(X-\mu)^p]^{1/p}$ for $p=1,2,3,...$ (note that $\mu$ fits into both the moment sequence and this one as the first term) and then defining moments -- and all manner of calculations in relation to moments -- in terms of them. Note that these quantities are all measured in the original units, which is one advantage over moments (which are in $p$-th powers of the original units, and so harder to interpret). This would make the population standard deviation the defined quantity and variance defined in terms of it. However, it would make quantities like the moment generating function (or some equivalent relating to the new quantities defined above) rather less "natural", which would make things a little more awkward (but some conventions are a bit like that). There's some convenient properties of the MGF that would not be as convenient cast the other way. More basic, to my mind (but related to it), is that there are a number of basic properties of variance that are more convenient when written as properties of variance than when written as properties of standard deviation (e.g. the variance of sums of independent random variables is the sum of the variances). This additivity is a property that's not shared by other measures of dispersion and it has a number of important consequences. [There are similar relationships between the other cumulants, so this is a sense in which we might want to define things in relation to moments more generally.] All of these reasons are arguably either convention or convenience but to some extent it's a matter of viewpoint (e.g. from some points of view moments are pretty important quantities, from others they're not all that important). It may be that the "at a deep level" bit is intended to imply nothing more than kjetil's "when developing the theory". I would agree with kjetil's point that you raised in your question; to some extent this answer is merely a hand-wavy discussion of it.
Is variance a more fundamental concept than standard deviation?
Robert's and Bey's answers do give part of the story (i.e. moments tend to be regarded as basic properties of distributions, and conventionally standard deviation is defined in terms of the second cen
Is variance a more fundamental concept than standard deviation? Robert's and Bey's answers do give part of the story (i.e. moments tend to be regarded as basic properties of distributions, and conventionally standard deviation is defined in terms of the second central moment rather than the other way around), but the extent to which those things are really fundamental depends partly on what we mean by the term. There would be no insurmountable problem, for example, if our conventions went the other way -- there's nothing stopping us conventionally defining some other sequence of quantities in place of the usual moments, say $E[(X-\mu)^p]^{1/p}$ for $p=1,2,3,...$ (note that $\mu$ fits into both the moment sequence and this one as the first term) and then defining moments -- and all manner of calculations in relation to moments -- in terms of them. Note that these quantities are all measured in the original units, which is one advantage over moments (which are in $p$-th powers of the original units, and so harder to interpret). This would make the population standard deviation the defined quantity and variance defined in terms of it. However, it would make quantities like the moment generating function (or some equivalent relating to the new quantities defined above) rather less "natural", which would make things a little more awkward (but some conventions are a bit like that). There's some convenient properties of the MGF that would not be as convenient cast the other way. More basic, to my mind (but related to it), is that there are a number of basic properties of variance that are more convenient when written as properties of variance than when written as properties of standard deviation (e.g. the variance of sums of independent random variables is the sum of the variances). This additivity is a property that's not shared by other measures of dispersion and it has a number of important consequences. [There are similar relationships between the other cumulants, so this is a sense in which we might want to define things in relation to moments more generally.] All of these reasons are arguably either convention or convenience but to some extent it's a matter of viewpoint (e.g. from some points of view moments are pretty important quantities, from others they're not all that important). It may be that the "at a deep level" bit is intended to imply nothing more than kjetil's "when developing the theory". I would agree with kjetil's point that you raised in your question; to some extent this answer is merely a hand-wavy discussion of it.
Is variance a more fundamental concept than standard deviation? Robert's and Bey's answers do give part of the story (i.e. moments tend to be regarded as basic properties of distributions, and conventionally standard deviation is defined in terms of the second cen
15,688
Is variance a more fundamental concept than standard deviation?
Variance is defined by the first and second moments of a distribution. In contrast, the standard deviation is more like a "norm" than a moment. Moments are fundamental properties of a distribution, whereas norms are just ways to make a distinction.
Is variance a more fundamental concept than standard deviation?
Variance is defined by the first and second moments of a distribution. In contrast, the standard deviation is more like a "norm" than a moment. Moments are fundamental properties of a distribution, wh
Is variance a more fundamental concept than standard deviation? Variance is defined by the first and second moments of a distribution. In contrast, the standard deviation is more like a "norm" than a moment. Moments are fundamental properties of a distribution, whereas norms are just ways to make a distinction.
Is variance a more fundamental concept than standard deviation? Variance is defined by the first and second moments of a distribution. In contrast, the standard deviation is more like a "norm" than a moment. Moments are fundamental properties of a distribution, wh
15,689
Is variance a more fundamental concept than standard deviation?
The variance is more fundamental than the standard deviation because the standard deviation is defined as 'the square root of the variance', e.g. its definition depends completely on the variance. Variance, on the other hand is defined - completely independently - as the 'the expectation of the squared difference between a sample and the mean'.
Is variance a more fundamental concept than standard deviation?
The variance is more fundamental than the standard deviation because the standard deviation is defined as 'the square root of the variance', e.g. its definition depends completely on the variance. Var
Is variance a more fundamental concept than standard deviation? The variance is more fundamental than the standard deviation because the standard deviation is defined as 'the square root of the variance', e.g. its definition depends completely on the variance. Variance, on the other hand is defined - completely independently - as the 'the expectation of the squared difference between a sample and the mean'.
Is variance a more fundamental concept than standard deviation? The variance is more fundamental than the standard deviation because the standard deviation is defined as 'the square root of the variance', e.g. its definition depends completely on the variance. Var
15,690
Is variance a more fundamental concept than standard deviation?
In addition to the answers given here, one could point out that variance is more 'fundamental' than standard deviation in some sense, if we consider estimation from a (e.g. normal) population. For a sample of size $n$ drawn from a population $X$ with $\mathrm{Var}[X] = \sigma^2$, it is known that the sample variance $S^2$ is an unbiased estimator of $\sigma^2$, but $S$ is in general not an unbiased estimator of $\sigma$: $$ \mathrm{E}[S^2] = \sigma^2\,,\ \mathrm{E}[S]\neq \sigma\,, $$ see here, which follows from Jensen's inequality.
Is variance a more fundamental concept than standard deviation?
In addition to the answers given here, one could point out that variance is more 'fundamental' than standard deviation in some sense, if we consider estimation from a (e.g. normal) population. For a s
Is variance a more fundamental concept than standard deviation? In addition to the answers given here, one could point out that variance is more 'fundamental' than standard deviation in some sense, if we consider estimation from a (e.g. normal) population. For a sample of size $n$ drawn from a population $X$ with $\mathrm{Var}[X] = \sigma^2$, it is known that the sample variance $S^2$ is an unbiased estimator of $\sigma^2$, but $S$ is in general not an unbiased estimator of $\sigma$: $$ \mathrm{E}[S^2] = \sigma^2\,,\ \mathrm{E}[S]\neq \sigma\,, $$ see here, which follows from Jensen's inequality.
Is variance a more fundamental concept than standard deviation? In addition to the answers given here, one could point out that variance is more 'fundamental' than standard deviation in some sense, if we consider estimation from a (e.g. normal) population. For a s
15,691
Including Interaction Terms in Random Forest
Although feature engineering is very important in real life, trees (and random forests) are very good at finding interaction terms of the form x*y. Here is a toy example of a regression with a two-way interaction. A naive linear model is compared with a tree and a bag of trees (which is a simpler alternative to a random forest.) As you can see, the tree by itself is pretty good at finding the interaction but the linear model is no good in this example. # fake data x <- rnorm(1000, sd=3) y <- rnorm(1000, sd=3) z <- x + y + 10*x*y + rnorm(1000, 0, 0.2) dat <- data.frame(x, y, z) # test and train split test <- sample(1:nrow(dat), 200) train <- (1:1000)[-test] # bag of trees model function boot_tree <- function(formula, dat, N=100){ models <- list() for (i in 1:N){ models[[i]] <- rpart(formula, dat[sample(nrow(dat), nrow(dat), replace=T), ]) } class(models) <- "boot_tree" models } # prediction function for bag of trees predict.boot_tree <- function(models, newdat){ preds <- matrix(0, nc=length(models), nr=nrow(newdat)) for (i in 1:length(models)){ preds[,i] <- predict(models[[i]], newdat) } apply(preds, 1, function(x) mean(x, trim=0.1)) } ## Fit models and predict: # linear model model1 <- lm(z ~ x + y, data=dat[train,]) pred1 <- predict(model1, dat[test,]) # tree require(rpart) model2 <- rpart(z ~ x + y, data=dat[train,]) pred2 <- predict(model2, dat[test,]) # bag of trees model3 <- boot_tree("z ~ x+y", dat) pred3 <- predict(model3, dat[test,]) ylim = range(c(pred1, pred2, pred3)) # plot predictions and true z plot(dat$z[test], predict(model1, dat[test,]), pch=19, xlab="Actual z", ylab="Predicted z", ylim=ylim) points(dat$z[test], predict(model2, dat[test,]), col="green", pch=19) points(dat$z[test], predict(model3, dat[test,]), col="blue", pch=19) abline(0, 1, lwd=3, col="orange") legend("topleft", pch=rep(19,3), col=c("black", "green", "blue"), legend=c("Linear", "Tree", "Forest"))
Including Interaction Terms in Random Forest
Although feature engineering is very important in real life, trees (and random forests) are very good at finding interaction terms of the form x*y. Here is a toy example of a regression with a two-way
Including Interaction Terms in Random Forest Although feature engineering is very important in real life, trees (and random forests) are very good at finding interaction terms of the form x*y. Here is a toy example of a regression with a two-way interaction. A naive linear model is compared with a tree and a bag of trees (which is a simpler alternative to a random forest.) As you can see, the tree by itself is pretty good at finding the interaction but the linear model is no good in this example. # fake data x <- rnorm(1000, sd=3) y <- rnorm(1000, sd=3) z <- x + y + 10*x*y + rnorm(1000, 0, 0.2) dat <- data.frame(x, y, z) # test and train split test <- sample(1:nrow(dat), 200) train <- (1:1000)[-test] # bag of trees model function boot_tree <- function(formula, dat, N=100){ models <- list() for (i in 1:N){ models[[i]] <- rpart(formula, dat[sample(nrow(dat), nrow(dat), replace=T), ]) } class(models) <- "boot_tree" models } # prediction function for bag of trees predict.boot_tree <- function(models, newdat){ preds <- matrix(0, nc=length(models), nr=nrow(newdat)) for (i in 1:length(models)){ preds[,i] <- predict(models[[i]], newdat) } apply(preds, 1, function(x) mean(x, trim=0.1)) } ## Fit models and predict: # linear model model1 <- lm(z ~ x + y, data=dat[train,]) pred1 <- predict(model1, dat[test,]) # tree require(rpart) model2 <- rpart(z ~ x + y, data=dat[train,]) pred2 <- predict(model2, dat[test,]) # bag of trees model3 <- boot_tree("z ~ x+y", dat) pred3 <- predict(model3, dat[test,]) ylim = range(c(pred1, pred2, pred3)) # plot predictions and true z plot(dat$z[test], predict(model1, dat[test,]), pch=19, xlab="Actual z", ylab="Predicted z", ylim=ylim) points(dat$z[test], predict(model2, dat[test,]), col="green", pch=19) points(dat$z[test], predict(model3, dat[test,]), col="blue", pch=19) abline(0, 1, lwd=3, col="orange") legend("topleft", pch=rep(19,3), col=c("black", "green", "blue"), legend=c("Linear", "Tree", "Forest"))
Including Interaction Terms in Random Forest Although feature engineering is very important in real life, trees (and random forests) are very good at finding interaction terms of the form x*y. Here is a toy example of a regression with a two-way
15,692
Definition of normalized Euclidean distance
The normalized squared euclidean distance gives the squared distance between two vectors where there lengths have been scaled to have unit norm. This is helpful when the direction of the vector is meaningful but the magnitude is not. It's not related to Mahalanobis distance.
Definition of normalized Euclidean distance
The normalized squared euclidean distance gives the squared distance between two vectors where there lengths have been scaled to have unit norm. This is helpful when the direction of the vector is mea
Definition of normalized Euclidean distance The normalized squared euclidean distance gives the squared distance between two vectors where there lengths have been scaled to have unit norm. This is helpful when the direction of the vector is meaningful but the magnitude is not. It's not related to Mahalanobis distance.
Definition of normalized Euclidean distance The normalized squared euclidean distance gives the squared distance between two vectors where there lengths have been scaled to have unit norm. This is helpful when the direction of the vector is mea
15,693
Definition of normalized Euclidean distance
The weighted Minkowski distance of order $q$ between two real vectors $u, v \in \mathbb{R}^n$ is given by $$d^{(q)} (u, v) = \left(\sum_{i=1}^n w_i (u_i - v_i)^q \right)^\frac{1}{q}$$ [See equation $3.1.7$, Clustering Methodology for Symbolic Data By Lynne Billard, Edwin Diday (2019)] If we choose $w_i = \frac{1}{n}$ and $q = 2$, we have the so called "normalized Euclidean distance" between $u$ and $v$ $$d_{NE}^2(u, v) = \frac{1}{n} \sum_{i=1}^n \left(u_i - v_i \right)^2$$ Unfortunately, the above definition does not have nice properties... Another definition given at Wolfram.com has one nice property; $d_W$ is always between $0$ and $1$ NormalizedSquaredEuclideanDistance[u,v] is equivalent to 1/2*Norm[(u-Mean[u])-(v-Mean[v])]^2/(Norm[u-Mean[u]]^2+Norm[v-Mean[v]]^2) For computational purposes, I simplified the definitions given above: $$d_{NE}^2(u, v) = \mathrm{Var}(u-v) + (\bar{u} - \bar{v})^2$$ $$NED^2(u, v) = d_W ^2(u, v) = \frac{1}{2}\frac{\mathrm{Var}(u-v)}{\mathrm{Var}(u) + \mathrm{Var}(v)}$$ where $\mathrm{Var}(x) = \displaystyle \frac{1}{n}\sum_{i=1}^n (x_i - \bar{x})^2$ and $\bar{x} = \frac{\sum_{i=1}^n x_i}{n}$ A few properties/special cases: If (i) $||u||_2 = ||v||_2 = 1$, i.e., $\sum_{i=1}^n u_i^2 = \sum_{i=1}^n v_i^2 = 1$ and (ii) $\bar{u} = \bar{v} = 0$, i.e., $\sum_{i=1}^n u_i = \sum_{i=1}^n v_i = 0$ then (A) $\mathrm{Var}(u) = \mathrm{Var}(v) = \frac{1}{n}$, $\mathrm{Cov}(u, v) = \frac{1}{n}\sum_{i=1}^n u_i v_i$ and $\rho(u,v) = \sum_{i=1}^n u_i v_i = \cos \theta$ where $\theta$ is the angle between the vectors $u$ and $v$ (B) $$d_{NE}^2(u, v) = \frac{2}{n}(1 - \cos \theta)$$ (C) $$d_W^2 (u, v) = \frac{1}{2}(1 - \cos \theta)$$ Discussion: Suppose we define the following distance measure $d_E^2(u, v)$ between the vectors $u, v \in \mathbb{R^n}$ $$d_E^2(u, v) = \frac{\sum_{i=1}^n (u_i - v_i)^2}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2}$$ This measure lies between $0$ and $\sqrt{2}$ The Wolfram.com definition is closely related to the above. Instead of $u$ and $v$, it considers the mean centered version of the above definition and adds a factor of $\frac{1}{2}$ so that the value lies between $0$ and $1$ Proof: $$\sum_{i=1}^n (u_i - v_i)^2 \geq 0 \implies \frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2} \leq 1$$ $$\sum_{i=1}^n (u_i + v_i)^2 \geq 0 \implies -1 \leq \frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2}$$ Combining the above two inequalities: $$-1 \leq \frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2} \leq 1$$ Or, $$-1 \leq -\frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2} \leq 1$$ Or, $$0 \leq 1-\frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2} \leq 2$$ Or, $$0 \leq \frac{1}{2}\left( 1-\frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2} \right)\leq 1$$ Or, $$0 \leq \frac{1}{2} d_E^2(u, v)\leq 1$$ Or, $$0 \leq d_E(u, v)\leq \sqrt{2}$$ How do we prove that $$0 \leq d_W ^2(u, v) = \frac{1}{2}\frac{\mathrm{Var}(u-v)}{\mathrm{Var}(u) + \mathrm{Var}(v)} \leq 1$$ Proof: We are required to prove that (TPT) $$0 \leq \frac{1}{2}\frac{\mathrm{Var}(u-v)}{\mathrm{Var}(u) + \mathrm{Var}(v)} \leq 1$$ i.e., TPT $$0 \leq \mathrm{Var}(u-v) \leq 2(\mathrm{Var}(u) + \mathrm{Var}(v))$$ Now $\mathrm{Var}(u-v) \geq 0$ since variance is always non-negative. We need TPT $$\mathrm{Var}(u-v) \leq 2(\mathrm{Var}(u) + \mathrm{Var}(v))$$ i.e., TPT $$\mathrm{Var}(u-v) = \mathrm{Var}(u) + \mathrm{Var}(v) - 2 \mathrm{Cov}(u, v) \leq 2(\mathrm{Var}(u) + \mathrm{Var}(v))$$ i.e., TPT $$\mathrm{Var}(u) + \mathrm{Var}(v) + 2 \mathrm{Cov}(u, v) \geq 0$$ i.e., TPT $$\mathrm{Var}(u+v) \geq 0$$ which is always true since variance is always non-negative.
Definition of normalized Euclidean distance
The weighted Minkowski distance of order $q$ between two real vectors $u, v \in \mathbb{R}^n$ is given by $$d^{(q)} (u, v) = \left(\sum_{i=1}^n w_i (u_i - v_i)^q \right)^\frac{1}{q}$$ [See equation $
Definition of normalized Euclidean distance The weighted Minkowski distance of order $q$ between two real vectors $u, v \in \mathbb{R}^n$ is given by $$d^{(q)} (u, v) = \left(\sum_{i=1}^n w_i (u_i - v_i)^q \right)^\frac{1}{q}$$ [See equation $3.1.7$, Clustering Methodology for Symbolic Data By Lynne Billard, Edwin Diday (2019)] If we choose $w_i = \frac{1}{n}$ and $q = 2$, we have the so called "normalized Euclidean distance" between $u$ and $v$ $$d_{NE}^2(u, v) = \frac{1}{n} \sum_{i=1}^n \left(u_i - v_i \right)^2$$ Unfortunately, the above definition does not have nice properties... Another definition given at Wolfram.com has one nice property; $d_W$ is always between $0$ and $1$ NormalizedSquaredEuclideanDistance[u,v] is equivalent to 1/2*Norm[(u-Mean[u])-(v-Mean[v])]^2/(Norm[u-Mean[u]]^2+Norm[v-Mean[v]]^2) For computational purposes, I simplified the definitions given above: $$d_{NE}^2(u, v) = \mathrm{Var}(u-v) + (\bar{u} - \bar{v})^2$$ $$NED^2(u, v) = d_W ^2(u, v) = \frac{1}{2}\frac{\mathrm{Var}(u-v)}{\mathrm{Var}(u) + \mathrm{Var}(v)}$$ where $\mathrm{Var}(x) = \displaystyle \frac{1}{n}\sum_{i=1}^n (x_i - \bar{x})^2$ and $\bar{x} = \frac{\sum_{i=1}^n x_i}{n}$ A few properties/special cases: If (i) $||u||_2 = ||v||_2 = 1$, i.e., $\sum_{i=1}^n u_i^2 = \sum_{i=1}^n v_i^2 = 1$ and (ii) $\bar{u} = \bar{v} = 0$, i.e., $\sum_{i=1}^n u_i = \sum_{i=1}^n v_i = 0$ then (A) $\mathrm{Var}(u) = \mathrm{Var}(v) = \frac{1}{n}$, $\mathrm{Cov}(u, v) = \frac{1}{n}\sum_{i=1}^n u_i v_i$ and $\rho(u,v) = \sum_{i=1}^n u_i v_i = \cos \theta$ where $\theta$ is the angle between the vectors $u$ and $v$ (B) $$d_{NE}^2(u, v) = \frac{2}{n}(1 - \cos \theta)$$ (C) $$d_W^2 (u, v) = \frac{1}{2}(1 - \cos \theta)$$ Discussion: Suppose we define the following distance measure $d_E^2(u, v)$ between the vectors $u, v \in \mathbb{R^n}$ $$d_E^2(u, v) = \frac{\sum_{i=1}^n (u_i - v_i)^2}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2}$$ This measure lies between $0$ and $\sqrt{2}$ The Wolfram.com definition is closely related to the above. Instead of $u$ and $v$, it considers the mean centered version of the above definition and adds a factor of $\frac{1}{2}$ so that the value lies between $0$ and $1$ Proof: $$\sum_{i=1}^n (u_i - v_i)^2 \geq 0 \implies \frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2} \leq 1$$ $$\sum_{i=1}^n (u_i + v_i)^2 \geq 0 \implies -1 \leq \frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2}$$ Combining the above two inequalities: $$-1 \leq \frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2} \leq 1$$ Or, $$-1 \leq -\frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2} \leq 1$$ Or, $$0 \leq 1-\frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2} \leq 2$$ Or, $$0 \leq \frac{1}{2}\left( 1-\frac{2\sum_{i=1}^n u_i v_i}{\sum_{i=1}^n u_i^2 + \sum_{i=1}^n v_i^2} \right)\leq 1$$ Or, $$0 \leq \frac{1}{2} d_E^2(u, v)\leq 1$$ Or, $$0 \leq d_E(u, v)\leq \sqrt{2}$$ How do we prove that $$0 \leq d_W ^2(u, v) = \frac{1}{2}\frac{\mathrm{Var}(u-v)}{\mathrm{Var}(u) + \mathrm{Var}(v)} \leq 1$$ Proof: We are required to prove that (TPT) $$0 \leq \frac{1}{2}\frac{\mathrm{Var}(u-v)}{\mathrm{Var}(u) + \mathrm{Var}(v)} \leq 1$$ i.e., TPT $$0 \leq \mathrm{Var}(u-v) \leq 2(\mathrm{Var}(u) + \mathrm{Var}(v))$$ Now $\mathrm{Var}(u-v) \geq 0$ since variance is always non-negative. We need TPT $$\mathrm{Var}(u-v) \leq 2(\mathrm{Var}(u) + \mathrm{Var}(v))$$ i.e., TPT $$\mathrm{Var}(u-v) = \mathrm{Var}(u) + \mathrm{Var}(v) - 2 \mathrm{Cov}(u, v) \leq 2(\mathrm{Var}(u) + \mathrm{Var}(v))$$ i.e., TPT $$\mathrm{Var}(u) + \mathrm{Var}(v) + 2 \mathrm{Cov}(u, v) \geq 0$$ i.e., TPT $$\mathrm{Var}(u+v) \geq 0$$ which is always true since variance is always non-negative.
Definition of normalized Euclidean distance The weighted Minkowski distance of order $q$ between two real vectors $u, v \in \mathbb{R}^n$ is given by $$d^{(q)} (u, v) = \left(\sum_{i=1}^n w_i (u_i - v_i)^q \right)^\frac{1}{q}$$ [See equation $
15,694
Definition of normalized Euclidean distance
Here is one way of thinking about the Normalised Squared Euclidean Distance $NED^2$, defined as $$NED^2(u,v) = 0.5 \frac{ \text{Var}(u-v) }{ \text{Var}(u) + \text{Var}(v) }$$ for two vectors $u,v\in\mathbb{R}^k$. This definition does not appear very much in the scientific literature. I can see at least two problems with this definition. First, it does not make sense in the case where the dimension $k=1$ because all the variances are zero in this case. Secondly, if both $u$ and $v$ are constant, i.e. $u_i=c$, $v_i=c'$ for all $i$, then the distance is undefined regardless of $k$. In fact, this second scenario covers the first as a special case. One principle by which to handle these problems with the definition is to consider the underlying context. Although not well used in the literature, I suspect that $NED^2$ was originally defined in the context of image processing of the kind described in this question. Here, an image is regarded as a vector of pixel intensity values, so we may think of $u$ and $v$ as representing images we wish to compare, with $k$ being the number of pixels in each image. Frequently, in image processing, we are only interested in relative spatial variation in pixel intensities rather than the absolute values of the pixel intensities, which motivates the use of a distance measure which 'de-means' the pixel intensity vectors. Two images which are 'shifts' of each other, so that $u_i=v_i+c$ for all $i$, are essentially 'the same' for many purposes. So, roughly speaking, $NED^2$ quantifies the variation in the difference image $u-v$, normalised by the sum of the variation apparent in the two original images $u$,$v$. With this in mind, let's go back to the problem with the definition of $NED^2$. If $u_i=c$, $v_i=c'$ for all $i$, then $NED^2$ is undefined. However, the images are just shifts of one another, so should be regarded as essentially the same. Therefore, in the context of image processing I suggest that $NED^2$ should be set to zero in all cases where it is apparently undefined. How should you proceed if you are working in in a different context or application area? I can see three possible outcomes: The same principles apply as for image processing, so you define $NED^2$ to be zero in all undefined cases. The context motivates an alternative definition of $NED^2$ in the undefined cases e.g. the one you have proposed in the above question. The problems with the definition motivate you to reject $NED^2$ as a useful distance measure, so you look for other measures instead. Which of these three options applies will depend on your problem and your reasons for using $NED^2$. Additional details: more formally, $NED^2$ is really a distance measure on the quotient vector space $\mathbb{R}^k/\mathbb{R}\mathbf{1}$ where $\mathbf{1}$ denotes the vector $(1,1,\cdots,1)$. This is just a consequence of $NED^2$ being invariant to adding multiples of $\mathbf{1}$ to either $u$ or $v$. On the quotient space $NED^2$ is defined everywhere except at $([\mathbf{0}],[\mathbf{0}])$, where $\mathbf{0}$ is the zero vector and $[\mathbf{0}]=\mathbb{R}\mathbf{1}$ is the equivalence class of the zero vector. In this setting it seems very logical to define $NED^2$ to be zero at this single undefined point.
Definition of normalized Euclidean distance
Here is one way of thinking about the Normalised Squared Euclidean Distance $NED^2$, defined as $$NED^2(u,v) = 0.5 \frac{ \text{Var}(u-v) }{ \text{Var}(u) + \text{Var}(v) }$$ for two vectors $u,v\in\m
Definition of normalized Euclidean distance Here is one way of thinking about the Normalised Squared Euclidean Distance $NED^2$, defined as $$NED^2(u,v) = 0.5 \frac{ \text{Var}(u-v) }{ \text{Var}(u) + \text{Var}(v) }$$ for two vectors $u,v\in\mathbb{R}^k$. This definition does not appear very much in the scientific literature. I can see at least two problems with this definition. First, it does not make sense in the case where the dimension $k=1$ because all the variances are zero in this case. Secondly, if both $u$ and $v$ are constant, i.e. $u_i=c$, $v_i=c'$ for all $i$, then the distance is undefined regardless of $k$. In fact, this second scenario covers the first as a special case. One principle by which to handle these problems with the definition is to consider the underlying context. Although not well used in the literature, I suspect that $NED^2$ was originally defined in the context of image processing of the kind described in this question. Here, an image is regarded as a vector of pixel intensity values, so we may think of $u$ and $v$ as representing images we wish to compare, with $k$ being the number of pixels in each image. Frequently, in image processing, we are only interested in relative spatial variation in pixel intensities rather than the absolute values of the pixel intensities, which motivates the use of a distance measure which 'de-means' the pixel intensity vectors. Two images which are 'shifts' of each other, so that $u_i=v_i+c$ for all $i$, are essentially 'the same' for many purposes. So, roughly speaking, $NED^2$ quantifies the variation in the difference image $u-v$, normalised by the sum of the variation apparent in the two original images $u$,$v$. With this in mind, let's go back to the problem with the definition of $NED^2$. If $u_i=c$, $v_i=c'$ for all $i$, then $NED^2$ is undefined. However, the images are just shifts of one another, so should be regarded as essentially the same. Therefore, in the context of image processing I suggest that $NED^2$ should be set to zero in all cases where it is apparently undefined. How should you proceed if you are working in in a different context or application area? I can see three possible outcomes: The same principles apply as for image processing, so you define $NED^2$ to be zero in all undefined cases. The context motivates an alternative definition of $NED^2$ in the undefined cases e.g. the one you have proposed in the above question. The problems with the definition motivate you to reject $NED^2$ as a useful distance measure, so you look for other measures instead. Which of these three options applies will depend on your problem and your reasons for using $NED^2$. Additional details: more formally, $NED^2$ is really a distance measure on the quotient vector space $\mathbb{R}^k/\mathbb{R}\mathbf{1}$ where $\mathbf{1}$ denotes the vector $(1,1,\cdots,1)$. This is just a consequence of $NED^2$ being invariant to adding multiples of $\mathbf{1}$ to either $u$ or $v$. On the quotient space $NED^2$ is defined everywhere except at $([\mathbf{0}],[\mathbf{0}])$, where $\mathbf{0}$ is the zero vector and $[\mathbf{0}]=\mathbb{R}\mathbf{1}$ is the equivalence class of the zero vector. In this setting it seems very logical to define $NED^2$ to be zero at this single undefined point.
Definition of normalized Euclidean distance Here is one way of thinking about the Normalised Squared Euclidean Distance $NED^2$, defined as $$NED^2(u,v) = 0.5 \frac{ \text{Var}(u-v) }{ \text{Var}(u) + \text{Var}(v) }$$ for two vectors $u,v\in\m
15,695
Definition of normalized Euclidean distance
I believe this is the correct implementation in pytorch (should be easy to translate to numpy etc): import torch.nn as nn def ned(x1, x2, dim=1, eps=1e-8): ned_2 = 0.5 * ((x1 - x2).var(dim=dim) / (x1.var(dim=dim) + x2.var(dim=dim) + eps)) return ned_2 ** 0.5 def nes(x1, x2, dim=1, eps=1e-8): return 1 - ned(x1, x2, dim, eps) dim = 1 # apply cosine accross the second dimension/feature dimension k = 4 # number of examples d = 8 # dimension of feature space x1 = torch.randn(k, d) x2 = x1 * 3 print(f'x1 = {x1.size()}') ned_tensor = ned(x1, x2, dim=dim) print(ned_tensor) print(ned_tensor.size()) print(nes(x1, x2, dim=dim)) output: x1 = torch.Size([4, 8]) tensor([0.4472, 0.4472, 0.4472, 0.4472]) torch.Size([4]) tensor([0.5528, 0.5528, 0.5528, 0.5528]) feel free to comment if you see anything wrong. Related: https://discuss.pytorch.org/t/how-does-one-compute-the-normalized-euclidean-distance-similarity-in-a-numerically-stable-way-in-a-vectorized-way-in-pytorch/110829 https://github.com/pytorch/pytorch/issues/52005 Definition of normalized Euclidean distance Update: Edge cases taken care of def ned_torch(x1: torch.Tensor, x2: torch.Tensor, dim=1, eps=1e-8) -> torch.Tensor: """ Normalized eucledian distance in pytorch. Cases: 1. For comparison of two vecs directly make sure vecs are of size [B] e.g. when using nes as a loss function. in this case each number is not considered a representation but a number and B is the entire vector to compare x1 and x2. 2. For comparison of two batch of representation of size 1D (e.g. scores) make sure it's of shape [B, 1]. In this case each number *is* the representation of the example. Thus a collection of reps [B, 1] is mapped to a rep of the same size [B, 1]. Note usually D does decrease since reps are not of size 1 (see case 3) 3. For the rest specify the dimension. Common use case [B, D] -> [B, 1] for comparing two set of activations of size D. In the case when D=1 then we have [B, 1] -> [B, 1]. If you meant x1, x2 [D, 1] to be two vectors of size D to be compare feed them with shape [D]. https://discuss.pytorch.org/t/how-does-one-compute-the-normalized-euclidean-distance-similarity-in-a-numerically-stable-way-in-a-vectorized-way-in-pytorch/110829 https://stats.stackexchange.com/questions/136232/definition-of-normalized-euclidean-distance/498753?noredirect=1#comment937825_498753 """ # to compute ned for two individual vectors e.g to compute a loss (NOT BATCHES/COLLECTIONS of vectorsc) if len(x1.size()) == 1: # [K] -> [1] ned_2 = 0.5 * ((x1 - x2).var() / (x1.var() + x2.var() + eps)) # if the input is a (row) vector e.g. when comparing two batches of acts of D=1 like with scores right before sf elif x1.size() == torch.Size([x1.size(0), 1]): # note this special case is needed since var over dim=1 is nan (1 value has no variance). # [B, 1] -> [B] ned_2 = 0.5 * ((x1 - x2)**2 / (x1**2 + x2**2 + eps)).squeeze() # Squeeze important to be consistent with .var, otherwise tensors of different sizes come out without the user expecting it # common case is if input is a batch else: # e.g. [B, D] -> [B] ned_2 = 0.5 * ((x1 - x2).var(dim=dim) / (x1.var(dim=dim) + x2.var(dim=dim) + eps)) return ned_2 ** 0.5 def nes_torch(x1, x2, dim=1, eps=1e-8): return 1 - ned_torch(x1, x2, dim, eps) def nes_torch(x1, x2, dim=1, eps=1e-8): return 1 - ned_torch(x1, x2, dim, eps) repo: https://github.com/brando90/Normalized-Eucledian-Distance-and-Similarity
Definition of normalized Euclidean distance
I believe this is the correct implementation in pytorch (should be easy to translate to numpy etc): import torch.nn as nn def ned(x1, x2, dim=1, eps=1e-8): ned_2 = 0.5 * ((x1 - x2).var(dim=dim)
Definition of normalized Euclidean distance I believe this is the correct implementation in pytorch (should be easy to translate to numpy etc): import torch.nn as nn def ned(x1, x2, dim=1, eps=1e-8): ned_2 = 0.5 * ((x1 - x2).var(dim=dim) / (x1.var(dim=dim) + x2.var(dim=dim) + eps)) return ned_2 ** 0.5 def nes(x1, x2, dim=1, eps=1e-8): return 1 - ned(x1, x2, dim, eps) dim = 1 # apply cosine accross the second dimension/feature dimension k = 4 # number of examples d = 8 # dimension of feature space x1 = torch.randn(k, d) x2 = x1 * 3 print(f'x1 = {x1.size()}') ned_tensor = ned(x1, x2, dim=dim) print(ned_tensor) print(ned_tensor.size()) print(nes(x1, x2, dim=dim)) output: x1 = torch.Size([4, 8]) tensor([0.4472, 0.4472, 0.4472, 0.4472]) torch.Size([4]) tensor([0.5528, 0.5528, 0.5528, 0.5528]) feel free to comment if you see anything wrong. Related: https://discuss.pytorch.org/t/how-does-one-compute-the-normalized-euclidean-distance-similarity-in-a-numerically-stable-way-in-a-vectorized-way-in-pytorch/110829 https://github.com/pytorch/pytorch/issues/52005 Definition of normalized Euclidean distance Update: Edge cases taken care of def ned_torch(x1: torch.Tensor, x2: torch.Tensor, dim=1, eps=1e-8) -> torch.Tensor: """ Normalized eucledian distance in pytorch. Cases: 1. For comparison of two vecs directly make sure vecs are of size [B] e.g. when using nes as a loss function. in this case each number is not considered a representation but a number and B is the entire vector to compare x1 and x2. 2. For comparison of two batch of representation of size 1D (e.g. scores) make sure it's of shape [B, 1]. In this case each number *is* the representation of the example. Thus a collection of reps [B, 1] is mapped to a rep of the same size [B, 1]. Note usually D does decrease since reps are not of size 1 (see case 3) 3. For the rest specify the dimension. Common use case [B, D] -> [B, 1] for comparing two set of activations of size D. In the case when D=1 then we have [B, 1] -> [B, 1]. If you meant x1, x2 [D, 1] to be two vectors of size D to be compare feed them with shape [D]. https://discuss.pytorch.org/t/how-does-one-compute-the-normalized-euclidean-distance-similarity-in-a-numerically-stable-way-in-a-vectorized-way-in-pytorch/110829 https://stats.stackexchange.com/questions/136232/definition-of-normalized-euclidean-distance/498753?noredirect=1#comment937825_498753 """ # to compute ned for two individual vectors e.g to compute a loss (NOT BATCHES/COLLECTIONS of vectorsc) if len(x1.size()) == 1: # [K] -> [1] ned_2 = 0.5 * ((x1 - x2).var() / (x1.var() + x2.var() + eps)) # if the input is a (row) vector e.g. when comparing two batches of acts of D=1 like with scores right before sf elif x1.size() == torch.Size([x1.size(0), 1]): # note this special case is needed since var over dim=1 is nan (1 value has no variance). # [B, 1] -> [B] ned_2 = 0.5 * ((x1 - x2)**2 / (x1**2 + x2**2 + eps)).squeeze() # Squeeze important to be consistent with .var, otherwise tensors of different sizes come out without the user expecting it # common case is if input is a batch else: # e.g. [B, D] -> [B] ned_2 = 0.5 * ((x1 - x2).var(dim=dim) / (x1.var(dim=dim) + x2.var(dim=dim) + eps)) return ned_2 ** 0.5 def nes_torch(x1, x2, dim=1, eps=1e-8): return 1 - ned_torch(x1, x2, dim, eps) def nes_torch(x1, x2, dim=1, eps=1e-8): return 1 - ned_torch(x1, x2, dim, eps) repo: https://github.com/brando90/Normalized-Eucledian-Distance-and-Similarity
Definition of normalized Euclidean distance I believe this is the correct implementation in pytorch (should be easy to translate to numpy etc): import torch.nn as nn def ned(x1, x2, dim=1, eps=1e-8): ned_2 = 0.5 * ((x1 - x2).var(dim=dim)
15,696
Gelman and Rubin convergence diagnostic, how to generalise to work with vectors?
A recommendation: just compute the PSRF separately for each scalar component The original article by Gelman & Rubin [1], as well as the Bayesian Data Analysis textbook of Gelman et al. [2], recommends calculating the potential scale reduction factor (PSRF) separately for each scalar parameter of interest. To deduce convergence, it is then required that all PSRFs are close to 1. It does not matter that your parameters are interpreted as random vectors, their components are scalars for which you can compute PSRFs. Brooks & Gelman [3] have proposed a multivariate extension of the PSRF, which I review in the next section of this answer. However, to quote Gelman & Shirley [4]: [...] these methods may sometimes represent overkill: individual parameters can be well estimated even while approximate convergence of simulations of a multivariate distribution can take a very long time. Alternative: multivariate extension by Brooks&Gelman Brooks & Gelman [3] propose a multivariate extension of the PSRF, where indeed one computes the estimated covariance matrix (your step 4) as a weighted sum of the within-chain ($W$) and between-chain ($B$) covariance matrices (your step 3): \begin{equation} \hat{V} = \frac{n-1}{n}W + \left ( 1 + \frac{1}{m} \right )\frac{B}{n}, \end{equation} where $n$ is the chain length. Then, one needs to define some scalar metric for the distance between the covariance matrices $\hat{V},W$. The authors propose \begin{equation} \hat{R} = \max_a \frac{a^T\hat{V}a}{a^TWa} = \frac{n-1}{n} + \left(\frac{m+1}{m}\right)\lambda_1, \end{equation} where $m$ is the number of chains, the equality is shown in the article with $\lambda_1$ being the largest positive eigenvalue of $W^{-1}\hat{V}/n$. Then, the authors argue that under convergence of the chains, $\lambda_1\rightarrow 0$ and thus with big $n$ this multivariate $\hat{R}$ should converge near 1. References [1] Gelman, Andrew, and Donald B. Rubin. "Inference from iterative simulation using multiple sequences." Statistical Science (1992): 457-472. [2] Gelman, Andrew, et al. Bayesian data analysis. CRC press, 2013. [3] Brooks, Stephen P., and Andrew Gelman. "General methods for monitoring convergence of iterative simulations." Journal of Computational and Graphical Statistics 7.4 (1998): 434-455. [4] Gelman, Andrew, and Kenneth Shirley. "Inference from simulations and monitoring convergence". (Chapter 6 in Brooks, Steve, et al., eds. Handbook of Markov Chain Monte Carlo. CRC Press, 2011.) All articles except the textbook [2] are available at Andrew Gelman's website Andrew Gelman's website.
Gelman and Rubin convergence diagnostic, how to generalise to work with vectors?
A recommendation: just compute the PSRF separately for each scalar component The original article by Gelman & Rubin [1], as well as the Bayesian Data Analysis textbook of Gelman et al. [2], recommends
Gelman and Rubin convergence diagnostic, how to generalise to work with vectors? A recommendation: just compute the PSRF separately for each scalar component The original article by Gelman & Rubin [1], as well as the Bayesian Data Analysis textbook of Gelman et al. [2], recommends calculating the potential scale reduction factor (PSRF) separately for each scalar parameter of interest. To deduce convergence, it is then required that all PSRFs are close to 1. It does not matter that your parameters are interpreted as random vectors, their components are scalars for which you can compute PSRFs. Brooks & Gelman [3] have proposed a multivariate extension of the PSRF, which I review in the next section of this answer. However, to quote Gelman & Shirley [4]: [...] these methods may sometimes represent overkill: individual parameters can be well estimated even while approximate convergence of simulations of a multivariate distribution can take a very long time. Alternative: multivariate extension by Brooks&Gelman Brooks & Gelman [3] propose a multivariate extension of the PSRF, where indeed one computes the estimated covariance matrix (your step 4) as a weighted sum of the within-chain ($W$) and between-chain ($B$) covariance matrices (your step 3): \begin{equation} \hat{V} = \frac{n-1}{n}W + \left ( 1 + \frac{1}{m} \right )\frac{B}{n}, \end{equation} where $n$ is the chain length. Then, one needs to define some scalar metric for the distance between the covariance matrices $\hat{V},W$. The authors propose \begin{equation} \hat{R} = \max_a \frac{a^T\hat{V}a}{a^TWa} = \frac{n-1}{n} + \left(\frac{m+1}{m}\right)\lambda_1, \end{equation} where $m$ is the number of chains, the equality is shown in the article with $\lambda_1$ being the largest positive eigenvalue of $W^{-1}\hat{V}/n$. Then, the authors argue that under convergence of the chains, $\lambda_1\rightarrow 0$ and thus with big $n$ this multivariate $\hat{R}$ should converge near 1. References [1] Gelman, Andrew, and Donald B. Rubin. "Inference from iterative simulation using multiple sequences." Statistical Science (1992): 457-472. [2] Gelman, Andrew, et al. Bayesian data analysis. CRC press, 2013. [3] Brooks, Stephen P., and Andrew Gelman. "General methods for monitoring convergence of iterative simulations." Journal of Computational and Graphical Statistics 7.4 (1998): 434-455. [4] Gelman, Andrew, and Kenneth Shirley. "Inference from simulations and monitoring convergence". (Chapter 6 in Brooks, Steve, et al., eds. Handbook of Markov Chain Monte Carlo. CRC Press, 2011.) All articles except the textbook [2] are available at Andrew Gelman's website Andrew Gelman's website.
Gelman and Rubin convergence diagnostic, how to generalise to work with vectors? A recommendation: just compute the PSRF separately for each scalar component The original article by Gelman & Rubin [1], as well as the Bayesian Data Analysis textbook of Gelman et al. [2], recommends
15,697
Are standardized betas in multiple linear regression partial correlations? [duplicate]
Longer answer. If I have this right -- Partial correlation: $$ r_{y1.2} = \frac{r_{y1}-r_{y2}r_{12}}{\sqrt{(1-r^2_{y2})(1-r^2_{12})}} $$ equivalent standardized beta: $$ \beta_1 = \frac{r_{y1}-r_{y2}r_{12}}{(1-r^2_{12})} $$ As you see, the denominator is different. Their relative size depends on whether $\sqrt{(1-r^2_{y2})}$ or $\sqrt{(1-r^2_{12})}$ is smaller.
Are standardized betas in multiple linear regression partial correlations? [duplicate]
Longer answer. If I have this right -- Partial correlation: $$ r_{y1.2} = \frac{r_{y1}-r_{y2}r_{12}}{\sqrt{(1-r^2_{y2})(1-r^2_{12})}} $$ equivalent standardized beta: $$ \beta_1 = \frac{r_{y1}-r_{y2}r
Are standardized betas in multiple linear regression partial correlations? [duplicate] Longer answer. If I have this right -- Partial correlation: $$ r_{y1.2} = \frac{r_{y1}-r_{y2}r_{12}}{\sqrt{(1-r^2_{y2})(1-r^2_{12})}} $$ equivalent standardized beta: $$ \beta_1 = \frac{r_{y1}-r_{y2}r_{12}}{(1-r^2_{12})} $$ As you see, the denominator is different. Their relative size depends on whether $\sqrt{(1-r^2_{y2})}$ or $\sqrt{(1-r^2_{12})}$ is smaller.
Are standardized betas in multiple linear regression partial correlations? [duplicate] Longer answer. If I have this right -- Partial correlation: $$ r_{y1.2} = \frac{r_{y1}-r_{y2}r_{12}}{\sqrt{(1-r^2_{y2})(1-r^2_{12})}} $$ equivalent standardized beta: $$ \beta_1 = \frac{r_{y1}-r_{y2}r
15,698
Are standardized betas in multiple linear regression partial correlations? [duplicate]
I've in another question the following correlation matrix C for the three variables X,Y,Z given: $$ \text{ C =} \small \left[ \begin{array} {rrr} 1&-0.286122&-0.448535\\ -0.286122&1&0.928251\\ -0.448535&0.928251&1 \end{array} \right] $$ From its cholesky-decomposition L $$ \text{ L =} \small \left[ \begin{array} {rrr} X\\Y\\Z \end{array} \right] = \left[ \begin{array} {rrr} 1&.&.\\ -0.286122&0.958193&.\\ -0.448535&0.834816&0.319215 \end{array} \right] $$ we can directly retrieve the partial correlation between Y,Z wrt. X as $ \small corr(Y,Z)_{\cdot X} = 0.958193 \cdot 0.834816 $ Now if we have the variables ordered such that the dependent variable is Z then the betas are computed by inverting the square-submatrix of the range in L which is populated by the independent variables X,Y: $$ L_{X,Y} = \small \left[ \begin{array} {rrr} 1&.\\ -0.286122&0.958193 \end{array} \right] $$ and its inverse, which is inserted into a 3x3 identity-matrix to form the matrix $M$: $$ M = \small \left[ \begin{array} {rrr} 1&.&.\\ 0.298605&1.043631&.\\ .&.&1 \end{array} \right] $$ Then the betas occur by the matrix-multiplication $ \beta = L \cdot M $ $$ \beta =\small \left[ \begin{array} {rrr} X\\Y\\Z \end{array} \right] = \small \left[ \begin{array} {rrr} 1&.&.\\ .&1&.\\ -0.199254&0.871240&0.319215 \end{array} \right] $$ which indicates, that the $\beta_X$ contribution for $Z$ is $\small \beta_X=-0.199254$ and the $\beta_Y$ contribution for $Z$ is $\small \beta_Y=0.871240$ . The unexplained variance in Z is the bottom-right entry squared: $\small resid^2= (0.319215)^2$ We see in $M$ that -being an inverse of a partial cholesky-matrix- it can contain values bigger than $1$ - and as well the Beta-matrix can then have entries bigger than 1. So - to come back to your question- the partial correlation between $Y$ and $Z$ were the product of the entries in the second column of the L-matrix. The $ \small \beta_Y$ however is the product of the entry in the second column of the Z-row with the inverse of that in the Y-row and the relation between the concepts of partial correlation and $\small \beta$ can be described by this observation. Additional comment: I find it a nice feature, that we get by this also the compositions of $X$ and $Y$ in terms of $X$ and $Y$ - which of course are trivially 1. It is also obvious, how we would proceed, if we had a second dependent variable, say $W$, and even that scheme can smoothly be extended to compute/show the coefficients of the generalization to the canonical correlation - but that's another story....
Are standardized betas in multiple linear regression partial correlations? [duplicate]
I've in another question the following correlation matrix C for the three variables X,Y,Z given: $$ \text{ C =} \small \left[ \begin{array} {rrr} 1&-0.286122&-0.448535\\ -0.286122&1&0.928251\\ -0.44
Are standardized betas in multiple linear regression partial correlations? [duplicate] I've in another question the following correlation matrix C for the three variables X,Y,Z given: $$ \text{ C =} \small \left[ \begin{array} {rrr} 1&-0.286122&-0.448535\\ -0.286122&1&0.928251\\ -0.448535&0.928251&1 \end{array} \right] $$ From its cholesky-decomposition L $$ \text{ L =} \small \left[ \begin{array} {rrr} X\\Y\\Z \end{array} \right] = \left[ \begin{array} {rrr} 1&.&.\\ -0.286122&0.958193&.\\ -0.448535&0.834816&0.319215 \end{array} \right] $$ we can directly retrieve the partial correlation between Y,Z wrt. X as $ \small corr(Y,Z)_{\cdot X} = 0.958193 \cdot 0.834816 $ Now if we have the variables ordered such that the dependent variable is Z then the betas are computed by inverting the square-submatrix of the range in L which is populated by the independent variables X,Y: $$ L_{X,Y} = \small \left[ \begin{array} {rrr} 1&.\\ -0.286122&0.958193 \end{array} \right] $$ and its inverse, which is inserted into a 3x3 identity-matrix to form the matrix $M$: $$ M = \small \left[ \begin{array} {rrr} 1&.&.\\ 0.298605&1.043631&.\\ .&.&1 \end{array} \right] $$ Then the betas occur by the matrix-multiplication $ \beta = L \cdot M $ $$ \beta =\small \left[ \begin{array} {rrr} X\\Y\\Z \end{array} \right] = \small \left[ \begin{array} {rrr} 1&.&.\\ .&1&.\\ -0.199254&0.871240&0.319215 \end{array} \right] $$ which indicates, that the $\beta_X$ contribution for $Z$ is $\small \beta_X=-0.199254$ and the $\beta_Y$ contribution for $Z$ is $\small \beta_Y=0.871240$ . The unexplained variance in Z is the bottom-right entry squared: $\small resid^2= (0.319215)^2$ We see in $M$ that -being an inverse of a partial cholesky-matrix- it can contain values bigger than $1$ - and as well the Beta-matrix can then have entries bigger than 1. So - to come back to your question- the partial correlation between $Y$ and $Z$ were the product of the entries in the second column of the L-matrix. The $ \small \beta_Y$ however is the product of the entry in the second column of the Z-row with the inverse of that in the Y-row and the relation between the concepts of partial correlation and $\small \beta$ can be described by this observation. Additional comment: I find it a nice feature, that we get by this also the compositions of $X$ and $Y$ in terms of $X$ and $Y$ - which of course are trivially 1. It is also obvious, how we would proceed, if we had a second dependent variable, say $W$, and even that scheme can smoothly be extended to compute/show the coefficients of the generalization to the canonical correlation - but that's another story....
Are standardized betas in multiple linear regression partial correlations? [duplicate] I've in another question the following correlation matrix C for the three variables X,Y,Z given: $$ \text{ C =} \small \left[ \begin{array} {rrr} 1&-0.286122&-0.448535\\ -0.286122&1&0.928251\\ -0.44
15,699
Are truncated numbers from a random number generator still 'random'?
Yes, the truncated values are random. The distribution has changed from a continuous distribution to a discrete distribution. Random values with discrete distributions are often used. There are senses in which this change to the distribution is very small. The maximum difference between the cumulative distribution functions is bounded by the maximum density of the original times the maximum change from rounding. The changes to the expected value and the standard deviation can be bounded similarly. There are senses in which the change to the distribution is large, e.g., the $L_1$ distance between any continuous distribution and any discrete distribution is maximal. The average of some discontinuous functions of the value may change a lot.
Are truncated numbers from a random number generator still 'random'?
Yes, the truncated values are random. The distribution has changed from a continuous distribution to a discrete distribution. Random values with discrete distributions are often used. There are senses
Are truncated numbers from a random number generator still 'random'? Yes, the truncated values are random. The distribution has changed from a continuous distribution to a discrete distribution. Random values with discrete distributions are often used. There are senses in which this change to the distribution is very small. The maximum difference between the cumulative distribution functions is bounded by the maximum density of the original times the maximum change from rounding. The changes to the expected value and the standard deviation can be bounded similarly. There are senses in which the change to the distribution is large, e.g., the $L_1$ distance between any continuous distribution and any discrete distribution is maximal. The average of some discontinuous functions of the value may change a lot.
Are truncated numbers from a random number generator still 'random'? Yes, the truncated values are random. The distribution has changed from a continuous distribution to a discrete distribution. Random values with discrete distributions are often used. There are senses
15,700
Why does the supremum of the Brownian bridge have the Kolmogorov–Smirnov distribution?
$\sqrt{n}\sup_x|F_n-F|=\sup_x|\frac{1}{\sqrt{n}}\sum_{i=1}^nZ_i(x)| $ where $Z_i(x)=1_{X_i\leq x}-E[1_{X_i\leq x}]$ by CLT you have $G_n=\frac{1}{\sqrt{n}}\sum_{i=1}^nZ_i(x)\rightarrow \mathcal{N}(0,F(x)(1-F(x)))$ this is the intuition... brownian bridge $B(t)$ has variance $t(1-t)$ http://en.wikipedia.org/wiki/Brownian_bridge replace $t$ by $F(x)$. This is for one $x$... You also need to check the covariance and hence it still is easy to show (CLT) that for ($x_1,\dots,x_k$) $(G_n(x_1),\dots,G_n(x_k))\rightarrow (B_1,\dots,B_k)$ where $(B_1,\dots,B_k)$ is $\mathcal{N}(0,\Sigma)$ with $\Sigma=(\sigma_{ij})$, $\sigma_{ij}=\min(F(x_i),F(x_j))-F(x_i)F(x_j)$. The difficult part is to show that the distribution of the suppremum of the limit is the supremum of the distribution of the limit... Understanding why this happens requires some empirical process theory, reading books such as van der Waart and Welner (not easy). The name of the Theorem is Donsker Theorem http://en.wikipedia.org/wiki/Donsker%27s_theorem ...
Why does the supremum of the Brownian bridge have the Kolmogorov–Smirnov distribution?
$\sqrt{n}\sup_x|F_n-F|=\sup_x|\frac{1}{\sqrt{n}}\sum_{i=1}^nZ_i(x)| $ where $Z_i(x)=1_{X_i\leq x}-E[1_{X_i\leq x}]$ by CLT you have $G_n=\frac{1}{\sqrt{n}}\sum_{i=1}^nZ_i(x)\rightarrow \mathcal{N}(0
Why does the supremum of the Brownian bridge have the Kolmogorov–Smirnov distribution? $\sqrt{n}\sup_x|F_n-F|=\sup_x|\frac{1}{\sqrt{n}}\sum_{i=1}^nZ_i(x)| $ where $Z_i(x)=1_{X_i\leq x}-E[1_{X_i\leq x}]$ by CLT you have $G_n=\frac{1}{\sqrt{n}}\sum_{i=1}^nZ_i(x)\rightarrow \mathcal{N}(0,F(x)(1-F(x)))$ this is the intuition... brownian bridge $B(t)$ has variance $t(1-t)$ http://en.wikipedia.org/wiki/Brownian_bridge replace $t$ by $F(x)$. This is for one $x$... You also need to check the covariance and hence it still is easy to show (CLT) that for ($x_1,\dots,x_k$) $(G_n(x_1),\dots,G_n(x_k))\rightarrow (B_1,\dots,B_k)$ where $(B_1,\dots,B_k)$ is $\mathcal{N}(0,\Sigma)$ with $\Sigma=(\sigma_{ij})$, $\sigma_{ij}=\min(F(x_i),F(x_j))-F(x_i)F(x_j)$. The difficult part is to show that the distribution of the suppremum of the limit is the supremum of the distribution of the limit... Understanding why this happens requires some empirical process theory, reading books such as van der Waart and Welner (not easy). The name of the Theorem is Donsker Theorem http://en.wikipedia.org/wiki/Donsker%27s_theorem ...
Why does the supremum of the Brownian bridge have the Kolmogorov–Smirnov distribution? $\sqrt{n}\sup_x|F_n-F|=\sup_x|\frac{1}{\sqrt{n}}\sum_{i=1}^nZ_i(x)| $ where $Z_i(x)=1_{X_i\leq x}-E[1_{X_i\leq x}]$ by CLT you have $G_n=\frac{1}{\sqrt{n}}\sum_{i=1}^nZ_i(x)\rightarrow \mathcal{N}(0