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
26,401
Why variational inference and not maximum likelihood?
The equation you use is not correct: $$\log p(\mathbf x) \color{red}{\neq} \int \log p(\mathbf x | \mathbf z) p(\mathbf z) d\mathbf z = \mathop{\mathbb{E}}_{p(\mathbf z)} [\log p(\mathbf x | \mathbf z)].$$ You are not allowed to push the log in. Instead: $$\log p(\mathbf x) = \log \int p(\mathbf x | \mathbf z) p(\mathbf z) d\mathbf z = \log \mathop{\mathbb{E}}_{p(\mathbf z)} [p(\mathbf x | \mathbf z)].$$ You could now sample from within the log, but then you would not get an unbiased estimate. A further option is to use Jensen's identity to get a lower bound and optimise that. And that's exactly what variational inference does.
Why variational inference and not maximum likelihood?
The equation you use is not correct: $$\log p(\mathbf x) \color{red}{\neq} \int \log p(\mathbf x | \mathbf z) p(\mathbf z) d\mathbf z = \mathop{\mathbb{E}}_{p(\mathbf z)} [\log p(\mathbf x | \mathbf z
Why variational inference and not maximum likelihood? The equation you use is not correct: $$\log p(\mathbf x) \color{red}{\neq} \int \log p(\mathbf x | \mathbf z) p(\mathbf z) d\mathbf z = \mathop{\mathbb{E}}_{p(\mathbf z)} [\log p(\mathbf x | \mathbf z)].$$ You are not allowed to push the log in. Instead: $$\log p(\mathbf x) = \log \int p(\mathbf x | \mathbf z) p(\mathbf z) d\mathbf z = \log \mathop{\mathbb{E}}_{p(\mathbf z)} [p(\mathbf x | \mathbf z)].$$ You could now sample from within the log, but then you would not get an unbiased estimate. A further option is to use Jensen's identity to get a lower bound and optimise that. And that's exactly what variational inference does.
Why variational inference and not maximum likelihood? The equation you use is not correct: $$\log p(\mathbf x) \color{red}{\neq} \int \log p(\mathbf x | \mathbf z) p(\mathbf z) d\mathbf z = \mathop{\mathbb{E}}_{p(\mathbf z)} [\log p(\mathbf x | \mathbf z
26,402
Proper terminology for what happens at knots in a cubic spline function
This answer on math.stackexchange.com suggests one way to proceed. In particular: The typical mathematical definition of "smooth" says something about how many continuous derivatives the function has. But these sorts of definitions bear little relationship to the intuitive notion of "smoothness" of a curve. Starting from the limitations of fitting an infinitely mathematically smooth (in the sense of infinite differentiability) high-degree polynomial might help heuristically. I'd suggest something like: At knots the required level of mathematical smoothness is relaxed, better to match the intuitive notion of smoothness while allowing the curve to pass through the knots. The curve between each pair of adjacent knots can then be a simple, infinitely smooth, 3rd-degree polynomial. If there is time, an illustration like the following based on Runge's phenomenon might help. Consider the following 9 points joined with straight lines: We want to fit a smooth curve to these points, to avoid the sharp changes in the line at the points. We could try to fit a curve that is infinitely smooth mathematically through these points, in the sense that not only is the curve continuous, but the slope of the curve is continuous, as is the slope of the slope, and so on forever (infinite differentiability). Polynomials are infinitely smooth in that sense, but here's what you get if you fit a polynomial through these points: As @bubba has put it about the high-degree polynomials needed for this type of fitting: No-one (except a mathematician) would call them "smooth". If we remove the requirement for infinite mathematical smoothness at the knots, however, we can do much better. Then we can use an infinitely smooth 3rd-degree polynomial between each pair of adjacent knots, and at the knots require just the minimum smoothness needed to make the joins invisible: where the orange line is a cubic spline fit and the blue line shows the smooth Runge function from which the points were sampled. This approach provides "the least possible amount of wiggling in between" the knots and thus meets an intuitive sense of "smoothness."
Proper terminology for what happens at knots in a cubic spline function
This answer on math.stackexchange.com suggests one way to proceed. In particular: The typical mathematical definition of "smooth" says something about how many continuous derivatives the function has
Proper terminology for what happens at knots in a cubic spline function This answer on math.stackexchange.com suggests one way to proceed. In particular: The typical mathematical definition of "smooth" says something about how many continuous derivatives the function has. But these sorts of definitions bear little relationship to the intuitive notion of "smoothness" of a curve. Starting from the limitations of fitting an infinitely mathematically smooth (in the sense of infinite differentiability) high-degree polynomial might help heuristically. I'd suggest something like: At knots the required level of mathematical smoothness is relaxed, better to match the intuitive notion of smoothness while allowing the curve to pass through the knots. The curve between each pair of adjacent knots can then be a simple, infinitely smooth, 3rd-degree polynomial. If there is time, an illustration like the following based on Runge's phenomenon might help. Consider the following 9 points joined with straight lines: We want to fit a smooth curve to these points, to avoid the sharp changes in the line at the points. We could try to fit a curve that is infinitely smooth mathematically through these points, in the sense that not only is the curve continuous, but the slope of the curve is continuous, as is the slope of the slope, and so on forever (infinite differentiability). Polynomials are infinitely smooth in that sense, but here's what you get if you fit a polynomial through these points: As @bubba has put it about the high-degree polynomials needed for this type of fitting: No-one (except a mathematician) would call them "smooth". If we remove the requirement for infinite mathematical smoothness at the knots, however, we can do much better. Then we can use an infinitely smooth 3rd-degree polynomial between each pair of adjacent knots, and at the knots require just the minimum smoothness needed to make the joins invisible: where the orange line is a cubic spline fit and the blue line shows the smooth Runge function from which the points were sampled. This approach provides "the least possible amount of wiggling in between" the knots and thus meets an intuitive sense of "smoothness."
Proper terminology for what happens at knots in a cubic spline function This answer on math.stackexchange.com suggests one way to proceed. In particular: The typical mathematical definition of "smooth" says something about how many continuous derivatives the function has
26,403
Proper terminology for what happens at knots in a cubic spline function
Disclaimer: I'm not a native speaker and I learned about cubic splines many years ago. Taking this into account: Both of your proposals, staring with Knots are where different cubic polynomials are joined are clear to me, although I didn't know the technical meaning of "jolt". But, the way you state it has a touch -- at least to my ear -- of implying that knots are some properties of the curve; that we first construct the curve and then find the knots on it based on the properties you list. It is like saying "An extreme is where the first derivative is zero". There is a causal implication here: First we have a curve (which might follow e.g. from the laws of physics) and on that curve we find the extremes. Since for splines it's the other way round -- we first choose the knots, and then construct the curve around them, -- I'd start from the cubic segments and explain that points where they are joined are called "knots". Something like: (These) different cubic polynomial segments are joined together to produce a (visually) smooth curve. In order to achieve this, cubic splines enforce three levels of continuity: the function, its slope, and its acceleration or second derivative (slope of the slope) do not change at the joints. Only the jolt -- the third derivative of the curve -- may abruptly change. These joints are called "knots".
Proper terminology for what happens at knots in a cubic spline function
Disclaimer: I'm not a native speaker and I learned about cubic splines many years ago. Taking this into account: Both of your proposals, staring with Knots are where different cubic polynomials are j
Proper terminology for what happens at knots in a cubic spline function Disclaimer: I'm not a native speaker and I learned about cubic splines many years ago. Taking this into account: Both of your proposals, staring with Knots are where different cubic polynomials are joined are clear to me, although I didn't know the technical meaning of "jolt". But, the way you state it has a touch -- at least to my ear -- of implying that knots are some properties of the curve; that we first construct the curve and then find the knots on it based on the properties you list. It is like saying "An extreme is where the first derivative is zero". There is a causal implication here: First we have a curve (which might follow e.g. from the laws of physics) and on that curve we find the extremes. Since for splines it's the other way round -- we first choose the knots, and then construct the curve around them, -- I'd start from the cubic segments and explain that points where they are joined are called "knots". Something like: (These) different cubic polynomial segments are joined together to produce a (visually) smooth curve. In order to achieve this, cubic splines enforce three levels of continuity: the function, its slope, and its acceleration or second derivative (slope of the slope) do not change at the joints. Only the jolt -- the third derivative of the curve -- may abruptly change. These joints are called "knots".
Proper terminology for what happens at knots in a cubic spline function Disclaimer: I'm not a native speaker and I learned about cubic splines many years ago. Taking this into account: Both of your proposals, staring with Knots are where different cubic polynomials are j
26,404
How to find a statistical significance difference of classification results?
I don't think that you can accomplish exactly what you want with respect to the set of KNN models based on different distance metrics on your single data set, but you can try to evaluate the relative performance of the modeling approaches based on the different distance metrics. You will, however, have to make two adjustments. Much of what follows is informed by the discussion on this page. First, you should evaluate performance with a proper scoring rule like the Brier score instead of accuracy, specificity, sensitivity, and F1 score. Those are notoriously poor measures for comparing models, and they make implicit assumptions about the cost tradeoffs between different types of classification errors.* The Brier score is effectively the mean square error between the predicted probabilities of class membership and actual membership. You will have to see how your KNN software provides access to the class probabilities, but this is typically possible as in this sklearn function. Second, instead of simply fitting the model one time to your data, you need to see how well the modeling process works in repeated application to your data set. One way to proceed would be to work with multiple bootstrap samples, say a few hundred to a thousand, of the data. For each bootstrap sample as a training set, build KNN models with each of your distance metrics, then evaluate their performances on the entire original data set as the test set. The distribution of Brier scores for each type of model over the few hundred to a thousand bootstraps could then indicate significant differences, among the models based on different distance metrics, in terms of that proper scoring rule. Even this approach has its limits, however; see this answer by cbeleities for further discussion. *Using accuracy (fraction of cases correctly assigned) as the measure of model performance makes an implicit assumption that false negatives and false positives have the same importance. See this page for further discussion. In practical applications this assumption can be unhelpful. One example is the overdiagnosis and overtreatment of prostate cancer; false-positives in the usual diagnostic tests have led to many men who were unlikely to have died from this cancer nevertheless undergoing life-altering therapies with frequently undesirable side effects. The F1-score does not take true negative cases/rates into account, which might be critical in some applications. Sensitivity and specificity values depend on a particular choice of tradeoff between them. Sometimes that tradeoff is made silently by software, for example setting the classification cutoff in logistic regression at a predicted value of $p>0.5$. The explicit or hidden assumptions underlying all of these measures mean that they can be affected dramatically by small changes in the assumptions. The most generally useful approach is to produce a good model of class membership probabilities, then use judgements about the costs of tradeoffs to inform final assignments of predicted classes (if needed). The Brier score and other proper scoring rules provide continuous measures of the quality of a probability model that are optimized when the model is the true model.
How to find a statistical significance difference of classification results?
I don't think that you can accomplish exactly what you want with respect to the set of KNN models based on different distance metrics on your single data set, but you can try to evaluate the relative
How to find a statistical significance difference of classification results? I don't think that you can accomplish exactly what you want with respect to the set of KNN models based on different distance metrics on your single data set, but you can try to evaluate the relative performance of the modeling approaches based on the different distance metrics. You will, however, have to make two adjustments. Much of what follows is informed by the discussion on this page. First, you should evaluate performance with a proper scoring rule like the Brier score instead of accuracy, specificity, sensitivity, and F1 score. Those are notoriously poor measures for comparing models, and they make implicit assumptions about the cost tradeoffs between different types of classification errors.* The Brier score is effectively the mean square error between the predicted probabilities of class membership and actual membership. You will have to see how your KNN software provides access to the class probabilities, but this is typically possible as in this sklearn function. Second, instead of simply fitting the model one time to your data, you need to see how well the modeling process works in repeated application to your data set. One way to proceed would be to work with multiple bootstrap samples, say a few hundred to a thousand, of the data. For each bootstrap sample as a training set, build KNN models with each of your distance metrics, then evaluate their performances on the entire original data set as the test set. The distribution of Brier scores for each type of model over the few hundred to a thousand bootstraps could then indicate significant differences, among the models based on different distance metrics, in terms of that proper scoring rule. Even this approach has its limits, however; see this answer by cbeleities for further discussion. *Using accuracy (fraction of cases correctly assigned) as the measure of model performance makes an implicit assumption that false negatives and false positives have the same importance. See this page for further discussion. In practical applications this assumption can be unhelpful. One example is the overdiagnosis and overtreatment of prostate cancer; false-positives in the usual diagnostic tests have led to many men who were unlikely to have died from this cancer nevertheless undergoing life-altering therapies with frequently undesirable side effects. The F1-score does not take true negative cases/rates into account, which might be critical in some applications. Sensitivity and specificity values depend on a particular choice of tradeoff between them. Sometimes that tradeoff is made silently by software, for example setting the classification cutoff in logistic regression at a predicted value of $p>0.5$. The explicit or hidden assumptions underlying all of these measures mean that they can be affected dramatically by small changes in the assumptions. The most generally useful approach is to produce a good model of class membership probabilities, then use judgements about the costs of tradeoffs to inform final assignments of predicted classes (if needed). The Brier score and other proper scoring rules provide continuous measures of the quality of a probability model that are optimized when the model is the true model.
How to find a statistical significance difference of classification results? I don't think that you can accomplish exactly what you want with respect to the set of KNN models based on different distance metrics on your single data set, but you can try to evaluate the relative
26,405
How to find a statistical significance difference of classification results?
Disclaimer: I think this answers OP's questions only to some extent. I had seen Friedman post hoc test used in these settings. For example: let us say on particular dataset A - Algorithm X gives $A_x$ % accuracy, Algorithm Y gives $A_y$ % accuracy and Algorithm Z gives $A_z$ % accuracy. Similarly on Dataset B - Algorithm X gives $B_x$ % accuracy, Algorithm Y gives $B_y$ % accuracy and Algorithm Z gives $B_z$ % accuracy. Let us say we have 5 such datasets(A,B,C,D and E) on which these algorithms were run. In such a setting, Friedman post hoc test can be used to check if Algorithm X's accuracy is significantly different from others (Y and Z). Friedman's test is similar to ANOVA but without the assumptions of normality. Luckily in R, it is fairly straightforward to implement this test.
How to find a statistical significance difference of classification results?
Disclaimer: I think this answers OP's questions only to some extent. I had seen Friedman post hoc test used in these settings. For example: let us say on particular dataset A - Algorithm X gives $A_x
How to find a statistical significance difference of classification results? Disclaimer: I think this answers OP's questions only to some extent. I had seen Friedman post hoc test used in these settings. For example: let us say on particular dataset A - Algorithm X gives $A_x$ % accuracy, Algorithm Y gives $A_y$ % accuracy and Algorithm Z gives $A_z$ % accuracy. Similarly on Dataset B - Algorithm X gives $B_x$ % accuracy, Algorithm Y gives $B_y$ % accuracy and Algorithm Z gives $B_z$ % accuracy. Let us say we have 5 such datasets(A,B,C,D and E) on which these algorithms were run. In such a setting, Friedman post hoc test can be used to check if Algorithm X's accuracy is significantly different from others (Y and Z). Friedman's test is similar to ANOVA but without the assumptions of normality. Luckily in R, it is fairly straightforward to implement this test.
How to find a statistical significance difference of classification results? Disclaimer: I think this answers OP's questions only to some extent. I had seen Friedman post hoc test used in these settings. For example: let us say on particular dataset A - Algorithm X gives $A_x
26,406
Writing AR(1) as a MA($\infty$) process
The usual sense in which convergence is understood in this case is in mean square: $$ E[Y_t-(\epsilon_t+\phi\epsilon_{t-1}+\phi^2\epsilon_{t-2} +\ldots+\phi^j\epsilon_{t-j})]^2=\phi^{2(j+1)} E[Y_{t-j-1}]^2 $$ If $Y_t$ is stationary $$ E[Y_{t-j-1}]^2=\gamma_0+\mu^2 $$ Hence $$ \lim_{j\to\infty}E[Y_t-(\epsilon_t+\phi\epsilon_{t-1}+\phi^2\epsilon_{t-2} +\ldots+\phi^j\epsilon_{t-j})]^2=0 $$
Writing AR(1) as a MA($\infty$) process
The usual sense in which convergence is understood in this case is in mean square: $$ E[Y_t-(\epsilon_t+\phi\epsilon_{t-1}+\phi^2\epsilon_{t-2} +\ldots+\phi^j\epsilon_{t-j})]^2=\phi^{2(j+1)} E[Y_{t-j-
Writing AR(1) as a MA($\infty$) process The usual sense in which convergence is understood in this case is in mean square: $$ E[Y_t-(\epsilon_t+\phi\epsilon_{t-1}+\phi^2\epsilon_{t-2} +\ldots+\phi^j\epsilon_{t-j})]^2=\phi^{2(j+1)} E[Y_{t-j-1}]^2 $$ If $Y_t$ is stationary $$ E[Y_{t-j-1}]^2=\gamma_0+\mu^2 $$ Hence $$ \lim_{j\to\infty}E[Y_t-(\epsilon_t+\phi\epsilon_{t-1}+\phi^2\epsilon_{t-2} +\ldots+\phi^j\epsilon_{t-j})]^2=0 $$
Writing AR(1) as a MA($\infty$) process The usual sense in which convergence is understood in this case is in mean square: $$ E[Y_t-(\epsilon_t+\phi\epsilon_{t-1}+\phi^2\epsilon_{t-2} +\ldots+\phi^j\epsilon_{t-j})]^2=\phi^{2(j+1)} E[Y_{t-j-
26,407
Writing AR(1) as a MA($\infty$) process
You are right to be suspicious of this step, and in fact, without further assumptions to limit the size of $X_{-\infty}$ you cannot get the required form. Remember that the recursive equation for the AR model is insufficient to yield the joint distribution of the process. (You need to impose a distribution for the error process, and even then, you either need to impose stationarity or specify an initial distribution that leads to some non-stationary model.) If you only have this recursive equation, there is no reason that the time-series values could not explode out to large values as $t \rightarrow -\infty$. For example, the deterministic non-stationary AR process $X_t = \phi^t$ satisfies the recursive equation you have specified (with zero errors), and in this case you have $\lim_{k \rightarrow \infty} X_{t-k} = \infty$. In this model, for any $\phi \neq 0$ you also have: $$\phi^k X_{t-k} = \phi^k \phi^{t-k} = \phi^t \neq 0.$$ Since the errors are zero in this deterministic model, this gives you the limiting result: $$X_t = \underbrace{\sum_{k=0}^\infty \phi^k \varepsilon_{t-k}}_{0} + \underbrace{\lim_{k \rightarrow \infty} \phi^k X_{t-k}}_{\phi^t}. \\[6pt]$$ Clearly, in this case, the limiting term is non-zero, and cannot be removed from the result. If you would like to be able to remove this last term, you need to add further assumptions to your model (e.g, stationarity).
Writing AR(1) as a MA($\infty$) process
You are right to be suspicious of this step, and in fact, without further assumptions to limit the size of $X_{-\infty}$ you cannot get the required form. Remember that the recursive equation for the
Writing AR(1) as a MA($\infty$) process You are right to be suspicious of this step, and in fact, without further assumptions to limit the size of $X_{-\infty}$ you cannot get the required form. Remember that the recursive equation for the AR model is insufficient to yield the joint distribution of the process. (You need to impose a distribution for the error process, and even then, you either need to impose stationarity or specify an initial distribution that leads to some non-stationary model.) If you only have this recursive equation, there is no reason that the time-series values could not explode out to large values as $t \rightarrow -\infty$. For example, the deterministic non-stationary AR process $X_t = \phi^t$ satisfies the recursive equation you have specified (with zero errors), and in this case you have $\lim_{k \rightarrow \infty} X_{t-k} = \infty$. In this model, for any $\phi \neq 0$ you also have: $$\phi^k X_{t-k} = \phi^k \phi^{t-k} = \phi^t \neq 0.$$ Since the errors are zero in this deterministic model, this gives you the limiting result: $$X_t = \underbrace{\sum_{k=0}^\infty \phi^k \varepsilon_{t-k}}_{0} + \underbrace{\lim_{k \rightarrow \infty} \phi^k X_{t-k}}_{\phi^t}. \\[6pt]$$ Clearly, in this case, the limiting term is non-zero, and cannot be removed from the result. If you would like to be able to remove this last term, you need to add further assumptions to your model (e.g, stationarity).
Writing AR(1) as a MA($\infty$) process You are right to be suspicious of this step, and in fact, without further assumptions to limit the size of $X_{-\infty}$ you cannot get the required form. Remember that the recursive equation for the
26,408
How to know if model is overfitting or underfitting?
You can determine the difference between an underfitting and overfitting experimentally by comparing fitted models to training-data and test-data. Typical graphs: a b c d These plots will show you the accuracy of the model, as function of some parameter (e.g. 'complexity'), for both the training-data (the data use for fitting) and test data (data kept separate from the training phase) One normally chooses the model that does the best on the test-data. If you deviate then for... For underfitting models, you do worse because they do not capture the true trend sufficiently. If you get more underfitting then you get both worse fits for training and testing data. for overfitting models, you do worse because they respond too much to the noise, rather than the true trend. If you get more overfitting then you get better fits for training data (capturing the noise, but it is useless or even detrimental), but still worse for testing data. After performing these steps, you should remain in sight that, while you may have selected the least underfitting/overfitting model out of your options, this does not mean that there would not be some other better model. In particular: the true model, might be an overfitting model in circumstances of high noise-signal ratios (see https://stats.stackexchange.com/a/299523/164061 )
How to know if model is overfitting or underfitting?
You can determine the difference between an underfitting and overfitting experimentally by comparing fitted models to training-data and test-data. Typical graphs: a b c d These plots will show y
How to know if model is overfitting or underfitting? You can determine the difference between an underfitting and overfitting experimentally by comparing fitted models to training-data and test-data. Typical graphs: a b c d These plots will show you the accuracy of the model, as function of some parameter (e.g. 'complexity'), for both the training-data (the data use for fitting) and test data (data kept separate from the training phase) One normally chooses the model that does the best on the test-data. If you deviate then for... For underfitting models, you do worse because they do not capture the true trend sufficiently. If you get more underfitting then you get both worse fits for training and testing data. for overfitting models, you do worse because they respond too much to the noise, rather than the true trend. If you get more overfitting then you get better fits for training data (capturing the noise, but it is useless or even detrimental), but still worse for testing data. After performing these steps, you should remain in sight that, while you may have selected the least underfitting/overfitting model out of your options, this does not mean that there would not be some other better model. In particular: the true model, might be an overfitting model in circumstances of high noise-signal ratios (see https://stats.stackexchange.com/a/299523/164061 )
How to know if model is overfitting or underfitting? You can determine the difference between an underfitting and overfitting experimentally by comparing fitted models to training-data and test-data. Typical graphs: a b c d These plots will show y
26,409
How to know if model is overfitting or underfitting?
A sign of Underfitting could be when the accuracy of the test and training are very similar. The way to "fix" it and through "tuning". If you are trainning a NN you could increase the number of training cycles, on the other hand, if you are working with traditionalML, for example a Logistic Regression, you coudl try to tune certain parameters(that come by default) of the algorithm that leas to a better perfomance of this, in the case of Logistic Regression it would be changing the differente values of C i.e signal of underfitting, then I tune my model # default logreg = LogisticRegression(solver='liblinear', random_state=0) worst performance, discard it # instantiate the model logreg001 = LogisticRegression(C=0.01, solver='liblinear', random_state=0) it improves performance so I keep it. # instantiate the model logreg100 = LogisticRegression(C=100, solver='liblinear', random_state=0)
How to know if model is overfitting or underfitting?
A sign of Underfitting could be when the accuracy of the test and training are very similar. The way to "fix" it and through "tuning". If you are trainning a NN you could increase the number of traini
How to know if model is overfitting or underfitting? A sign of Underfitting could be when the accuracy of the test and training are very similar. The way to "fix" it and through "tuning". If you are trainning a NN you could increase the number of training cycles, on the other hand, if you are working with traditionalML, for example a Logistic Regression, you coudl try to tune certain parameters(that come by default) of the algorithm that leas to a better perfomance of this, in the case of Logistic Regression it would be changing the differente values of C i.e signal of underfitting, then I tune my model # default logreg = LogisticRegression(solver='liblinear', random_state=0) worst performance, discard it # instantiate the model logreg001 = LogisticRegression(C=0.01, solver='liblinear', random_state=0) it improves performance so I keep it. # instantiate the model logreg100 = LogisticRegression(C=100, solver='liblinear', random_state=0)
How to know if model is overfitting or underfitting? A sign of Underfitting could be when the accuracy of the test and training are very similar. The way to "fix" it and through "tuning". If you are trainning a NN you could increase the number of traini
26,410
Interpretation of entropy for continuous distribution?
Because of Limiting density of discrete points, the interpretation of $$S = -\sum_x p(x)\ln p(x)$$ cannot be generalized to $$S= -\int dx (p(x)\ln p(x))$$ Because the direct generalization leads to $$S= -\int dx p(x)\ln (p(x)dx) = -\int dx p(x)\ln (p(x)) -\int dx p(x)\ln (dx) $$ Clearly, $\ln dx$ explodes. Intuitively, since $p(x)dx = 0$, so the reasoning of using fewer bits for encoding something that is more likely to happen does not hold. So, we need to find another way to interpret $S= -\int dx p(x)\ln (p(x)dx)$, and the choice is $KL$ divergence. Say we have a uniform distribution $q(x)$ in the same state space, then we have $$KL(p(x)\Vert q(x)) = \int dx p(x) \ln (\frac{p(x)dx}{q(x)dx})$$ Since $q(x)$ is just a constant, so we effectively keep the form of $S= -\int dx (p(x)\ln (p(x)dx))$, and at the same time construct a well-defined quantity for the continuous distribution $p(x)$. So from $KL$ divergence, the entropy of a continuous distribution $p(x)$ can be interpreted as: If we use a uniform distribution for encoding $p(x)$, then how many bits that is unnecessary on average.
Interpretation of entropy for continuous distribution?
Because of Limiting density of discrete points, the interpretation of $$S = -\sum_x p(x)\ln p(x)$$ cannot be generalized to $$S= -\int dx (p(x)\ln p(x))$$ Because the direct generalization leads to
Interpretation of entropy for continuous distribution? Because of Limiting density of discrete points, the interpretation of $$S = -\sum_x p(x)\ln p(x)$$ cannot be generalized to $$S= -\int dx (p(x)\ln p(x))$$ Because the direct generalization leads to $$S= -\int dx p(x)\ln (p(x)dx) = -\int dx p(x)\ln (p(x)) -\int dx p(x)\ln (dx) $$ Clearly, $\ln dx$ explodes. Intuitively, since $p(x)dx = 0$, so the reasoning of using fewer bits for encoding something that is more likely to happen does not hold. So, we need to find another way to interpret $S= -\int dx p(x)\ln (p(x)dx)$, and the choice is $KL$ divergence. Say we have a uniform distribution $q(x)$ in the same state space, then we have $$KL(p(x)\Vert q(x)) = \int dx p(x) \ln (\frac{p(x)dx}{q(x)dx})$$ Since $q(x)$ is just a constant, so we effectively keep the form of $S= -\int dx (p(x)\ln (p(x)dx))$, and at the same time construct a well-defined quantity for the continuous distribution $p(x)$. So from $KL$ divergence, the entropy of a continuous distribution $p(x)$ can be interpreted as: If we use a uniform distribution for encoding $p(x)$, then how many bits that is unnecessary on average.
Interpretation of entropy for continuous distribution? Because of Limiting density of discrete points, the interpretation of $$S = -\sum_x p(x)\ln p(x)$$ cannot be generalized to $$S= -\int dx (p(x)\ln p(x))$$ Because the direct generalization leads to
26,411
Interpretation of entropy for continuous distribution?
You discretize the problem via a probability density. A continous random variable has a density $f(x)$, which locally approximates the probably $P(X\in [x,x+\delta x]) \approx f(x)\delta x$, which is now an analogue of the discrete case. And by the theory of calculus, your sums equivalently become integrals over you state space.
Interpretation of entropy for continuous distribution?
You discretize the problem via a probability density. A continous random variable has a density $f(x)$, which locally approximates the probably $P(X\in [x,x+\delta x]) \approx f(x)\delta x$, which is
Interpretation of entropy for continuous distribution? You discretize the problem via a probability density. A continous random variable has a density $f(x)$, which locally approximates the probably $P(X\in [x,x+\delta x]) \approx f(x)\delta x$, which is now an analogue of the discrete case. And by the theory of calculus, your sums equivalently become integrals over you state space.
Interpretation of entropy for continuous distribution? You discretize the problem via a probability density. A continous random variable has a density $f(x)$, which locally approximates the probably $P(X\in [x,x+\delta x]) \approx f(x)\delta x$, which is
26,412
Why building the sum of a filter over several channels in a convolutional layer?
Okay, the weights can be different for each channel that might help, but I still don't see the advantage of a summation over other operations. Exactly. You miss the fact that weights are learnable. Of course, initially it's possible that the edges from different channels will cancel each other and the output tensor will lose this information. But this will result in big loss value, i.e., big backpropagation gradients, that will tweak the weights accordingly. In reality, the network learns to capture the edges (or corners or more complex patterns) in any channel. When the filter does not match the patch, the convolution result is very close to zero, rather than large negative number, so that nothing is lost in the sum. (In fact, after some training, most of the values in the kernels are close to zero.) The reason to do a summation is because it's efficient (both forward and backward operations are vectorizable) and allows nice gradients flow. You can view this as a sophisticated linear layer with shared weights. If the concern you express was actual, you would see the same problem in all linear layers in any network: when different features are summed up with some weights, they can cancel each other out, right? Luckily, this does not happen (unless the features are correlated, e.g., specially crafted), due to reasons described earlier, so the linear operation is the crucial building block of any neural network.
Why building the sum of a filter over several channels in a convolutional layer?
Okay, the weights can be different for each channel that might help, but I still don't see the advantage of a summation over other operations. Exactly. You miss the fact that weights are learnable. O
Why building the sum of a filter over several channels in a convolutional layer? Okay, the weights can be different for each channel that might help, but I still don't see the advantage of a summation over other operations. Exactly. You miss the fact that weights are learnable. Of course, initially it's possible that the edges from different channels will cancel each other and the output tensor will lose this information. But this will result in big loss value, i.e., big backpropagation gradients, that will tweak the weights accordingly. In reality, the network learns to capture the edges (or corners or more complex patterns) in any channel. When the filter does not match the patch, the convolution result is very close to zero, rather than large negative number, so that nothing is lost in the sum. (In fact, after some training, most of the values in the kernels are close to zero.) The reason to do a summation is because it's efficient (both forward and backward operations are vectorizable) and allows nice gradients flow. You can view this as a sophisticated linear layer with shared weights. If the concern you express was actual, you would see the same problem in all linear layers in any network: when different features are summed up with some weights, they can cancel each other out, right? Luckily, this does not happen (unless the features are correlated, e.g., specially crafted), due to reasons described earlier, so the linear operation is the crucial building block of any neural network.
Why building the sum of a filter over several channels in a convolutional layer? Okay, the weights can be different for each channel that might help, but I still don't see the advantage of a summation over other operations. Exactly. You miss the fact that weights are learnable. O
26,413
Whitening/Decorrelation - why does it work?
Whitening is par for the course in computer vision applications, and may help a variety of machine learning algorithms converge to an optimal solution, beyond SVMs. (More on that towards the end of my answer.) Now, we whiten data and get a round blob as output. To put that more mathematically, whitening transforms a distribution using its eigenvectors $\boldsymbol{u}_j$ in such a way that its covariance matrix becomes the unit matrix. Bishop (1995) pp. 300 illustrates this in a stylised manner: Whitening is a useful preprocessing step because it both decorrelates and normalises the inputs. Decorrelation The training step of machine learning algorithms is simply an optimisation problem, however it is defined. Whitening gives nice optimisation properties to the input variables, causing such optimisation steps to converge faster. The mechanism for this improvement is that it affects the condition number of the Hessian in steepest descent-style optimisation algorithms. Here are some sources for further reading: Maurya's answer on Quora Smith - Conditioning and Hessians in analytical and numerical optimisation: Some illustrations Normalisation The fact that input variables now have unit variance is an example of feature normalisation, which is a prerequisite for many ML algorithms. Indeed, SVMs (along with regularized linear regression and neural networks) requires that features be normalised to work effectively, so whitening may be improving your SVMs' performance significantly thanks only to the feature normalisation effect.
Whitening/Decorrelation - why does it work?
Whitening is par for the course in computer vision applications, and may help a variety of machine learning algorithms converge to an optimal solution, beyond SVMs. (More on that towards the end of my
Whitening/Decorrelation - why does it work? Whitening is par for the course in computer vision applications, and may help a variety of machine learning algorithms converge to an optimal solution, beyond SVMs. (More on that towards the end of my answer.) Now, we whiten data and get a round blob as output. To put that more mathematically, whitening transforms a distribution using its eigenvectors $\boldsymbol{u}_j$ in such a way that its covariance matrix becomes the unit matrix. Bishop (1995) pp. 300 illustrates this in a stylised manner: Whitening is a useful preprocessing step because it both decorrelates and normalises the inputs. Decorrelation The training step of machine learning algorithms is simply an optimisation problem, however it is defined. Whitening gives nice optimisation properties to the input variables, causing such optimisation steps to converge faster. The mechanism for this improvement is that it affects the condition number of the Hessian in steepest descent-style optimisation algorithms. Here are some sources for further reading: Maurya's answer on Quora Smith - Conditioning and Hessians in analytical and numerical optimisation: Some illustrations Normalisation The fact that input variables now have unit variance is an example of feature normalisation, which is a prerequisite for many ML algorithms. Indeed, SVMs (along with regularized linear regression and neural networks) requires that features be normalised to work effectively, so whitening may be improving your SVMs' performance significantly thanks only to the feature normalisation effect.
Whitening/Decorrelation - why does it work? Whitening is par for the course in computer vision applications, and may help a variety of machine learning algorithms converge to an optimal solution, beyond SVMs. (More on that towards the end of my
26,414
Why is Maximum Likelihood used for ARIMA instead of least squares?
OLS only works when all regressors are observable, because it employs the design matrix $X$ in estimating the model coefficients ($\beta=(X'X)^{-1}X'y$). Meanwhile, the ARIMA model specification contains unobservable variables in the moving average part (the lagged errors); hence, the OLS estimator is infeasible when the moving-average order $q>0$. On the other hand, an AR model can be estimated with OLS, and this is in fact quite a common approach. For normally distributed errors, it is also very close to the Maximum Likelihood (ML) solution. (There are subtle differences on how to treat the initial values in the ML estimation, but other than that it coincides with OLS for AR models.)
Why is Maximum Likelihood used for ARIMA instead of least squares?
OLS only works when all regressors are observable, because it employs the design matrix $X$ in estimating the model coefficients ($\beta=(X'X)^{-1}X'y$). Meanwhile, the ARIMA model specification conta
Why is Maximum Likelihood used for ARIMA instead of least squares? OLS only works when all regressors are observable, because it employs the design matrix $X$ in estimating the model coefficients ($\beta=(X'X)^{-1}X'y$). Meanwhile, the ARIMA model specification contains unobservable variables in the moving average part (the lagged errors); hence, the OLS estimator is infeasible when the moving-average order $q>0$. On the other hand, an AR model can be estimated with OLS, and this is in fact quite a common approach. For normally distributed errors, it is also very close to the Maximum Likelihood (ML) solution. (There are subtle differences on how to treat the initial values in the ML estimation, but other than that it coincides with OLS for AR models.)
Why is Maximum Likelihood used for ARIMA instead of least squares? OLS only works when all regressors are observable, because it employs the design matrix $X$ in estimating the model coefficients ($\beta=(X'X)^{-1}X'y$). Meanwhile, the ARIMA model specification conta
26,415
What are the support vectors in a support vector machine?
Short answer The support vectors are those points for which the Lagrange multipliers are not zero (there is more than just $b$ in a Support Vector Machine). Long answer Hard Margin For a simple hard-margin SVM, we have to solve the following minimisation problem: $$\min_{\boldsymbol{w}, b} \frac{1}{2} \|\boldsymbol{w}\|^2$$ subject to $$\forall i : y_i (\boldsymbol{w} \cdot \boldsymbol{x}_i + b) - 1 \geq 0$$ The solution can be found with help of Lagrange multipliers $\alpha_i$. In the process of minimising the Lagrange function, it can be found that $$\boldsymbol{w} = \sum_i \alpha_i y_i \boldsymbol{x}_i.$$ Therefore, $\boldsymbol{w}$ only depends on those samples for which $\alpha_i \neq 0$. Additionally, the Karush-Kuhn-Tucker conditions require that the solution satisfies $$\alpha_i (y_i (\boldsymbol{w} \cdot \boldsymbol{x}_i + b) - 1) = 0.$$ In order to compute $b$, the constraint for sample $i$ must be tight, i.e. $\alpha_i > 0$, so that $y_i (\boldsymbol{w} \cdot \boldsymbol{x}_i + b) - 1 = 0$. Hence, $b$ depends only on those samples for which $\alpha_i > 0$. Therefore, we can conclude that the solution depends on all samples for which $\alpha_i > 0$. Soft Margin For the C-SVM, which seems to be known as soft-margin SVM, the minimisation problem is given by: $$\min_{\boldsymbol{w}, b} \frac{1}{2} \|\boldsymbol{w}\|^2 + C \sum_i \xi_i$$ subject to $$\forall i : \begin{aligned}y_i (\boldsymbol{w} \cdot \boldsymbol{x}_i + b) - 1 + \xi_i & \geq 0 \\ \xi_i &\geq 0\end{aligned}$$ Using Lagrange multipliers $\alpha_i$ and $\lambda_i = (C - \alpha_i)$, the weights are (again) given by $$\boldsymbol{w} = \sum_i \alpha_i y_i \boldsymbol{x}_i,$$ and therefore $\boldsymbol{w}$ does depends only on samples for which $\alpha_i \neq 0$. Due to the Karush-Kuhn-Tucker conditions, the solution must satisfy $$\begin{align} \alpha_i (y_i (\boldsymbol{w} \cdot \boldsymbol{x}_i + b) - 1 + \xi_i) & = 0 \\ (C - \alpha_i) \xi_i & = 0, \end{align}$$ which allows to compute $b$ if $\alpha_i > 0$ and $\xi_i = 0$. If both constraints are tight, i.e. $\alpha_i < C$, $\xi_i$ must be zero. Therefore, $b$ depends on those samples for which $0 < \alpha_i < C$. Therefore, we can conclude that the solution depends on all samples for which $\alpha_i > 0$. After all, $\boldsymbol{w}$ still depends on those samples for which $\alpha_i = C$.
What are the support vectors in a support vector machine?
Short answer The support vectors are those points for which the Lagrange multipliers are not zero (there is more than just $b$ in a Support Vector Machine). Long answer Hard Margin For a simple hard-m
What are the support vectors in a support vector machine? Short answer The support vectors are those points for which the Lagrange multipliers are not zero (there is more than just $b$ in a Support Vector Machine). Long answer Hard Margin For a simple hard-margin SVM, we have to solve the following minimisation problem: $$\min_{\boldsymbol{w}, b} \frac{1}{2} \|\boldsymbol{w}\|^2$$ subject to $$\forall i : y_i (\boldsymbol{w} \cdot \boldsymbol{x}_i + b) - 1 \geq 0$$ The solution can be found with help of Lagrange multipliers $\alpha_i$. In the process of minimising the Lagrange function, it can be found that $$\boldsymbol{w} = \sum_i \alpha_i y_i \boldsymbol{x}_i.$$ Therefore, $\boldsymbol{w}$ only depends on those samples for which $\alpha_i \neq 0$. Additionally, the Karush-Kuhn-Tucker conditions require that the solution satisfies $$\alpha_i (y_i (\boldsymbol{w} \cdot \boldsymbol{x}_i + b) - 1) = 0.$$ In order to compute $b$, the constraint for sample $i$ must be tight, i.e. $\alpha_i > 0$, so that $y_i (\boldsymbol{w} \cdot \boldsymbol{x}_i + b) - 1 = 0$. Hence, $b$ depends only on those samples for which $\alpha_i > 0$. Therefore, we can conclude that the solution depends on all samples for which $\alpha_i > 0$. Soft Margin For the C-SVM, which seems to be known as soft-margin SVM, the minimisation problem is given by: $$\min_{\boldsymbol{w}, b} \frac{1}{2} \|\boldsymbol{w}\|^2 + C \sum_i \xi_i$$ subject to $$\forall i : \begin{aligned}y_i (\boldsymbol{w} \cdot \boldsymbol{x}_i + b) - 1 + \xi_i & \geq 0 \\ \xi_i &\geq 0\end{aligned}$$ Using Lagrange multipliers $\alpha_i$ and $\lambda_i = (C - \alpha_i)$, the weights are (again) given by $$\boldsymbol{w} = \sum_i \alpha_i y_i \boldsymbol{x}_i,$$ and therefore $\boldsymbol{w}$ does depends only on samples for which $\alpha_i \neq 0$. Due to the Karush-Kuhn-Tucker conditions, the solution must satisfy $$\begin{align} \alpha_i (y_i (\boldsymbol{w} \cdot \boldsymbol{x}_i + b) - 1 + \xi_i) & = 0 \\ (C - \alpha_i) \xi_i & = 0, \end{align}$$ which allows to compute $b$ if $\alpha_i > 0$ and $\xi_i = 0$. If both constraints are tight, i.e. $\alpha_i < C$, $\xi_i$ must be zero. Therefore, $b$ depends on those samples for which $0 < \alpha_i < C$. Therefore, we can conclude that the solution depends on all samples for which $\alpha_i > 0$. After all, $\boldsymbol{w}$ still depends on those samples for which $\alpha_i = C$.
What are the support vectors in a support vector machine? Short answer The support vectors are those points for which the Lagrange multipliers are not zero (there is more than just $b$ in a Support Vector Machine). Long answer Hard Margin For a simple hard-m
26,416
Akaike Information criterion for k-means
I think that the answer you refer to in the link in Stackoverflow, is in turn based on another link: http://sherrytowers.com/2013/10/24/k-means-clustering/. In that post the data used is standardized the variance is equal to 1 and the formula makes sense. In any case I think your line of reasoning is absolutely correct, and one should refrain to use that expression if the underlying assumption is not correct.
Akaike Information criterion for k-means
I think that the answer you refer to in the link in Stackoverflow, is in turn based on another link: http://sherrytowers.com/2013/10/24/k-means-clustering/. In that post the data used is standardized
Akaike Information criterion for k-means I think that the answer you refer to in the link in Stackoverflow, is in turn based on another link: http://sherrytowers.com/2013/10/24/k-means-clustering/. In that post the data used is standardized the variance is equal to 1 and the formula makes sense. In any case I think your line of reasoning is absolutely correct, and one should refrain to use that expression if the underlying assumption is not correct.
Akaike Information criterion for k-means I think that the answer you refer to in the link in Stackoverflow, is in turn based on another link: http://sherrytowers.com/2013/10/24/k-means-clustering/. In that post the data used is standardized
26,417
Akaike Information criterion for k-means
The model for which k-means is maximum likelihood is not a mixture model (there are no mixture proportions, and the classification of observations to clusters is crisp whereas in mixture models there are posterior probabilities for this), but a model for which every observation has its own parameter indicating to which cluster it belongs. This is nonstandard as the number of parameters converges to infinity, and standard maximum likelihood theory doesn't hold (it is well known that the estimated k-means are not consistent for the means of the corresponding model, which is contrary to standard ML theory). This means that also any theory behind AIC and BIC doesn't hold, and these methods are theoretically invalid. (Obviously it may be that they do a good job in some situations anyway; note also that it doesn't matter whether these strange discrete observation parameters are counted into the general number of parameters or not, because for a given dataset their number is constant. One would need to deal with them though in any attempt to derive asymptotic theory.) The model does not assume $\sigma^2=1$, and it is invalid as well to assume $\sigma^2$ to be dependent of the data. In fact it makes some sense to have a penalty that depends on $\sigma^2$, because if the data have a certain variation, more clusters with a low variance are needed to cover them in a Voronoi tesselation fashion (which is what k-means does) than if the clusters have a larger variance. In fact in this way using the AIC you could also choose a variance estimator, which is connected to the number of clusters in that fashion - smaller variance, more clusters needed. This looks surprising because the variance in k-means is usually ignored because people are only interested in the clustering for given k. Despite this, AIC and BIC are invalid anyway, for the reason stated above, or rather, nobody has yet demonstrated how they may be valid, and the standard arguments don't apply.
Akaike Information criterion for k-means
The model for which k-means is maximum likelihood is not a mixture model (there are no mixture proportions, and the classification of observations to clusters is crisp whereas in mixture models there
Akaike Information criterion for k-means The model for which k-means is maximum likelihood is not a mixture model (there are no mixture proportions, and the classification of observations to clusters is crisp whereas in mixture models there are posterior probabilities for this), but a model for which every observation has its own parameter indicating to which cluster it belongs. This is nonstandard as the number of parameters converges to infinity, and standard maximum likelihood theory doesn't hold (it is well known that the estimated k-means are not consistent for the means of the corresponding model, which is contrary to standard ML theory). This means that also any theory behind AIC and BIC doesn't hold, and these methods are theoretically invalid. (Obviously it may be that they do a good job in some situations anyway; note also that it doesn't matter whether these strange discrete observation parameters are counted into the general number of parameters or not, because for a given dataset their number is constant. One would need to deal with them though in any attempt to derive asymptotic theory.) The model does not assume $\sigma^2=1$, and it is invalid as well to assume $\sigma^2$ to be dependent of the data. In fact it makes some sense to have a penalty that depends on $\sigma^2$, because if the data have a certain variation, more clusters with a low variance are needed to cover them in a Voronoi tesselation fashion (which is what k-means does) than if the clusters have a larger variance. In fact in this way using the AIC you could also choose a variance estimator, which is connected to the number of clusters in that fashion - smaller variance, more clusters needed. This looks surprising because the variance in k-means is usually ignored because people are only interested in the clustering for given k. Despite this, AIC and BIC are invalid anyway, for the reason stated above, or rather, nobody has yet demonstrated how they may be valid, and the standard arguments don't apply.
Akaike Information criterion for k-means The model for which k-means is maximum likelihood is not a mixture model (there are no mixture proportions, and the classification of observations to clusters is crisp whereas in mixture models there
26,418
Akaike Information criterion for k-means
I know this is an old (and answered) question, but I wanted to jump in because I ran into this same question, and was surprised by how little information there was available. Before diving in to my answer, I wanted to echo what was said by FinanceGuyThatCantCode: you have a small error in your proposal. The $\sigma$ in your question really should be $\sigma_i$, since it depends on each cluster. So what you're asking is not why total variance is assumed equal to 1, but rather why each cluster variance is assumed equal to 1. The answer is that the $\sigma_i=1$ assumption is actually an assumption of the k-means algorithm. Lets extend your analogy that k-means is really a latent Gaussian problem, now look at the k-means loss function: $$ \min_{\mu_i} \sum_i \sum_{x_i \in S_i} |x_i - \mu_i|^2 $$ Where $S_i$ is the set of $x_i$ assigned to center $\mu_i$. If we imagine that this loss function is the negative log-likelihood, and that what we're really doing is a likelihood maximization of the latent Gaussian means, we'd get the following equivalent likelihood maximization: $$ \max_{\mu_i} \prod_i \prod_{x_i \in S_i} \exp \left[ (x_i - \mu_i)^2 \right] $$ Playing a little fast and loose with scaling constants, this is the same as: $$ \max_{\mu_i} \prod_i \prod_{x_i \in S_i} N(x_i;\mu_i,\sigma_i^2 = 1) $$ Where $N(x_i;\mu_i,\sigma_i^2 = 1)$ is the normal PDf. So we see that k-means implicitly assumes that the latent Gaussians have unit variance. This is because k-means isn't really meant to be a probabilistic model of the data; it's not a "generative" model which is intended to predict future datapoints. It's just an algorithm which uses a reasonable heuristic to produce label assignments. Speculation incoming: I believe that if you wanted to relax the assumption that $\sigma_i=1$, then your best estimate would probably be something like $\frac{1}{|S_i|-1} \sum_{x_i \in S_i} |x_i-\mu_i|^2$, and so the AIC you propose (with the correction of $\sigma$ to $\sigma_i$) would collapse into something like: $$ \sum_i |S_i| + 2 k d = n + 2 k d $$ Which is just a direct penalty on $k$.
Akaike Information criterion for k-means
I know this is an old (and answered) question, but I wanted to jump in because I ran into this same question, and was surprised by how little information there was available. Before diving in to my an
Akaike Information criterion for k-means I know this is an old (and answered) question, but I wanted to jump in because I ran into this same question, and was surprised by how little information there was available. Before diving in to my answer, I wanted to echo what was said by FinanceGuyThatCantCode: you have a small error in your proposal. The $\sigma$ in your question really should be $\sigma_i$, since it depends on each cluster. So what you're asking is not why total variance is assumed equal to 1, but rather why each cluster variance is assumed equal to 1. The answer is that the $\sigma_i=1$ assumption is actually an assumption of the k-means algorithm. Lets extend your analogy that k-means is really a latent Gaussian problem, now look at the k-means loss function: $$ \min_{\mu_i} \sum_i \sum_{x_i \in S_i} |x_i - \mu_i|^2 $$ Where $S_i$ is the set of $x_i$ assigned to center $\mu_i$. If we imagine that this loss function is the negative log-likelihood, and that what we're really doing is a likelihood maximization of the latent Gaussian means, we'd get the following equivalent likelihood maximization: $$ \max_{\mu_i} \prod_i \prod_{x_i \in S_i} \exp \left[ (x_i - \mu_i)^2 \right] $$ Playing a little fast and loose with scaling constants, this is the same as: $$ \max_{\mu_i} \prod_i \prod_{x_i \in S_i} N(x_i;\mu_i,\sigma_i^2 = 1) $$ Where $N(x_i;\mu_i,\sigma_i^2 = 1)$ is the normal PDf. So we see that k-means implicitly assumes that the latent Gaussians have unit variance. This is because k-means isn't really meant to be a probabilistic model of the data; it's not a "generative" model which is intended to predict future datapoints. It's just an algorithm which uses a reasonable heuristic to produce label assignments. Speculation incoming: I believe that if you wanted to relax the assumption that $\sigma_i=1$, then your best estimate would probably be something like $\frac{1}{|S_i|-1} \sum_{x_i \in S_i} |x_i-\mu_i|^2$, and so the AIC you propose (with the correction of $\sigma$ to $\sigma_i$) would collapse into something like: $$ \sum_i |S_i| + 2 k d = n + 2 k d $$ Which is just a direct penalty on $k$.
Akaike Information criterion for k-means I know this is an old (and answered) question, but I wanted to jump in because I ran into this same question, and was surprised by how little information there was available. Before diving in to my an
26,419
Akaike Information criterion for k-means
An alternative to assume $\sigma^2=1$, is to assume $$ \begin{aligned} \sigma^2 = \text{average residual sum of square} = \\ \frac{RSS}{\text{number of cell}} = \\ \frac{\sum_{l=1}^k\sum_{i=1}^{n_l}(\vec{x_{i,l}}-\vec{\mu_l})^2}{nd} \end{aligned} $$ The resulting formula seems to agree with the BIC in the Gaussian special case, where The modified code: kmeansAIC = function(fit){ d = ncol(fit$centers) n = length(fit$cluster) k = nrow(fit$centers) D = fit$tot.withinss # return(D + 2*d*k) # original # return(n*d*log(D/n/d) + 2*d*k) # for individual cell return(n*log(D/n) + 2*k) # for individual row } Following your log-likelihood function $\mathcal{L}$ for a cluster $$ \begin{aligned} \mathcal{L}(\Theta;\vec{x}) = \sum_{i=1}^{n} log( \frac{1}{\sqrt{(2 \pi \sigma^2)^d}} \exp(-\frac{(\vec{x_i}-\vec{\mu})^2}{2 \sigma^2}) ) = \\ - n \log( \sqrt{(2 \pi \sigma^2)^d}) - \frac{1}{2 \sigma^2} \sum_{i=1}^{n} (\vec{x_i}-\vec{\mu})^2 \end{aligned} $$ Instead of assuming $\sigma^2=1$, we get $$ \begin{aligned} =-\frac{nd}{2}(log(2 \pi) + log( \sigma^2)) - \frac{1}{2 \sigma^2} \sum_{i=1}^{n} (\vec{x_i}-\vec{\mu})^2 = \\ -\frac{nd}{2}log(2 \pi) -\frac{nd}{2} log( \frac{RSS}{nd}) - \frac{1}{2 \frac{RSS}{nd}}\text{RSS} = \\ -\frac{nd}{2} log( \frac{RSS}{nd}) + Constant(nd) \end{aligned} $$ which brings us back to the special case BIC above except that nd refers to number of cells and n to number of rows.
Akaike Information criterion for k-means
An alternative to assume $\sigma^2=1$, is to assume $$ \begin{aligned} \sigma^2 = \text{average residual sum of square} = \\ \frac{RSS}{\text{number of cell}} = \\ \frac{\sum_{l=1}^k\sum_{i=1}^{n_l}(\
Akaike Information criterion for k-means An alternative to assume $\sigma^2=1$, is to assume $$ \begin{aligned} \sigma^2 = \text{average residual sum of square} = \\ \frac{RSS}{\text{number of cell}} = \\ \frac{\sum_{l=1}^k\sum_{i=1}^{n_l}(\vec{x_{i,l}}-\vec{\mu_l})^2}{nd} \end{aligned} $$ The resulting formula seems to agree with the BIC in the Gaussian special case, where The modified code: kmeansAIC = function(fit){ d = ncol(fit$centers) n = length(fit$cluster) k = nrow(fit$centers) D = fit$tot.withinss # return(D + 2*d*k) # original # return(n*d*log(D/n/d) + 2*d*k) # for individual cell return(n*log(D/n) + 2*k) # for individual row } Following your log-likelihood function $\mathcal{L}$ for a cluster $$ \begin{aligned} \mathcal{L}(\Theta;\vec{x}) = \sum_{i=1}^{n} log( \frac{1}{\sqrt{(2 \pi \sigma^2)^d}} \exp(-\frac{(\vec{x_i}-\vec{\mu})^2}{2 \sigma^2}) ) = \\ - n \log( \sqrt{(2 \pi \sigma^2)^d}) - \frac{1}{2 \sigma^2} \sum_{i=1}^{n} (\vec{x_i}-\vec{\mu})^2 \end{aligned} $$ Instead of assuming $\sigma^2=1$, we get $$ \begin{aligned} =-\frac{nd}{2}(log(2 \pi) + log( \sigma^2)) - \frac{1}{2 \sigma^2} \sum_{i=1}^{n} (\vec{x_i}-\vec{\mu})^2 = \\ -\frac{nd}{2}log(2 \pi) -\frac{nd}{2} log( \frac{RSS}{nd}) - \frac{1}{2 \frac{RSS}{nd}}\text{RSS} = \\ -\frac{nd}{2} log( \frac{RSS}{nd}) + Constant(nd) \end{aligned} $$ which brings us back to the special case BIC above except that nd refers to number of cells and n to number of rows.
Akaike Information criterion for k-means An alternative to assume $\sigma^2=1$, is to assume $$ \begin{aligned} \sigma^2 = \text{average residual sum of square} = \\ \frac{RSS}{\text{number of cell}} = \\ \frac{\sum_{l=1}^k\sum_{i=1}^{n_l}(\
26,420
Akaike Information criterion for k-means
It doesn't matter anyway because you typically compare which AIC is better, in which case the constant doesn't matter (if $A > B$, $cA > cB$ for positive $c$).
Akaike Information criterion for k-means
It doesn't matter anyway because you typically compare which AIC is better, in which case the constant doesn't matter (if $A > B$, $cA > cB$ for positive $c$).
Akaike Information criterion for k-means It doesn't matter anyway because you typically compare which AIC is better, in which case the constant doesn't matter (if $A > B$, $cA > cB$ for positive $c$).
Akaike Information criterion for k-means It doesn't matter anyway because you typically compare which AIC is better, in which case the constant doesn't matter (if $A > B$, $cA > cB$ for positive $c$).
26,421
do we ever normalize categorical variables? does it make any sense?
This is still a matter of debate and it also depends strongly on the algorithms you're using. For example, if you're using Lasso for feature selection, all of the features should be on the same scale and standardization of binary features is recommended (see The Elements of Statistical Learning by Tibshirani et al.: http://web.stanford.edu/~hastie/ElemStatLearn/). Logistic regression doesn't profit as much from normalization of binary variables: Should you ever standardise binary variables?. Interestingly enough, Andrew Gelman suggested standardizing all numeric variables by dividing with two times the standard deviation and leave binary variables as they are, such that you can interpret and compare the influence of the regression coefficients more easily: http://www.stat.columbia.edu/~gelman/research/published/standardizing7.pdf.
do we ever normalize categorical variables? does it make any sense?
This is still a matter of debate and it also depends strongly on the algorithms you're using. For example, if you're using Lasso for feature selection, all of the features should be on the same scale
do we ever normalize categorical variables? does it make any sense? This is still a matter of debate and it also depends strongly on the algorithms you're using. For example, if you're using Lasso for feature selection, all of the features should be on the same scale and standardization of binary features is recommended (see The Elements of Statistical Learning by Tibshirani et al.: http://web.stanford.edu/~hastie/ElemStatLearn/). Logistic regression doesn't profit as much from normalization of binary variables: Should you ever standardise binary variables?. Interestingly enough, Andrew Gelman suggested standardizing all numeric variables by dividing with two times the standard deviation and leave binary variables as they are, such that you can interpret and compare the influence of the regression coefficients more easily: http://www.stat.columbia.edu/~gelman/research/published/standardizing7.pdf.
do we ever normalize categorical variables? does it make any sense? This is still a matter of debate and it also depends strongly on the algorithms you're using. For example, if you're using Lasso for feature selection, all of the features should be on the same scale
26,422
Difference between the types of SVM
Short answer You can select what to used based on your goal and what kind of data you have. If you have a classification problem, i.e., discrete label to predict, you can use C-classification and nu-classification. If you have a regression problem, i.e., continuous number to predict, you can use eps-regression and nu-regression. If you only have one class of the data, i.e., normal behavior, and want to detect outliers. one-classification. Details C-classification and nu-classification is for binary classification usage. Say if you want to build a model to classify cat vs. dog based on features for animals, i.e., prediction target is a discrete variable/label. For details about difference between C-classification and nu-classification. You can find in the FAQ from LIBSVM Q: What is the difference between nu-SVC and C-SVC? Basically they are the same thing but with different parameters. The range of C is from zero to infinity but nu is always between [0,1]. A nice property of nu is that it is related to the ratio of support vectors and the ratio of the training error. One-classification is for "outlier detection", where you only have one classes data. For example, you want to detect "unusual" behaviors of one user's account. But you do not have "unusual behavior" to train the model. But only the normal behavior. eps-regression and nu-regression are used for regression problems, where you want to predict a continuous number say housing price. Detailed difference can be found here: Difference between ep-SVR and nu-SVR (and least squares SVR)
Difference between the types of SVM
Short answer You can select what to used based on your goal and what kind of data you have. If you have a classification problem, i.e., discrete label to predict, you can use C-classification and nu
Difference between the types of SVM Short answer You can select what to used based on your goal and what kind of data you have. If you have a classification problem, i.e., discrete label to predict, you can use C-classification and nu-classification. If you have a regression problem, i.e., continuous number to predict, you can use eps-regression and nu-regression. If you only have one class of the data, i.e., normal behavior, and want to detect outliers. one-classification. Details C-classification and nu-classification is for binary classification usage. Say if you want to build a model to classify cat vs. dog based on features for animals, i.e., prediction target is a discrete variable/label. For details about difference between C-classification and nu-classification. You can find in the FAQ from LIBSVM Q: What is the difference between nu-SVC and C-SVC? Basically they are the same thing but with different parameters. The range of C is from zero to infinity but nu is always between [0,1]. A nice property of nu is that it is related to the ratio of support vectors and the ratio of the training error. One-classification is for "outlier detection", where you only have one classes data. For example, you want to detect "unusual" behaviors of one user's account. But you do not have "unusual behavior" to train the model. But only the normal behavior. eps-regression and nu-regression are used for regression problems, where you want to predict a continuous number say housing price. Detailed difference can be found here: Difference between ep-SVR and nu-SVR (and least squares SVR)
Difference between the types of SVM Short answer You can select what to used based on your goal and what kind of data you have. If you have a classification problem, i.e., discrete label to predict, you can use C-classification and nu
26,423
How to plot prior distributions in Stan?
As my previous answer was deleted, here is a more explicit one, with an example using a simple sampling from the prior: library(rstan) model = " parameters { real p; } model { p ~ normal(1,3); } " fit = stan(model_code = model, pars = c('p'), control=list(adapt_delta=0.99, max_treedepth=10), iter = 5000, chains = 1, warmup = 1000, verbose=FALSE) print(fit) with output: Inference for Stan model: a067aa7e9d60dcf5fa2c08c3db339374. 1 chains, each with iter=5000; warmup=1000; thin=1; post-warmup draws per chain=4000, total post-warmup draws=4000. mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat p 1.02 0.07 3.0 -4.84 -1.02 1.01 3.07 6.83 1607 1 lp__ -0.50 0.02 0.7 -2.47 -0.66 -0.23 -0.05 0.00 1346 1 Hope this helps...
How to plot prior distributions in Stan?
As my previous answer was deleted, here is a more explicit one, with an example using a simple sampling from the prior: library(rstan) model = " parameters { real p; } model { p ~ normal(1,3); }
How to plot prior distributions in Stan? As my previous answer was deleted, here is a more explicit one, with an example using a simple sampling from the prior: library(rstan) model = " parameters { real p; } model { p ~ normal(1,3); } " fit = stan(model_code = model, pars = c('p'), control=list(adapt_delta=0.99, max_treedepth=10), iter = 5000, chains = 1, warmup = 1000, verbose=FALSE) print(fit) with output: Inference for Stan model: a067aa7e9d60dcf5fa2c08c3db339374. 1 chains, each with iter=5000; warmup=1000; thin=1; post-warmup draws per chain=4000, total post-warmup draws=4000. mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat p 1.02 0.07 3.0 -4.84 -1.02 1.01 3.07 6.83 1607 1 lp__ -0.50 0.02 0.7 -2.47 -0.66 -0.23 -0.05 0.00 1346 1 Hope this helps...
How to plot prior distributions in Stan? As my previous answer was deleted, here is a more explicit one, with an example using a simple sampling from the prior: library(rstan) model = " parameters { real p; } model { p ~ normal(1,3); }
26,424
How to interpret TBATS model results and model diagnostics
In the help page for ?tbats, we find that: The fitted model is designated TBATS(omega, p,q, phi, ,...,) where omega is the Box-Cox parameter and phi is the damping parameter; the error is modelled as an ARMA(p,q) process and m1,...,mJ list the seasonal periods used in the model and k1,...,kJ are the corresponding number of Fourier terms used for each seasonality. So: omega = 1, meaning that indeed, there was no Box-Cox transformation. phi = 0.838, meaning that the trend will be dampened. (To be honest, I don't know whether $\phi=0$ or $\phi=1$ corresponds to total dampening. Best to play around a little with simulated data.) See the use.damped.trend parameter for tbats(). You have three different seasonal cycles, one of length 48 = 24*2 (daily), one of length 336 = 7*24*2 (weekly) and one of length 17520 = 365*24*2 (yearly). tbats fits the first one using six Fourier terms, the second again with six, the last with five. The original TBATS paper by De Livera, Hyndman & Snyder (2011, JASA) is of course useful. Next: The "level" is the local level of the time series. The "trend" is the local trend. These are analogous to the more common season-trend decomposition using lowess (STL). Take a look at the stl() command. To get a clearer plot for season1 and season2, you can look into the numerical values of the separate components of your TBATS model. Look at str(tbats.components(model1)) and summary(tbats.components(model1)). tbats.components() gives you a multiple time series (mts) object, which is essentially a matrix - one of the columns will give you each seasonal component. residuals() should work like it works everywhere in R; that is, it should return the final residuals. These should indeed be white noise, because they are the residuals after applying an ARMA(5,4). The peaks in your ACF appear to be regular - it looks like there is some remaining seasonality. Can you deduce their periodicity? (It doesn't really help that the lags are counted in multiples of the longest seasonal cycle.) Finally, yes, the root mean squared error, which is a common point forecast accuracy measure, has the same acronym out-of sample: RMSE.
How to interpret TBATS model results and model diagnostics
In the help page for ?tbats, we find that: The fitted model is designated TBATS(omega, p,q, phi, ,...,) where omega is the Box-Cox parameter and phi is the damping parameter; the
How to interpret TBATS model results and model diagnostics In the help page for ?tbats, we find that: The fitted model is designated TBATS(omega, p,q, phi, ,...,) where omega is the Box-Cox parameter and phi is the damping parameter; the error is modelled as an ARMA(p,q) process and m1,...,mJ list the seasonal periods used in the model and k1,...,kJ are the corresponding number of Fourier terms used for each seasonality. So: omega = 1, meaning that indeed, there was no Box-Cox transformation. phi = 0.838, meaning that the trend will be dampened. (To be honest, I don't know whether $\phi=0$ or $\phi=1$ corresponds to total dampening. Best to play around a little with simulated data.) See the use.damped.trend parameter for tbats(). You have three different seasonal cycles, one of length 48 = 24*2 (daily), one of length 336 = 7*24*2 (weekly) and one of length 17520 = 365*24*2 (yearly). tbats fits the first one using six Fourier terms, the second again with six, the last with five. The original TBATS paper by De Livera, Hyndman & Snyder (2011, JASA) is of course useful. Next: The "level" is the local level of the time series. The "trend" is the local trend. These are analogous to the more common season-trend decomposition using lowess (STL). Take a look at the stl() command. To get a clearer plot for season1 and season2, you can look into the numerical values of the separate components of your TBATS model. Look at str(tbats.components(model1)) and summary(tbats.components(model1)). tbats.components() gives you a multiple time series (mts) object, which is essentially a matrix - one of the columns will give you each seasonal component. residuals() should work like it works everywhere in R; that is, it should return the final residuals. These should indeed be white noise, because they are the residuals after applying an ARMA(5,4). The peaks in your ACF appear to be regular - it looks like there is some remaining seasonality. Can you deduce their periodicity? (It doesn't really help that the lags are counted in multiples of the longest seasonal cycle.) Finally, yes, the root mean squared error, which is a common point forecast accuracy measure, has the same acronym out-of sample: RMSE.
How to interpret TBATS model results and model diagnostics In the help page for ?tbats, we find that: The fitted model is designated TBATS(omega, p,q, phi, ,...,) where omega is the Box-Cox parameter and phi is the damping parameter; the
26,425
Ranking features in logistic regression
I think the answer you are looking for might be the Boruta algorithm. This is a wrapper method that directly measures the importance of features in an "all relevance" sense and is implemented in an R package, which produces nice plots such as where the importance of any feature is on the y-axis and is compared with a null plotted in blue here. This blog post describes the approach and I would recommend you read it as a very clear intro.
Ranking features in logistic regression
I think the answer you are looking for might be the Boruta algorithm. This is a wrapper method that directly measures the importance of features in an "all relevance" sense and is implemented in an R
Ranking features in logistic regression I think the answer you are looking for might be the Boruta algorithm. This is a wrapper method that directly measures the importance of features in an "all relevance" sense and is implemented in an R package, which produces nice plots such as where the importance of any feature is on the y-axis and is compared with a null plotted in blue here. This blog post describes the approach and I would recommend you read it as a very clear intro.
Ranking features in logistic regression I think the answer you are looking for might be the Boruta algorithm. This is a wrapper method that directly measures the importance of features in an "all relevance" sense and is implemented in an R
26,426
Ranking features in logistic regression
To begin understanding how to rank variables by importance for regression models, you can start with linear regression. A popular approach to rank a variable's importance in a linear regression model is to decompose $R^2$ into contributions attributed to each variable. But variable importance is not straightforward in linear regression due to correlations between variables. Refer to the document describing the PMD method (Feldman, 2005)[3]. Another popular approach is averaging over orderings (LMG, 1980)[2]. There isn't much consensus over how to rank variables for logistic regression. A good overview of this topic is given in [1], it describes adaptations of the linear regression relative importance techniques using Pseudo-$R^2$ for logistic regression. A list of the popular approaches to rank feature importance in logistic regression models are: Logistic pseudo partial correlation (using Pseudo-$R^2$) Adequacy: the proportion of the full model log‐likelihood that is explainable by each predictor individually Concordance: Indicates a model’s ability to differentiate between the positive and negative response variables. A separate model is constructed for each predictor and the importance score is the predicted probability of true positives based on that predictor alone. Information value: Information values quantify the amount of information about the outcome gained from a predictor. It is based on an analysis of each predictor in turn, without taking into account the other predictors. References: On Measuring the Relative Importance of Explanatory Variables in a Logistic Regression Relative importance of Linear Regressors in R Relative Importance and Value, Barry Feldman (PMD method)
Ranking features in logistic regression
To begin understanding how to rank variables by importance for regression models, you can start with linear regression. A popular approach to rank a variable's importance in a linear regression model
Ranking features in logistic regression To begin understanding how to rank variables by importance for regression models, you can start with linear regression. A popular approach to rank a variable's importance in a linear regression model is to decompose $R^2$ into contributions attributed to each variable. But variable importance is not straightforward in linear regression due to correlations between variables. Refer to the document describing the PMD method (Feldman, 2005)[3]. Another popular approach is averaging over orderings (LMG, 1980)[2]. There isn't much consensus over how to rank variables for logistic regression. A good overview of this topic is given in [1], it describes adaptations of the linear regression relative importance techniques using Pseudo-$R^2$ for logistic regression. A list of the popular approaches to rank feature importance in logistic regression models are: Logistic pseudo partial correlation (using Pseudo-$R^2$) Adequacy: the proportion of the full model log‐likelihood that is explainable by each predictor individually Concordance: Indicates a model’s ability to differentiate between the positive and negative response variables. A separate model is constructed for each predictor and the importance score is the predicted probability of true positives based on that predictor alone. Information value: Information values quantify the amount of information about the outcome gained from a predictor. It is based on an analysis of each predictor in turn, without taking into account the other predictors. References: On Measuring the Relative Importance of Explanatory Variables in a Logistic Regression Relative importance of Linear Regressors in R Relative Importance and Value, Barry Feldman (PMD method)
Ranking features in logistic regression To begin understanding how to rank variables by importance for regression models, you can start with linear regression. A popular approach to rank a variable's importance in a linear regression model
26,427
Ranking features in logistic regression
Don't be alarmed. Logistic Regression (LR) can very much be a classification scheme. LR minimizes the following loss: $$ \mathop {\min }\limits_{{\bf{w}},b} \sum\limits_{i = 1}^n {\log \left( {1 + \exp \left( { - {y_i}{f_{{\bf{w}},b}}({x_i})} \right)} \right) + \lambda {{\left\| {\bf{w}} \right\|}^2}} $$ where the $x_i$ and $y_i$ are the feature vector and target vector for example $i$ from your training set. This function originates from the joint likelihood over all training examples, which explains its probabalistic nature even though we use it for classification. In the equation $\mathbf{w}$ is your weight vector and $b$ your bias. I trust that you know what ${{f_{w,b}}({x_i})}$ is. The last term in the minimization problem is the regularization term, which, among other things, controls the generalization of the model. Assuming all your $\mathbf{x}$ are normalized, for example by deviding by the magnitude of $\mathbf{x}$, it is quite easy to see which variables are more important: those wich are larger c.f. the others or (on the negative side) smaller c.f. the others. They influence the loss the most. If you are keen on finding the variables which really are important and in the process don't mind kicking a few out, you can $\ell_1$ regularize your loss function: $$ \mathop {\min }\limits_{{\bf{w}},b} \sum\limits_{i = 1}^n {\log \left( {1 + \exp \left( { - {y_i}{f_{{\bf{w}},b}}({x_i})} \right)} \right) + \lambda \left| {\bf{w}} \right|} $$ The derivatives or the regularizer are quite straightforward, so I will not mention them here. Using this form of regularization and an appropriate $\lambda$ will enforce the less important elements in $\mathbf{w}$ to become zero and the others not. I hope this helps. Ask if you have any further questions.
Ranking features in logistic regression
Don't be alarmed. Logistic Regression (LR) can very much be a classification scheme. LR minimizes the following loss: $$ \mathop {\min }\limits_{{\bf{w}},b} \sum\limits_{i = 1}^n {\log \left( {1 + \ex
Ranking features in logistic regression Don't be alarmed. Logistic Regression (LR) can very much be a classification scheme. LR minimizes the following loss: $$ \mathop {\min }\limits_{{\bf{w}},b} \sum\limits_{i = 1}^n {\log \left( {1 + \exp \left( { - {y_i}{f_{{\bf{w}},b}}({x_i})} \right)} \right) + \lambda {{\left\| {\bf{w}} \right\|}^2}} $$ where the $x_i$ and $y_i$ are the feature vector and target vector for example $i$ from your training set. This function originates from the joint likelihood over all training examples, which explains its probabalistic nature even though we use it for classification. In the equation $\mathbf{w}$ is your weight vector and $b$ your bias. I trust that you know what ${{f_{w,b}}({x_i})}$ is. The last term in the minimization problem is the regularization term, which, among other things, controls the generalization of the model. Assuming all your $\mathbf{x}$ are normalized, for example by deviding by the magnitude of $\mathbf{x}$, it is quite easy to see which variables are more important: those wich are larger c.f. the others or (on the negative side) smaller c.f. the others. They influence the loss the most. If you are keen on finding the variables which really are important and in the process don't mind kicking a few out, you can $\ell_1$ regularize your loss function: $$ \mathop {\min }\limits_{{\bf{w}},b} \sum\limits_{i = 1}^n {\log \left( {1 + \exp \left( { - {y_i}{f_{{\bf{w}},b}}({x_i})} \right)} \right) + \lambda \left| {\bf{w}} \right|} $$ The derivatives or the regularizer are quite straightforward, so I will not mention them here. Using this form of regularization and an appropriate $\lambda$ will enforce the less important elements in $\mathbf{w}$ to become zero and the others not. I hope this helps. Ask if you have any further questions.
Ranking features in logistic regression Don't be alarmed. Logistic Regression (LR) can very much be a classification scheme. LR minimizes the following loss: $$ \mathop {\min }\limits_{{\bf{w}},b} \sum\limits_{i = 1}^n {\log \left( {1 + \ex
26,428
Wald Test and Z Test
Some people call both "the Wald test". See, for example, Wikipedia on the Wald test. Note that if you square the Z statistic you get the chi-square statistic; similarly the square of the two tailed Z critical value is the chi square critical value. So they're not really doing different things. I wouldn't say one really generalizes the other in the case of a single parameter (aside from the Z-version arguably has the advantage of making a one-tailed test possible), but the Wald chi-square approach readily extends to multiple parameters, so in that sense you could say it was more general.
Wald Test and Z Test
Some people call both "the Wald test". See, for example, Wikipedia on the Wald test. Note that if you square the Z statistic you get the chi-square statistic; similarly the square of the two tailed Z
Wald Test and Z Test Some people call both "the Wald test". See, for example, Wikipedia on the Wald test. Note that if you square the Z statistic you get the chi-square statistic; similarly the square of the two tailed Z critical value is the chi square critical value. So they're not really doing different things. I wouldn't say one really generalizes the other in the case of a single parameter (aside from the Z-version arguably has the advantage of making a one-tailed test possible), but the Wald chi-square approach readily extends to multiple parameters, so in that sense you could say it was more general.
Wald Test and Z Test Some people call both "the Wald test". See, for example, Wikipedia on the Wald test. Note that if you square the Z statistic you get the chi-square statistic; similarly the square of the two tailed Z
26,429
How to generate uniformly random orthogonal matrices of positive determinant?
The choice of column doesn't matter: the resulting distribution on the special orthogonal matrices, $SO(n)$, is still uniform. I will explain this by using an argument that extends, in an obvious manner, to many related questions about uniform generation of elements of groups. Each step of this argument is trivial, requiring nothing more than reference to suitable definitions or a simple calculation (such as noting that the matrix $\mathbb{I}_1$ is orthogonal and self-inverse). The argument is a generalization of a familiar situation. Consider the task of drawing positive real numbers according to a specified continuous distribution $F$. This can be done by drawing any real number from a continuous distribution $G$ and negating the result, if necessary, to guarantee a positive value (almost surely). In order for this process to have the distribution $F$, $G$ must have the property that $$G(x) - G(-x) = F(x).$$ The simplest way to accomplish this is when $G$ is symmetric around $0$ so that $G(x) - 1/2 = 1/2 - G(-x)$, entailing $F(x) = 2G(x) - 1$: all positive probability densities are simply doubled and all negative outcomes are eliminated. The familiar relationship between the half-normal distribution ($F$) and normal distribution ($G$) is of this kind. In the following, the group $O(n)$ plays the role of the non-zero real numbers (considered as a multiplicative group) and its subgroup $SO(n)$ plays the role of the positive real numbers $\mathbb{R}_{+}$. The Haar measure $dx/x$ is invariant under negation, so when it is "folded" from $\mathbb{R}-\{0\}$ to $\mathbb{R}_{+}$, the distribution of the positive values does not change. (This measure, unfortunately, cannot be normalized to a probability measure--but that is the only way in which the analogy breaks down.) Negating a specific column of an orthogonal matrix (when its determinant is negative) is the analog of negating a negative real number to fold it into the positive subgroup. More generally, you could pick in advance any orthogonal matrix $\mathbb{J}$ of negative determinant and use it instead of $\mathbb{I}_1$: the results would be the same. Although the question is phrased in terms of generating random variables, it really asks about probability distributions on the matrix groups $O(n, \mathbb{R}) = O(n)$ and $SO(n, \mathbb{R}) = SO(n)$. The connection between these groups is described in terms of the orthogonal matrix $$\mathbb{I}_1 = \pmatrix{-1 & 0 & 0 & \ldots & 0 \\ 0 & 1 & 0 & \ldots & 0 \\ \vdots & \vdots & \vdots & \ldots & 0 \\ 0 & 0 & 0 & \ldots & 1}$$ because negating the first column of an orthogonal matrix $\mathbb X$ means right-multiplying $\mathbb{X}$ by $\mathbb{I}_1$. Notice that $SO(n)\subset O(n)$ and $O(n)$ is the disjoint union $$O(n) = SO(n) \cup SO(n)\,\mathbb{I}_1^{-1}.$$ Given a probability space $(O(n), \mathfrak{S}, \mathbb{P})$ defined on $O(n)$, the process described in the question defines a map $$f:O(n)\to SO(n)$$ by setting $$f(\mathbb{X}) = \mathbb{X}$$ when $\mathbb{X}\in SO(n)$ and $$f(\mathbb{X}) = \mathbb{X}\mathbb{I}_1$$ for $\mathbb{X}\in SO(n)\,{\mathbb{I}_1}^{-1}$. The question is concerned about generating random elements in $SO(n)$ by obtaining random elements $\omega\in O(n)$: that is, by "pushing them forward" via $f$ to produce $f_{*}\omega = f(\omega)\in SO(n)$. The pushforward creates a probability space $(SO(n), \mathfrak{S}^\prime, \mathbb{P}^\prime)$ with $$\mathfrak{S}^\prime = f_{*}\mathfrak{S} = \{f(E)\,|\,E\subset\mathfrak{S}\} $$ and $$\mathbb{P}^\prime(E) = (f_{*}\mathbb{P})(E) = \mathbb{P}(f^{-1}(E)) = \mathbb{P}(E \cup E\,\mathbb{I}_1)$$ for all $E \subset \mathfrak{S}^\prime$. Assuming right multiplication by $\mathbb{I}_1$ is measure-preserving, and noting that in any event $E \cap E\,\mathbb{I}_1 = \emptyset$, it would follow immediately that for all $E\in\mathfrak{S}^\prime$, $$\mathbb{P}^\prime(E) = \mathbb{P}(E\cup E\,\mathbb{I}_1^{-1}) = \mathbb{P}(E) + \mathbb{P}(E\,\mathbb{I}_1^{-1}) = 2\mathbb{P}(E).$$ In particular, when $\mathbb{P}$ is invariant under right-multiplication in $O(n)$ (which is what "uniform" typically means), the obvious fact that $\mathbb{I}_1$ and its inverse (which happens to equal $\mathbb{I}_1$ itself) are both orthogonal means the foregoing holds, demonstrating that $\mathbb{P}^\prime$ is uniform, too. Thus it is unnecessary to select a random column for negation.
How to generate uniformly random orthogonal matrices of positive determinant?
The choice of column doesn't matter: the resulting distribution on the special orthogonal matrices, $SO(n)$, is still uniform. I will explain this by using an argument that extends, in an obvious mann
How to generate uniformly random orthogonal matrices of positive determinant? The choice of column doesn't matter: the resulting distribution on the special orthogonal matrices, $SO(n)$, is still uniform. I will explain this by using an argument that extends, in an obvious manner, to many related questions about uniform generation of elements of groups. Each step of this argument is trivial, requiring nothing more than reference to suitable definitions or a simple calculation (such as noting that the matrix $\mathbb{I}_1$ is orthogonal and self-inverse). The argument is a generalization of a familiar situation. Consider the task of drawing positive real numbers according to a specified continuous distribution $F$. This can be done by drawing any real number from a continuous distribution $G$ and negating the result, if necessary, to guarantee a positive value (almost surely). In order for this process to have the distribution $F$, $G$ must have the property that $$G(x) - G(-x) = F(x).$$ The simplest way to accomplish this is when $G$ is symmetric around $0$ so that $G(x) - 1/2 = 1/2 - G(-x)$, entailing $F(x) = 2G(x) - 1$: all positive probability densities are simply doubled and all negative outcomes are eliminated. The familiar relationship between the half-normal distribution ($F$) and normal distribution ($G$) is of this kind. In the following, the group $O(n)$ plays the role of the non-zero real numbers (considered as a multiplicative group) and its subgroup $SO(n)$ plays the role of the positive real numbers $\mathbb{R}_{+}$. The Haar measure $dx/x$ is invariant under negation, so when it is "folded" from $\mathbb{R}-\{0\}$ to $\mathbb{R}_{+}$, the distribution of the positive values does not change. (This measure, unfortunately, cannot be normalized to a probability measure--but that is the only way in which the analogy breaks down.) Negating a specific column of an orthogonal matrix (when its determinant is negative) is the analog of negating a negative real number to fold it into the positive subgroup. More generally, you could pick in advance any orthogonal matrix $\mathbb{J}$ of negative determinant and use it instead of $\mathbb{I}_1$: the results would be the same. Although the question is phrased in terms of generating random variables, it really asks about probability distributions on the matrix groups $O(n, \mathbb{R}) = O(n)$ and $SO(n, \mathbb{R}) = SO(n)$. The connection between these groups is described in terms of the orthogonal matrix $$\mathbb{I}_1 = \pmatrix{-1 & 0 & 0 & \ldots & 0 \\ 0 & 1 & 0 & \ldots & 0 \\ \vdots & \vdots & \vdots & \ldots & 0 \\ 0 & 0 & 0 & \ldots & 1}$$ because negating the first column of an orthogonal matrix $\mathbb X$ means right-multiplying $\mathbb{X}$ by $\mathbb{I}_1$. Notice that $SO(n)\subset O(n)$ and $O(n)$ is the disjoint union $$O(n) = SO(n) \cup SO(n)\,\mathbb{I}_1^{-1}.$$ Given a probability space $(O(n), \mathfrak{S}, \mathbb{P})$ defined on $O(n)$, the process described in the question defines a map $$f:O(n)\to SO(n)$$ by setting $$f(\mathbb{X}) = \mathbb{X}$$ when $\mathbb{X}\in SO(n)$ and $$f(\mathbb{X}) = \mathbb{X}\mathbb{I}_1$$ for $\mathbb{X}\in SO(n)\,{\mathbb{I}_1}^{-1}$. The question is concerned about generating random elements in $SO(n)$ by obtaining random elements $\omega\in O(n)$: that is, by "pushing them forward" via $f$ to produce $f_{*}\omega = f(\omega)\in SO(n)$. The pushforward creates a probability space $(SO(n), \mathfrak{S}^\prime, \mathbb{P}^\prime)$ with $$\mathfrak{S}^\prime = f_{*}\mathfrak{S} = \{f(E)\,|\,E\subset\mathfrak{S}\} $$ and $$\mathbb{P}^\prime(E) = (f_{*}\mathbb{P})(E) = \mathbb{P}(f^{-1}(E)) = \mathbb{P}(E \cup E\,\mathbb{I}_1)$$ for all $E \subset \mathfrak{S}^\prime$. Assuming right multiplication by $\mathbb{I}_1$ is measure-preserving, and noting that in any event $E \cap E\,\mathbb{I}_1 = \emptyset$, it would follow immediately that for all $E\in\mathfrak{S}^\prime$, $$\mathbb{P}^\prime(E) = \mathbb{P}(E\cup E\,\mathbb{I}_1^{-1}) = \mathbb{P}(E) + \mathbb{P}(E\,\mathbb{I}_1^{-1}) = 2\mathbb{P}(E).$$ In particular, when $\mathbb{P}$ is invariant under right-multiplication in $O(n)$ (which is what "uniform" typically means), the obvious fact that $\mathbb{I}_1$ and its inverse (which happens to equal $\mathbb{I}_1$ itself) are both orthogonal means the foregoing holds, demonstrating that $\mathbb{P}^\prime$ is uniform, too. Thus it is unnecessary to select a random column for negation.
How to generate uniformly random orthogonal matrices of positive determinant? The choice of column doesn't matter: the resulting distribution on the special orthogonal matrices, $SO(n)$, is still uniform. I will explain this by using an argument that extends, in an obvious mann
26,430
Question about Continuous Bag of Words
Figure 1 there clarifies things a bit. All word vectors from window of a given size are summed up, result is multiplied by (1/window size) and then fed into output layer. Projection matrix means a whole lookup table where each word corresponds to single real-valued vector. Projection layer is effectivly a process that takes a word (word index) and returns corresponding vector. One can either concatenate them (obtaining input of size k*n where k is window size and n is vector length) or as in CBOW model, just sum all of them (obtaining input of size n).
Question about Continuous Bag of Words
Figure 1 there clarifies things a bit. All word vectors from window of a given size are summed up, result is multiplied by (1/window size) and then fed into output layer. Projection matrix means a wh
Question about Continuous Bag of Words Figure 1 there clarifies things a bit. All word vectors from window of a given size are summed up, result is multiplied by (1/window size) and then fed into output layer. Projection matrix means a whole lookup table where each word corresponds to single real-valued vector. Projection layer is effectivly a process that takes a word (word index) and returns corresponding vector. One can either concatenate them (obtaining input of size k*n where k is window size and n is vector length) or as in CBOW model, just sum all of them (obtaining input of size n).
Question about Continuous Bag of Words Figure 1 there clarifies things a bit. All word vectors from window of a given size are summed up, result is multiplied by (1/window size) and then fed into output layer. Projection matrix means a wh
26,431
Question about Continuous Bag of Words
As I was browsing around regarding CBOW issues and stumbled upon this, here is an alternative answer to your (first) question ("What is a projection layer vs. matrix?"), by looking at the NNLM model (Bengio et al., 2003): If comparing this to Mikolov's model[s] (shown in an alternative answer to this question), the cited sentence (in the question) means that Mikolov removed the (non-linear!) $tanh$ layer seen in Bengio's model shown above. And Mikolov's first (and only) hidden layer, instead of having individual vectors $C(w_i)$ for each word, only uses one vector that sums up the "word parameters", and then those sums get averaged. So this explains the last question ("What does it mean that the vectors are averaged?"). The words are "projected into the same position" because the weights assigned to the individual input words are summed up and averaged in Mikolov's model. Therefore, his projection layer looses all positional information, unlike Bengio's first hidden layer (aka. the projection matrix) - thereby answering the second question ("What does it mean that all words get projected into the same position?"). So Mikolov's model[s] retained the "word parameters" (the input weight matrix), removed the projection matrix $C$ and the $tanh$ layer, and replaced both with a "simple" projection layer. To add, and "just for the record": The real exciting part is Mikolov's approach to solving the part where in Bengio's image you see the phrase "most computation here". Bengio tried to lessen that problem by doing something that is called hierarchical softmax (instead of just using the softmax) in a later paper (Morin & Bengio 2005). But Mikolov, with his strategy of negative subsampling took this a step further: He doesn't compute the negative log-likelihood of all "wrong" words (or Huffman codings, as Bengio suggested in 2005) at all, and just computes a very small sample of negative cases, which, given enough such computations and a clever probability distribution, works extremely well. And the second and even more major contribution, naturally, is that the whole thing about his additive "compositionality" ("man + king = woman + ?" with answer queen), which only really works well with his Skip-Gram model, and can be roughly understood as taking Bengio's model, applying the changes Mikolov suggested (i.e., the phrase cited in your question), and then inverting the whole process. That is, guessing the surrounding words from the output words (now used as input), $P(context | w_t = i)$, instead.
Question about Continuous Bag of Words
As I was browsing around regarding CBOW issues and stumbled upon this, here is an alternative answer to your (first) question ("What is a projection layer vs. matrix?"), by looking at the NNLM model (
Question about Continuous Bag of Words As I was browsing around regarding CBOW issues and stumbled upon this, here is an alternative answer to your (first) question ("What is a projection layer vs. matrix?"), by looking at the NNLM model (Bengio et al., 2003): If comparing this to Mikolov's model[s] (shown in an alternative answer to this question), the cited sentence (in the question) means that Mikolov removed the (non-linear!) $tanh$ layer seen in Bengio's model shown above. And Mikolov's first (and only) hidden layer, instead of having individual vectors $C(w_i)$ for each word, only uses one vector that sums up the "word parameters", and then those sums get averaged. So this explains the last question ("What does it mean that the vectors are averaged?"). The words are "projected into the same position" because the weights assigned to the individual input words are summed up and averaged in Mikolov's model. Therefore, his projection layer looses all positional information, unlike Bengio's first hidden layer (aka. the projection matrix) - thereby answering the second question ("What does it mean that all words get projected into the same position?"). So Mikolov's model[s] retained the "word parameters" (the input weight matrix), removed the projection matrix $C$ and the $tanh$ layer, and replaced both with a "simple" projection layer. To add, and "just for the record": The real exciting part is Mikolov's approach to solving the part where in Bengio's image you see the phrase "most computation here". Bengio tried to lessen that problem by doing something that is called hierarchical softmax (instead of just using the softmax) in a later paper (Morin & Bengio 2005). But Mikolov, with his strategy of negative subsampling took this a step further: He doesn't compute the negative log-likelihood of all "wrong" words (or Huffman codings, as Bengio suggested in 2005) at all, and just computes a very small sample of negative cases, which, given enough such computations and a clever probability distribution, works extremely well. And the second and even more major contribution, naturally, is that the whole thing about his additive "compositionality" ("man + king = woman + ?" with answer queen), which only really works well with his Skip-Gram model, and can be roughly understood as taking Bengio's model, applying the changes Mikolov suggested (i.e., the phrase cited in your question), and then inverting the whole process. That is, guessing the surrounding words from the output words (now used as input), $P(context | w_t = i)$, instead.
Question about Continuous Bag of Words As I was browsing around regarding CBOW issues and stumbled upon this, here is an alternative answer to your (first) question ("What is a projection layer vs. matrix?"), by looking at the NNLM model (
26,432
Observed Fisher information under a transformation
The absolute value is unnecessary. It may be just a typo. You're right. An even better notation would be $\frac{dg(\theta)}{d\theta}\Bigg|_{\theta=\hat{\theta}}$. It doesn't hold in general. Fix some $\psi_0$ and define $g:\mathbb{R}\to\mathbb{R}$ by $g(\theta)=\psi_0$. The rhs would be undefined since the derivative is zero for every $\theta$. A sketch of the regular case: For smooth one-to-one $g$ with $\psi=g(\theta)$. Since, $d/d\psi = d\theta/d\psi\cdot d/d\theta$, we have $$ \begin{align} I^*(\psi) &= -\frac{d^2L^*(\psi)}{d\psi^2} = -\frac{d}{d\psi}\left(\frac{dL^*(\psi)}{d\psi} \right) = -\frac{d}{d\psi}\left(\frac{dL^*(\psi)}{d\theta} \frac{d\theta}{d\psi}\right) \\ &= - \frac{d^2L^*(\psi)}{d\theta^2}\left(\frac{d\theta}{d\psi}\right)^2 - \frac{dL^*(\psi)}{d\theta}\frac{d^2\theta}{d\psi^2} \frac{d\theta}{d\psi}\, . \end{align} $$ Therefore, $$ \begin{align} I^*(g(\hat{\theta})) &= -\frac{d^2L^*(g(\hat{\theta}))}{d\theta^2}\left(\frac{d\theta}{d\psi}\right)^2 - \frac{dL^*(g(\hat{\theta}))}{d\theta}\frac{d^2\theta}{d\psi^2} \frac{d\theta}{d\psi} \\ &= -\frac{d^2L(g^{-1}(g(\hat{\theta})))}{d\theta^2} \left(\frac{dg(\theta)}{d\theta}\Bigg|_{\theta=g^{-1}(g(\hat{\theta}))}\right)^{-2} - \frac{dL(g^{-1}(g(\hat{\theta})))}{d\theta}\frac{d^2\theta}{d\psi^2} \frac{d\theta}{d\psi} \\ &= I(\hat{\theta}) \left(\frac{dg(\theta)}{d\theta}\Bigg|_{\theta=\hat{\theta}}\right)^{-2} \, , \end{align} $$ in which we used $dL(g^{-1}(g(\hat{\theta})))/d\theta=dL(\hat{\theta})/d\theta=0$.
Observed Fisher information under a transformation
The absolute value is unnecessary. It may be just a typo. You're right. An even better notation would be $\frac{dg(\theta)}{d\theta}\Bigg|_{\theta=\hat{\theta}}$. It doesn't hold in general. Fix som
Observed Fisher information under a transformation The absolute value is unnecessary. It may be just a typo. You're right. An even better notation would be $\frac{dg(\theta)}{d\theta}\Bigg|_{\theta=\hat{\theta}}$. It doesn't hold in general. Fix some $\psi_0$ and define $g:\mathbb{R}\to\mathbb{R}$ by $g(\theta)=\psi_0$. The rhs would be undefined since the derivative is zero for every $\theta$. A sketch of the regular case: For smooth one-to-one $g$ with $\psi=g(\theta)$. Since, $d/d\psi = d\theta/d\psi\cdot d/d\theta$, we have $$ \begin{align} I^*(\psi) &= -\frac{d^2L^*(\psi)}{d\psi^2} = -\frac{d}{d\psi}\left(\frac{dL^*(\psi)}{d\psi} \right) = -\frac{d}{d\psi}\left(\frac{dL^*(\psi)}{d\theta} \frac{d\theta}{d\psi}\right) \\ &= - \frac{d^2L^*(\psi)}{d\theta^2}\left(\frac{d\theta}{d\psi}\right)^2 - \frac{dL^*(\psi)}{d\theta}\frac{d^2\theta}{d\psi^2} \frac{d\theta}{d\psi}\, . \end{align} $$ Therefore, $$ \begin{align} I^*(g(\hat{\theta})) &= -\frac{d^2L^*(g(\hat{\theta}))}{d\theta^2}\left(\frac{d\theta}{d\psi}\right)^2 - \frac{dL^*(g(\hat{\theta}))}{d\theta}\frac{d^2\theta}{d\psi^2} \frac{d\theta}{d\psi} \\ &= -\frac{d^2L(g^{-1}(g(\hat{\theta})))}{d\theta^2} \left(\frac{dg(\theta)}{d\theta}\Bigg|_{\theta=g^{-1}(g(\hat{\theta}))}\right)^{-2} - \frac{dL(g^{-1}(g(\hat{\theta})))}{d\theta}\frac{d^2\theta}{d\psi^2} \frac{d\theta}{d\psi} \\ &= I(\hat{\theta}) \left(\frac{dg(\theta)}{d\theta}\Bigg|_{\theta=\hat{\theta}}\right)^{-2} \, , \end{align} $$ in which we used $dL(g^{-1}(g(\hat{\theta})))/d\theta=dL(\hat{\theta})/d\theta=0$.
Observed Fisher information under a transformation The absolute value is unnecessary. It may be just a typo. You're right. An even better notation would be $\frac{dg(\theta)}{d\theta}\Bigg|_{\theta=\hat{\theta}}$. It doesn't hold in general. Fix som
26,433
Using k-means with other metrics
It's not as if k-means will necessarily blow up and fail if you use a different metric. In many cases it will return some result. It is just not guaranteed that it finds the optimum centroids or partitions with other metrics, because the mean may not be suitable for minimizing distances. Consider Earth movers distance. Given the three vectors 3 0 0 0 0 0 0 3 0 0 0 0 0 0 3 The arithmetic mean is 1 0 1 0 1 which has EMD distances 6, 4, 6 (total 16). If the algorithm had instead used 0 0 3 0 0 the EMD distances would have been 6, 0, 6; i.e. better (total 12). The arithmetic mean does not minimize EMD, and the result of using k-means (with artihmetic mean) will not yield optimal representatives. Similar things will hold for edit distances.
Using k-means with other metrics
It's not as if k-means will necessarily blow up and fail if you use a different metric. In many cases it will return some result. It is just not guaranteed that it finds the optimum centroids or parti
Using k-means with other metrics It's not as if k-means will necessarily blow up and fail if you use a different metric. In many cases it will return some result. It is just not guaranteed that it finds the optimum centroids or partitions with other metrics, because the mean may not be suitable for minimizing distances. Consider Earth movers distance. Given the three vectors 3 0 0 0 0 0 0 3 0 0 0 0 0 0 3 The arithmetic mean is 1 0 1 0 1 which has EMD distances 6, 4, 6 (total 16). If the algorithm had instead used 0 0 3 0 0 the EMD distances would have been 6, 0, 6; i.e. better (total 12). The arithmetic mean does not minimize EMD, and the result of using k-means (with artihmetic mean) will not yield optimal representatives. Similar things will hold for edit distances.
Using k-means with other metrics It's not as if k-means will necessarily blow up and fail if you use a different metric. In many cases it will return some result. It is just not guaranteed that it finds the optimum centroids or parti
26,434
Using k-means with other metrics
K-means is appropriate to use in combination with the Euclidean distance because the main objective of k-means is to minimize the sum of within-cluster variances, and the within-cluster variance is calculated in exactly the same way as the sum of Euclidean distances between all points in the cluster to the cluster centroid. As other answers point out, the algorithm is only guaranteed to converge (even if to a local minimum) if both the centroid update step and the data points reassignment step are done in the same n-dimensional Euclidean space. Also, it has been shown (and I put a link here because I myself cannot explain this) that the mean is the best estimator to be used when one needs to minimize total variance. So k-means tie to the Euclidean distance is two-fold: the algorithm must have some way to calculate the mean of a set of data points (hence the name k-means), but this mean only makes sense and guarantees convergence of the clustering process if the Euclidean distance is used to reassign data points to the nearest centroids. You can still use k-means with other distance measures, as in this paper, in which the author uses the algorithm with the Minkowski distance, which is a generalization of the Manhattan, Euclidean and Chebyshev distances. However, in these cases, convergence is not guaranteed and, as a consequence, you might expect that future iterations of the algorithm will actually have greater total variance than previous iterations. Even so, as shown in the paper above, even without the guarantee of convergence, k-means can achieve better clustering results in some scenarios by using other distance measures. If you take the $L^p$ norms, for example, and knowing that the Euclidean distance is the $L^2$ norm and that the Manhattan distance is the $L^1$ norm, it has been shown that, for sparse distance matrices, k-means used in conjunction with an $L^p$ norm with $0 < p \leq 1$ achieves greater clustering accuracy than when using the Euclidean distance. Lastly, I think it is interesting to point out that there are some similarity measures that can in some way be converted to the Euclidean distance, in such a way that if you use said similarity measure in conjunction with k-means, you ought to get similar results. An example of that is the cosine similarity.
Using k-means with other metrics
K-means is appropriate to use in combination with the Euclidean distance because the main objective of k-means is to minimize the sum of within-cluster variances, and the within-cluster variance is ca
Using k-means with other metrics K-means is appropriate to use in combination with the Euclidean distance because the main objective of k-means is to minimize the sum of within-cluster variances, and the within-cluster variance is calculated in exactly the same way as the sum of Euclidean distances between all points in the cluster to the cluster centroid. As other answers point out, the algorithm is only guaranteed to converge (even if to a local minimum) if both the centroid update step and the data points reassignment step are done in the same n-dimensional Euclidean space. Also, it has been shown (and I put a link here because I myself cannot explain this) that the mean is the best estimator to be used when one needs to minimize total variance. So k-means tie to the Euclidean distance is two-fold: the algorithm must have some way to calculate the mean of a set of data points (hence the name k-means), but this mean only makes sense and guarantees convergence of the clustering process if the Euclidean distance is used to reassign data points to the nearest centroids. You can still use k-means with other distance measures, as in this paper, in which the author uses the algorithm with the Minkowski distance, which is a generalization of the Manhattan, Euclidean and Chebyshev distances. However, in these cases, convergence is not guaranteed and, as a consequence, you might expect that future iterations of the algorithm will actually have greater total variance than previous iterations. Even so, as shown in the paper above, even without the guarantee of convergence, k-means can achieve better clustering results in some scenarios by using other distance measures. If you take the $L^p$ norms, for example, and knowing that the Euclidean distance is the $L^2$ norm and that the Manhattan distance is the $L^1$ norm, it has been shown that, for sparse distance matrices, k-means used in conjunction with an $L^p$ norm with $0 < p \leq 1$ achieves greater clustering accuracy than when using the Euclidean distance. Lastly, I think it is interesting to point out that there are some similarity measures that can in some way be converted to the Euclidean distance, in such a way that if you use said similarity measure in conjunction with k-means, you ought to get similar results. An example of that is the cosine similarity.
Using k-means with other metrics K-means is appropriate to use in combination with the Euclidean distance because the main objective of k-means is to minimize the sum of within-cluster variances, and the within-cluster variance is ca
26,435
Using k-means with other metrics
I don't know if this is what the linked papers are doing, but it is possible to do k-means with non-Euclidean distance functions using the kernel trick. That is, we implicitly map the inputs to a high-dimensional (often infinite-dimensional) space where Euclidean distances correspond to the distance function we want to use, and run the algorithm there. For Lloyd's k-means algorithm in particular, we can assign points to their clusters easily, but we represent the cluster centers implicitly and finding their representation in the input space would require finding a Fréchet mean. The following paper discusses the algorithm and relates it to spectral clustering: I. Dhillon, Y. Guan, and B. Kulis. Kernel k-means, Spectral Clustering and Normalized Cuts. KDD 2005. There are kernels based on the edit distance and based on the earth mover's distance.
Using k-means with other metrics
I don't know if this is what the linked papers are doing, but it is possible to do k-means with non-Euclidean distance functions using the kernel trick. That is, we implicitly map the inputs to a high
Using k-means with other metrics I don't know if this is what the linked papers are doing, but it is possible to do k-means with non-Euclidean distance functions using the kernel trick. That is, we implicitly map the inputs to a high-dimensional (often infinite-dimensional) space where Euclidean distances correspond to the distance function we want to use, and run the algorithm there. For Lloyd's k-means algorithm in particular, we can assign points to their clusters easily, but we represent the cluster centers implicitly and finding their representation in the input space would require finding a Fréchet mean. The following paper discusses the algorithm and relates it to spectral clustering: I. Dhillon, Y. Guan, and B. Kulis. Kernel k-means, Spectral Clustering and Normalized Cuts. KDD 2005. There are kernels based on the edit distance and based on the earth mover's distance.
Using k-means with other metrics I don't know if this is what the linked papers are doing, but it is possible to do k-means with non-Euclidean distance functions using the kernel trick. That is, we implicitly map the inputs to a high
26,436
What are the properties for independence
covariance=0 implies correlation=0 (as long as the variances aren't 0). correlation (or covariance 0) is necessary but not sufficient for independence. Independence implies both correlation and covariance are 0, but both can be 0 with perfectly dependent data. See here: If the variables are independent, Pearson's correlation coefficient is 0, but the converse is not true because the correlation coefficient detects only linear dependencies between two variables. For example, suppose the random variable X is symmetrically distributed about zero, and $Y = X^2$. Then Y is completely determined by X, so that X and Y are perfectly dependent, but their correlation is zero As Dilip says, we need $E[|X^3|]$ to be finite for the specific example here; there will be similar criteria in other cases. For example, if $Y=f(X)$ for some even $f$, we'd need $E[|X.f(X)|]$ to be finite for the symmetry to make the covariance 0. As it says here: I(X; Y) = 0 if and only if X and Y are independent random variables. That is, mutual information 0 implies independence (and vice versa).
What are the properties for independence
covariance=0 implies correlation=0 (as long as the variances aren't 0). correlation (or covariance 0) is necessary but not sufficient for independence. Independence implies both correlation and covar
What are the properties for independence covariance=0 implies correlation=0 (as long as the variances aren't 0). correlation (or covariance 0) is necessary but not sufficient for independence. Independence implies both correlation and covariance are 0, but both can be 0 with perfectly dependent data. See here: If the variables are independent, Pearson's correlation coefficient is 0, but the converse is not true because the correlation coefficient detects only linear dependencies between two variables. For example, suppose the random variable X is symmetrically distributed about zero, and $Y = X^2$. Then Y is completely determined by X, so that X and Y are perfectly dependent, but their correlation is zero As Dilip says, we need $E[|X^3|]$ to be finite for the specific example here; there will be similar criteria in other cases. For example, if $Y=f(X)$ for some even $f$, we'd need $E[|X.f(X)|]$ to be finite for the symmetry to make the covariance 0. As it says here: I(X; Y) = 0 if and only if X and Y are independent random variables. That is, mutual information 0 implies independence (and vice versa).
What are the properties for independence covariance=0 implies correlation=0 (as long as the variances aren't 0). correlation (or covariance 0) is necessary but not sufficient for independence. Independence implies both correlation and covar
26,437
What are the properties for independence
Two variables are considered independent if they are orthogonal to each other. Which means that their dot product is equal to 0. $\mathbf{a}\cdot \mathbf{b} = \sum_{i=1}^n a_ib_i = a_1b_1 + a_2b_2 + \cdots + a_nb_n = 0$ In other words one variable doesn't contain any information on the second variable. Different conditions for independence come from different scientific fields like linear algebra or probability theory, but the underlying concept is always the same.
What are the properties for independence
Two variables are considered independent if they are orthogonal to each other. Which means that their dot product is equal to 0. $\mathbf{a}\cdot \mathbf{b} = \sum_{i=1}^n a_ib_i = a_1b_1 + a_2b_2 + \
What are the properties for independence Two variables are considered independent if they are orthogonal to each other. Which means that their dot product is equal to 0. $\mathbf{a}\cdot \mathbf{b} = \sum_{i=1}^n a_ib_i = a_1b_1 + a_2b_2 + \cdots + a_nb_n = 0$ In other words one variable doesn't contain any information on the second variable. Different conditions for independence come from different scientific fields like linear algebra or probability theory, but the underlying concept is always the same.
What are the properties for independence Two variables are considered independent if they are orthogonal to each other. Which means that their dot product is equal to 0. $\mathbf{a}\cdot \mathbf{b} = \sum_{i=1}^n a_ib_i = a_1b_1 + a_2b_2 + \
26,438
Oversampling with categorical variables
ROSE and SMOTE are designed to handle categorical variables, so, unless your categorical variables are expressed in a binary format, you shouldn't normally have to worry about synthetic observations being assigned mutually exclusive categorical features. If they are, you can always restructure them as factors. In your two-region example, you would create a new region variable with two levels, "A" and "B". Your records would take the appropriate values by referencing your original columns. Now, if you are in a situation where your new synthetic observations could generate conflicting categories because they are spread across multiple, otherwise unrelated variables (e.g. syntheticObservation.isPig = 1 and syntheticObservation.hasWings = 1), you could always perform some additional data munging before doing your model estimation in order to clean such aberrations. Also, since you do have about 600 event observations in your dataset, maybe consider the potential benefits of using synthetic observations derived through undersampling the majority class?
Oversampling with categorical variables
ROSE and SMOTE are designed to handle categorical variables, so, unless your categorical variables are expressed in a binary format, you shouldn't normally have to worry about synthetic observations b
Oversampling with categorical variables ROSE and SMOTE are designed to handle categorical variables, so, unless your categorical variables are expressed in a binary format, you shouldn't normally have to worry about synthetic observations being assigned mutually exclusive categorical features. If they are, you can always restructure them as factors. In your two-region example, you would create a new region variable with two levels, "A" and "B". Your records would take the appropriate values by referencing your original columns. Now, if you are in a situation where your new synthetic observations could generate conflicting categories because they are spread across multiple, otherwise unrelated variables (e.g. syntheticObservation.isPig = 1 and syntheticObservation.hasWings = 1), you could always perform some additional data munging before doing your model estimation in order to clean such aberrations. Also, since you do have about 600 event observations in your dataset, maybe consider the potential benefits of using synthetic observations derived through undersampling the majority class?
Oversampling with categorical variables ROSE and SMOTE are designed to handle categorical variables, so, unless your categorical variables are expressed in a binary format, you shouldn't normally have to worry about synthetic observations b
26,439
correlation of bootstrap sample means
I used to think the answer should be 0, but I see what I did wrong before. The problem is not looking for the conditioned correlation, so without loss of generality, we can look at the case where $\mu=0,\sigma^2=1$: Let $x_i^{(k)}$ be sample $i$ from the $k$th bootstrap. Then $\bar{x}_k^* = \frac{1}{n} \sum_{i}{x_i^{(k)}}$. Key values we need to compute are: $E\ x_i^{(k)}=E(E[x_i^{(k)}|\mathbf{x}])=E \bar{x}=0$ $var(x_i^{(k)})=E(var(x_i^{(k)}|\mathbf{x}))+var(E[x_i^{(k)}|\mathbf{x}])=\frac{n-1}{n}+\frac{1}{n}=1$ $cov(x_i^{(1)},x_j^{(2)})=E(x_i^{(1)}-0)(x_j^{(2)}-0)=E(E[x_i^{(1)}x_j^{(2)}|\mathbf{x}])=E\bar{x}^2=\frac{1}{n}$ (same is true for $(x_i^{(k)},x_j^{(k)}) \, i\neq j$) With above, calculation for the following should be easy: $cov(\bar{x}_1^*,\bar{x}_2^*)=\frac{1}{n^2} (\sum_{i,j}{cov(x_i^{(1)},x_j^{(2)})})=\frac{1}{n}$ $var(\bar{x}^*_i)=\frac{1}{n^2}\left(n*var(x_1^{(1)})+n(n-1)*cov(x_1^{(1)},x_2^{(1)}) \right)\\ \quad \quad \ \ = \frac{2n-1}{n^2}$ $\rightarrow corr(\bar{x}_1^*,\bar{x}_2^*)=\frac{n}{2n-1}$
correlation of bootstrap sample means
I used to think the answer should be 0, but I see what I did wrong before. The problem is not looking for the conditioned correlation, so without loss of generality, we can look at the case where $\mu
correlation of bootstrap sample means I used to think the answer should be 0, but I see what I did wrong before. The problem is not looking for the conditioned correlation, so without loss of generality, we can look at the case where $\mu=0,\sigma^2=1$: Let $x_i^{(k)}$ be sample $i$ from the $k$th bootstrap. Then $\bar{x}_k^* = \frac{1}{n} \sum_{i}{x_i^{(k)}}$. Key values we need to compute are: $E\ x_i^{(k)}=E(E[x_i^{(k)}|\mathbf{x}])=E \bar{x}=0$ $var(x_i^{(k)})=E(var(x_i^{(k)}|\mathbf{x}))+var(E[x_i^{(k)}|\mathbf{x}])=\frac{n-1}{n}+\frac{1}{n}=1$ $cov(x_i^{(1)},x_j^{(2)})=E(x_i^{(1)}-0)(x_j^{(2)}-0)=E(E[x_i^{(1)}x_j^{(2)}|\mathbf{x}])=E\bar{x}^2=\frac{1}{n}$ (same is true for $(x_i^{(k)},x_j^{(k)}) \, i\neq j$) With above, calculation for the following should be easy: $cov(\bar{x}_1^*,\bar{x}_2^*)=\frac{1}{n^2} (\sum_{i,j}{cov(x_i^{(1)},x_j^{(2)})})=\frac{1}{n}$ $var(\bar{x}^*_i)=\frac{1}{n^2}\left(n*var(x_1^{(1)})+n(n-1)*cov(x_1^{(1)},x_2^{(1)}) \right)\\ \quad \quad \ \ = \frac{2n-1}{n^2}$ $\rightarrow corr(\bar{x}_1^*,\bar{x}_2^*)=\frac{n}{2n-1}$
correlation of bootstrap sample means I used to think the answer should be 0, but I see what I did wrong before. The problem is not looking for the conditioned correlation, so without loss of generality, we can look at the case where $\mu
26,440
How to interpret dendrogram height for clustering by correlation
Recall that in hierarchical clustering, you must define a distance metric between clusters. For example, in hierarchical average linkage clustering (probably the most popular option), the distance between clusters is define as the average distance between all inter-cluster pairs. The distance between pairs must also be defined and could be, for example, euclidean distance (or correlation distance in your case). So the distance between clusters is a way of generalizing the distance between pairs. In the dendrogram, the y-axis is simply the value of this distance metric between clusters. For example, if you see two clusters merged at a height $x$, it means that the distance between those clusters was $x$.
How to interpret dendrogram height for clustering by correlation
Recall that in hierarchical clustering, you must define a distance metric between clusters. For example, in hierarchical average linkage clustering (probably the most popular option), the distance bet
How to interpret dendrogram height for clustering by correlation Recall that in hierarchical clustering, you must define a distance metric between clusters. For example, in hierarchical average linkage clustering (probably the most popular option), the distance between clusters is define as the average distance between all inter-cluster pairs. The distance between pairs must also be defined and could be, for example, euclidean distance (or correlation distance in your case). So the distance between clusters is a way of generalizing the distance between pairs. In the dendrogram, the y-axis is simply the value of this distance metric between clusters. For example, if you see two clusters merged at a height $x$, it means that the distance between those clusters was $x$.
How to interpret dendrogram height for clustering by correlation Recall that in hierarchical clustering, you must define a distance metric between clusters. For example, in hierarchical average linkage clustering (probably the most popular option), the distance bet
26,441
Parameter estimates for skew normal distribution
Indeed, the "skew-normal family" has exploded in membership (the wikipedia article does not attest to this). So, let's consider the mother of them all, that has probability density function $$f_X(x) = \frac{2}{\omega}\phi\left(\frac{x-\xi}{\omega}\right)\Phi\left(\alpha \left(\frac{x-\xi}{\omega}\right)\right)$$ where $\phi()$ is the standard normal pdf and $\Phi()$ the standard normal cdf. $\xi$ is the location parameter, $\omega$ is the scale parameter, and $\alpha$ is the skew parameter. Closed-form solutions for the ML estimator do not exist. Method-of-Moments estimator provides closed forms as follows, assuming that all three parameters are non-zero (obviously if $\omega$ and/or $\xi$ are zero, then the steps below are simplified): 1) Obtain a MoM estimate $\hat \delta$ by solving for $\delta$ the expression for the skewness of the distribution, $$\gamma_3 = \frac{4 - \pi}{2} \frac{\left(\delta \sqrt{2/\pi} \right)^3}{\left(1 - 2\delta^2/\pi\right)^{3/2}}$$ using the estimated sample skewness coefficient $\hat \gamma_3$. 2) Obtain an estimate $\hat \alpha$ using $$\delta = \frac {\alpha}{\sqrt {(1+\alpha^2)}} \implies \hat \alpha = \frac {\hat \delta}{\sqrt{1-\hat \delta^2}}$$ 3) Obtain a MoM estimate $\hat \omega$ by solving for $\omega$ the expression for the variance, $$\hat \sigma^2_x = \omega^2\cdot \left(1-\frac{2\hat \delta^2}{\pi}\right)$$ using the sample variance and the estimated $\delta$ derived in the previous step 4) Obtain a MoM estimate $\hat \xi$ by solving for $\xi$ the expression for the mean of the distribution, $$\hat \mu_x = \xi + \hat \omega \hat \delta\sqrt {2/\pi}$$ using the sample mean and the previous estimates. And don't forget to propagate estimation error in this sequential procedure, as regards the estimator variance.
Parameter estimates for skew normal distribution
Indeed, the "skew-normal family" has exploded in membership (the wikipedia article does not attest to this). So, let's consider the mother of them all, that has probability density function $$f_X(x) =
Parameter estimates for skew normal distribution Indeed, the "skew-normal family" has exploded in membership (the wikipedia article does not attest to this). So, let's consider the mother of them all, that has probability density function $$f_X(x) = \frac{2}{\omega}\phi\left(\frac{x-\xi}{\omega}\right)\Phi\left(\alpha \left(\frac{x-\xi}{\omega}\right)\right)$$ where $\phi()$ is the standard normal pdf and $\Phi()$ the standard normal cdf. $\xi$ is the location parameter, $\omega$ is the scale parameter, and $\alpha$ is the skew parameter. Closed-form solutions for the ML estimator do not exist. Method-of-Moments estimator provides closed forms as follows, assuming that all three parameters are non-zero (obviously if $\omega$ and/or $\xi$ are zero, then the steps below are simplified): 1) Obtain a MoM estimate $\hat \delta$ by solving for $\delta$ the expression for the skewness of the distribution, $$\gamma_3 = \frac{4 - \pi}{2} \frac{\left(\delta \sqrt{2/\pi} \right)^3}{\left(1 - 2\delta^2/\pi\right)^{3/2}}$$ using the estimated sample skewness coefficient $\hat \gamma_3$. 2) Obtain an estimate $\hat \alpha$ using $$\delta = \frac {\alpha}{\sqrt {(1+\alpha^2)}} \implies \hat \alpha = \frac {\hat \delta}{\sqrt{1-\hat \delta^2}}$$ 3) Obtain a MoM estimate $\hat \omega$ by solving for $\omega$ the expression for the variance, $$\hat \sigma^2_x = \omega^2\cdot \left(1-\frac{2\hat \delta^2}{\pi}\right)$$ using the sample variance and the estimated $\delta$ derived in the previous step 4) Obtain a MoM estimate $\hat \xi$ by solving for $\xi$ the expression for the mean of the distribution, $$\hat \mu_x = \xi + \hat \omega \hat \delta\sqrt {2/\pi}$$ using the sample mean and the previous estimates. And don't forget to propagate estimation error in this sequential procedure, as regards the estimator variance.
Parameter estimates for skew normal distribution Indeed, the "skew-normal family" has exploded in membership (the wikipedia article does not attest to this). So, let's consider the mother of them all, that has probability density function $$f_X(x) =
26,442
Is there a reason to leave an exploratory factor analysis solution unrotated?
Yes, there may be a reason to withdraw from rotation in factor analysis. That reason is actually similar to why we usually do not rotate principal components in PCA (i.e. when we use it primarily for dimensionality reduction and not to model latent traits). After extraction, factors (or components) are orthogonal$^1$ and are usually output in descending order of their variances (column sum-of-squares of the loadings). The 1st factor thus dominates. Junior factors statistically explain what the 1st one leaves unexplained. Often that factor loads quite highly on all the variables, and that means that it is responsible for the background correlatedness among the variables. Such 1st factor is sometimes called general factor or g-factor. It is considered responsible for the fact that positive correlations prevail in psychometrics. If you are interested in exploring that factor rather than disregard it and let it dissolve behind the simple structure, don't rotate the extracted factors. You may even partial out the effect of general factor from the correlations and proceed to factor-analyze the residual correlations. $^1$ The difference between extraction factor/component solution, on one hand, and that solution after its rotation (orthogonal or oblique), on the other hand, is that - the extracted loading matrix $\bf A$ has orthogonal (or nearly orthogonal, for some methods of extraction) columns: $\bf A'A$ is diagonal; in other words, the loadings reside in the "principle axis structure". After rotation - even a rotation preserving orthogonality of factors/components, such as varimax - the orthogonality of loadings is lost: "principle axis structure" is abandoned for "simple structure". Principal axis structure allows to sort out among the factors/components as "more principal" or "less principal" (and the 1st column of $\bf A$ being the most general component of all), while in simple structure equal importance of all the rotated factors/components is assumed - logically speaking, you cannot select them after the rotation: accept all of them (Pt 2 here). See picture here displaying loadings before rotation and after varimax rotation.
Is there a reason to leave an exploratory factor analysis solution unrotated?
Yes, there may be a reason to withdraw from rotation in factor analysis. That reason is actually similar to why we usually do not rotate principal components in PCA (i.e. when we use it primarily for
Is there a reason to leave an exploratory factor analysis solution unrotated? Yes, there may be a reason to withdraw from rotation in factor analysis. That reason is actually similar to why we usually do not rotate principal components in PCA (i.e. when we use it primarily for dimensionality reduction and not to model latent traits). After extraction, factors (or components) are orthogonal$^1$ and are usually output in descending order of their variances (column sum-of-squares of the loadings). The 1st factor thus dominates. Junior factors statistically explain what the 1st one leaves unexplained. Often that factor loads quite highly on all the variables, and that means that it is responsible for the background correlatedness among the variables. Such 1st factor is sometimes called general factor or g-factor. It is considered responsible for the fact that positive correlations prevail in psychometrics. If you are interested in exploring that factor rather than disregard it and let it dissolve behind the simple structure, don't rotate the extracted factors. You may even partial out the effect of general factor from the correlations and proceed to factor-analyze the residual correlations. $^1$ The difference between extraction factor/component solution, on one hand, and that solution after its rotation (orthogonal or oblique), on the other hand, is that - the extracted loading matrix $\bf A$ has orthogonal (or nearly orthogonal, for some methods of extraction) columns: $\bf A'A$ is diagonal; in other words, the loadings reside in the "principle axis structure". After rotation - even a rotation preserving orthogonality of factors/components, such as varimax - the orthogonality of loadings is lost: "principle axis structure" is abandoned for "simple structure". Principal axis structure allows to sort out among the factors/components as "more principal" or "less principal" (and the 1st column of $\bf A$ being the most general component of all), while in simple structure equal importance of all the rotated factors/components is assumed - logically speaking, you cannot select them after the rotation: accept all of them (Pt 2 here). See picture here displaying loadings before rotation and after varimax rotation.
Is there a reason to leave an exploratory factor analysis solution unrotated? Yes, there may be a reason to withdraw from rotation in factor analysis. That reason is actually similar to why we usually do not rotate principal components in PCA (i.e. when we use it primarily for
26,443
Is there a reason to leave an exploratory factor analysis solution unrotated?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. I think this might help you: https://www.utdallas.edu/~herve/Abdi-rotations-pretty.pdf Regards,
Is there a reason to leave an exploratory factor analysis solution unrotated?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Is there a reason to leave an exploratory factor analysis solution unrotated? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. I think this might help you: https://www.utdallas.edu/~herve/Abdi-rotations-pretty.pdf Regards,
Is there a reason to leave an exploratory factor analysis solution unrotated? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
26,444
Lasso on Negative Binomial Regression Model
LASSO and other penalized methods for negative binomial and zero-inflated negative binomial are provided by the mpath package in R, as has been noted on a more recent Cross Validated page. One answer on that page, however, indicates some difficulty in using mpath. A recent publication illustrates an application of the mpath package; a vignette in the R package reproduces the data analysis of that publication.
Lasso on Negative Binomial Regression Model
LASSO and other penalized methods for negative binomial and zero-inflated negative binomial are provided by the mpath package in R, as has been noted on a more recent Cross Validated page. One answer
Lasso on Negative Binomial Regression Model LASSO and other penalized methods for negative binomial and zero-inflated negative binomial are provided by the mpath package in R, as has been noted on a more recent Cross Validated page. One answer on that page, however, indicates some difficulty in using mpath. A recent publication illustrates an application of the mpath package; a vignette in the R package reproduces the data analysis of that publication.
Lasso on Negative Binomial Regression Model LASSO and other penalized methods for negative binomial and zero-inflated negative binomial are provided by the mpath package in R, as has been noted on a more recent Cross Validated page. One answer
26,445
How to project high dimensional space into a two-dimensional plane?
A general framework which addresses your problem is called dimensionality reduction. You would like to project data from N dimensions to 2 dimensions, while preserving the "essential information" in your data. The most suitable method depends on the distribution of your data, i.e. the N-dimensional manifold. PCA will fit a plane using least squares criterion. This will probably work poorly for the "swiss roll" example: swiss roll. More modern methods include Kernel PCA, LLE, diffusion maps and sparse dictionary representations. Regarding distance preservation, some methods can preserve non-euclidean distances.
How to project high dimensional space into a two-dimensional plane?
A general framework which addresses your problem is called dimensionality reduction. You would like to project data from N dimensions to 2 dimensions, while preserving the "essential information" in y
How to project high dimensional space into a two-dimensional plane? A general framework which addresses your problem is called dimensionality reduction. You would like to project data from N dimensions to 2 dimensions, while preserving the "essential information" in your data. The most suitable method depends on the distribution of your data, i.e. the N-dimensional manifold. PCA will fit a plane using least squares criterion. This will probably work poorly for the "swiss roll" example: swiss roll. More modern methods include Kernel PCA, LLE, diffusion maps and sparse dictionary representations. Regarding distance preservation, some methods can preserve non-euclidean distances.
How to project high dimensional space into a two-dimensional plane? A general framework which addresses your problem is called dimensionality reduction. You would like to project data from N dimensions to 2 dimensions, while preserving the "essential information" in y
26,446
How to project high dimensional space into a two-dimensional plane?
As mentioned in the previous answer, there are a number of methods of dimensionality reduction, and an important thing to consider is what are you trying to represent - are you interested in Euclidean distance measures? Or a metric of similarity across samples? For the former, PCA can be appropriate. It is commonly used with continuous measures such as measurements of samples (animals, plants, etc...). I would look into the more modern mentions in the earlier answer too though. For the latter, where you might be trying to compare similarity using a non-euclidean distance metric, a few good methods exist such as Principle Components Ordination (PCoA) and Non-metric Multidimensional Scaling (NMDS). An example of when you might use these is when you are comparing the ecological communities among different areas, and you have numbers of different types of organisms that were found. So, your data are "count" data. There are a number of similarity metrics such as Jaccard, Sorensen, Bray-Curtis, that effectively let you estimate how similar the sites are in their composition of organisms. PCoA and NMDS basically let you to plot the samples (sites) to represent the ecological distance (similarity), and you have a score for site on each axis. There are lots of good books and other resources for multivariate analysis. Search for "Ordination" on Google. Also, there's an R package called 'vegan' that is really good for actually carrying out a lot of this work.
How to project high dimensional space into a two-dimensional plane?
As mentioned in the previous answer, there are a number of methods of dimensionality reduction, and an important thing to consider is what are you trying to represent - are you interested in Euclidean
How to project high dimensional space into a two-dimensional plane? As mentioned in the previous answer, there are a number of methods of dimensionality reduction, and an important thing to consider is what are you trying to represent - are you interested in Euclidean distance measures? Or a metric of similarity across samples? For the former, PCA can be appropriate. It is commonly used with continuous measures such as measurements of samples (animals, plants, etc...). I would look into the more modern mentions in the earlier answer too though. For the latter, where you might be trying to compare similarity using a non-euclidean distance metric, a few good methods exist such as Principle Components Ordination (PCoA) and Non-metric Multidimensional Scaling (NMDS). An example of when you might use these is when you are comparing the ecological communities among different areas, and you have numbers of different types of organisms that were found. So, your data are "count" data. There are a number of similarity metrics such as Jaccard, Sorensen, Bray-Curtis, that effectively let you estimate how similar the sites are in their composition of organisms. PCoA and NMDS basically let you to plot the samples (sites) to represent the ecological distance (similarity), and you have a score for site on each axis. There are lots of good books and other resources for multivariate analysis. Search for "Ordination" on Google. Also, there's an R package called 'vegan' that is really good for actually carrying out a lot of this work.
How to project high dimensional space into a two-dimensional plane? As mentioned in the previous answer, there are a number of methods of dimensionality reduction, and an important thing to consider is what are you trying to represent - are you interested in Euclidean
26,447
How to project high dimensional space into a two-dimensional plane?
Your problem sounds like a text-book application for multidimensional scaling. A good introduction can be found here: http://www.mathpsyc.uni-bonn.de/doc/delbeke/delbeke.htm Of course you can try PCA. But PCA has no intention to keep the relative distance information in the original space.
How to project high dimensional space into a two-dimensional plane?
Your problem sounds like a text-book application for multidimensional scaling. A good introduction can be found here: http://www.mathpsyc.uni-bonn.de/doc/delbeke/delbeke.htm Of course you can try PCA.
How to project high dimensional space into a two-dimensional plane? Your problem sounds like a text-book application for multidimensional scaling. A good introduction can be found here: http://www.mathpsyc.uni-bonn.de/doc/delbeke/delbeke.htm Of course you can try PCA. But PCA has no intention to keep the relative distance information in the original space.
How to project high dimensional space into a two-dimensional plane? Your problem sounds like a text-book application for multidimensional scaling. A good introduction can be found here: http://www.mathpsyc.uni-bonn.de/doc/delbeke/delbeke.htm Of course you can try PCA.
26,448
Two-sample $t$-test vs Tukey's method
It's simply that if (under the null hypothesis of no effects) there's a 5% chance, say, of a false positive in each one of 20 tests, say; there's a greater than 5% chance of a false positive in any one of those 20 tests. If the tests are independent, the change of getting a false positive in none is $95\%^{20}=35.8\%$, and so the chance of a false positive in at least one is $64.2\%$—this is the family-wise error that multiple comparisons tests control. Of course pairwise comparisons of all means after ANOVA are not independent, and Tukey's test takes this into account.
Two-sample $t$-test vs Tukey's method
It's simply that if (under the null hypothesis of no effects) there's a 5% chance, say, of a false positive in each one of 20 tests, say; there's a greater than 5% chance of a false positive in any on
Two-sample $t$-test vs Tukey's method It's simply that if (under the null hypothesis of no effects) there's a 5% chance, say, of a false positive in each one of 20 tests, say; there's a greater than 5% chance of a false positive in any one of those 20 tests. If the tests are independent, the change of getting a false positive in none is $95\%^{20}=35.8\%$, and so the chance of a false positive in at least one is $64.2\%$—this is the family-wise error that multiple comparisons tests control. Of course pairwise comparisons of all means after ANOVA are not independent, and Tukey's test takes this into account.
Two-sample $t$-test vs Tukey's method It's simply that if (under the null hypothesis of no effects) there's a 5% chance, say, of a false positive in each one of 20 tests, say; there's a greater than 5% chance of a false positive in any on
26,449
Neg Binomial and the Jeffreys' Prior
The problem arises because the negative binomial distribution can be formulated differently. As a consequence, the expectation differs for different formulations. The way you have specified the negative binomial distribution, the expectation of $n$ is $E(n) = m/\theta$ (e.g. see here on page 3). With that, the Fisher information simplifies to $$I(\theta) = m\left(\frac{1}{\theta^2(1-\theta)}\right)$$ Thus the Jeffreys' prior is $$ \pi_{J}(\theta) = |I(\theta)|^{1/2}\propto \theta^{-1}(1-\theta)^{-1/2} $$ as you already noted.
Neg Binomial and the Jeffreys' Prior
The problem arises because the negative binomial distribution can be formulated differently. As a consequence, the expectation differs for different formulations. The way you have specified the negati
Neg Binomial and the Jeffreys' Prior The problem arises because the negative binomial distribution can be formulated differently. As a consequence, the expectation differs for different formulations. The way you have specified the negative binomial distribution, the expectation of $n$ is $E(n) = m/\theta$ (e.g. see here on page 3). With that, the Fisher information simplifies to $$I(\theta) = m\left(\frac{1}{\theta^2(1-\theta)}\right)$$ Thus the Jeffreys' prior is $$ \pi_{J}(\theta) = |I(\theta)|^{1/2}\propto \theta^{-1}(1-\theta)^{-1/2} $$ as you already noted.
Neg Binomial and the Jeffreys' Prior The problem arises because the negative binomial distribution can be formulated differently. As a consequence, the expectation differs for different formulations. The way you have specified the negati
26,450
Is there overfitting in this modellng approach
Imagine instead of just selecting GBM vs RF, you instead were choosing among 100 different GBM classifiers (assuming GBM training uses some kind of randomness, and you assign them random seeds 1 to 100). Then you'd pick one of those 100 GBMs as the best GBM. But it's almost certainly the case that the one of 100 models that you picked got lucky to beat its 99 siblings, and so your performance estimate will be optimistic. You only used two learners, and they weren't trained by an identical algorithm, so your single GBM probably didn't have much selection pressure on it (especially if it dramatically outperformed the RF), but your error estimate is still going to be a little bit optimistic.
Is there overfitting in this modellng approach
Imagine instead of just selecting GBM vs RF, you instead were choosing among 100 different GBM classifiers (assuming GBM training uses some kind of randomness, and you assign them random seeds 1 to 10
Is there overfitting in this modellng approach Imagine instead of just selecting GBM vs RF, you instead were choosing among 100 different GBM classifiers (assuming GBM training uses some kind of randomness, and you assign them random seeds 1 to 100). Then you'd pick one of those 100 GBMs as the best GBM. But it's almost certainly the case that the one of 100 models that you picked got lucky to beat its 99 siblings, and so your performance estimate will be optimistic. You only used two learners, and they weren't trained by an identical algorithm, so your single GBM probably didn't have much selection pressure on it (especially if it dramatically outperformed the RF), but your error estimate is still going to be a little bit optimistic.
Is there overfitting in this modellng approach Imagine instead of just selecting GBM vs RF, you instead were choosing among 100 different GBM classifiers (assuming GBM training uses some kind of randomness, and you assign them random seeds 1 to 10
26,451
Is there overfitting in this modellng approach
It sounds like you've tried mixing two techniques, each of which is legitimate, but the way you've done it feels like you'll end up with data leaking between cases. At the lower level, you seem to be using CV correctly. Which would suggest that the top level should also be a CV, resulting in a nested CV, but your top level isn't CV. At the top level, it sounds like you might've wanted to do a bootstrap validation, in which case a double-bootstrap would work for the top and lower levels, but your top level's not a proper bootstrap. You might want to look at this stackexchange article. and the articles it links to, and perhaps restructure your top level to be a CV. Also, note that none other than Frank Harrell posts in that thread and suggests that CV be repeated a boatload of times. (I was shocked, thinking one repetition should do it.)
Is there overfitting in this modellng approach
It sounds like you've tried mixing two techniques, each of which is legitimate, but the way you've done it feels like you'll end up with data leaking between cases. At the lower level, you seem to be
Is there overfitting in this modellng approach It sounds like you've tried mixing two techniques, each of which is legitimate, but the way you've done it feels like you'll end up with data leaking between cases. At the lower level, you seem to be using CV correctly. Which would suggest that the top level should also be a CV, resulting in a nested CV, but your top level isn't CV. At the top level, it sounds like you might've wanted to do a bootstrap validation, in which case a double-bootstrap would work for the top and lower levels, but your top level's not a proper bootstrap. You might want to look at this stackexchange article. and the articles it links to, and perhaps restructure your top level to be a CV. Also, note that none other than Frank Harrell posts in that thread and suggests that CV be repeated a boatload of times. (I was shocked, thinking one repetition should do it.)
Is there overfitting in this modellng approach It sounds like you've tried mixing two techniques, each of which is legitimate, but the way you've done it feels like you'll end up with data leaking between cases. At the lower level, you seem to be
26,452
Histogram with uniform vs non-uniform Bins
When is a uniform-bin histogram better than a non-uniform bin one? This requires some kind of identification of what we'd seek to optimize; many people try to optimize average integrated mean square error, but in many cases I think that somewhat misses the point of doing a histogram; it often (to my eye) 'oversmooths'; for an exploratory tool like a histogram I can tolerate a good deal more roughness, since the roughness itself gives me a sense of the extent to which I should "smooth" by eye; I tend to at least double the usual number of bins from such rules, sometimes a good deal more. I tend to agree with Andrew Gelman on this; indeed if my interest was really getting a good AIMSE, I probably shouldn't be considering a histogram anyway. So we need a criterion. Let me start by discussing some of the options of non-equal area histograms: There are some approaches that do more smoothing (fewer, wider bins) in areas of lower density and have narrower bins where the density is higher - such as "equal-area" or "equal count" histograms. Your edited question seems to consider the equal count possibility. The histogram function in R's lattice package can produce approximately equal-area bars: library("lattice") histogram(islands^(1/3)) # equal width histogram(islands^(1/3),breaks=NULL,equal.widths=FALSE) # approx. equal area That dip just to the right of the leftmost bin is even clearer if you take fourth roots; with equal-width bins you can't see it unless you use 15 to 20 times as many bins, and then the right tail looks terrible. There's an equal-count histogram here, with R-code, which uses sample-quantiles to find the breaks. For example, on the same data as above, here's 6 bins with (hopefully) 8 observations each: ibr=quantile(islands^(1/3),0:6/6) hist(islands^(1/3),breaks=ibr,col=5,main="") This CV question points to a paper by Denby and Mallows a version of which is downloadable from here which describes a compromise between equal-width bins and equal-area bins. It also addresses the questions you had to some extent. You could perhaps consider the problem as one of identifying the breaks in a piecewise-constant Poisson process. That would lead to work like this. There's also the related possibility of looking at clustering/classification type algorithms on (say) Poisson counts, some of which algorithms would yield a number of bins. Clustering has been used on 2D histograms (images, in effect) to identify regions that are relatively homogenous. -- If we had an equal-count histogram, and some criterion to optimize we could then try a range of counts per bin and evaluate the criterion in some way. The Wand paper mentioned here [paper, or working paper pdf] and some of its references (e.g. to the Sheather et al papers for example) outline "plug in" bin width estimation based on kernel smoothing ideas to optimize AIMSE; broadly speaking that kind of approach should be adaptable to this situation, though I don't recall seeing it done.
Histogram with uniform vs non-uniform Bins
When is a uniform-bin histogram better than a non-uniform bin one? This requires some kind of identification of what we'd seek to optimize; many people try to optimize average integrated mean square
Histogram with uniform vs non-uniform Bins When is a uniform-bin histogram better than a non-uniform bin one? This requires some kind of identification of what we'd seek to optimize; many people try to optimize average integrated mean square error, but in many cases I think that somewhat misses the point of doing a histogram; it often (to my eye) 'oversmooths'; for an exploratory tool like a histogram I can tolerate a good deal more roughness, since the roughness itself gives me a sense of the extent to which I should "smooth" by eye; I tend to at least double the usual number of bins from such rules, sometimes a good deal more. I tend to agree with Andrew Gelman on this; indeed if my interest was really getting a good AIMSE, I probably shouldn't be considering a histogram anyway. So we need a criterion. Let me start by discussing some of the options of non-equal area histograms: There are some approaches that do more smoothing (fewer, wider bins) in areas of lower density and have narrower bins where the density is higher - such as "equal-area" or "equal count" histograms. Your edited question seems to consider the equal count possibility. The histogram function in R's lattice package can produce approximately equal-area bars: library("lattice") histogram(islands^(1/3)) # equal width histogram(islands^(1/3),breaks=NULL,equal.widths=FALSE) # approx. equal area That dip just to the right of the leftmost bin is even clearer if you take fourth roots; with equal-width bins you can't see it unless you use 15 to 20 times as many bins, and then the right tail looks terrible. There's an equal-count histogram here, with R-code, which uses sample-quantiles to find the breaks. For example, on the same data as above, here's 6 bins with (hopefully) 8 observations each: ibr=quantile(islands^(1/3),0:6/6) hist(islands^(1/3),breaks=ibr,col=5,main="") This CV question points to a paper by Denby and Mallows a version of which is downloadable from here which describes a compromise between equal-width bins and equal-area bins. It also addresses the questions you had to some extent. You could perhaps consider the problem as one of identifying the breaks in a piecewise-constant Poisson process. That would lead to work like this. There's also the related possibility of looking at clustering/classification type algorithms on (say) Poisson counts, some of which algorithms would yield a number of bins. Clustering has been used on 2D histograms (images, in effect) to identify regions that are relatively homogenous. -- If we had an equal-count histogram, and some criterion to optimize we could then try a range of counts per bin and evaluate the criterion in some way. The Wand paper mentioned here [paper, or working paper pdf] and some of its references (e.g. to the Sheather et al papers for example) outline "plug in" bin width estimation based on kernel smoothing ideas to optimize AIMSE; broadly speaking that kind of approach should be adaptable to this situation, though I don't recall seeing it done.
Histogram with uniform vs non-uniform Bins When is a uniform-bin histogram better than a non-uniform bin one? This requires some kind of identification of what we'd seek to optimize; many people try to optimize average integrated mean square
26,453
What's a good visualization for Poisson regressions?
After you've fit the model, why not use predicted defects as a variable to compare to the others using whatever standard techniques are meaningful to them? It has the advantage of being a continuous variable so you can see even small differences. For example, people will understand the difference between an expected number of defects of 1.4 and of 0.6 even though they both round to one. For an example of how the predicted value depends on two variables you could do a contour plot of time v. complexity as the two axes and colour and contours to show the predicted defects; and superimpose the actual data points on top. The plot below needs some polishing and a legend but might be a starting point. An alternative is the added variable plot or partial regression plot, more familiar from a traditional Gaussian response regression. These are implemented in the car library. Effectively the show the relationship between what is left of the response and what is left of one of the explanatory variables, after the rest of the explanatory variables have had their contribution to both the response and explanatory variables removed. In my experience most non-statistical audiences find these a bit difficult to appreciate (could by my poor explanations, of course). #-------------------------------------------------------------------- # Simulate some data n<-200 time <- rexp(n,.01) complexity <- sample(1:5, n, prob=c(.1,.25,.35,.2,.1), replace=TRUE) trueMod <- exp(-1 + time*.005 + complexity*.1 + complexity^2*.05) defects <- rpois(n, trueMod) cbind(trueMod, defects) #---------------------------------------------------------------------- # Fit model model <- glm(defects~time + poly(complexity,2), family=poisson) # all sorts of diagnostic checks should be done here - not shown #--------------------------------------------------------------------- # Two variables at once in a contour plot # create grid gridded <- data.frame( time=seq(from=0, to=max(time)*1.1, length.out=100), complexity=seq(from=0, to=max(complexity)*1.1, length.out=100)) # create predicted values (on the original scale) yhat <- predict(model, newdata=expand.grid(gridded), type="response") # draw plot image(gridded$time, gridded$complexity, matrix(yhat,nrow=100, byrow=FALSE), xlab="Time", ylab="Complexity", main="Predicted average number of defects shown as colour and contours\n(actual data shown as circles)") contour(gridded$time, gridded$complexity, matrix(yhat,nrow=100, byrow=FALSE), add=TRUE, levels=c(1,2,4,8,15,20,30,40,50,60,70,80,100)) # Add the original data symbols(time, complexity, circles=sqrt(defects), add=T, inches=.5) #-------------------------------------------------------------------- # added variable plots library(car) avPlots(model, layout=c(1,3))
What's a good visualization for Poisson regressions?
After you've fit the model, why not use predicted defects as a variable to compare to the others using whatever standard techniques are meaningful to them? It has the advantage of being a continuous
What's a good visualization for Poisson regressions? After you've fit the model, why not use predicted defects as a variable to compare to the others using whatever standard techniques are meaningful to them? It has the advantage of being a continuous variable so you can see even small differences. For example, people will understand the difference between an expected number of defects of 1.4 and of 0.6 even though they both round to one. For an example of how the predicted value depends on two variables you could do a contour plot of time v. complexity as the two axes and colour and contours to show the predicted defects; and superimpose the actual data points on top. The plot below needs some polishing and a legend but might be a starting point. An alternative is the added variable plot or partial regression plot, more familiar from a traditional Gaussian response regression. These are implemented in the car library. Effectively the show the relationship between what is left of the response and what is left of one of the explanatory variables, after the rest of the explanatory variables have had their contribution to both the response and explanatory variables removed. In my experience most non-statistical audiences find these a bit difficult to appreciate (could by my poor explanations, of course). #-------------------------------------------------------------------- # Simulate some data n<-200 time <- rexp(n,.01) complexity <- sample(1:5, n, prob=c(.1,.25,.35,.2,.1), replace=TRUE) trueMod <- exp(-1 + time*.005 + complexity*.1 + complexity^2*.05) defects <- rpois(n, trueMod) cbind(trueMod, defects) #---------------------------------------------------------------------- # Fit model model <- glm(defects~time + poly(complexity,2), family=poisson) # all sorts of diagnostic checks should be done here - not shown #--------------------------------------------------------------------- # Two variables at once in a contour plot # create grid gridded <- data.frame( time=seq(from=0, to=max(time)*1.1, length.out=100), complexity=seq(from=0, to=max(complexity)*1.1, length.out=100)) # create predicted values (on the original scale) yhat <- predict(model, newdata=expand.grid(gridded), type="response") # draw plot image(gridded$time, gridded$complexity, matrix(yhat,nrow=100, byrow=FALSE), xlab="Time", ylab="Complexity", main="Predicted average number of defects shown as colour and contours\n(actual data shown as circles)") contour(gridded$time, gridded$complexity, matrix(yhat,nrow=100, byrow=FALSE), add=TRUE, levels=c(1,2,4,8,15,20,30,40,50,60,70,80,100)) # Add the original data symbols(time, complexity, circles=sqrt(defects), add=T, inches=.5) #-------------------------------------------------------------------- # added variable plots library(car) avPlots(model, layout=c(1,3))
What's a good visualization for Poisson regressions? After you've fit the model, why not use predicted defects as a variable to compare to the others using whatever standard techniques are meaningful to them? It has the advantage of being a continuous
26,454
What's a good visualization for Poisson regressions?
So you run a poisson regression on the count data variable "defects" and want to visualize significant differences. What you do when you estimate that regression is estimate the conditional mean $E[y_i| x_i]$, where $y_i$ are the defects and $x_i$ are your regressors, like code complexity. The easiest way to visualize it is to just take two different values for $x_i$, e.g., high complexity and low complexity, and then plot the predicted frequency of $y_i=0, y_i=1$ etc. for both complexity levels. The resulting histogram would look like this on slide 3. If the differences are strong, the histrograms of those frequencies will look very different (e.g., many zeros for low complexity and many high defects for high complexity). It might look nice of you overlay these two histograms, or you plot the difference in predicted defects. If you feel reducing your $x_i$ to 2 categories is oversimplification, you can do the same for any discrete set of $x_i$, but it doesn't make for a good visual presentation if you throw more than, say, 4 graphs at your audience at once. Alternatively, if your $x_i$ is continuous, you could plot one predicted count (e.g., defects=0) depending on that $x_i$. Maybe this results in a nice monotone fuction that is in line with your results. Btw: have your also run a negative binomial regression on your data? Are the results very different? If so, your Poisson assumption (conditional mean equal to conditional variance) might be too restrictive (see "overdispersion"). That could be the case, for example, if your variable "defect" has many zeros.
What's a good visualization for Poisson regressions?
So you run a poisson regression on the count data variable "defects" and want to visualize significant differences. What you do when you estimate that regression is estimate the conditional mean $E[y_
What's a good visualization for Poisson regressions? So you run a poisson regression on the count data variable "defects" and want to visualize significant differences. What you do when you estimate that regression is estimate the conditional mean $E[y_i| x_i]$, where $y_i$ are the defects and $x_i$ are your regressors, like code complexity. The easiest way to visualize it is to just take two different values for $x_i$, e.g., high complexity and low complexity, and then plot the predicted frequency of $y_i=0, y_i=1$ etc. for both complexity levels. The resulting histogram would look like this on slide 3. If the differences are strong, the histrograms of those frequencies will look very different (e.g., many zeros for low complexity and many high defects for high complexity). It might look nice of you overlay these two histograms, or you plot the difference in predicted defects. If you feel reducing your $x_i$ to 2 categories is oversimplification, you can do the same for any discrete set of $x_i$, but it doesn't make for a good visual presentation if you throw more than, say, 4 graphs at your audience at once. Alternatively, if your $x_i$ is continuous, you could plot one predicted count (e.g., defects=0) depending on that $x_i$. Maybe this results in a nice monotone fuction that is in line with your results. Btw: have your also run a negative binomial regression on your data? Are the results very different? If so, your Poisson assumption (conditional mean equal to conditional variance) might be too restrictive (see "overdispersion"). That could be the case, for example, if your variable "defect" has many zeros.
What's a good visualization for Poisson regressions? So you run a poisson regression on the count data variable "defects" and want to visualize significant differences. What you do when you estimate that regression is estimate the conditional mean $E[y_
26,455
How do I calculate prediction intervals for random forest predictions?
I'm assuming you're talking about the continuous response case. If so, I'd recommend the quantregForest package that layers on top of the basic randomForest package and gives conditional quantile predictions. The documentation is quite good. Instead of assuming a gaussian distribution, it build an empirical density function from the terminal nodes.
How do I calculate prediction intervals for random forest predictions?
I'm assuming you're talking about the continuous response case. If so, I'd recommend the quantregForest package that layers on top of the basic randomForest package and gives conditional quantile pre
How do I calculate prediction intervals for random forest predictions? I'm assuming you're talking about the continuous response case. If so, I'd recommend the quantregForest package that layers on top of the basic randomForest package and gives conditional quantile predictions. The documentation is quite good. Instead of assuming a gaussian distribution, it build an empirical density function from the terminal nodes.
How do I calculate prediction intervals for random forest predictions? I'm assuming you're talking about the continuous response case. If so, I'd recommend the quantregForest package that layers on top of the basic randomForest package and gives conditional quantile pre
26,456
How do I calculate prediction intervals for random forest predictions?
The ranger package supports quantile predictions and hence prediction intervals: predict(ranger_fit, type = "quantile", quantiles = c(0.025, 0.975)).
How do I calculate prediction intervals for random forest predictions?
The ranger package supports quantile predictions and hence prediction intervals: predict(ranger_fit, type = "quantile", quantiles = c(0.025, 0.975)).
How do I calculate prediction intervals for random forest predictions? The ranger package supports quantile predictions and hence prediction intervals: predict(ranger_fit, type = "quantile", quantiles = c(0.025, 0.975)).
How do I calculate prediction intervals for random forest predictions? The ranger package supports quantile predictions and hence prediction intervals: predict(ranger_fit, type = "quantile", quantiles = c(0.025, 0.975)).
26,457
Is ordinal or interval data required for the Wilcoxon signed rank test?
You can't use the signed rank test as a paired difference test for ordinal data, because you can't take differences of ordinal data. If your scale were from A to K, & one patient's before and after scores were F and C, then what's F minus C equal to?† The question really needs to be about the pain scale - is it reasonable to treat it as an interval scale, or can you transform it to an interval scale, so that going from '8' to '6' is the same reduction as going from '4' to '2'? Just because you label it with numbers doesn't make that the case, & if it's not you need to use the sign test (which requires only the judgements that '8' is more than '6', & '4' is more than '2') instead. The medical literature would be the place to start looking for more information. † You could still use the signed-rank test if you're able to rank all the differences: F minus C may not have a numerical value but you know it's bigger than G minus D. But there could be a lot to compare & it's not often very practical.
Is ordinal or interval data required for the Wilcoxon signed rank test?
You can't use the signed rank test as a paired difference test for ordinal data, because you can't take differences of ordinal data. If your scale were from A to K, & one patient's before and after s
Is ordinal or interval data required for the Wilcoxon signed rank test? You can't use the signed rank test as a paired difference test for ordinal data, because you can't take differences of ordinal data. If your scale were from A to K, & one patient's before and after scores were F and C, then what's F minus C equal to?† The question really needs to be about the pain scale - is it reasonable to treat it as an interval scale, or can you transform it to an interval scale, so that going from '8' to '6' is the same reduction as going from '4' to '2'? Just because you label it with numbers doesn't make that the case, & if it's not you need to use the sign test (which requires only the judgements that '8' is more than '6', & '4' is more than '2') instead. The medical literature would be the place to start looking for more information. † You could still use the signed-rank test if you're able to rank all the differences: F minus C may not have a numerical value but you know it's bigger than G minus D. But there could be a lot to compare & it's not often very practical.
Is ordinal or interval data required for the Wilcoxon signed rank test? You can't use the signed rank test as a paired difference test for ordinal data, because you can't take differences of ordinal data. If your scale were from A to K, & one patient's before and after s
26,458
Is ordinal or interval data required for the Wilcoxon signed rank test?
According to the wikipedia page on Wilcoxon signed signed rank test, which could take ordinal data, it could still be applied to paired measurements like those in your case. I also found an examples using this test at this textbook. However, with a closer look, in both examples, the magnitude of difference is assumed and require for computing the statistics. So It is not clear how, if possible to subtract e.g. 'Agree' from 'Strongly Agree' (quote @Scortchi below). In contrast, a sign test signtest does not have this problem.
Is ordinal or interval data required for the Wilcoxon signed rank test?
According to the wikipedia page on Wilcoxon signed signed rank test, which could take ordinal data, it could still be applied to paired measurements like those in your case. I also found an examples u
Is ordinal or interval data required for the Wilcoxon signed rank test? According to the wikipedia page on Wilcoxon signed signed rank test, which could take ordinal data, it could still be applied to paired measurements like those in your case. I also found an examples using this test at this textbook. However, with a closer look, in both examples, the magnitude of difference is assumed and require for computing the statistics. So It is not clear how, if possible to subtract e.g. 'Agree' from 'Strongly Agree' (quote @Scortchi below). In contrast, a sign test signtest does not have this problem.
Is ordinal or interval data required for the Wilcoxon signed rank test? According to the wikipedia page on Wilcoxon signed signed rank test, which could take ordinal data, it could still be applied to paired measurements like those in your case. I also found an examples u
26,459
Does the multivariate Central Limit Theorem (CLT) hold when variables exhibit perfect contemporaneous dependence?
The short answer as I understand your q is "yes, but ..." the rates of convergence on S, T, and any other moments are not necessarily the same -- check out determining bounds with the Berry-Esseen Theorem. In case I misunderstand your q, Sn and Tn even hold to the CLT under conditions of weak dependence (mixing): check out Wikipedia's CLT for dependent processes. CLT is such a general theorem -- the basic proof requires nothing more than the characteristic function of Sn and Tn converges to the characteristic function of the standard normal, then Levy Continuity Theorem says the convergence of the characteristic function implies convergence of the distribution. John Cook provides a great explanation of CLT error here.
Does the multivariate Central Limit Theorem (CLT) hold when variables exhibit perfect contemporaneou
The short answer as I understand your q is "yes, but ..." the rates of convergence on S, T, and any other moments are not necessarily the same -- check out determining bounds with the Berry-Esseen The
Does the multivariate Central Limit Theorem (CLT) hold when variables exhibit perfect contemporaneous dependence? The short answer as I understand your q is "yes, but ..." the rates of convergence on S, T, and any other moments are not necessarily the same -- check out determining bounds with the Berry-Esseen Theorem. In case I misunderstand your q, Sn and Tn even hold to the CLT under conditions of weak dependence (mixing): check out Wikipedia's CLT for dependent processes. CLT is such a general theorem -- the basic proof requires nothing more than the characteristic function of Sn and Tn converges to the characteristic function of the standard normal, then Levy Continuity Theorem says the convergence of the characteristic function implies convergence of the distribution. John Cook provides a great explanation of CLT error here.
Does the multivariate Central Limit Theorem (CLT) hold when variables exhibit perfect contemporaneou The short answer as I understand your q is "yes, but ..." the rates of convergence on S, T, and any other moments are not necessarily the same -- check out determining bounds with the Berry-Esseen The
26,460
Does the multivariate Central Limit Theorem (CLT) hold when variables exhibit perfect contemporaneous dependence?
This doesn't prove anything, of course, but I always find doing simulations and plotting graphs to be very handy for making sense of theoretical results. This is a particularly simple case. We generate $n$ random normal variates and compute $S_n$ and $T_n$; repeat $m$ times. Plotted are the graphs for $n = 1, 10, 100$ and $1000$. It's easy to see the dependence weakening as $n$ increases; at $n = 100$ the graph is almost indistinguishable from independence. test <- function (m, n) { r <- matrix(rnorm(m * n), nrow = m) cbind(rowMeans(r), rowSums(r^2 - 1)/n) } par(mfrow=c(2,2)) plot(test(100, 1)) plot(test(100, 2)) plot(test(100, 5)) plot(test(100, 100))
Does the multivariate Central Limit Theorem (CLT) hold when variables exhibit perfect contemporaneou
This doesn't prove anything, of course, but I always find doing simulations and plotting graphs to be very handy for making sense of theoretical results. This is a particularly simple case. We generat
Does the multivariate Central Limit Theorem (CLT) hold when variables exhibit perfect contemporaneous dependence? This doesn't prove anything, of course, but I always find doing simulations and plotting graphs to be very handy for making sense of theoretical results. This is a particularly simple case. We generate $n$ random normal variates and compute $S_n$ and $T_n$; repeat $m$ times. Plotted are the graphs for $n = 1, 10, 100$ and $1000$. It's easy to see the dependence weakening as $n$ increases; at $n = 100$ the graph is almost indistinguishable from independence. test <- function (m, n) { r <- matrix(rnorm(m * n), nrow = m) cbind(rowMeans(r), rowSums(r^2 - 1)/n) } par(mfrow=c(2,2)) plot(test(100, 1)) plot(test(100, 2)) plot(test(100, 5)) plot(test(100, 100))
Does the multivariate Central Limit Theorem (CLT) hold when variables exhibit perfect contemporaneou This doesn't prove anything, of course, but I always find doing simulations and plotting graphs to be very handy for making sense of theoretical results. This is a particularly simple case. We generat
26,461
Why do Anova( ) and drop1( ) provided different answers for GLMMs?
I think it is the difference of which tests are computed. car::Anova uses Wald tests, whereas drop1 refits the model dropping single terms. John Fox once wrote me, that Wald tests and tests from refitted models using likelihood ratio tests (i.e., the strategy from drop1) agree for linear but not necessarily non-linear models. Unfortunately this mail was offlist and did not contain any reference. But I know that his book has a chapter on Wald tests, which could contain the desired info. The help to car::Anova says: Type-II tests are calculated according to the principle of marginality, testing each term after all others, except ignoring the term's higher-order relatives; so-called type-III tests violate marginality, testing each term in the model after all of the others. This definition of Type-II tests corresponds to the tests produced by SAS for analysis-of-variance models, where all of the predictors are factors, but not more generally (i.e., when there are quantitative predictors). Be very careful in formulating the model for type-III tests, or the hypotheses tested will not make sense. Unfortunately I cannot answer you second or third question as I also would like to know that. Update reagrding comment: There are no Wald, LR and F tests for generalized mixed models. Anova just allows for "chisq" and "F" tests for mixed models (i.e. "mer" objects as returned by lmer). The usage section says: ## S3 method for class 'mer' Anova(mod, type=c("II","III", 2, 3), test.statistic=c("chisq", "F"), vcov.=vcov(mod), singular.ok, ...) But as the F-tests for mer objects are calculated by pbkrtest, which for my knowledge only works for linear mixed models, Anova for GLMMs should always return chisq (hence you see no difference). Update regarding the question: My previous answer just tried to respond to your main question, the difference between Anova() and drop1(). But now I understand that you want to test if certainf fixed effects are significant or not. The R-sig-mixed modeling FAQ says the following regarding this: Tests of single parameters From worst to best: Wald Z-tests For balanced, nested LMMs where df can be computed: Wald t-tests Likelihood ratio test, either by setting up the model so that the parameter can be isolated/dropped (via anova or drop1), or via computing likelihood profiles MCMC or parametric bootstrap confidence intervals Tests of effects (i.e. testing that several parameters are simultaneously zero) From worst to best: Wald chi-square tests (e.g. car::Anova) Likelihood ratio test (via anova or drop1) For balanced, nested LMMs where df can be computed: conditional F-tests For LMMs: conditional F-tests with df correction (e.g. Kenward-Roger in pbkrtest package) MCMC or parametric, or nonparametric, bootstrap comparisons (nonparametric bootstrapping must be implemented carefully to account for grouping factors) (emphasis added) This indicates that your approach of using car::Anova() for GLMMs is generally not recommended, but an approach using MCMC or bootstrap should be used. I don't know if pvals.fnc from the languageR package woks with GLMMs, but it is worth a try.
Why do Anova( ) and drop1( ) provided different answers for GLMMs?
I think it is the difference of which tests are computed. car::Anova uses Wald tests, whereas drop1 refits the model dropping single terms. John Fox once wrote me, that Wald tests and tests from refit
Why do Anova( ) and drop1( ) provided different answers for GLMMs? I think it is the difference of which tests are computed. car::Anova uses Wald tests, whereas drop1 refits the model dropping single terms. John Fox once wrote me, that Wald tests and tests from refitted models using likelihood ratio tests (i.e., the strategy from drop1) agree for linear but not necessarily non-linear models. Unfortunately this mail was offlist and did not contain any reference. But I know that his book has a chapter on Wald tests, which could contain the desired info. The help to car::Anova says: Type-II tests are calculated according to the principle of marginality, testing each term after all others, except ignoring the term's higher-order relatives; so-called type-III tests violate marginality, testing each term in the model after all of the others. This definition of Type-II tests corresponds to the tests produced by SAS for analysis-of-variance models, where all of the predictors are factors, but not more generally (i.e., when there are quantitative predictors). Be very careful in formulating the model for type-III tests, or the hypotheses tested will not make sense. Unfortunately I cannot answer you second or third question as I also would like to know that. Update reagrding comment: There are no Wald, LR and F tests for generalized mixed models. Anova just allows for "chisq" and "F" tests for mixed models (i.e. "mer" objects as returned by lmer). The usage section says: ## S3 method for class 'mer' Anova(mod, type=c("II","III", 2, 3), test.statistic=c("chisq", "F"), vcov.=vcov(mod), singular.ok, ...) But as the F-tests for mer objects are calculated by pbkrtest, which for my knowledge only works for linear mixed models, Anova for GLMMs should always return chisq (hence you see no difference). Update regarding the question: My previous answer just tried to respond to your main question, the difference between Anova() and drop1(). But now I understand that you want to test if certainf fixed effects are significant or not. The R-sig-mixed modeling FAQ says the following regarding this: Tests of single parameters From worst to best: Wald Z-tests For balanced, nested LMMs where df can be computed: Wald t-tests Likelihood ratio test, either by setting up the model so that the parameter can be isolated/dropped (via anova or drop1), or via computing likelihood profiles MCMC or parametric bootstrap confidence intervals Tests of effects (i.e. testing that several parameters are simultaneously zero) From worst to best: Wald chi-square tests (e.g. car::Anova) Likelihood ratio test (via anova or drop1) For balanced, nested LMMs where df can be computed: conditional F-tests For LMMs: conditional F-tests with df correction (e.g. Kenward-Roger in pbkrtest package) MCMC or parametric, or nonparametric, bootstrap comparisons (nonparametric bootstrapping must be implemented carefully to account for grouping factors) (emphasis added) This indicates that your approach of using car::Anova() for GLMMs is generally not recommended, but an approach using MCMC or bootstrap should be used. I don't know if pvals.fnc from the languageR package woks with GLMMs, but it is worth a try.
Why do Anova( ) and drop1( ) provided different answers for GLMMs? I think it is the difference of which tests are computed. car::Anova uses Wald tests, whereas drop1 refits the model dropping single terms. John Fox once wrote me, that Wald tests and tests from refit
26,462
How to find similarities between time series?
What you have is K (5) Groups where you have a dependent (water temp) and an independent series(air temp). This problems is called Pooled Cross-Sectional Time Series Analysis. Construct a separate Transfer Function (ARMAX) model for each of the K groups. Identify a common model (outlier resistant) that would be appropriate. Estimate that model globally using all of the data and then perform an F test to test the hypothesis of a common set of parameters. Upon finding a statistically significant F value examine the coefficients to determine which groups (of the K) that are similar. My current research has been to develop an automatic test for this and we have it operational in a current Beta Version of AUTOBOX (http://www.autobox.com). I would be glad to demonstrate this for you, please post your data. Upon finding out how AUTOBOX conducts this test you might be able to program it yourself or at least have a "destination". Hope this helps. ADDITIONAL COMMENTS USING KATE'S DATA: I took the first 4 Groups ( depth of .5,4,6 and 8) and used the first 52 values to construct this example analysis. Following are 4 graphs depicting the Y (water temp) and the X (Air temp) over time for the 4 depths; depth1 ; ; depth 2; ; depth 3; and depth 4; . An analysis of the within relationship of Y versus X yielded a typical model of the form . I elected to add another AR term to the noise for purposes of a more general expression. All four examples are significantly influenced by anomalies so one might argue/suggest that one should continue with outlier-adjusted series or intervention-scrubbed series i.e. "cleansed series". For presentation purposes here this was not done. We now proceeded to estimate the "typical model" for each of the 4 data sets AND for the composite. This yielded . The F test is simply the Chow Test for constant parameters http://en.wikipedia.org/wiki/Chow_test which yielded a significant F. The Chow test simply sums the error sos from each of the 4 cases (each with 52 values) and compares it to the error sos for the composite (208 values). Hope this helps.
How to find similarities between time series?
What you have is K (5) Groups where you have a dependent (water temp) and an independent series(air temp). This problems is called Pooled Cross-Sectional Time Series Analysis. Construct a separate Tra
How to find similarities between time series? What you have is K (5) Groups where you have a dependent (water temp) and an independent series(air temp). This problems is called Pooled Cross-Sectional Time Series Analysis. Construct a separate Transfer Function (ARMAX) model for each of the K groups. Identify a common model (outlier resistant) that would be appropriate. Estimate that model globally using all of the data and then perform an F test to test the hypothesis of a common set of parameters. Upon finding a statistically significant F value examine the coefficients to determine which groups (of the K) that are similar. My current research has been to develop an automatic test for this and we have it operational in a current Beta Version of AUTOBOX (http://www.autobox.com). I would be glad to demonstrate this for you, please post your data. Upon finding out how AUTOBOX conducts this test you might be able to program it yourself or at least have a "destination". Hope this helps. ADDITIONAL COMMENTS USING KATE'S DATA: I took the first 4 Groups ( depth of .5,4,6 and 8) and used the first 52 values to construct this example analysis. Following are 4 graphs depicting the Y (water temp) and the X (Air temp) over time for the 4 depths; depth1 ; ; depth 2; ; depth 3; and depth 4; . An analysis of the within relationship of Y versus X yielded a typical model of the form . I elected to add another AR term to the noise for purposes of a more general expression. All four examples are significantly influenced by anomalies so one might argue/suggest that one should continue with outlier-adjusted series or intervention-scrubbed series i.e. "cleansed series". For presentation purposes here this was not done. We now proceeded to estimate the "typical model" for each of the 4 data sets AND for the composite. This yielded . The F test is simply the Chow Test for constant parameters http://en.wikipedia.org/wiki/Chow_test which yielded a significant F. The Chow test simply sums the error sos from each of the 4 cases (each with 52 values) and compares it to the error sos for the composite (208 values). Hope this helps.
How to find similarities between time series? What you have is K (5) Groups where you have a dependent (water temp) and an independent series(air temp). This problems is called Pooled Cross-Sectional Time Series Analysis. Construct a separate Tra
26,463
How to find similarities between time series?
"Similarity" is problem-dependent. From what you write, I have the feeling that estimation of the cross-spectra and coherence might be a good way to proceed, at least if your series are stationary and long enough. Other references that I happen to have handy and may or may not be relevant to your problem are: Coke, Geoffrey and Tsao, Min (2010). Random effects mixture models for clustering electrical load series. Journal of Time Series Analysis 6: 451-464. Warren Liao, T (2005). Clustering of time series data - a survey. Pattern Recognition 11: 1857-1874.
How to find similarities between time series?
"Similarity" is problem-dependent. From what you write, I have the feeling that estimation of the cross-spectra and coherence might be a good way to proceed, at least if your series are stationary and
How to find similarities between time series? "Similarity" is problem-dependent. From what you write, I have the feeling that estimation of the cross-spectra and coherence might be a good way to proceed, at least if your series are stationary and long enough. Other references that I happen to have handy and may or may not be relevant to your problem are: Coke, Geoffrey and Tsao, Min (2010). Random effects mixture models for clustering electrical load series. Journal of Time Series Analysis 6: 451-464. Warren Liao, T (2005). Clustering of time series data - a survey. Pattern Recognition 11: 1857-1874.
How to find similarities between time series? "Similarity" is problem-dependent. From what you write, I have the feeling that estimation of the cross-spectra and coherence might be a good way to proceed, at least if your series are stationary and
26,464
How to find similarities between time series?
Cross-spectra is just the Fourier transform of the cross-correlation function. The cross-correlation should be high at lag 0 and may drop as the time difference between the series increase. This should be done if both series are stationary. If there are trends or seasonal changes in temperature you could fit time trends or cosine functions to the two series and look for similarities in the model coefficients. For stationary series the same could be done for fitted ARMA models. Do the best fitting series have the same orders p and q? If so how close are the parameter estimates?
How to find similarities between time series?
Cross-spectra is just the Fourier transform of the cross-correlation function. The cross-correlation should be high at lag 0 and may drop as the time difference between the series increase. This sh
How to find similarities between time series? Cross-spectra is just the Fourier transform of the cross-correlation function. The cross-correlation should be high at lag 0 and may drop as the time difference between the series increase. This should be done if both series are stationary. If there are trends or seasonal changes in temperature you could fit time trends or cosine functions to the two series and look for similarities in the model coefficients. For stationary series the same could be done for fitted ARMA models. Do the best fitting series have the same orders p and q? If so how close are the parameter estimates?
How to find similarities between time series? Cross-spectra is just the Fourier transform of the cross-correlation function. The cross-correlation should be high at lag 0 and may drop as the time difference between the series increase. This sh
26,465
Why can't we trust our intuition with probability?
There are two main approaches to understanding this question. The first (and I believe most successful) is the literature on cognitive biases (see this LessWrong link). Much has been written on this topic and it would be too presumptuous to summarize it here. In general, this just means that the cognitive machinery humans are endowed with through the evolutionary process employs lots of heuristics and shortcuts to make survival decisions more efficiently. These survival decisions mostly applied to ancestral environments which we rarely face anymore, and so the frequency with which we face scenarios where our heuristics fail might be expected to increase. Humans, for example, are great at generating beliefs. If positing a new belief costs very little, but failing to employ a belief that would have lead to survival has high cost (even if the belief is in general incorrect), then one would expect to see lots of rationalization and low evidence barriers to believing propositions (which is what we do see with humans). You also get behaviors such as probability matching for similar reasons. One could go on at length describing all of the fascinating ways that we deviate from opimal decision making. Check Kahneman's recent book Thinking, Fast and Slow and Dan Ariely's book Predictably Irrational for popular, readable accounts with lots of examples. I recommend reading some of the sequences at LessWrong for more principled discussion of cognitive bias, and lots of interesting academic literature reviews regarding steps one can take to avoid these biases in certain circumstances. The other approach to this problem is (I think) far more tenuous. This is the notion that probability is itself not the correct normative theory for dealing with uncertainty. I don't have time to annotate some sources for this now, but I will update my answer later with some discussion of this view.
Why can't we trust our intuition with probability?
There are two main approaches to understanding this question. The first (and I believe most successful) is the literature on cognitive biases (see this LessWrong link). Much has been written on this
Why can't we trust our intuition with probability? There are two main approaches to understanding this question. The first (and I believe most successful) is the literature on cognitive biases (see this LessWrong link). Much has been written on this topic and it would be too presumptuous to summarize it here. In general, this just means that the cognitive machinery humans are endowed with through the evolutionary process employs lots of heuristics and shortcuts to make survival decisions more efficiently. These survival decisions mostly applied to ancestral environments which we rarely face anymore, and so the frequency with which we face scenarios where our heuristics fail might be expected to increase. Humans, for example, are great at generating beliefs. If positing a new belief costs very little, but failing to employ a belief that would have lead to survival has high cost (even if the belief is in general incorrect), then one would expect to see lots of rationalization and low evidence barriers to believing propositions (which is what we do see with humans). You also get behaviors such as probability matching for similar reasons. One could go on at length describing all of the fascinating ways that we deviate from opimal decision making. Check Kahneman's recent book Thinking, Fast and Slow and Dan Ariely's book Predictably Irrational for popular, readable accounts with lots of examples. I recommend reading some of the sequences at LessWrong for more principled discussion of cognitive bias, and lots of interesting academic literature reviews regarding steps one can take to avoid these biases in certain circumstances. The other approach to this problem is (I think) far more tenuous. This is the notion that probability is itself not the correct normative theory for dealing with uncertainty. I don't have time to annotate some sources for this now, but I will update my answer later with some discussion of this view.
Why can't we trust our intuition with probability? There are two main approaches to understanding this question. The first (and I believe most successful) is the literature on cognitive biases (see this LessWrong link). Much has been written on this
26,466
How to formally test for a "break" in a normal (or other) distribution
It is important to frame the question properly and to adopt a useful conceptual model of the scores. The question The potential cheating thresholds, such as 55, 65, and 85, are known a priori independently of the data: they do not have to be determined from the data. (Therefore this is neither an outlier detection problem nor a distribution fitting problem.) The test should assess the evidence that some (not all) scores just less than these thresholds were moved to those thresholds (or, perhaps, just over those thresholds). Conceptual model For the conceptual model, it is crucial to understand that the scores are unlikely to have a normal distribution (nor any other easily parameterized distribution). That is abundantly clear in the posted example and in every other example from the original report. These scores represent a mixture of schools; even if distributions within any school were normal (they are not), the mixture is not likely to be normal. A simple approach accepts that there is a true score distribution: the one that would be reported except for this particular form of cheating. It is therefore a non-parametric setting. That seems too broad, but there are some characteristics of the score distribution that can be anticipated or observed in the actual data: The counts of scores $i-1$, $i$, and $i+1$ will be closely correlated, $1 \le i \le 99$. There will be variations in these counts around some idealized smooth version of the score distribution. These variations will typically be of a size equal to the square root of the count. Cheating relative to a threshold $t$ will not affect the counts for any score $i\ge t$. Its effect is proportional to the count of each score (the number of students "at risk" for being affected by cheating). For scores $i$ below this threshold, the count $c(i)$ will be reduced by some fraction $\delta(t-i)c(i)$ and this amount will be added to $t(i)$. The amount of change decreases with the distance between a score and the threshold: $\delta(i)$ is a decreasing function of $i=1,2,\ldots$. Given a threshold $t$, the null hypothesis (no cheating) is that $\delta(1)=0$, implying $\delta$ is identically $0$. The alternative is that $\delta(1)\gt 0$. Constructing a test What test statistic to use? According to these assumptions, (a) the effect is additive in the counts and (b) the greatest effect will occur right around the threshold. This indicates looking at first differences of the counts, $c'(i) = c(i+1)-c(i)$. Further consideration suggests going one step further: under the alternative hypothesis, we expect to see a sequence of gradually depressed counts as the score $i$ approaches the threshold $t$ from below, then (i) a large positive change at $t$ followed by (ii) a large negative change at $t+1$. To maximize the power of the test, then, let's look at second differences, $$c''(i) = c'(i+1) - c'(i) = c(i+2) - 2c(i+1) + c(i),$$ because at $i = t-1$ this will combine a largish negative decline $c(t+1)-c(t)$ with the negative of a large positive increase $c(t) - c(t-1)$, thereby magnifying the cheating effect. I am going to hypothesize--and this can be checked--that the serial correlation of the counts near the threshold is fairly small. (Serial correlation elsewhere is irrelevant.) This implies that the variance of $c''(t-1) = c(t+1) - 2c(t) + c(t-1)$ is approximately $$\text{var}(c''(t-1)) \approx \text{var}(c(t+1)) + (-2)^2\text{var}(c(t)) + \text{var}(c(t-1)).$$ I previously suggested that $\text{var}(c(i)) \approx c(i)$ for all $i$ (something that also can be checked). Whence $$z = c''(t-1) / \sqrt{c(t+1) + 4c(t) + c(t-1)}$$ should approximately have unit variance. For large score populations (the posted one looks to be around 20,000) we can expect an approximately Normal distribution of $c''(t-1)$, too. Since we expect a highly negative value to indicate a cheating pattern, we easily obtain a test of size $\alpha$: writing $\Phi$ for the cdf of the standard Normal distribution, reject the hypothesis of no cheating at threshold $t$ when $\Phi(z) \lt \alpha$. Example For example, consider this set of true test scores, drawn iid from a mixture of three Normal distributions: To this I applied a cheating schedule at the threshold $t=65$ defined by $\delta(i) = \exp(-2 i)$. This focuses almost all cheating on the one or two scores immediately below 65: To get a sense of what the test does, I computed $z$ for every score, not just $t$, and plotted it against the score: (Actually, to avoid troubles with small counts, I first added 1 to every count from 0 through 100 in order to calculate the denominator of $z$.) The fluctuation near 65 is apparent, as is the tendency for all other fluctuations to be about 1 in size, consistent with the assumptions of this test. The test statistic is $z = -4.19$ with a corresponding p-value of $\Phi(z) = 0.0000136$, an extremely significant result. Visual comparison with the figure in the question itself suggests this test would return a p-value at least as small. (Please note, though, that the test itself does not use this plot, which is shown to illustrate the ideas. The test looks only at the plotted value at the threshold, nowhere else. It would nevertheless be good practice to make such a plot to confirm that the test statistic really does single out the expected thresholds as loci of cheating and that all other scores are not subject to such changes. Here, we see that at all other scores there is fluctuation between about -2 and 2, but rarely greater. Note, too, that one need not actually compute the standard deviation of the values in this plot in order to compute $z$, thereby avoiding problems associated with cheating effects inflating the fluctuations at multiple locations.) When applying this test to multiple thresholds, a Bonferroni adjustment of the test size would be wise. Additional adjustment when applied to multiple tests at the same time would also be a good idea. Evaluation This procedure cannot seriously be proposed for use until it is tested on actual data. A good way would be to take scores for one test and use a non-critical score for the test as threshold. Presumably such a threshold has not been subject to this form of cheating. Simulate cheating according to this conceptual model and study the simulated distribution of $z$. This will indicate (a) whether the p-values are accurate and (b) the power of the test to indicate the simulated form of cheating. Indeed, one could employ such a simulation study on the very data one is evaluating, providing an extremely effective way of testing whether the test is appropriate and what its actual power is. Because the test statistic $z$ is so simple, simulations will be practicable to do and fast to execute.
How to formally test for a "break" in a normal (or other) distribution
It is important to frame the question properly and to adopt a useful conceptual model of the scores. The question The potential cheating thresholds, such as 55, 65, and 85, are known a priori independ
How to formally test for a "break" in a normal (or other) distribution It is important to frame the question properly and to adopt a useful conceptual model of the scores. The question The potential cheating thresholds, such as 55, 65, and 85, are known a priori independently of the data: they do not have to be determined from the data. (Therefore this is neither an outlier detection problem nor a distribution fitting problem.) The test should assess the evidence that some (not all) scores just less than these thresholds were moved to those thresholds (or, perhaps, just over those thresholds). Conceptual model For the conceptual model, it is crucial to understand that the scores are unlikely to have a normal distribution (nor any other easily parameterized distribution). That is abundantly clear in the posted example and in every other example from the original report. These scores represent a mixture of schools; even if distributions within any school were normal (they are not), the mixture is not likely to be normal. A simple approach accepts that there is a true score distribution: the one that would be reported except for this particular form of cheating. It is therefore a non-parametric setting. That seems too broad, but there are some characteristics of the score distribution that can be anticipated or observed in the actual data: The counts of scores $i-1$, $i$, and $i+1$ will be closely correlated, $1 \le i \le 99$. There will be variations in these counts around some idealized smooth version of the score distribution. These variations will typically be of a size equal to the square root of the count. Cheating relative to a threshold $t$ will not affect the counts for any score $i\ge t$. Its effect is proportional to the count of each score (the number of students "at risk" for being affected by cheating). For scores $i$ below this threshold, the count $c(i)$ will be reduced by some fraction $\delta(t-i)c(i)$ and this amount will be added to $t(i)$. The amount of change decreases with the distance between a score and the threshold: $\delta(i)$ is a decreasing function of $i=1,2,\ldots$. Given a threshold $t$, the null hypothesis (no cheating) is that $\delta(1)=0$, implying $\delta$ is identically $0$. The alternative is that $\delta(1)\gt 0$. Constructing a test What test statistic to use? According to these assumptions, (a) the effect is additive in the counts and (b) the greatest effect will occur right around the threshold. This indicates looking at first differences of the counts, $c'(i) = c(i+1)-c(i)$. Further consideration suggests going one step further: under the alternative hypothesis, we expect to see a sequence of gradually depressed counts as the score $i$ approaches the threshold $t$ from below, then (i) a large positive change at $t$ followed by (ii) a large negative change at $t+1$. To maximize the power of the test, then, let's look at second differences, $$c''(i) = c'(i+1) - c'(i) = c(i+2) - 2c(i+1) + c(i),$$ because at $i = t-1$ this will combine a largish negative decline $c(t+1)-c(t)$ with the negative of a large positive increase $c(t) - c(t-1)$, thereby magnifying the cheating effect. I am going to hypothesize--and this can be checked--that the serial correlation of the counts near the threshold is fairly small. (Serial correlation elsewhere is irrelevant.) This implies that the variance of $c''(t-1) = c(t+1) - 2c(t) + c(t-1)$ is approximately $$\text{var}(c''(t-1)) \approx \text{var}(c(t+1)) + (-2)^2\text{var}(c(t)) + \text{var}(c(t-1)).$$ I previously suggested that $\text{var}(c(i)) \approx c(i)$ for all $i$ (something that also can be checked). Whence $$z = c''(t-1) / \sqrt{c(t+1) + 4c(t) + c(t-1)}$$ should approximately have unit variance. For large score populations (the posted one looks to be around 20,000) we can expect an approximately Normal distribution of $c''(t-1)$, too. Since we expect a highly negative value to indicate a cheating pattern, we easily obtain a test of size $\alpha$: writing $\Phi$ for the cdf of the standard Normal distribution, reject the hypothesis of no cheating at threshold $t$ when $\Phi(z) \lt \alpha$. Example For example, consider this set of true test scores, drawn iid from a mixture of three Normal distributions: To this I applied a cheating schedule at the threshold $t=65$ defined by $\delta(i) = \exp(-2 i)$. This focuses almost all cheating on the one or two scores immediately below 65: To get a sense of what the test does, I computed $z$ for every score, not just $t$, and plotted it against the score: (Actually, to avoid troubles with small counts, I first added 1 to every count from 0 through 100 in order to calculate the denominator of $z$.) The fluctuation near 65 is apparent, as is the tendency for all other fluctuations to be about 1 in size, consistent with the assumptions of this test. The test statistic is $z = -4.19$ with a corresponding p-value of $\Phi(z) = 0.0000136$, an extremely significant result. Visual comparison with the figure in the question itself suggests this test would return a p-value at least as small. (Please note, though, that the test itself does not use this plot, which is shown to illustrate the ideas. The test looks only at the plotted value at the threshold, nowhere else. It would nevertheless be good practice to make such a plot to confirm that the test statistic really does single out the expected thresholds as loci of cheating and that all other scores are not subject to such changes. Here, we see that at all other scores there is fluctuation between about -2 and 2, but rarely greater. Note, too, that one need not actually compute the standard deviation of the values in this plot in order to compute $z$, thereby avoiding problems associated with cheating effects inflating the fluctuations at multiple locations.) When applying this test to multiple thresholds, a Bonferroni adjustment of the test size would be wise. Additional adjustment when applied to multiple tests at the same time would also be a good idea. Evaluation This procedure cannot seriously be proposed for use until it is tested on actual data. A good way would be to take scores for one test and use a non-critical score for the test as threshold. Presumably such a threshold has not been subject to this form of cheating. Simulate cheating according to this conceptual model and study the simulated distribution of $z$. This will indicate (a) whether the p-values are accurate and (b) the power of the test to indicate the simulated form of cheating. Indeed, one could employ such a simulation study on the very data one is evaluating, providing an extremely effective way of testing whether the test is appropriate and what its actual power is. Because the test statistic $z$ is so simple, simulations will be practicable to do and fast to execute.
How to formally test for a "break" in a normal (or other) distribution It is important to frame the question properly and to adopt a useful conceptual model of the scores. The question The potential cheating thresholds, such as 55, 65, and 85, are known a priori independ
26,467
How to formally test for a "break" in a normal (or other) distribution
I suggest fitting a model which explicitly predicts the dips and then showing that it significantly better fits the data than a naive one. You need two components: initial distribution of scores, procedure of rechecking (honest or not) of scores when one fits below a threshold. One possible model for a single threshold (of value $t$) is the following: $$p_{final}(s) = p_{initial}(s) - p_{initial}(s)m(s\rightarrow t)+ \delta(s=t)\sum_{s'=0}^{t-1}p_{initial}(s')m(s'\rightarrow t),$$ where $p_{final}(s)$ - the probability distribution of the final score, $p_{initial}(s)$ - the probability distribution if there were not thresholds, $m(s'\rightarrow t)$ - the probability of manipulation score $s'$ into passing score $t$, $\delta(s=t)$ is the Kronecker delta, i.e. 1 if $s=t$ and 0 otherwise. Typically you cannot rise scores much. I would suspect exponential decay $m(s'\rightarrow t)\approx a q^{t-s'}$, where $a$ is the proportion of rechecked (manipulated) scores. As the initial distribution you can try to use Poisson or Gaussian distribution. Of course it would be ideally to have the same test but for one group of teachers provide thresholds and for the other - no thresholds. If there are more thresholds then one can apply the same formula but with corrections for each $t_i$. Perhaps $a_i$ would be different as well (e.g. as the difference between fail-pass can be more important that between two passing grades). Notes: Sometimes there are procedures of rechecking tests if there are just below passing grade. Then it is more difficult to say which instances were honest and which - not. $m(s\rightarrow t)$ will surely depend on the type of test. For example if there are open questions, then some answers may be ambiguous and number of them depends on $s$ (so for low-scoring it may be easier to rise the score). Whereas for closed-choice test there should be little to no difference on the number of the correct and incorrect answers. Sometimes the 'corrected' scores may be above $t$ - the instead of idealized $\delta(s=t)$ one may plug sth different.
How to formally test for a "break" in a normal (or other) distribution
I suggest fitting a model which explicitly predicts the dips and then showing that it significantly better fits the data than a naive one. You need two components: initial distribution of scores, pro
How to formally test for a "break" in a normal (or other) distribution I suggest fitting a model which explicitly predicts the dips and then showing that it significantly better fits the data than a naive one. You need two components: initial distribution of scores, procedure of rechecking (honest or not) of scores when one fits below a threshold. One possible model for a single threshold (of value $t$) is the following: $$p_{final}(s) = p_{initial}(s) - p_{initial}(s)m(s\rightarrow t)+ \delta(s=t)\sum_{s'=0}^{t-1}p_{initial}(s')m(s'\rightarrow t),$$ where $p_{final}(s)$ - the probability distribution of the final score, $p_{initial}(s)$ - the probability distribution if there were not thresholds, $m(s'\rightarrow t)$ - the probability of manipulation score $s'$ into passing score $t$, $\delta(s=t)$ is the Kronecker delta, i.e. 1 if $s=t$ and 0 otherwise. Typically you cannot rise scores much. I would suspect exponential decay $m(s'\rightarrow t)\approx a q^{t-s'}$, where $a$ is the proportion of rechecked (manipulated) scores. As the initial distribution you can try to use Poisson or Gaussian distribution. Of course it would be ideally to have the same test but for one group of teachers provide thresholds and for the other - no thresholds. If there are more thresholds then one can apply the same formula but with corrections for each $t_i$. Perhaps $a_i$ would be different as well (e.g. as the difference between fail-pass can be more important that between two passing grades). Notes: Sometimes there are procedures of rechecking tests if there are just below passing grade. Then it is more difficult to say which instances were honest and which - not. $m(s\rightarrow t)$ will surely depend on the type of test. For example if there are open questions, then some answers may be ambiguous and number of them depends on $s$ (so for low-scoring it may be easier to rise the score). Whereas for closed-choice test there should be little to no difference on the number of the correct and incorrect answers. Sometimes the 'corrected' scores may be above $t$ - the instead of idealized $\delta(s=t)$ one may plug sth different.
How to formally test for a "break" in a normal (or other) distribution I suggest fitting a model which explicitly predicts the dips and then showing that it significantly better fits the data than a naive one. You need two components: initial distribution of scores, pro
26,468
How to formally test for a "break" in a normal (or other) distribution
I would split this problem into two subproblems: Estimate the parameters of a distribution to fit the data Perform outlier detection using the fitted distribution There are various ways of tackling either of the subproblems. It seems to me that a Poisson distribution would fit the data, if it were independently and identically distributed (iid), which of course we think it isn't. If we naively try to estimate the parameters of the distribution we will be skewed by the outliers. Two possible ways to overcome this are to use Robust Regression techniques, or a heuristic method such as cross-validation. For the outlier detection there are again numerous approaches. The simplest is to use the confidence intervals from the distribution we fitted in stage 1. Other methods include bootstrap methods and Monte-Carlo approaches. Although this won't tell you that there is a "jump" in the distribution, it will tell you whether there are more outliers than expected for the sample size. A more complex approach would be to construct various models for the data, such as compound distributions, and use some kind of model comparison method (AIC/BIC) to determine which of the models is the best fit for the data. However if you are simply looking for "deviation from an expected distribution" then this seems like overkill.
How to formally test for a "break" in a normal (or other) distribution
I would split this problem into two subproblems: Estimate the parameters of a distribution to fit the data Perform outlier detection using the fitted distribution There are various ways of tackling
How to formally test for a "break" in a normal (or other) distribution I would split this problem into two subproblems: Estimate the parameters of a distribution to fit the data Perform outlier detection using the fitted distribution There are various ways of tackling either of the subproblems. It seems to me that a Poisson distribution would fit the data, if it were independently and identically distributed (iid), which of course we think it isn't. If we naively try to estimate the parameters of the distribution we will be skewed by the outliers. Two possible ways to overcome this are to use Robust Regression techniques, or a heuristic method such as cross-validation. For the outlier detection there are again numerous approaches. The simplest is to use the confidence intervals from the distribution we fitted in stage 1. Other methods include bootstrap methods and Monte-Carlo approaches. Although this won't tell you that there is a "jump" in the distribution, it will tell you whether there are more outliers than expected for the sample size. A more complex approach would be to construct various models for the data, such as compound distributions, and use some kind of model comparison method (AIC/BIC) to determine which of the models is the best fit for the data. However if you are simply looking for "deviation from an expected distribution" then this seems like overkill.
How to formally test for a "break" in a normal (or other) distribution I would split this problem into two subproblems: Estimate the parameters of a distribution to fit the data Perform outlier detection using the fitted distribution There are various ways of tackling
26,469
Norm of residuals to measure goodness of fit
Residuals are "acceptable" when they have, at least approximately, the following characteristics: They are not associated with the fitted values (there's no evident trend or relationship between them). They are centered around zero. Their distribution is symmetric. They contain no, or extremely few, unusually large or small values ("outliers"). They are not correlated with other variables you have in the data set. These are not criteria; they're guidelines. For instance, correlation with other variables is sometimes ok. The correlation merely suggests that the residuals could be further improved by including those variables in the model. But the first three points are as close to criteria as we can get in general, in the sense that a strong violation of any of the them is a clear indication the model is wrong. There are plenty of examples of evaluating residuals and goodness of fit in postings on this site; one recent one where the residuals look acceptable appears at Looking for estimates for my data using cumulative beta distribution. An example of clearly unacceptable residuals appears (inter alia) in the question at Testing homoscedasticity with Breusch-Pagan test. There, the distribution of residuals is asymmetric (there is a long tail in the negative range), the residuals vary in important ways with another variable (the "index"), and they exhibit a v-shaped association with the fitted values. A set of acceptable residuals is "good" when their typical size is small enough to alleviate any worries that your conclusions might be incorrect. "Small enough" depends on how the model will be used, but the main point is that you want to pay attention to how large the residuals can be, because that measures the typical deviation between the dependent variable and the fit. When your data are representative of a process or population, that typical deviation estimates how closely the model will predict the unsampled members of the population. For example, a model of survivorship from a medical procedure might express its residuals as percentage of survival time. If a typical size is 100%, the model may be almost worthless ("you might die any time between tomorrow and 20 years from now) but if it's 10%, the model is probably excellent for anybody ("people with your condition usually live between 9 and 11 years"). A 1 km residual in a spatial location model would be great for sending a satellite to Mars but could shipwreck boats in a harbor. Context matters when evaluating the goodness of fit. Several measures of residual size are in use, again depending on the purpose of the analysis. The commonest is an (adjusted) root mean square, which is almost always reported by least squares software. It would be naive and foolhardy to rely on this number without checking the guidelines for acceptability. Once you have confirmed the residuals are acceptable, though, this number is an effective way to evaluate and report the goodness of fit. Among the alternative measures of residual size, an excellent one is the "H-spread" of the residuals. (Split the set of residuals into an upper half and lower half. The H-spread is the difference between the median of the upper half and the median of the lower half. It is practically the same as the interquartile range of the residuals). This measure is not as sensitive to the most extreme residuals as the root mean square. Nevertheless, as indicated in the guideline about outliers, it's also a good idea to look at the sizes of the most positive and most negative residuals. Because it is mentioned elsewhere in this thread, let's look at $R^2$. This figure is related to the size of residuals, but the relation is indirect. As you can see from the formula, it depends on the total variation in the dependent variable, which in turn depends on how much the independent variables vary in the dataset. This makes it much less useful than directly examining the root mean square residual. $R^2$ values can also be erroneous: they can become extremely high due to the presence of even a single "high leverage" value in the data, giving a false impression of a good fit. Any decent measure of the typical residual size will not have this problem.
Norm of residuals to measure goodness of fit
Residuals are "acceptable" when they have, at least approximately, the following characteristics: They are not associated with the fitted values (there's no evident trend or relationship between them
Norm of residuals to measure goodness of fit Residuals are "acceptable" when they have, at least approximately, the following characteristics: They are not associated with the fitted values (there's no evident trend or relationship between them). They are centered around zero. Their distribution is symmetric. They contain no, or extremely few, unusually large or small values ("outliers"). They are not correlated with other variables you have in the data set. These are not criteria; they're guidelines. For instance, correlation with other variables is sometimes ok. The correlation merely suggests that the residuals could be further improved by including those variables in the model. But the first three points are as close to criteria as we can get in general, in the sense that a strong violation of any of the them is a clear indication the model is wrong. There are plenty of examples of evaluating residuals and goodness of fit in postings on this site; one recent one where the residuals look acceptable appears at Looking for estimates for my data using cumulative beta distribution. An example of clearly unacceptable residuals appears (inter alia) in the question at Testing homoscedasticity with Breusch-Pagan test. There, the distribution of residuals is asymmetric (there is a long tail in the negative range), the residuals vary in important ways with another variable (the "index"), and they exhibit a v-shaped association with the fitted values. A set of acceptable residuals is "good" when their typical size is small enough to alleviate any worries that your conclusions might be incorrect. "Small enough" depends on how the model will be used, but the main point is that you want to pay attention to how large the residuals can be, because that measures the typical deviation between the dependent variable and the fit. When your data are representative of a process or population, that typical deviation estimates how closely the model will predict the unsampled members of the population. For example, a model of survivorship from a medical procedure might express its residuals as percentage of survival time. If a typical size is 100%, the model may be almost worthless ("you might die any time between tomorrow and 20 years from now) but if it's 10%, the model is probably excellent for anybody ("people with your condition usually live between 9 and 11 years"). A 1 km residual in a spatial location model would be great for sending a satellite to Mars but could shipwreck boats in a harbor. Context matters when evaluating the goodness of fit. Several measures of residual size are in use, again depending on the purpose of the analysis. The commonest is an (adjusted) root mean square, which is almost always reported by least squares software. It would be naive and foolhardy to rely on this number without checking the guidelines for acceptability. Once you have confirmed the residuals are acceptable, though, this number is an effective way to evaluate and report the goodness of fit. Among the alternative measures of residual size, an excellent one is the "H-spread" of the residuals. (Split the set of residuals into an upper half and lower half. The H-spread is the difference between the median of the upper half and the median of the lower half. It is practically the same as the interquartile range of the residuals). This measure is not as sensitive to the most extreme residuals as the root mean square. Nevertheless, as indicated in the guideline about outliers, it's also a good idea to look at the sizes of the most positive and most negative residuals. Because it is mentioned elsewhere in this thread, let's look at $R^2$. This figure is related to the size of residuals, but the relation is indirect. As you can see from the formula, it depends on the total variation in the dependent variable, which in turn depends on how much the independent variables vary in the dataset. This makes it much less useful than directly examining the root mean square residual. $R^2$ values can also be erroneous: they can become extremely high due to the presence of even a single "high leverage" value in the data, giving a false impression of a good fit. Any decent measure of the typical residual size will not have this problem.
Norm of residuals to measure goodness of fit Residuals are "acceptable" when they have, at least approximately, the following characteristics: They are not associated with the fitted values (there's no evident trend or relationship between them
26,470
Norm of residuals to measure goodness of fit
Imagine that we didn't model anything and we didn't have any information on $x$ to use in our predictions. What would our guess of $y$ be? If we performed the following regression: $$ \begin{align*} y_i = \beta_0 + \epsilon_i \end{align*}$$ then $\hat{\beta}_0 = \bar{y}$. We can write $$ \begin{align*} y_i = \hat{y}_i + e_i, \end{align*}$$ where $e$ is the residual. Now, subtract $\bar{y}$ from both sides: $$ \begin{align*} y_i - \bar{y} = \hat{y}_i - \bar{y} + e_i. \end{align*}$$ Let's square both sides and sum over all $i$: $$ \begin{align*} \sum{\left(y_i - \bar{y}\right)^2} = \sum{\left(\hat{y}_i - \bar{y}\right)^2} + \sum{e_i^2} \end{align*}$$ (we used the fact that $\sum{\left(\hat{y}_i - \bar{y}\right)e_i} = 0$). } We create a statistic called $R^2$: $$ \begin{align*} R^2 = \frac{\sum{\left(\hat{y}_i - \bar{y}\right)^2}}{\sum{\left(y_i - \bar{y}\right)^2}} = 1 - \frac{\sum{e_i^2}}{\sum{\left(y_i - \bar{y}\right)^2}}. \end{align*}$$ This is the ratio of the variation predicted by our model to the variation not predicted by the mean alone, the simplest possible model of our outcome. Of the variation to be predicted, what fraction is predicted by your model? Alternatively, it is 1 minus the variation that remains relative to the total variation. Since OLS minimizes the sum of squared residuals, for any given data $y$, you can view OLS as choosing coefficients to maximize the $R^2$. Because our models include an intercept, the regression line goes through the point of means ($\bar{x}, \bar{y}$) and thus they predict no less than the mean alone. Using the derivation above and the fact that our regression includes an intercept term, $R^2$ is bounded between 0 and 1. Additionally, $R^2$ is equal to the sample correlation squared $\left(r_{x,y} \text{ for univariate regression and }r_{\hat{y},y} \text{ generally}\right)$. $R^2$ is the most common goodness-of-fit measure for regression, but it needs to come with a warning siren. All that $R^2$ tells you is the proportion of the overall variation that is predicted by your model. Note that I avoid the typical "is explained by your model" phrasing that people use. This implies causality and $R^2$ does not measure that. You can have a perfect model: $y$ is just its mean plus some error---that's the definition of $y$---but, the $R^2$ is 0. Your model is exactly right, but it has a small $R^2$ simply because you can't predict the variation of $y$ no matter what information (variables) you use. On the other hand, you can have a really high $R^2$, but have a completely wrong model when two things are correlated for some other reason. A time series example is if I regress my weight from ages 0 to 27 on the weight of someone else from ages 0 to 27. We'll get a high $R^2$ simply because our weights were trending up for a while as we grew and relatively plateaued later on; my weighted was not caused by or related to in any way the weight of the other person (see this question on spurious causation).
Norm of residuals to measure goodness of fit
Imagine that we didn't model anything and we didn't have any information on $x$ to use in our predictions. What would our guess of $y$ be? If we performed the following regression: $$ \begin{align*}
Norm of residuals to measure goodness of fit Imagine that we didn't model anything and we didn't have any information on $x$ to use in our predictions. What would our guess of $y$ be? If we performed the following regression: $$ \begin{align*} y_i = \beta_0 + \epsilon_i \end{align*}$$ then $\hat{\beta}_0 = \bar{y}$. We can write $$ \begin{align*} y_i = \hat{y}_i + e_i, \end{align*}$$ where $e$ is the residual. Now, subtract $\bar{y}$ from both sides: $$ \begin{align*} y_i - \bar{y} = \hat{y}_i - \bar{y} + e_i. \end{align*}$$ Let's square both sides and sum over all $i$: $$ \begin{align*} \sum{\left(y_i - \bar{y}\right)^2} = \sum{\left(\hat{y}_i - \bar{y}\right)^2} + \sum{e_i^2} \end{align*}$$ (we used the fact that $\sum{\left(\hat{y}_i - \bar{y}\right)e_i} = 0$). } We create a statistic called $R^2$: $$ \begin{align*} R^2 = \frac{\sum{\left(\hat{y}_i - \bar{y}\right)^2}}{\sum{\left(y_i - \bar{y}\right)^2}} = 1 - \frac{\sum{e_i^2}}{\sum{\left(y_i - \bar{y}\right)^2}}. \end{align*}$$ This is the ratio of the variation predicted by our model to the variation not predicted by the mean alone, the simplest possible model of our outcome. Of the variation to be predicted, what fraction is predicted by your model? Alternatively, it is 1 minus the variation that remains relative to the total variation. Since OLS minimizes the sum of squared residuals, for any given data $y$, you can view OLS as choosing coefficients to maximize the $R^2$. Because our models include an intercept, the regression line goes through the point of means ($\bar{x}, \bar{y}$) and thus they predict no less than the mean alone. Using the derivation above and the fact that our regression includes an intercept term, $R^2$ is bounded between 0 and 1. Additionally, $R^2$ is equal to the sample correlation squared $\left(r_{x,y} \text{ for univariate regression and }r_{\hat{y},y} \text{ generally}\right)$. $R^2$ is the most common goodness-of-fit measure for regression, but it needs to come with a warning siren. All that $R^2$ tells you is the proportion of the overall variation that is predicted by your model. Note that I avoid the typical "is explained by your model" phrasing that people use. This implies causality and $R^2$ does not measure that. You can have a perfect model: $y$ is just its mean plus some error---that's the definition of $y$---but, the $R^2$ is 0. Your model is exactly right, but it has a small $R^2$ simply because you can't predict the variation of $y$ no matter what information (variables) you use. On the other hand, you can have a really high $R^2$, but have a completely wrong model when two things are correlated for some other reason. A time series example is if I regress my weight from ages 0 to 27 on the weight of someone else from ages 0 to 27. We'll get a high $R^2$ simply because our weights were trending up for a while as we grew and relatively plateaued later on; my weighted was not caused by or related to in any way the weight of the other person (see this question on spurious causation).
Norm of residuals to measure goodness of fit Imagine that we didn't model anything and we didn't have any information on $x$ to use in our predictions. What would our guess of $y$ be? If we performed the following regression: $$ \begin{align*}
26,471
Why does bootstrapping the residuals from a mixed effects model yield anti-conservative confidence intervals?
Remember all bootstrap confidence intervals are only asymptotically at the stated confidence level. There are also a slew of possible methods for selecting bootstrap confidence intervals Efron's percentile method, Hall's percentile method, double bootstrap, bootstrap t, tilted bootstrap, BC, BCa and maybe a few more. You haven't told us which method you use. Schenker's paper in JASA 1985 showed that for certain chi square distributions the BC bootstrap confidence interval undercovered the advertised percentage. In small sample size problems this problem can be severe. LaBudde and I have two papers showing how in small samples even BCa can have very poor coverage when estimating a variance from a lognormal distribution and a similar problem exists for testing equality of two variances. This is just for a simple problem. I expect the same thing can happen with residuals from mixed models. In our new book "An Introduction to Bootstrap Methods with Applications to R" published by Wiley in 2011 we cover this topic in Section 3.7 and provide references. The surprise is that the percentile method sometimes does better than the higher order accurate BCa method, when the sample size is small.
Why does bootstrapping the residuals from a mixed effects model yield anti-conservative confidence i
Remember all bootstrap confidence intervals are only asymptotically at the stated confidence level. There are also a slew of possible methods for selecting bootstrap confidence intervals Efron's perc
Why does bootstrapping the residuals from a mixed effects model yield anti-conservative confidence intervals? Remember all bootstrap confidence intervals are only asymptotically at the stated confidence level. There are also a slew of possible methods for selecting bootstrap confidence intervals Efron's percentile method, Hall's percentile method, double bootstrap, bootstrap t, tilted bootstrap, BC, BCa and maybe a few more. You haven't told us which method you use. Schenker's paper in JASA 1985 showed that for certain chi square distributions the BC bootstrap confidence interval undercovered the advertised percentage. In small sample size problems this problem can be severe. LaBudde and I have two papers showing how in small samples even BCa can have very poor coverage when estimating a variance from a lognormal distribution and a similar problem exists for testing equality of two variances. This is just for a simple problem. I expect the same thing can happen with residuals from mixed models. In our new book "An Introduction to Bootstrap Methods with Applications to R" published by Wiley in 2011 we cover this topic in Section 3.7 and provide references. The surprise is that the percentile method sometimes does better than the higher order accurate BCa method, when the sample size is small.
Why does bootstrapping the residuals from a mixed effects model yield anti-conservative confidence i Remember all bootstrap confidence intervals are only asymptotically at the stated confidence level. There are also a slew of possible methods for selecting bootstrap confidence intervals Efron's perc
26,472
Comparing correlation coefficients
A general way to compare two correlation coefficients $\hat{\rho}_{1}, \hat{\rho}_{2}$ is to use Fisher's z-transform method, which says that ${\rm arctanh}(\hat{\rho})$ is approximately normal with mean ${\rm arctanh}(\rho)$ and standard deviation $1/\sqrt{n-3}$. If the samples are independent, then you transform each correlation coefficient and the difference between the two transformed correlations will be normal with mean ${\rm arctanh}(\rho_{1})-{\rm arctanh}(\rho_{2})$ and standard deviation $\sqrt{1/(n_{1}-3) + 1/(n_{2}-3)}$. From this you can form a $z$-statistic and do testing as you would in an ordinary two-sample $z$-test.
Comparing correlation coefficients
A general way to compare two correlation coefficients $\hat{\rho}_{1}, \hat{\rho}_{2}$ is to use Fisher's z-transform method, which says that ${\rm arctanh}(\hat{\rho})$ is approximately normal with m
Comparing correlation coefficients A general way to compare two correlation coefficients $\hat{\rho}_{1}, \hat{\rho}_{2}$ is to use Fisher's z-transform method, which says that ${\rm arctanh}(\hat{\rho})$ is approximately normal with mean ${\rm arctanh}(\rho)$ and standard deviation $1/\sqrt{n-3}$. If the samples are independent, then you transform each correlation coefficient and the difference between the two transformed correlations will be normal with mean ${\rm arctanh}(\rho_{1})-{\rm arctanh}(\rho_{2})$ and standard deviation $\sqrt{1/(n_{1}-3) + 1/(n_{2}-3)}$. From this you can form a $z$-statistic and do testing as you would in an ordinary two-sample $z$-test.
Comparing correlation coefficients A general way to compare two correlation coefficients $\hat{\rho}_{1}, \hat{\rho}_{2}$ is to use Fisher's z-transform method, which says that ${\rm arctanh}(\hat{\rho})$ is approximately normal with m
26,473
Comparing correlation coefficients
Though @Macro's answer is nice, it does require an assumption about the (in)dependence of the statistics. Another approach would be to use bootstrapping. The idea would be to keep one one variable fixed and shuffle the other variable, calculate the correlation for each of your samples, and take their difference. Repeat many times to get a distribution and use this distribution to test the hypothesis that the correlations are the same. The structure of your data set isn't that clear to me, so it's hard to provide more details.
Comparing correlation coefficients
Though @Macro's answer is nice, it does require an assumption about the (in)dependence of the statistics. Another approach would be to use bootstrapping. The idea would be to keep one one variable fix
Comparing correlation coefficients Though @Macro's answer is nice, it does require an assumption about the (in)dependence of the statistics. Another approach would be to use bootstrapping. The idea would be to keep one one variable fixed and shuffle the other variable, calculate the correlation for each of your samples, and take their difference. Repeat many times to get a distribution and use this distribution to test the hypothesis that the correlations are the same. The structure of your data set isn't that clear to me, so it's hard to provide more details.
Comparing correlation coefficients Though @Macro's answer is nice, it does require an assumption about the (in)dependence of the statistics. Another approach would be to use bootstrapping. The idea would be to keep one one variable fix
26,474
Expected Value and Variance of Estimation of Slope Parameter $\beta_1$ in Simple Linear Regression
$E\left(\frac{\sum (x_i - \bar{x})\beta_1 x_i}{S_{xx}}\right)$ = $\frac{\sum (x_i - \bar{x})\beta_1 x_i}{S_{xx}}$ because everything is constant. The rest is just algebra. Evidently you need to show $\sum (x_i - \bar{x}) x_i = S_{xx}$. Looking at the definition of $S_{xx}$ and comparing the two sides leads one to suspect $\sum(x_i - \bar{x}) \bar{x} = 0$. This follows easily from the definition of $\bar{x}$. $Var\left(\frac{\sum (x_i - \bar{x})\epsilon}{S_{xx}}\right)$ = $\sum \left[\frac{(x_i - \bar{x})^2}{S_{xx}^2}\sigma^2\right] $. It simplifies, using the definition of $S_{xx}$, to the desired result.
Expected Value and Variance of Estimation of Slope Parameter $\beta_1$ in Simple Linear Regression
$E\left(\frac{\sum (x_i - \bar{x})\beta_1 x_i}{S_{xx}}\right)$ = $\frac{\sum (x_i - \bar{x})\beta_1 x_i}{S_{xx}}$ because everything is constant. The rest is just algebra. Evidently you need to show
Expected Value and Variance of Estimation of Slope Parameter $\beta_1$ in Simple Linear Regression $E\left(\frac{\sum (x_i - \bar{x})\beta_1 x_i}{S_{xx}}\right)$ = $\frac{\sum (x_i - \bar{x})\beta_1 x_i}{S_{xx}}$ because everything is constant. The rest is just algebra. Evidently you need to show $\sum (x_i - \bar{x}) x_i = S_{xx}$. Looking at the definition of $S_{xx}$ and comparing the two sides leads one to suspect $\sum(x_i - \bar{x}) \bar{x} = 0$. This follows easily from the definition of $\bar{x}$. $Var\left(\frac{\sum (x_i - \bar{x})\epsilon}{S_{xx}}\right)$ = $\sum \left[\frac{(x_i - \bar{x})^2}{S_{xx}^2}\sigma^2\right] $. It simplifies, using the definition of $S_{xx}$, to the desired result.
Expected Value and Variance of Estimation of Slope Parameter $\beta_1$ in Simple Linear Regression $E\left(\frac{\sum (x_i - \bar{x})\beta_1 x_i}{S_{xx}}\right)$ = $\frac{\sum (x_i - \bar{x})\beta_1 x_i}{S_{xx}}$ because everything is constant. The rest is just algebra. Evidently you need to show
26,475
How to generate random correlation matrix that has approximately normally distributed off-diagonal entries with given standard deviation?
I have first provided what I now believe is a sub-optimal answer; therefore I edited my answer to start with a better suggestion. Using vine method In this thread: How to efficiently generate random positive-semidefinite correlation matrices? -- I described and provided the code for two efficient algorithms of generating random correlation matrices. Both come from a paper by Lewandowski, Kurowicka, and Joe (2009). Please see my answer there for a lot of figures and matlab code. Here I would only like to say that the vine method allows to generate random correlation matrices with any distribution of partial correlations (note the word "partial") and can be used to generate correlation matrices with large off-diagonal values. Here is the relevant figure from that thread: The only thing that changes between subplots, is one parameter that controls how much the distribution of partial correlations is concentrated around $\pm 1$. As OP was asking for an approximately normal distribution off-diagonal, here is the plot with histograms of the off-diagonal elements (for the same matrices as above): I think this distributions are reasonably "normal", and one can see how the standard deviation gradually increases. I should add that the algorithm is very fast. See linked thread for the details. My original answer A straight-forward modification of your method might do the trick (depending on how close you want the distribution to be to normal). This answer was inspired by @cardinal's comments above and by @psarka's answer to my own question How to generate a large full-rank random correlation matrix with some strong correlations present? The trick is to make samples of your $\mathbf X$ correlated (not features, but samples). Here is an example: I generate random matrix $\mathbf X$ of $1000 \times 100$ size (all elements from standard normal), and then add a random number from $[-a/2, a/2]$ to each row, for $a=0,1,2,5$. For $a=0$ the correlation matrix $\mathbf X^\top \mathbf X$ (after standardizing the features) will have off-diagonal elements approximately normally distributed with standard deviation $1/\sqrt{1000}$. For $a>0$, I compute correlation matrix without centering the variables (this preserves the inserted correlations), and the standard deviation of the off-diagonal elements grow with $a$ as shown on this figure (rows correspond to $a=0,1,2,5$): All these matrices are of course positive definite. Here is the matlab code: offsets = [0 1 2 5]; n = 1000; p = 100; rng(42) %// random seed figure for offset = 1:length(offsets) X = randn(n,p); for i=1:p X(:,i) = X(:,i) + (rand-0.5) * offsets(offset); end C = 1/(n-1)*transpose(X)*X; %// covariance matrix (non-centred!) %// convert to correlation d = diag(C); C = diag(1./sqrt(d))*C*diag(1./sqrt(d)); %// displaying C subplot(length(offsets),3,(offset-1)*3+1) imagesc(C, [-1 1]) %// histogram of the off-diagonal elements subplot(length(offsets),3,(offset-1)*3+2) offd = C(logical(ones(size(C))-eye(size(C)))); hist(offd) xlim([-1 1]) %// QQ-plot to check the normality subplot(length(offsets),3,(offset-1)*3+3) qqplot(offd) %// eigenvalues eigv = eig(C); display([num2str(min(eigv),2) ' ... ' num2str(max(eigv),2)]) end The output of this code (minimum and maximum eigenvalues) is: 0.51 ... 1.7 0.44 ... 8.6 0.32 ... 22 0.1 ... 48
How to generate random correlation matrix that has approximately normally distributed off-diagonal e
I have first provided what I now believe is a sub-optimal answer; therefore I edited my answer to start with a better suggestion. Using vine method In this thread: How to efficiently generate random
How to generate random correlation matrix that has approximately normally distributed off-diagonal entries with given standard deviation? I have first provided what I now believe is a sub-optimal answer; therefore I edited my answer to start with a better suggestion. Using vine method In this thread: How to efficiently generate random positive-semidefinite correlation matrices? -- I described and provided the code for two efficient algorithms of generating random correlation matrices. Both come from a paper by Lewandowski, Kurowicka, and Joe (2009). Please see my answer there for a lot of figures and matlab code. Here I would only like to say that the vine method allows to generate random correlation matrices with any distribution of partial correlations (note the word "partial") and can be used to generate correlation matrices with large off-diagonal values. Here is the relevant figure from that thread: The only thing that changes between subplots, is one parameter that controls how much the distribution of partial correlations is concentrated around $\pm 1$. As OP was asking for an approximately normal distribution off-diagonal, here is the plot with histograms of the off-diagonal elements (for the same matrices as above): I think this distributions are reasonably "normal", and one can see how the standard deviation gradually increases. I should add that the algorithm is very fast. See linked thread for the details. My original answer A straight-forward modification of your method might do the trick (depending on how close you want the distribution to be to normal). This answer was inspired by @cardinal's comments above and by @psarka's answer to my own question How to generate a large full-rank random correlation matrix with some strong correlations present? The trick is to make samples of your $\mathbf X$ correlated (not features, but samples). Here is an example: I generate random matrix $\mathbf X$ of $1000 \times 100$ size (all elements from standard normal), and then add a random number from $[-a/2, a/2]$ to each row, for $a=0,1,2,5$. For $a=0$ the correlation matrix $\mathbf X^\top \mathbf X$ (after standardizing the features) will have off-diagonal elements approximately normally distributed with standard deviation $1/\sqrt{1000}$. For $a>0$, I compute correlation matrix without centering the variables (this preserves the inserted correlations), and the standard deviation of the off-diagonal elements grow with $a$ as shown on this figure (rows correspond to $a=0,1,2,5$): All these matrices are of course positive definite. Here is the matlab code: offsets = [0 1 2 5]; n = 1000; p = 100; rng(42) %// random seed figure for offset = 1:length(offsets) X = randn(n,p); for i=1:p X(:,i) = X(:,i) + (rand-0.5) * offsets(offset); end C = 1/(n-1)*transpose(X)*X; %// covariance matrix (non-centred!) %// convert to correlation d = diag(C); C = diag(1./sqrt(d))*C*diag(1./sqrt(d)); %// displaying C subplot(length(offsets),3,(offset-1)*3+1) imagesc(C, [-1 1]) %// histogram of the off-diagonal elements subplot(length(offsets),3,(offset-1)*3+2) offd = C(logical(ones(size(C))-eye(size(C)))); hist(offd) xlim([-1 1]) %// QQ-plot to check the normality subplot(length(offsets),3,(offset-1)*3+3) qqplot(offd) %// eigenvalues eigv = eig(C); display([num2str(min(eigv),2) ' ... ' num2str(max(eigv),2)]) end The output of this code (minimum and maximum eigenvalues) is: 0.51 ... 1.7 0.44 ... 8.6 0.32 ... 22 0.1 ... 48
How to generate random correlation matrix that has approximately normally distributed off-diagonal e I have first provided what I now believe is a sub-optimal answer; therefore I edited my answer to start with a better suggestion. Using vine method In this thread: How to efficiently generate random
26,476
How to generate random correlation matrix that has approximately normally distributed off-diagonal entries with given standard deviation?
You might be interested in some of the code at the following link: Correlation and Co-integration
How to generate random correlation matrix that has approximately normally distributed off-diagonal e
You might be interested in some of the code at the following link: Correlation and Co-integration
How to generate random correlation matrix that has approximately normally distributed off-diagonal entries with given standard deviation? You might be interested in some of the code at the following link: Correlation and Co-integration
How to generate random correlation matrix that has approximately normally distributed off-diagonal e You might be interested in some of the code at the following link: Correlation and Co-integration
26,477
How to generate random correlation matrix that has approximately normally distributed off-diagonal entries with given standard deviation?
If you are trying to generate random correlation matrices, consider sampling from the Wishart distribution. This following question provides information the Wishart distribution as well as advice on how to sample: How to efficiently generate random positive-semidefinite correlation matrices?
How to generate random correlation matrix that has approximately normally distributed off-diagonal e
If you are trying to generate random correlation matrices, consider sampling from the Wishart distribution. This following question provides information the Wishart distribution as well as advice on h
How to generate random correlation matrix that has approximately normally distributed off-diagonal entries with given standard deviation? If you are trying to generate random correlation matrices, consider sampling from the Wishart distribution. This following question provides information the Wishart distribution as well as advice on how to sample: How to efficiently generate random positive-semidefinite correlation matrices?
How to generate random correlation matrix that has approximately normally distributed off-diagonal e If you are trying to generate random correlation matrices, consider sampling from the Wishart distribution. This following question provides information the Wishart distribution as well as advice on h
26,478
How to generate random correlation matrix that has approximately normally distributed off-diagonal entries with given standard deviation?
This is not a very sophisticated answer, but I can't help but think it's still a good answer... If your motivation is that correlation parameters produced by time series data tend to look normal, why not just simulate time series data, calculate the correlation parameters and use those? You may have a good reason for not doing this, but it's not clear to me from your question.
How to generate random correlation matrix that has approximately normally distributed off-diagonal e
This is not a very sophisticated answer, but I can't help but think it's still a good answer... If your motivation is that correlation parameters produced by time series data tend to look normal, why
How to generate random correlation matrix that has approximately normally distributed off-diagonal entries with given standard deviation? This is not a very sophisticated answer, but I can't help but think it's still a good answer... If your motivation is that correlation parameters produced by time series data tend to look normal, why not just simulate time series data, calculate the correlation parameters and use those? You may have a good reason for not doing this, but it's not clear to me from your question.
How to generate random correlation matrix that has approximately normally distributed off-diagonal e This is not a very sophisticated answer, but I can't help but think it's still a good answer... If your motivation is that correlation parameters produced by time series data tend to look normal, why
26,479
Calculation of seasonality indexes for complex seasonality
For the kinds of seasonality you describe, the dummy variable approach is probably best. However, this is easier to handle in an ARIMA framework than an exponential smoothing framework. \begin{aligned} y_t &= a + b_1D_{t,1} + \cdots + b_mD_{t,m} + N_t\\ N_t &\sim \text{ARIMA} \end{aligned} where each $D_{t,k}$ variable corresponds to one of the holiday or festival events. This is how the arima function in R will fit regression variables (as a regression with ARIMA errors, not as an ARIMAX model). If you really want to stick with the exponential smoothing framework, there is a discussion of how to include covariates in my 2008 book on exponential smoothing. You might also look at my recent paper on exponential smoothing with complex seasonality although the types of seasonal complications we discuss there are more difficult than the moving festival kind that you describe.
Calculation of seasonality indexes for complex seasonality
For the kinds of seasonality you describe, the dummy variable approach is probably best. However, this is easier to handle in an ARIMA framework than an exponential smoothing framework. \begin{aligne
Calculation of seasonality indexes for complex seasonality For the kinds of seasonality you describe, the dummy variable approach is probably best. However, this is easier to handle in an ARIMA framework than an exponential smoothing framework. \begin{aligned} y_t &= a + b_1D_{t,1} + \cdots + b_mD_{t,m} + N_t\\ N_t &\sim \text{ARIMA} \end{aligned} where each $D_{t,k}$ variable corresponds to one of the holiday or festival events. This is how the arima function in R will fit regression variables (as a regression with ARIMA errors, not as an ARIMAX model). If you really want to stick with the exponential smoothing framework, there is a discussion of how to include covariates in my 2008 book on exponential smoothing. You might also look at my recent paper on exponential smoothing with complex seasonality although the types of seasonal complications we discuss there are more difficult than the moving festival kind that you describe.
Calculation of seasonality indexes for complex seasonality For the kinds of seasonality you describe, the dummy variable approach is probably best. However, this is easier to handle in an ARIMA framework than an exponential smoothing framework. \begin{aligne
26,480
Calculation of seasonality indexes for complex seasonality
A simple fix would be to include events dummies in your specification: $(1) \hat{y_t}=\lambda_1 y_{t-1}+...+\lambda_k y_{t-k}+\phi_1 D_{t,1}+\phi_m D_{t,m}$ where $D_{t,m}$ is an indicator taking value $1$ if week $t$ has event $m$ (say Mardi gras) and 0 otherwise, for all $m$ events you deem important. The first part of the specification $\lambda_1 y_{t-1}+...+\lambda_k y_{t-k}$ is essentially a exponential smoothers but with weight varying as a function of lags (and estimated by OLS). This pre-supposes that you have at least 20 observations for each event (i.e. 20 'mardi gras'). If this is not the case, you can try to bundle some events together (say mardi gras and labour day). The R to fit (1) is rather straighforward, assuming dlsales is stationnary and D is your matrix of dummy variables : fit<-arima(dlsales,order=c(4,0,0),seasonal = list(order = c(1, 0, 0),period=52),xreg = D) Starting from here, you can ask more specific questions about the part of my answer that are not familiar to you (i don't know what your level is in statistics).
Calculation of seasonality indexes for complex seasonality
A simple fix would be to include events dummies in your specification: $(1) \hat{y_t}=\lambda_1 y_{t-1}+...+\lambda_k y_{t-k}+\phi_1 D_{t,1}+\phi_m D_{t,m}$ where $D_{t,m}$ is an indicator taking valu
Calculation of seasonality indexes for complex seasonality A simple fix would be to include events dummies in your specification: $(1) \hat{y_t}=\lambda_1 y_{t-1}+...+\lambda_k y_{t-k}+\phi_1 D_{t,1}+\phi_m D_{t,m}$ where $D_{t,m}$ is an indicator taking value $1$ if week $t$ has event $m$ (say Mardi gras) and 0 otherwise, for all $m$ events you deem important. The first part of the specification $\lambda_1 y_{t-1}+...+\lambda_k y_{t-k}$ is essentially a exponential smoothers but with weight varying as a function of lags (and estimated by OLS). This pre-supposes that you have at least 20 observations for each event (i.e. 20 'mardi gras'). If this is not the case, you can try to bundle some events together (say mardi gras and labour day). The R to fit (1) is rather straighforward, assuming dlsales is stationnary and D is your matrix of dummy variables : fit<-arima(dlsales,order=c(4,0,0),seasonal = list(order = c(1, 0, 0),period=52),xreg = D) Starting from here, you can ask more specific questions about the part of my answer that are not familiar to you (i don't know what your level is in statistics).
Calculation of seasonality indexes for complex seasonality A simple fix would be to include events dummies in your specification: $(1) \hat{y_t}=\lambda_1 y_{t-1}+...+\lambda_k y_{t-k}+\phi_1 D_{t,1}+\phi_m D_{t,m}$ where $D_{t,m}$ is an indicator taking valu
26,481
Whether to use robust linear regression or bootstrapping when there is heteroscedasticity?
In economics, the Eicker-White or "robust" standard errors are typically reported. Bootstrapping (unfortunately, I'd say) is less common. I'd say that the robust estimates are the standard version.
Whether to use robust linear regression or bootstrapping when there is heteroscedasticity?
In economics, the Eicker-White or "robust" standard errors are typically reported. Bootstrapping (unfortunately, I'd say) is less common. I'd say that the robust estimates are the standard version.
Whether to use robust linear regression or bootstrapping when there is heteroscedasticity? In economics, the Eicker-White or "robust" standard errors are typically reported. Bootstrapping (unfortunately, I'd say) is less common. I'd say that the robust estimates are the standard version.
Whether to use robust linear regression or bootstrapping when there is heteroscedasticity? In economics, the Eicker-White or "robust" standard errors are typically reported. Bootstrapping (unfortunately, I'd say) is less common. I'd say that the robust estimates are the standard version.
26,482
Whether to use robust linear regression or bootstrapping when there is heteroscedasticity?
You could use generalized least squares, such as the gls() function from the nlme package, which allows you to specify a variance function using the weight argument.
Whether to use robust linear regression or bootstrapping when there is heteroscedasticity?
You could use generalized least squares, such as the gls() function from the nlme package, which allows you to specify a variance function using the weight argument.
Whether to use robust linear regression or bootstrapping when there is heteroscedasticity? You could use generalized least squares, such as the gls() function from the nlme package, which allows you to specify a variance function using the weight argument.
Whether to use robust linear regression or bootstrapping when there is heteroscedasticity? You could use generalized least squares, such as the gls() function from the nlme package, which allows you to specify a variance function using the weight argument.
26,483
What is the conceptual difference between posterior and likelihood? [duplicate]
First, to have a posterior distribution for $\theta$, $\theta$ must be (modeled as) a random variable. For the likelihood function that is not necessary. So this is deeper than the comment (by @gazza89) saying The likelihood is a pdf, it's just normalised w.r.t all possible data outcomes, and the posterior is a pdf, but it's normalised w.r.t all possible parameter values Even if the likelihood was (or could be normalized too, it is not always possible) to integrate to one, that is not enough to make it into a pdf (probability density function). A pdf must be the pdf of some random variable and if $\theta$ is not modeled as a random variable, then it cannot have a pdf, period. So conceptually it is quite clear-cut: If $\theta$ is a random variable (probably in some Bayesian model) then it can have a posterior, and it can have a likelihood function. Even if those two functions should be numerically equal (as for instance if the prior is uniform), they are distict mathematical entities. If $\theta$ is not (modeled as) a random variable the problem does not arise, only the likelihood function can be defined. You say And the likelihood is "the likelihood of θ having generated D" but that is not a good way of thinking about it. Likelihood tells you the probability (under the model ...) of the data if data was generated according to that value of $\theta$. There is no "probability of $\theta$" involved. To get that you need some extra assumptions, a Bayesian probability model. To understand likelihood better see all the answers to Maximum Likelihood Estimation (MLE) in layman terms.
What is the conceptual difference between posterior and likelihood? [duplicate]
First, to have a posterior distribution for $\theta$, $\theta$ must be (modeled as) a random variable. For the likelihood function that is not necessary. So this is deeper than the comment (by @gazza8
What is the conceptual difference between posterior and likelihood? [duplicate] First, to have a posterior distribution for $\theta$, $\theta$ must be (modeled as) a random variable. For the likelihood function that is not necessary. So this is deeper than the comment (by @gazza89) saying The likelihood is a pdf, it's just normalised w.r.t all possible data outcomes, and the posterior is a pdf, but it's normalised w.r.t all possible parameter values Even if the likelihood was (or could be normalized too, it is not always possible) to integrate to one, that is not enough to make it into a pdf (probability density function). A pdf must be the pdf of some random variable and if $\theta$ is not modeled as a random variable, then it cannot have a pdf, period. So conceptually it is quite clear-cut: If $\theta$ is a random variable (probably in some Bayesian model) then it can have a posterior, and it can have a likelihood function. Even if those two functions should be numerically equal (as for instance if the prior is uniform), they are distict mathematical entities. If $\theta$ is not (modeled as) a random variable the problem does not arise, only the likelihood function can be defined. You say And the likelihood is "the likelihood of θ having generated D" but that is not a good way of thinking about it. Likelihood tells you the probability (under the model ...) of the data if data was generated according to that value of $\theta$. There is no "probability of $\theta$" involved. To get that you need some extra assumptions, a Bayesian probability model. To understand likelihood better see all the answers to Maximum Likelihood Estimation (MLE) in layman terms.
What is the conceptual difference between posterior and likelihood? [duplicate] First, to have a posterior distribution for $\theta$, $\theta$ must be (modeled as) a random variable. For the likelihood function that is not necessary. So this is deeper than the comment (by @gazza8
26,484
What is the conceptual difference between posterior and likelihood? [duplicate]
To put simply, likelihood is "the likelihood of $\theta$ having generated $\mathcal{D}$" and posterior is essentially "the likelihood of $\theta$ having generated $\mathcal{D}$" further multiplied by the prior distribution of $\theta$. If the prior distribution is flat (or non-informative), likelihood is exactly the same as posterior.
What is the conceptual difference between posterior and likelihood? [duplicate]
To put simply, likelihood is "the likelihood of $\theta$ having generated $\mathcal{D}$" and posterior is essentially "the likelihood of $\theta$ having generated $\mathcal{D}$" further multiplied by
What is the conceptual difference between posterior and likelihood? [duplicate] To put simply, likelihood is "the likelihood of $\theta$ having generated $\mathcal{D}$" and posterior is essentially "the likelihood of $\theta$ having generated $\mathcal{D}$" further multiplied by the prior distribution of $\theta$. If the prior distribution is flat (or non-informative), likelihood is exactly the same as posterior.
What is the conceptual difference between posterior and likelihood? [duplicate] To put simply, likelihood is "the likelihood of $\theta$ having generated $\mathcal{D}$" and posterior is essentially "the likelihood of $\theta$ having generated $\mathcal{D}$" further multiplied by
26,485
The No-Free-Lunch Theorem and K-NN consistency
The way I understand the NFL theorem is that there is no learning algorithm that's better than the rest in every task. This isn't however a theorem in the clear mathematical sense that it has a proof, rather an empirical observation. Similar to what you said for the kNN, there is also the Universal Approximation Theorem for Neural Networks, which states that given a 2-layer neural network, we can approximate any function with any arbitrary error. Now, how does this not break the NFL? It basically states that you can solve any conceivable problem with a simple 2-layer NN. The reason is that while, theoretically NNs can approximate anything, in practice its very hard to teach them to approximate anything. That's why for some tasks, other algorithms are preferable. A more practical way to interpret NFL is the following: There is no way of determine a-priori which algorithm will do best for a given task.
The No-Free-Lunch Theorem and K-NN consistency
The way I understand the NFL theorem is that there is no learning algorithm that's better than the rest in every task. This isn't however a theorem in the clear mathematical sense that it has a proof,
The No-Free-Lunch Theorem and K-NN consistency The way I understand the NFL theorem is that there is no learning algorithm that's better than the rest in every task. This isn't however a theorem in the clear mathematical sense that it has a proof, rather an empirical observation. Similar to what you said for the kNN, there is also the Universal Approximation Theorem for Neural Networks, which states that given a 2-layer neural network, we can approximate any function with any arbitrary error. Now, how does this not break the NFL? It basically states that you can solve any conceivable problem with a simple 2-layer NN. The reason is that while, theoretically NNs can approximate anything, in practice its very hard to teach them to approximate anything. That's why for some tasks, other algorithms are preferable. A more practical way to interpret NFL is the following: There is no way of determine a-priori which algorithm will do best for a given task.
The No-Free-Lunch Theorem and K-NN consistency The way I understand the NFL theorem is that there is no learning algorithm that's better than the rest in every task. This isn't however a theorem in the clear mathematical sense that it has a proof,
26,486
The No-Free-Lunch Theorem and K-NN consistency
The answer to this question is already in the text of the question: "Assume $\mu$ has a density", which means the statement is only valid when the distribution $\mu(X,Y)$ is absolutely continuous. Hence NFL does not apply here. To expand on this point, NFL theorem says that (see eg. 7.2 in Devroye book): "given any classification rule, there exists a distribution such that the excess risk is large." Intuitively, NFL implies that inductive bias is unavoidable and any consistency result regarding the performance of a classifier must be accompanied with certain assumptions on the distribution of data. These assumptions are required to exclude those "bad" distributions that result in large excess risk. All consistency results for local averaging methods (histogram, k-NN, kernel) require absolute continuity of distribution of $(X,Y)$. Sometimes this assumption is stated in terms of continuity of the posterior probability function $\eta(x) = \mathbb{Pr}(Y=1\mid X)$. Such restrictions are very much necessary, since a local averaging method relies on labels varying "smoothly" within the feature space. In other words, two data points that are close with respect to some distance metric should have labels that are also close with high probability. Local averaging methods, such as nearest-neighbor, utilize the neighborhood of a test point to make a decision about its label. Therefore, a bad distribution for k-NN would be one where the conditional distribution function $\eta(X)$ is very rough and the labels of the neighbors are no longer useful. The NFL theorem is about the existence of such bad distributions, while consistency results are specialized to avoid such bad distributions.
The No-Free-Lunch Theorem and K-NN consistency
The answer to this question is already in the text of the question: "Assume $\mu$ has a density", which means the statement is only valid when the distribution $\mu(X,Y)$ is absolutely continuous. Hen
The No-Free-Lunch Theorem and K-NN consistency The answer to this question is already in the text of the question: "Assume $\mu$ has a density", which means the statement is only valid when the distribution $\mu(X,Y)$ is absolutely continuous. Hence NFL does not apply here. To expand on this point, NFL theorem says that (see eg. 7.2 in Devroye book): "given any classification rule, there exists a distribution such that the excess risk is large." Intuitively, NFL implies that inductive bias is unavoidable and any consistency result regarding the performance of a classifier must be accompanied with certain assumptions on the distribution of data. These assumptions are required to exclude those "bad" distributions that result in large excess risk. All consistency results for local averaging methods (histogram, k-NN, kernel) require absolute continuity of distribution of $(X,Y)$. Sometimes this assumption is stated in terms of continuity of the posterior probability function $\eta(x) = \mathbb{Pr}(Y=1\mid X)$. Such restrictions are very much necessary, since a local averaging method relies on labels varying "smoothly" within the feature space. In other words, two data points that are close with respect to some distance metric should have labels that are also close with high probability. Local averaging methods, such as nearest-neighbor, utilize the neighborhood of a test point to make a decision about its label. Therefore, a bad distribution for k-NN would be one where the conditional distribution function $\eta(X)$ is very rough and the labels of the neighbors are no longer useful. The NFL theorem is about the existence of such bad distributions, while consistency results are specialized to avoid such bad distributions.
The No-Free-Lunch Theorem and K-NN consistency The answer to this question is already in the text of the question: "Assume $\mu$ has a density", which means the statement is only valid when the distribution $\mu(X,Y)$ is absolutely continuous. Hen
26,487
Does Mercer's theorem work in reverse?
Does Mercer's theorem work in reverse? Not in all cases. Wikipedia: "In mathematics, specifically functional analysis, Mercer's theorem is a representation of a symmetric positive-definite function on a square as a sum of a convergent sequence of product functions. This theorem, presented in (Mercer 1909), is one of the most notable results of the work of James Mercer. It is an important theoretical tool in the theory of integral equations; it is used in the Hilbert space theory of stochastic processes, for example the Karhunen–Loève theorem; and it is also used to characterize a symmetric positive semi-definite kernel. It's a 'many to one mapping' on a Hilbert space. - a gross oversimplification would be to describe it as a hash or checksum that you can test against a file to determine identity or not. More technical explanation: Disintegration theorem "In mathematics, the disintegration theorem is a result in measure theory and probability theory. It rigorously defines the idea of a non-trivial "restriction" of a measure to a measure zero subset of the measure space in question. It is related to the existence of conditional probability measures. In a sense, "disintegration" is the opposite process to the construction of a product measure.". See also: "The Fubini–Tonelli theorem", "Hinge Loss", "Loss Function", and "How Good Is a Kernel When Used as a Similarity Measure?" (June 2007) by Nathan Srebro, the abstract: "Abstract. Recently, Balcan and Blum suggested a theory of learning based on general similarity functions, instead of positive semi-definite kernels. We study the gap between the learning guarantees based on kernel-based learning, and those that can be obtained by using the kernel as a similarity function, which was left open by Balcan and Blum. We provide a significantly improved bound on how good a kernel function is when used as a similarity function, and extend the result also to the more practically relevant hinge-loss rather then zero-one-error-rate. Furthermore, we show that this bound is tight, and hence establish that there is in-fact a real gap between the traditional kernel-based notion of margin and the newer similarity-based notion.". A colleague has a function $s$ and for our purposes it is a black-box. See: kernels and similarity (in R) It's a black box so you don't know for certain which kernel is used, if it's kernel based, and you don't know the details of the implementation of the kernel once you think you know which one it is. See: Equation of rbfKernel in kernlab is different from the standard?. On the other hand, this sounds kinda crazy. It is quick and effective, under a restricted set of circumstances. Like a hammer, if you carry a hammer with you will people call you crazy? "Kernel methods owe their name to the use of kernel functions, which enable them to operate in a high-dimensional, implicit feature space without ever computing the coordinates of the data in that space, but rather by simply computing the inner products between the images of all pairs of data in the feature space. This operation is often computationally cheaper than the explicit computation of the coordinates. This approach is called the "kernel trick". Kernel functions have been introduced for sequence data, graphs, text, images, as well as vectors.". Lesson: You (sometimes) get what you pay for. So my questions is "Does there exist an $f$ such that $f(s(a,b))=d(a,b)$ for $d$ some distance metric given these properties on $s$, and what is that $f$?" Many, see links above, "Popular Kernel Functions", RBF, and here's one (expensive) example: "A Likelihood Ratio Distance Measure for the Similarity Between the Fourier Transform of Time Series" (2005), by Janacek, Bagnall and Powell. If $f$ doesn't exist in these general circumstances on $s$, is there an additional set of requirements for which $f$ exists? Different spaces and methods can better target comparison (and disintegration) of specific problems, there are many methods for the Hilbert space alone. Yes, the list is big, see the links above and (for one example): Reproducing kernel Hilbert space.
Does Mercer's theorem work in reverse?
Does Mercer's theorem work in reverse? Not in all cases. Wikipedia: "In mathematics, specifically functional analysis, Mercer's theorem is a representation of a symmetric positive-definite function o
Does Mercer's theorem work in reverse? Does Mercer's theorem work in reverse? Not in all cases. Wikipedia: "In mathematics, specifically functional analysis, Mercer's theorem is a representation of a symmetric positive-definite function on a square as a sum of a convergent sequence of product functions. This theorem, presented in (Mercer 1909), is one of the most notable results of the work of James Mercer. It is an important theoretical tool in the theory of integral equations; it is used in the Hilbert space theory of stochastic processes, for example the Karhunen–Loève theorem; and it is also used to characterize a symmetric positive semi-definite kernel. It's a 'many to one mapping' on a Hilbert space. - a gross oversimplification would be to describe it as a hash or checksum that you can test against a file to determine identity or not. More technical explanation: Disintegration theorem "In mathematics, the disintegration theorem is a result in measure theory and probability theory. It rigorously defines the idea of a non-trivial "restriction" of a measure to a measure zero subset of the measure space in question. It is related to the existence of conditional probability measures. In a sense, "disintegration" is the opposite process to the construction of a product measure.". See also: "The Fubini–Tonelli theorem", "Hinge Loss", "Loss Function", and "How Good Is a Kernel When Used as a Similarity Measure?" (June 2007) by Nathan Srebro, the abstract: "Abstract. Recently, Balcan and Blum suggested a theory of learning based on general similarity functions, instead of positive semi-definite kernels. We study the gap between the learning guarantees based on kernel-based learning, and those that can be obtained by using the kernel as a similarity function, which was left open by Balcan and Blum. We provide a significantly improved bound on how good a kernel function is when used as a similarity function, and extend the result also to the more practically relevant hinge-loss rather then zero-one-error-rate. Furthermore, we show that this bound is tight, and hence establish that there is in-fact a real gap between the traditional kernel-based notion of margin and the newer similarity-based notion.". A colleague has a function $s$ and for our purposes it is a black-box. See: kernels and similarity (in R) It's a black box so you don't know for certain which kernel is used, if it's kernel based, and you don't know the details of the implementation of the kernel once you think you know which one it is. See: Equation of rbfKernel in kernlab is different from the standard?. On the other hand, this sounds kinda crazy. It is quick and effective, under a restricted set of circumstances. Like a hammer, if you carry a hammer with you will people call you crazy? "Kernel methods owe their name to the use of kernel functions, which enable them to operate in a high-dimensional, implicit feature space without ever computing the coordinates of the data in that space, but rather by simply computing the inner products between the images of all pairs of data in the feature space. This operation is often computationally cheaper than the explicit computation of the coordinates. This approach is called the "kernel trick". Kernel functions have been introduced for sequence data, graphs, text, images, as well as vectors.". Lesson: You (sometimes) get what you pay for. So my questions is "Does there exist an $f$ such that $f(s(a,b))=d(a,b)$ for $d$ some distance metric given these properties on $s$, and what is that $f$?" Many, see links above, "Popular Kernel Functions", RBF, and here's one (expensive) example: "A Likelihood Ratio Distance Measure for the Similarity Between the Fourier Transform of Time Series" (2005), by Janacek, Bagnall and Powell. If $f$ doesn't exist in these general circumstances on $s$, is there an additional set of requirements for which $f$ exists? Different spaces and methods can better target comparison (and disintegration) of specific problems, there are many methods for the Hilbert space alone. Yes, the list is big, see the links above and (for one example): Reproducing kernel Hilbert space.
Does Mercer's theorem work in reverse? Does Mercer's theorem work in reverse? Not in all cases. Wikipedia: "In mathematics, specifically functional analysis, Mercer's theorem is a representation of a symmetric positive-definite function o
26,488
Does Mercer's theorem work in reverse?
But it's not obvious that this rather general set of circumstances is sufficient to imply that the triangle inequality is respected. In fact, it isn't sufficient. Let's work with $d(a, b) = 1 - s(a, b)$. If there are three points $x, y, z$ with $d(x, y) = \frac{1}{3}$, $d(y, z) = \frac{1}{3}$, and $d(x, z) = 1$, then the triangle inequality fails, because $d(x, z) > d(x, y) + d(y, z)$.
Does Mercer's theorem work in reverse?
But it's not obvious that this rather general set of circumstances is sufficient to imply that the triangle inequality is respected. In fact, it isn't sufficient. Let's work with $d(a, b) = 1 - s(a,
Does Mercer's theorem work in reverse? But it's not obvious that this rather general set of circumstances is sufficient to imply that the triangle inequality is respected. In fact, it isn't sufficient. Let's work with $d(a, b) = 1 - s(a, b)$. If there are three points $x, y, z$ with $d(x, y) = \frac{1}{3}$, $d(y, z) = \frac{1}{3}$, and $d(x, z) = 1$, then the triangle inequality fails, because $d(x, z) > d(x, y) + d(y, z)$.
Does Mercer's theorem work in reverse? But it's not obvious that this rather general set of circumstances is sufficient to imply that the triangle inequality is respected. In fact, it isn't sufficient. Let's work with $d(a, b) = 1 - s(a,
26,489
Random Forest has almost perfect training AUC compared to other models
Hello guys! Sorry for my english. I undestand that so your problem is a question about model choise. You have to want the best test error, no the simility between train and test error. The minumum in the image shows your goal, to be sure about your decision, you can graph the errors versus complexity (depth pode, trees or min samples leaf). Indeed, the best parameters in the model securely will be for a lower train error than 0.999.
Random Forest has almost perfect training AUC compared to other models
Hello guys! Sorry for my english. I undestand that so your problem is a question about model choise. You have to want the best test error, no the simility between train and test error. The minumum in
Random Forest has almost perfect training AUC compared to other models Hello guys! Sorry for my english. I undestand that so your problem is a question about model choise. You have to want the best test error, no the simility between train and test error. The minumum in the image shows your goal, to be sure about your decision, you can graph the errors versus complexity (depth pode, trees or min samples leaf). Indeed, the best parameters in the model securely will be for a lower train error than 0.999.
Random Forest has almost perfect training AUC compared to other models Hello guys! Sorry for my english. I undestand that so your problem is a question about model choise. You have to want the best test error, no the simility between train and test error. The minumum in
26,490
Random Forest has almost perfect training AUC compared to other models
Random forests have many many degrees of freedom, so it is relatively easy for them to get to the point that they have near 100% accuracy in-sample. This is merely an overfitting problem. Likely you want to use some tuning parameters to reduce the model complexity some (reduce tree depth, raise minimal node size, etc). Some degree of cross-validation would help you here. Alternatively, it still has the best oob performance, so you can just use it anyhow.
Random Forest has almost perfect training AUC compared to other models
Random forests have many many degrees of freedom, so it is relatively easy for them to get to the point that they have near 100% accuracy in-sample. This is merely an overfitting problem. Likely you w
Random Forest has almost perfect training AUC compared to other models Random forests have many many degrees of freedom, so it is relatively easy for them to get to the point that they have near 100% accuracy in-sample. This is merely an overfitting problem. Likely you want to use some tuning parameters to reduce the model complexity some (reduce tree depth, raise minimal node size, etc). Some degree of cross-validation would help you here. Alternatively, it still has the best oob performance, so you can just use it anyhow.
Random Forest has almost perfect training AUC compared to other models Random forests have many many degrees of freedom, so it is relatively easy for them to get to the point that they have near 100% accuracy in-sample. This is merely an overfitting problem. Likely you w
26,491
Random Forest has almost perfect training AUC compared to other models
Because the ML algorithms works minimizing the error on the training, the expected accuracy on this data would be "naturally" better than your test results. Effectively when the training error is too low (aka accuracy too high) maybe there is something that has gone wrong (aka overfitting) As suggested by user5957401, you can try to cross-validate the training process. For example, if you have a good amount of instances, a 10 fold cross-validation would be fine. If you need also to tune hyper parameters, a nested-cross validation would be necessary. In this way the estimated error from the test-set will be "near" the expected one (aka, the one that you'll get on real Data). In this way, you can check if your result (AUC 0.80 on the test set) is a good estimate, or if you got this by chance You can try also other techniques, like shuffling several times your data before the cross-validation task, to increase the result reliability.
Random Forest has almost perfect training AUC compared to other models
Because the ML algorithms works minimizing the error on the training, the expected accuracy on this data would be "naturally" better than your test results. Effectively when the training error is too
Random Forest has almost perfect training AUC compared to other models Because the ML algorithms works minimizing the error on the training, the expected accuracy on this data would be "naturally" better than your test results. Effectively when the training error is too low (aka accuracy too high) maybe there is something that has gone wrong (aka overfitting) As suggested by user5957401, you can try to cross-validate the training process. For example, if you have a good amount of instances, a 10 fold cross-validation would be fine. If you need also to tune hyper parameters, a nested-cross validation would be necessary. In this way the estimated error from the test-set will be "near" the expected one (aka, the one that you'll get on real Data). In this way, you can check if your result (AUC 0.80 on the test set) is a good estimate, or if you got this by chance You can try also other techniques, like shuffling several times your data before the cross-validation task, to increase the result reliability.
Random Forest has almost perfect training AUC compared to other models Because the ML algorithms works minimizing the error on the training, the expected accuracy on this data would be "naturally" better than your test results. Effectively when the training error is too
26,492
Differentiation of Cross Entropy
Your $\frac{\partial E}{\partial o_j}$ is correct, but $\frac{\partial E}{\partial z_j}$ should be $$\frac{\partial E}{\partial z_j}=\sum_i\frac{\partial E}{\partial o_i}\frac{\partial o_i}{\partial z_j}$$ when $i=j$, using the results given in the post we have $$\frac{\partial E}{\partial o_j}\frac{\partial o_j}{\partial z_j}=-\frac{t_j}{o_j}o_j(1-o_j)=t_jo_j-t_j$$ when $i\neq j$ $$\frac{\partial o_i}{\partial z_j}=\frac{\partial \frac{e^{z_i}}{\sum_ke^{z_k}}}{\partial z_j}=-\frac{e^{z_i}}{(\sum_ke^{z_k})^2}e^{z_j}=-o_io_j$$ $$\frac{\partial E}{\partial o_i}\frac{\partial o_i}{\partial z_j}=-\frac{t_i}{o_i}(-o_io_j)=t_io_j$$ so the summation is $$\frac{\partial E}{\partial z_j}=\sum_i\frac{\partial E}{\partial o_i}\frac{\partial o_i}{\partial z_j}=\sum_it_io_j-t_j$$ since $t$ is a one-hot vector, $\sum_it_i=1$ therefore $$\frac{\partial E}{\partial z_j}=o_j-t_j$$ also see this question.
Differentiation of Cross Entropy
Your $\frac{\partial E}{\partial o_j}$ is correct, but $\frac{\partial E}{\partial z_j}$ should be $$\frac{\partial E}{\partial z_j}=\sum_i\frac{\partial E}{\partial o_i}\frac{\partial o_i}{\partial z
Differentiation of Cross Entropy Your $\frac{\partial E}{\partial o_j}$ is correct, but $\frac{\partial E}{\partial z_j}$ should be $$\frac{\partial E}{\partial z_j}=\sum_i\frac{\partial E}{\partial o_i}\frac{\partial o_i}{\partial z_j}$$ when $i=j$, using the results given in the post we have $$\frac{\partial E}{\partial o_j}\frac{\partial o_j}{\partial z_j}=-\frac{t_j}{o_j}o_j(1-o_j)=t_jo_j-t_j$$ when $i\neq j$ $$\frac{\partial o_i}{\partial z_j}=\frac{\partial \frac{e^{z_i}}{\sum_ke^{z_k}}}{\partial z_j}=-\frac{e^{z_i}}{(\sum_ke^{z_k})^2}e^{z_j}=-o_io_j$$ $$\frac{\partial E}{\partial o_i}\frac{\partial o_i}{\partial z_j}=-\frac{t_i}{o_i}(-o_io_j)=t_io_j$$ so the summation is $$\frac{\partial E}{\partial z_j}=\sum_i\frac{\partial E}{\partial o_i}\frac{\partial o_i}{\partial z_j}=\sum_it_io_j-t_j$$ since $t$ is a one-hot vector, $\sum_it_i=1$ therefore $$\frac{\partial E}{\partial z_j}=o_j-t_j$$ also see this question.
Differentiation of Cross Entropy Your $\frac{\partial E}{\partial o_j}$ is correct, but $\frac{\partial E}{\partial z_j}$ should be $$\frac{\partial E}{\partial z_j}=\sum_i\frac{\partial E}{\partial o_i}\frac{\partial o_i}{\partial z
26,493
Understand marginal likelihood of mixed effects models
I can reproduce the marginal log-likelihood returned by lme4:::logLik.merMod by realising that the marginal distribution of Y is multivariate normal (MVN) (as the marginal distribution of b and the conditional of Y are MVN). So this code will reproduce library(mvtnorm) dmvnorm(cake$angle, predict(model, re.form=NA), as.matrix(v), log=TRUE) #[1] -834.1132 where cake$angle are the observations, predict(model, re.form=NA) are the population predictions (calculated using the fixed effect coefficients), and v is the variance of the marginal model (as shown in question). A couple of comments on the failing efforts in my question. When calculating the conditional log-likelihood I used the univariate normal density function, whereas I could/should of used the multivariate. In this case it doesn't make a difference as within unit variance is $\sigma^2 I_n$ mvtnorm::dmvnorm(cake$angle, predict(model), diag(sigma(model)^2,270, 270), log=TRUE) #[1] -801.6044 Trying to calculate the marginal distribution First try used the predictions at population (XB) level but the incorrect variance (it ignored the between unit error) sum(dnorm(cake$angle, predict(model, re.form=NA), sd=sigma(model), log=TRUE)) Second try was just nonsense I think Third try uses the univariate rather than multivariate normal distribution.
Understand marginal likelihood of mixed effects models
I can reproduce the marginal log-likelihood returned by lme4:::logLik.merMod by realising that the marginal distribution of Y is multivariate normal (MVN) (as the marginal distribution of b and the co
Understand marginal likelihood of mixed effects models I can reproduce the marginal log-likelihood returned by lme4:::logLik.merMod by realising that the marginal distribution of Y is multivariate normal (MVN) (as the marginal distribution of b and the conditional of Y are MVN). So this code will reproduce library(mvtnorm) dmvnorm(cake$angle, predict(model, re.form=NA), as.matrix(v), log=TRUE) #[1] -834.1132 where cake$angle are the observations, predict(model, re.form=NA) are the population predictions (calculated using the fixed effect coefficients), and v is the variance of the marginal model (as shown in question). A couple of comments on the failing efforts in my question. When calculating the conditional log-likelihood I used the univariate normal density function, whereas I could/should of used the multivariate. In this case it doesn't make a difference as within unit variance is $\sigma^2 I_n$ mvtnorm::dmvnorm(cake$angle, predict(model), diag(sigma(model)^2,270, 270), log=TRUE) #[1] -801.6044 Trying to calculate the marginal distribution First try used the predictions at population (XB) level but the incorrect variance (it ignored the between unit error) sum(dnorm(cake$angle, predict(model, re.form=NA), sd=sigma(model), log=TRUE)) Second try was just nonsense I think Third try uses the univariate rather than multivariate normal distribution.
Understand marginal likelihood of mixed effects models I can reproduce the marginal log-likelihood returned by lme4:::logLik.merMod by realising that the marginal distribution of Y is multivariate normal (MVN) (as the marginal distribution of b and the co
26,494
Predictive maintenace model to identify indication of failure before it happens
That's a nicely asked and interesting question. I have some questions : Do you already have insights about the feasibility of your goal ? (anticipate some failures) Did you identify variable that augur a failure ? What is the typical time before failure ? I think the natural way to study such a problem would be to use survival analysis. And being familiar with it will be plus ! What I would do (despite I'm not aware all specificity of your problem) : Compute your time of interest variable ($y$) and occurrence of event variable ($delta$) : in this step you may : consider the failure time as event consider the preventive maintenance time as censoring variable skip the shift time for the computation of failure time and censoring Fit a Cox model on this data : Remark : you have time changing covariates (there is at this address a vignette about how to handle time dependent covariates in the Cox model : https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf ) This step may not be easy (I don't know I'm not a specialist of time dependent covariates). For instance I'm thinking you may be in trouble because you may have too much change points in your data (time when one of the covariate changes) Then, to use you model (and see if you can predict that a failure will occur in the future (enough time before)), you should use your Cox model : The Cox model will give you an estimation of the hazard rate. So the simplest thing you may do to use your model is to compute an online prediction as your machine is running, and decide to stop the machine when the hazard rate exceed a threshold) Though the natural way to study your problem would be to use survival analysis, you may use classification methods especially if the time before failure is short (this way you are analyzing past data and you will not be disturbed by censoring). In this case, I think the overall approach would be quite similar. Give us some feedback about your problem !
Predictive maintenace model to identify indication of failure before it happens
That's a nicely asked and interesting question. I have some questions : Do you already have insights about the feasibility of your goal ? (anticipate some failures) Did you identify variable that aug
Predictive maintenace model to identify indication of failure before it happens That's a nicely asked and interesting question. I have some questions : Do you already have insights about the feasibility of your goal ? (anticipate some failures) Did you identify variable that augur a failure ? What is the typical time before failure ? I think the natural way to study such a problem would be to use survival analysis. And being familiar with it will be plus ! What I would do (despite I'm not aware all specificity of your problem) : Compute your time of interest variable ($y$) and occurrence of event variable ($delta$) : in this step you may : consider the failure time as event consider the preventive maintenance time as censoring variable skip the shift time for the computation of failure time and censoring Fit a Cox model on this data : Remark : you have time changing covariates (there is at this address a vignette about how to handle time dependent covariates in the Cox model : https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf ) This step may not be easy (I don't know I'm not a specialist of time dependent covariates). For instance I'm thinking you may be in trouble because you may have too much change points in your data (time when one of the covariate changes) Then, to use you model (and see if you can predict that a failure will occur in the future (enough time before)), you should use your Cox model : The Cox model will give you an estimation of the hazard rate. So the simplest thing you may do to use your model is to compute an online prediction as your machine is running, and decide to stop the machine when the hazard rate exceed a threshold) Though the natural way to study your problem would be to use survival analysis, you may use classification methods especially if the time before failure is short (this way you are analyzing past data and you will not be disturbed by censoring). In this case, I think the overall approach would be quite similar. Give us some feedback about your problem !
Predictive maintenace model to identify indication of failure before it happens That's a nicely asked and interesting question. I have some questions : Do you already have insights about the feasibility of your goal ? (anticipate some failures) Did you identify variable that aug
26,495
Predictive maintenace model to identify indication of failure before it happens
I work on similar problems. I suggest to model this as a classification task: Label the data as ... systems/times when the system is close before a failure ... systems/times when the system is healthy Then you need to fit a model to do this classification. Probably you need to aggregate the data first on intervals.
Predictive maintenace model to identify indication of failure before it happens
I work on similar problems. I suggest to model this as a classification task: Label the data as ... systems/times when the system is close before a failure ... systems/times when the system is healthy
Predictive maintenace model to identify indication of failure before it happens I work on similar problems. I suggest to model this as a classification task: Label the data as ... systems/times when the system is close before a failure ... systems/times when the system is healthy Then you need to fit a model to do this classification. Probably you need to aggregate the data first on intervals.
Predictive maintenace model to identify indication of failure before it happens I work on similar problems. I suggest to model this as a classification task: Label the data as ... systems/times when the system is close before a failure ... systems/times when the system is healthy
26,496
"Manual" calculation of ACF of a time series in R - close but not quite
Apparently cor and acf are not using the same divisor. acf uses as divisor the number of observations and can be reproduced as shown below. For details, you can locate the code of C_acf in the file R-3.3.2/src/library/stats/src/filter.c (procedures acf and acf0): set.seed(0) # To reproduce results x = seq(pi, 10 * pi, 0.1) # Creating time-series as sin function. y = 0.1 * x + sin(x) + rnorm(x) # Time-series sinusoidal points with noise. y = ts(y, start = 1800) # Labeling time axis. model = lm(y ~ I(1801:2083)) # Detrending (0.1 * x) st.y = y - predict(model) lag.max <- 24 ydm <- st.y - mean(st.y) n <- length(ydm) ACF <- rep(NA, lag.max+1) for (tau in seq(0, lag.max)) ACF[tau+1] <- sum(ydm * lag(ydm, -tau)) / n ACF <- ACF/ACF[1] names(ACF) <- paste0("lag", seq.int(0, lag.max)) ACF head(ACF) # lag0 lag1 lag2 lag3 lag4 lag5 # 1.0000000 0.3187104 0.3329545 0.2857004 0.2745302 0.2907426 tail(ACF) # lag19 lag20 lag21 lag22 lag23 lag24 # -0.1144625 -0.1621018 -0.1737770 -0.1203673 -0.1924761 -0.3069342 all.equal(ACF, acf(st.y, lag.max=lag.max, plot=FALSE)$acf[,,1], check.names=FALSE) # [1] TRUE
"Manual" calculation of ACF of a time series in R - close but not quite
Apparently cor and acf are not using the same divisor. acf uses as divisor the number of observations and can be reproduced as shown below. For details, you can locate the code of C_acf in the file R-
"Manual" calculation of ACF of a time series in R - close but not quite Apparently cor and acf are not using the same divisor. acf uses as divisor the number of observations and can be reproduced as shown below. For details, you can locate the code of C_acf in the file R-3.3.2/src/library/stats/src/filter.c (procedures acf and acf0): set.seed(0) # To reproduce results x = seq(pi, 10 * pi, 0.1) # Creating time-series as sin function. y = 0.1 * x + sin(x) + rnorm(x) # Time-series sinusoidal points with noise. y = ts(y, start = 1800) # Labeling time axis. model = lm(y ~ I(1801:2083)) # Detrending (0.1 * x) st.y = y - predict(model) lag.max <- 24 ydm <- st.y - mean(st.y) n <- length(ydm) ACF <- rep(NA, lag.max+1) for (tau in seq(0, lag.max)) ACF[tau+1] <- sum(ydm * lag(ydm, -tau)) / n ACF <- ACF/ACF[1] names(ACF) <- paste0("lag", seq.int(0, lag.max)) ACF head(ACF) # lag0 lag1 lag2 lag3 lag4 lag5 # 1.0000000 0.3187104 0.3329545 0.2857004 0.2745302 0.2907426 tail(ACF) # lag19 lag20 lag21 lag22 lag23 lag24 # -0.1144625 -0.1621018 -0.1737770 -0.1203673 -0.1924761 -0.3069342 all.equal(ACF, acf(st.y, lag.max=lag.max, plot=FALSE)$acf[,,1], check.names=FALSE) # [1] TRUE
"Manual" calculation of ACF of a time series in R - close but not quite Apparently cor and acf are not using the same divisor. acf uses as divisor the number of observations and can be reproduced as shown below. For details, you can locate the code of C_acf in the file R-
26,497
Generating a high-dimensional dataset where nearest neighbor becomes meaningless
Read some of the newer follow-up articles, such as: Houle, M. E., Kriegel, H. P., Kröger, P., Schubert, E., & Zimek, A. (2010, June). Can shared-neighbor distances defeat the curse of dimensionality?. In International Conference on Scientific and Statistical Database Management (pp. 482-500). Springer Berlin Heidelberg. and Zimek, A., Schubert, E., & Kriegel, H. P. (2012). A survey on unsupervised outlier detection in high‐dimensional numerical data. Statistical Analysis and Data Mining, 5(5), 363-387. If I remember correctly, they show the properties of the theoretical distance concentration effect (which is proven) and the limitations why reality may behave very different. If these articles aren't helpful, ping me and I recheck the references (just typed what I remembered into Google Scholar, I didn't download the papers again). Beware that the "curse" does not say the difference of distances to the nearest and farthest neighbors approaches 0; nor that the distances would converge to some number. but rather that the relative difference compared to the absolute value becomes small. Then random deviations can cause neighbors to be incorrectly ranked. In this equartion, don't ignore the fraction, expected value, and $d\rightarrow\infty$: $$ \lim_{d \to \infty} E\left(\frac{\operatorname{dist}_{\max} (d) - \operatorname{dist}_{\min} (d)}{\operatorname{dist}_{\min} (d)}\right) \to 0 $$
Generating a high-dimensional dataset where nearest neighbor becomes meaningless
Read some of the newer follow-up articles, such as: Houle, M. E., Kriegel, H. P., Kröger, P., Schubert, E., & Zimek, A. (2010, June). Can shared-neighbor distances defeat the curse of dimensionality?
Generating a high-dimensional dataset where nearest neighbor becomes meaningless Read some of the newer follow-up articles, such as: Houle, M. E., Kriegel, H. P., Kröger, P., Schubert, E., & Zimek, A. (2010, June). Can shared-neighbor distances defeat the curse of dimensionality?. In International Conference on Scientific and Statistical Database Management (pp. 482-500). Springer Berlin Heidelberg. and Zimek, A., Schubert, E., & Kriegel, H. P. (2012). A survey on unsupervised outlier detection in high‐dimensional numerical data. Statistical Analysis and Data Mining, 5(5), 363-387. If I remember correctly, they show the properties of the theoretical distance concentration effect (which is proven) and the limitations why reality may behave very different. If these articles aren't helpful, ping me and I recheck the references (just typed what I remembered into Google Scholar, I didn't download the papers again). Beware that the "curse" does not say the difference of distances to the nearest and farthest neighbors approaches 0; nor that the distances would converge to some number. but rather that the relative difference compared to the absolute value becomes small. Then random deviations can cause neighbors to be incorrectly ranked. In this equartion, don't ignore the fraction, expected value, and $d\rightarrow\infty$: $$ \lim_{d \to \infty} E\left(\frac{\operatorname{dist}_{\max} (d) - \operatorname{dist}_{\min} (d)}{\operatorname{dist}_{\min} (d)}\right) \to 0 $$
Generating a high-dimensional dataset where nearest neighbor becomes meaningless Read some of the newer follow-up articles, such as: Houle, M. E., Kriegel, H. P., Kröger, P., Schubert, E., & Zimek, A. (2010, June). Can shared-neighbor distances defeat the curse of dimensionality?
26,498
Generating a high-dimensional dataset where nearest neighbor becomes meaningless
I hadn't heard of this before either, so I am little defensive, since I have seen that real and synthetic datasets in high dimensions really do not support the claim of the paper in question. As a result, what I would suggest, as a first, dirty, clumsy and maybe not good first attempt is to generate a sphere in a dimension of your choice (I do it like like this) and then place a query at the center of the sphere. In that case, every point lies in the same distance with the query point, thus the Nearest Neighbor has a distance equal to the Farthest Neighbor. This, of course, is independent from the dimension, but it's what came at a thought after looking at the figures of the paper. It should be enough to get you stared, but surely, better datasets may be generated, if any. Edit about: distances for each point got bigger with more dimensions!!!! this is expected, since the higher the dimensional space, the sparser the space is, thus the greater the distance is. Moreover, this is expected, if you think for example, the Euclidean distance, which gets grater as the dimensions grow.
Generating a high-dimensional dataset where nearest neighbor becomes meaningless
I hadn't heard of this before either, so I am little defensive, since I have seen that real and synthetic datasets in high dimensions really do not support the claim of the paper in question. As a re
Generating a high-dimensional dataset where nearest neighbor becomes meaningless I hadn't heard of this before either, so I am little defensive, since I have seen that real and synthetic datasets in high dimensions really do not support the claim of the paper in question. As a result, what I would suggest, as a first, dirty, clumsy and maybe not good first attempt is to generate a sphere in a dimension of your choice (I do it like like this) and then place a query at the center of the sphere. In that case, every point lies in the same distance with the query point, thus the Nearest Neighbor has a distance equal to the Farthest Neighbor. This, of course, is independent from the dimension, but it's what came at a thought after looking at the figures of the paper. It should be enough to get you stared, but surely, better datasets may be generated, if any. Edit about: distances for each point got bigger with more dimensions!!!! this is expected, since the higher the dimensional space, the sparser the space is, thus the greater the distance is. Moreover, this is expected, if you think for example, the Euclidean distance, which gets grater as the dimensions grow.
Generating a high-dimensional dataset where nearest neighbor becomes meaningless I hadn't heard of this before either, so I am little defensive, since I have seen that real and synthetic datasets in high dimensions really do not support the claim of the paper in question. As a re
26,499
Generating a high-dimensional dataset where nearest neighbor becomes meaningless
Of relevance to your question, is a family of examples that satisfies the hypothesis of the theorem by Beyer et. al., which is given in this paper "Concentration of Fractional Distances (Wertz. et. al.)", which basically states that (see its Theorem 5, P. 878) Theorem 5: If $X^{(d)}=(X_1 \dots X_d) \in \mathbb{R}^d$ is a $d$ -dimensional random vector with iid components, then $\frac{||X^{(d)}||}{\mathbb{E}||X^{(d)}||} \to_{p}1 \iff Var\left[\frac{||X^{(d)}||}{\mathbb{E}||X^{(d)}||}\right] \to 0, d \to \infty.$ So this means that if your generated iid random sample by using a random vector whose components are iid (e.g. a normal $\mathcal{N}(0, I_d)$ random vector), then its "relative variance $Var\left[\frac{||X^{(d)}||}{\mathbb{E}||X^{(d)}||}\right]$" will go to zero, and hence by Beyer's theorem the maximum norm (=distance to the query point as the origin) divided by minimum norm (=distance to the query point as origin) will converge in probability to $1,$ or equivalently the "relative contrast" (the ratio mentioned in Anony-Mousse's answer above, with query point the origin, i.e. ratio of the distances between the farthest and nearest point, minus one) wil go to zero as well. P.S. for application-minded people, you're very welcome take a look at my relevant question here seeking practical applications of these types of theorems.
Generating a high-dimensional dataset where nearest neighbor becomes meaningless
Of relevance to your question, is a family of examples that satisfies the hypothesis of the theorem by Beyer et. al., which is given in this paper "Concentration of Fractional Distances (Wertz. et. al
Generating a high-dimensional dataset where nearest neighbor becomes meaningless Of relevance to your question, is a family of examples that satisfies the hypothesis of the theorem by Beyer et. al., which is given in this paper "Concentration of Fractional Distances (Wertz. et. al.)", which basically states that (see its Theorem 5, P. 878) Theorem 5: If $X^{(d)}=(X_1 \dots X_d) \in \mathbb{R}^d$ is a $d$ -dimensional random vector with iid components, then $\frac{||X^{(d)}||}{\mathbb{E}||X^{(d)}||} \to_{p}1 \iff Var\left[\frac{||X^{(d)}||}{\mathbb{E}||X^{(d)}||}\right] \to 0, d \to \infty.$ So this means that if your generated iid random sample by using a random vector whose components are iid (e.g. a normal $\mathcal{N}(0, I_d)$ random vector), then its "relative variance $Var\left[\frac{||X^{(d)}||}{\mathbb{E}||X^{(d)}||}\right]$" will go to zero, and hence by Beyer's theorem the maximum norm (=distance to the query point as the origin) divided by minimum norm (=distance to the query point as origin) will converge in probability to $1,$ or equivalently the "relative contrast" (the ratio mentioned in Anony-Mousse's answer above, with query point the origin, i.e. ratio of the distances between the farthest and nearest point, minus one) wil go to zero as well. P.S. for application-minded people, you're very welcome take a look at my relevant question here seeking practical applications of these types of theorems.
Generating a high-dimensional dataset where nearest neighbor becomes meaningless Of relevance to your question, is a family of examples that satisfies the hypothesis of the theorem by Beyer et. al., which is given in this paper "Concentration of Fractional Distances (Wertz. et. al
26,500
Conditional mean independence implies unbiasedness and consistency of the OLS estimator
It's false. As you observe, if you read Stock and Watson closely, they don't actually endorse the claim that OLS is unbiased for $\beta$ under conditional mean independence. They endorse the much weaker claim that OLS is unbiased for $\beta$ if $E(u|x,z)=z\gamma$. Then, they say something vague about non-linear least squares. Your equation (4) contains what you need to see that the claim is false. Estimating equation (4) by OLS while omitting the variable $E(u|x,z)$ leads to omitted variables bias. As you probably recall, the bias term from omitted variables (when the omitted variable has a coefficient of 1) is controlled by the coefficients from the following auxiliary regression: \begin{align} E(u|z) = x\alpha_1 + z\alpha_2 + \nu \end{align} The bias in the original regression for $\beta$ is $\alpha_1$ from this regression, and the bias on $\gamma$ is $\alpha_2$. If $x$ is correlated with $E(u|z)$, after controlling linearly for $z$, then $\alpha_1$ will be non-zero and the OLS coefficient will be biased. Here is an example to prove the point: \begin{align} \xi &\sim F(), \; \zeta \sim G(), \; \nu \sim H()\quad \text{all independent}\\ z &=\xi\\ x &= z^2 + \zeta\\ u &= z+z^2-E(z+z^2)+\nu \end{align} Looking at the formula for $u$, it is clear that $E(u|x,z)=E(u|z)=z+z^2-E(z+z^2)$ Looking at the auxiliary regression, it is clear that (absent some fortuitous choice of $F,G,H$) $\alpha_1$ will not be zero. Here is a very simple example in R which demonstrates the point: set.seed(12344321) z <- runif(n=100000,min=0,max=10) x <- z^2 + runif(n=100000,min=0,max=20) u <- z + z^2 - mean(z+z^2) + rnorm(n=100000,mean=0,sd=20) y <- x + z + u summary(lm(y~x+z)) # auxiliary regression summary(lm(z+z^2~x+z)) Notice that the first regression gives you a coefficient on $x$ which is biased up by 0.63, reflecting the fact that $x$ "has some $z^2$ in it" as does $E(u|z)$. Notice also that the auxiliary regression gives you a bias estimate of about 0.63. So, what are Stock and Watson (and your lecturer) talking about? Let's go back to your equation (4): \begin{align} y = x\beta + z\gamma + E(u|z) + v \end{align} It's an important fact that the omitted variable is only a function of $z$. It seems like if we could control for $z$ really well, that would be enough to purge the bias from the regression, even though $x$ may be correlated with $u$. Suppose we estimated the equation below using either a non-parametric method to estimate the function $f()$ or using the correct functional form $f(z)=z\gamma+E(u|z)$. If we were using the correct functional form, we would be estimating it by non-linear least squares (explaining the cryptic comment about NLS): \begin{align} y = x\beta + f(z) + v \end{align} That would give us a consistent estimator for $\beta$ because there is no longer an omitted variable problem. Alternatively, if we had enough data, we could go ``all the way'' in controlling for $z$. We could look at a subset of the data where $z=1$, and just run the regression: \begin{align} y = x\beta + v \end{align} This would give unbiased, consistent estimators for the $\beta$ except for the intercept, of course, which would be polluted by $f(1)$. Obviously, you could also get a (different) consistent, unbiased estimator by running that regression only on data points for which $z=2$. And another one for the points where $z=3$. Etc. Then you'd have a bunch of good estimators from which you could make a great estimator by, say, averaging them all together somehow. This latter thought is the inspiration for matching estimators. Since we don't usually have enough data to literally run the regression only for $z=1$ or even for pairs of points where $z$ is identical, we instead run the regression for points where $z$ is ``close enough'' to being identical.
Conditional mean independence implies unbiasedness and consistency of the OLS estimator
It's false. As you observe, if you read Stock and Watson closely, they don't actually endorse the claim that OLS is unbiased for $\beta$ under conditional mean independence. They endorse the much we
Conditional mean independence implies unbiasedness and consistency of the OLS estimator It's false. As you observe, if you read Stock and Watson closely, they don't actually endorse the claim that OLS is unbiased for $\beta$ under conditional mean independence. They endorse the much weaker claim that OLS is unbiased for $\beta$ if $E(u|x,z)=z\gamma$. Then, they say something vague about non-linear least squares. Your equation (4) contains what you need to see that the claim is false. Estimating equation (4) by OLS while omitting the variable $E(u|x,z)$ leads to omitted variables bias. As you probably recall, the bias term from omitted variables (when the omitted variable has a coefficient of 1) is controlled by the coefficients from the following auxiliary regression: \begin{align} E(u|z) = x\alpha_1 + z\alpha_2 + \nu \end{align} The bias in the original regression for $\beta$ is $\alpha_1$ from this regression, and the bias on $\gamma$ is $\alpha_2$. If $x$ is correlated with $E(u|z)$, after controlling linearly for $z$, then $\alpha_1$ will be non-zero and the OLS coefficient will be biased. Here is an example to prove the point: \begin{align} \xi &\sim F(), \; \zeta \sim G(), \; \nu \sim H()\quad \text{all independent}\\ z &=\xi\\ x &= z^2 + \zeta\\ u &= z+z^2-E(z+z^2)+\nu \end{align} Looking at the formula for $u$, it is clear that $E(u|x,z)=E(u|z)=z+z^2-E(z+z^2)$ Looking at the auxiliary regression, it is clear that (absent some fortuitous choice of $F,G,H$) $\alpha_1$ will not be zero. Here is a very simple example in R which demonstrates the point: set.seed(12344321) z <- runif(n=100000,min=0,max=10) x <- z^2 + runif(n=100000,min=0,max=20) u <- z + z^2 - mean(z+z^2) + rnorm(n=100000,mean=0,sd=20) y <- x + z + u summary(lm(y~x+z)) # auxiliary regression summary(lm(z+z^2~x+z)) Notice that the first regression gives you a coefficient on $x$ which is biased up by 0.63, reflecting the fact that $x$ "has some $z^2$ in it" as does $E(u|z)$. Notice also that the auxiliary regression gives you a bias estimate of about 0.63. So, what are Stock and Watson (and your lecturer) talking about? Let's go back to your equation (4): \begin{align} y = x\beta + z\gamma + E(u|z) + v \end{align} It's an important fact that the omitted variable is only a function of $z$. It seems like if we could control for $z$ really well, that would be enough to purge the bias from the regression, even though $x$ may be correlated with $u$. Suppose we estimated the equation below using either a non-parametric method to estimate the function $f()$ or using the correct functional form $f(z)=z\gamma+E(u|z)$. If we were using the correct functional form, we would be estimating it by non-linear least squares (explaining the cryptic comment about NLS): \begin{align} y = x\beta + f(z) + v \end{align} That would give us a consistent estimator for $\beta$ because there is no longer an omitted variable problem. Alternatively, if we had enough data, we could go ``all the way'' in controlling for $z$. We could look at a subset of the data where $z=1$, and just run the regression: \begin{align} y = x\beta + v \end{align} This would give unbiased, consistent estimators for the $\beta$ except for the intercept, of course, which would be polluted by $f(1)$. Obviously, you could also get a (different) consistent, unbiased estimator by running that regression only on data points for which $z=2$. And another one for the points where $z=3$. Etc. Then you'd have a bunch of good estimators from which you could make a great estimator by, say, averaging them all together somehow. This latter thought is the inspiration for matching estimators. Since we don't usually have enough data to literally run the regression only for $z=1$ or even for pairs of points where $z$ is identical, we instead run the regression for points where $z$ is ``close enough'' to being identical.
Conditional mean independence implies unbiasedness and consistency of the OLS estimator It's false. As you observe, if you read Stock and Watson closely, they don't actually endorse the claim that OLS is unbiased for $\beta$ under conditional mean independence. They endorse the much we