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
35,401
Does the first principal component differ from simply computing the mean of all variables?
Some purely geometric meditation on the question. How can we graphically compare "mean as the construct" with "PC1 as the construct"? Let us have two variables $X$ and $Y$ with this covariance matrix and we have computed the variable which is the sum $S$ or the mean $M$ of $X$ and $Y$. We also performed PCA of the $X,Y$ centered data (i.e. PCA based on the covariance matrix). [Please note that it makes no difference whether you compute $M$ (or $S$) from the raw variables and then center the result, or you first center the variables and then compute $M$. The same, centered $M$ appears.] Below are vector representations of the variables in the subject space, convenient to depict analyses of few correlated variables (see e.g. this, this, this and other examples used by me). On the pictures, since the data were centered, the lengths of all the vectors shown equal the st. deviations of the respective variables. For example, length of $X$ is $\sqrt {\sigma_x^2}$. Angles are correlations: cosine between $X$ and $Y$ vectors is $\cos 45 = .7071$, Pearson $r$ observed between the two variables. Construct which is Mean of the variables (pic. 1). $M$ variable is the half of vector $S$ which is $X+Y$ variable. The squared lengths of $S$ and $M$ - the variances $\sigma_s^2$ and $\sigma_m^2$ - are easily computed by the law of parallelogram. We consider the red vector ($M$, or $S$) as the construct - i.e. the variable which one serves as a substitute for two, $X$ and $Y$. It is like Principal component 1 (also a construct) but is different. We may project $X$ and $Y$ on red construct to obtain their coordinates on that "axis", $a_{xs}$ and $a_{ys}$. I'd want to inform you that these quantities can be called "loadings", by the analogy of loadings in PCA (in PCA, you see loadings to be coordinates on a loading plot or biplot). OK, now what is most interesting to us thing on pic.1? It is the equality of the variables' coordinates onto the axis complementary and orthogonal to the construct: $h_x=h_y$, call this quantity $h$. So, what is most characteristic of taking the mean of two variables to be the construct is that this decision constrains the left-out, complementary (to the $a$'s) loadings $h_x$ and $h_y$ to be equal.$^1$ $^1$A reader familiar with subject space vector representations will immediately recognize in the $a$s and the $h$s the facets of simple regression (compare e.g. with the 2nd pic here). Clearly, loading $a_{xs}$, for example, is (the st. dev. of) the prediction of $X$ by $M$ and $h_x$ is (the st. dev. of) the error term of that regression. Since we have only two variables defining the mean, the two $h$s are equal. Principal Components (pic. 2). On the following picture, PCA is displayed. The construct is principal component 1, $P_1$, and we notice that it - gravitated to the longer variable - has gone lower than the parallelogram's diagonal, construct $M$ (=$S$). $P_2$, complement, is the principal component 2 to be left out. The squared lengths - the variances $\sigma_1^2$ and $\sigma_2^2$ - of $P_1$ and $P_2$ are the eigenvalues of the covariance matrix and are computed accordingly. The loadings, coordinates of the variables vectors onto the components vectors, are the subscripted black bold frames. We know, that the constraint which is the essence of PCA is to maximize variance of $P_1$ (which is equal to the sum of its squared loadings, $a_{x1}^2+a_{y1}^2$) and consequently to minimize variance of $P_2$ (equal $a_{x2}^2+a_{y2}^2$). In other words, the grey shaded area on the pic is what gets minimized. This is different constraint from the equality of the two loadings that was the constraint seen on pic.1. The Mean can be rescaled into Component 1 but it is weaker than Principal component 1 (pic. 3). The "axiom" of PCA is that all the components restore all the summative variance of the variables: $\sigma_1^2 + \sigma_2^2 = \sigma_x^2 + \sigma_y^2$. Actually, it is true for any component analysis, not just "principal" one. Can we turn our mean (or sum) variable $M$ chosen to become construct on pic.1 into component 1 (albeit not "principal component 1") of a component analysis which thus can be labeled, for a moment, "Mean component analysis"? Yes, why not (see now pic.3 which is based on pic.1). We only have to rescale variance (length) of $M$ so it, together with its left-out orthogonal complement, sums to $\sigma_x^2$ + $\sigma_y^2$. We can compute the variance of component $C_1$ (the rescaled $M$) as soon as we know its loadings, as $a_{x1}^2+a_{y1}^2$; and we can know the loadings by pythagorean theorem as soon as we know the error term $h$. The latter we can estimated as the altitude of the triangle (shaded beige) with known sides. We do it, and find that the variance of $C_1$ is weaker than the variance of $P_1$ (the vector lengths, st. deviations, are 5.988 vs 6.006). Selecting mean to be the (base of the) main component that we leave, as a substitute of the initial variables, is possible and can make sense, yet it is less optimal as a variance keeper than the true PCA component which is thus the recommended strategy. This answer examined a relation between PCA and mean-construct in a simple case of two variables (I believe it could be extended with some effort to more variables, except the ability to make pictures of 4+ dimensions and the complicating fact that error terms $h$s will generally not be equal then). Another answer elsewhere considers conditions when mean-construct can be a good substitute for PCA. See also a related discussion regarding computing scores vs summation/averaging in factor analysis.
Does the first principal component differ from simply computing the mean of all variables?
Some purely geometric meditation on the question. How can we graphically compare "mean as the construct" with "PC1 as the construct"? Let us have two variables $X$ and $Y$ with this covariance matrix
Does the first principal component differ from simply computing the mean of all variables? Some purely geometric meditation on the question. How can we graphically compare "mean as the construct" with "PC1 as the construct"? Let us have two variables $X$ and $Y$ with this covariance matrix and we have computed the variable which is the sum $S$ or the mean $M$ of $X$ and $Y$. We also performed PCA of the $X,Y$ centered data (i.e. PCA based on the covariance matrix). [Please note that it makes no difference whether you compute $M$ (or $S$) from the raw variables and then center the result, or you first center the variables and then compute $M$. The same, centered $M$ appears.] Below are vector representations of the variables in the subject space, convenient to depict analyses of few correlated variables (see e.g. this, this, this and other examples used by me). On the pictures, since the data were centered, the lengths of all the vectors shown equal the st. deviations of the respective variables. For example, length of $X$ is $\sqrt {\sigma_x^2}$. Angles are correlations: cosine between $X$ and $Y$ vectors is $\cos 45 = .7071$, Pearson $r$ observed between the two variables. Construct which is Mean of the variables (pic. 1). $M$ variable is the half of vector $S$ which is $X+Y$ variable. The squared lengths of $S$ and $M$ - the variances $\sigma_s^2$ and $\sigma_m^2$ - are easily computed by the law of parallelogram. We consider the red vector ($M$, or $S$) as the construct - i.e. the variable which one serves as a substitute for two, $X$ and $Y$. It is like Principal component 1 (also a construct) but is different. We may project $X$ and $Y$ on red construct to obtain their coordinates on that "axis", $a_{xs}$ and $a_{ys}$. I'd want to inform you that these quantities can be called "loadings", by the analogy of loadings in PCA (in PCA, you see loadings to be coordinates on a loading plot or biplot). OK, now what is most interesting to us thing on pic.1? It is the equality of the variables' coordinates onto the axis complementary and orthogonal to the construct: $h_x=h_y$, call this quantity $h$. So, what is most characteristic of taking the mean of two variables to be the construct is that this decision constrains the left-out, complementary (to the $a$'s) loadings $h_x$ and $h_y$ to be equal.$^1$ $^1$A reader familiar with subject space vector representations will immediately recognize in the $a$s and the $h$s the facets of simple regression (compare e.g. with the 2nd pic here). Clearly, loading $a_{xs}$, for example, is (the st. dev. of) the prediction of $X$ by $M$ and $h_x$ is (the st. dev. of) the error term of that regression. Since we have only two variables defining the mean, the two $h$s are equal. Principal Components (pic. 2). On the following picture, PCA is displayed. The construct is principal component 1, $P_1$, and we notice that it - gravitated to the longer variable - has gone lower than the parallelogram's diagonal, construct $M$ (=$S$). $P_2$, complement, is the principal component 2 to be left out. The squared lengths - the variances $\sigma_1^2$ and $\sigma_2^2$ - of $P_1$ and $P_2$ are the eigenvalues of the covariance matrix and are computed accordingly. The loadings, coordinates of the variables vectors onto the components vectors, are the subscripted black bold frames. We know, that the constraint which is the essence of PCA is to maximize variance of $P_1$ (which is equal to the sum of its squared loadings, $a_{x1}^2+a_{y1}^2$) and consequently to minimize variance of $P_2$ (equal $a_{x2}^2+a_{y2}^2$). In other words, the grey shaded area on the pic is what gets minimized. This is different constraint from the equality of the two loadings that was the constraint seen on pic.1. The Mean can be rescaled into Component 1 but it is weaker than Principal component 1 (pic. 3). The "axiom" of PCA is that all the components restore all the summative variance of the variables: $\sigma_1^2 + \sigma_2^2 = \sigma_x^2 + \sigma_y^2$. Actually, it is true for any component analysis, not just "principal" one. Can we turn our mean (or sum) variable $M$ chosen to become construct on pic.1 into component 1 (albeit not "principal component 1") of a component analysis which thus can be labeled, for a moment, "Mean component analysis"? Yes, why not (see now pic.3 which is based on pic.1). We only have to rescale variance (length) of $M$ so it, together with its left-out orthogonal complement, sums to $\sigma_x^2$ + $\sigma_y^2$. We can compute the variance of component $C_1$ (the rescaled $M$) as soon as we know its loadings, as $a_{x1}^2+a_{y1}^2$; and we can know the loadings by pythagorean theorem as soon as we know the error term $h$. The latter we can estimated as the altitude of the triangle (shaded beige) with known sides. We do it, and find that the variance of $C_1$ is weaker than the variance of $P_1$ (the vector lengths, st. deviations, are 5.988 vs 6.006). Selecting mean to be the (base of the) main component that we leave, as a substitute of the initial variables, is possible and can make sense, yet it is less optimal as a variance keeper than the true PCA component which is thus the recommended strategy. This answer examined a relation between PCA and mean-construct in a simple case of two variables (I believe it could be extended with some effort to more variables, except the ability to make pictures of 4+ dimensions and the complicating fact that error terms $h$s will generally not be equal then). Another answer elsewhere considers conditions when mean-construct can be a good substitute for PCA. See also a related discussion regarding computing scores vs summation/averaging in factor analysis.
Does the first principal component differ from simply computing the mean of all variables? Some purely geometric meditation on the question. How can we graphically compare "mean as the construct" with "PC1 as the construct"? Let us have two variables $X$ and $Y$ with this covariance matrix
35,402
How to train convolutional neural networks with multi-channel images?
You should work with each image as a volume of dimensions 224x224x5. You still do 2D convolution over the first 2 dimensions as usual, but keep the entire 3rd dimension. For instance, if you use a 7x7 convolution window, each filter will produce a 224x224x1 volume as output (with stride = 1 and zero padding), and the convolutional layer as a whole will produce a 224x224xN volume, where N is the number of filters. ConvNetJS and many other conv nets libraries take this approach.
How to train convolutional neural networks with multi-channel images?
You should work with each image as a volume of dimensions 224x224x5. You still do 2D convolution over the first 2 dimensions as usual, but keep the entire 3rd dimension. For instance, if you use a 7x7
How to train convolutional neural networks with multi-channel images? You should work with each image as a volume of dimensions 224x224x5. You still do 2D convolution over the first 2 dimensions as usual, but keep the entire 3rd dimension. For instance, if you use a 7x7 convolution window, each filter will produce a 224x224x1 volume as output (with stride = 1 and zero padding), and the convolutional layer as a whole will produce a 224x224xN volume, where N is the number of filters. ConvNetJS and many other conv nets libraries take this approach.
How to train convolutional neural networks with multi-channel images? You should work with each image as a volume of dimensions 224x224x5. You still do 2D convolution over the first 2 dimensions as usual, but keep the entire 3rd dimension. For instance, if you use a 7x7
35,403
How to train convolutional neural networks with multi-channel images?
Regarding your second question: What is the best way to train a CNN architecture using this data when mm is small (less than 2000)? There are some common ways to artificially increase the training set size, e.g. adding jitter or doing some transformation such as rotations.
How to train convolutional neural networks with multi-channel images?
Regarding your second question: What is the best way to train a CNN architecture using this data when mm is small (less than 2000)? There are some common ways to artificially increase the training
How to train convolutional neural networks with multi-channel images? Regarding your second question: What is the best way to train a CNN architecture using this data when mm is small (less than 2000)? There are some common ways to artificially increase the training set size, e.g. adding jitter or doing some transformation such as rotations.
How to train convolutional neural networks with multi-channel images? Regarding your second question: What is the best way to train a CNN architecture using this data when mm is small (less than 2000)? There are some common ways to artificially increase the training
35,404
Is each of the PCA or PLS components just one of the original variables?
The possible confusion here, as @amoeba points out in a comment, is the difference between variable selection and dimensionality reduction. Both PCA and PLS are intended to reduce the dimensionality of the problem. If you have measured 8 variables on each of your cases (and you have more than 8 cases) then the original dimension is 8. PCA and PLS help you choose a lower number of dimensions that will work well enough. But these procedures do not work by selecting subsets from your original 8 variables. Rather, they construct linear combinations of the 8 variables to make new sets of 8 predictors, then decide how many of these new combinations need to be included in the final model. For either PCA or PLS, these new predictors are designed to be orthogonal (multi-dimensional equivalent of perpendicular) to each other. If there are correlations among predictors, all 8 of your original variables are thus likely to be included to some extent even if you end up with a final dimension of, say, 4. So you are not typically performing all-or-none selection among your original variables. You just get rid of some less-important combinations of them. PCA simply examines the predictors themselves, finding first the combination that captures the most variance in the predictors, then the (orthogonal) combination that captures the next most, and so on. Several superb explanations of how this works are on this highly rated page. PLS includes in this type of scheme the relations of predictors to the outcome variable. At each step it finds the combination of predictors, orthogonal to all prior combinations, that maximizes the product of the variance of the predictors times the square of the correlation to the outcome variable. (See ESLII, eq. 3.64, page 81). For the first step, this is a linear combination weighted by each variable's individual correlation to outcome (unlike standard multiple regression, where all variables are considered together). PLS also gives a set of orthogonal predictors, made of linear combinations of the original variables, although different from those provided by PCA. In either procedure, a decision is made about how many of these new predictors to include, determining the final dimensionality. In either case, if you include all the new predictors, you just get back the original multiple regression. Also, please note that the above assumes that the predictor variables were first standardized so that differences in scales of the variables do not matter.
Is each of the PCA or PLS components just one of the original variables?
The possible confusion here, as @amoeba points out in a comment, is the difference between variable selection and dimensionality reduction. Both PCA and PLS are intended to reduce the dimensionality o
Is each of the PCA or PLS components just one of the original variables? The possible confusion here, as @amoeba points out in a comment, is the difference between variable selection and dimensionality reduction. Both PCA and PLS are intended to reduce the dimensionality of the problem. If you have measured 8 variables on each of your cases (and you have more than 8 cases) then the original dimension is 8. PCA and PLS help you choose a lower number of dimensions that will work well enough. But these procedures do not work by selecting subsets from your original 8 variables. Rather, they construct linear combinations of the 8 variables to make new sets of 8 predictors, then decide how many of these new combinations need to be included in the final model. For either PCA or PLS, these new predictors are designed to be orthogonal (multi-dimensional equivalent of perpendicular) to each other. If there are correlations among predictors, all 8 of your original variables are thus likely to be included to some extent even if you end up with a final dimension of, say, 4. So you are not typically performing all-or-none selection among your original variables. You just get rid of some less-important combinations of them. PCA simply examines the predictors themselves, finding first the combination that captures the most variance in the predictors, then the (orthogonal) combination that captures the next most, and so on. Several superb explanations of how this works are on this highly rated page. PLS includes in this type of scheme the relations of predictors to the outcome variable. At each step it finds the combination of predictors, orthogonal to all prior combinations, that maximizes the product of the variance of the predictors times the square of the correlation to the outcome variable. (See ESLII, eq. 3.64, page 81). For the first step, this is a linear combination weighted by each variable's individual correlation to outcome (unlike standard multiple regression, where all variables are considered together). PLS also gives a set of orthogonal predictors, made of linear combinations of the original variables, although different from those provided by PCA. In either procedure, a decision is made about how many of these new predictors to include, determining the final dimensionality. In either case, if you include all the new predictors, you just get back the original multiple regression. Also, please note that the above assumes that the predictor variables were first standardized so that differences in scales of the variables do not matter.
Is each of the PCA or PLS components just one of the original variables? The possible confusion here, as @amoeba points out in a comment, is the difference between variable selection and dimensionality reduction. Both PCA and PLS are intended to reduce the dimensionality o
35,405
Why do we use the chi-squared test to test independence of 2 categorical variables?
Instead of asking why the chi-squared test assesses independence, think about how you would test the association of two categorical variables against the null hypothesis of independence. For the sake of simplicity, consider two variables / properties A and B, each with two levels, "yes" and "no". A set of N units each has some combination of those properties. For example, A could be lung cancer, B could be exposure to radon, and the units could be people / patients. The numbers might look like this: table = as.table(rbind(c(1,2), c(3,4) )) names(dimnames(table)) = c("lung.cancer", "radon") rownames(table) = c("yes", "no") colnames(table) = c("no", "yes") table # radon # lung.cancer no yes # yes 1 2 # no 3 4 Now, we want to test these variables for independence; what do we mean by "independence"? We aren't interested in testing if any of the proportions are any particular value. We want to know if being in a particular column is associated with being in a particular row. If the rows and columns are independent, knowledge of which column a patient is in provides no information about which row they are in. Our total number of patients in this study is $N = 10$. How would those observations be distributed under the null (i.e., if the variables were independent)? Well, the probability of having been exposed to radon is $Pr(R = {\rm yes})$, and the probability of having lung cancer is $Pr(LC = {\rm yes})$, so from basic probability we know that the probability of having been exposed to radon and having lung cancer is $Pr(R = {\rm yes})Pr(LC = {\rm yes})$, and the probability of not having been exposed to radon and having lung cancer is $(1-Pr(R = {\rm yes}))Pr(LC = {\rm yes})$, etc. To get the expected count, we can multiply those probabilities by N. A problem here is that we don't know the probabilities of people being exposed to radon or of having lung cancer. We can estimate those probabilities from our data as the number who had been exposed to radon / have lung cancer divided by the total. Thus, we can estimate the component probabilities and ultimately the expected counts under the null. ex = chisq.test(table)$expected; ex # radon # lung.cancer no yes # yes 1.2 1.8 # no 2.8 4.2 When we try to compare the counts we observed to the expected counts we just calculated, we will run into two problems. The first is that the differences will sum to $0$: table-ex # radon # lung.cancer no yes # yes -0.2 0.2 # no 0.2 -0.2 To address that problem, we can square the differences and sum the squares. The second problem is that the magnitude of the differences (or their squares) will tend to increase as a function of the expected count. We can address that by dividing each squared difference by the expected count. So now we have a perfectly simple, intuitive way to test if the variables are independent. Notice, however, that we have just re-created the Pearson's chi-squared test statistic: $$ \chi^2 = \frac{\sum (O - E)^2}{E} $$ All we need to know now is how the test statistic should be distributed under the null. It turns out it is distributed as a chi-squared on $(r-1)(c-1)$ degrees of freedom, where $r$ is the number of rows and $c$ is the number of columns. (Actually, it isn't quite because the chi-squared distribution can take any non-negative real value, whereas the test statistic can only a specific set of values when $N$ is finite; this fact leads to some additional complications that I won't discuss here.) The above should cover questions 1 and 2. For question 3, it may help you to read this excellent CV thread: What is the meaning of p values and t values in statistical tests? To answer your explicit question about $.05$ and $.01$, those numbers are completely arbitrary and come from tradition. As far as I know, their exact origins are shrouded in the mists of time.
Why do we use the chi-squared test to test independence of 2 categorical variables?
Instead of asking why the chi-squared test assesses independence, think about how you would test the association of two categorical variables against the null hypothesis of independence. For the sake
Why do we use the chi-squared test to test independence of 2 categorical variables? Instead of asking why the chi-squared test assesses independence, think about how you would test the association of two categorical variables against the null hypothesis of independence. For the sake of simplicity, consider two variables / properties A and B, each with two levels, "yes" and "no". A set of N units each has some combination of those properties. For example, A could be lung cancer, B could be exposure to radon, and the units could be people / patients. The numbers might look like this: table = as.table(rbind(c(1,2), c(3,4) )) names(dimnames(table)) = c("lung.cancer", "radon") rownames(table) = c("yes", "no") colnames(table) = c("no", "yes") table # radon # lung.cancer no yes # yes 1 2 # no 3 4 Now, we want to test these variables for independence; what do we mean by "independence"? We aren't interested in testing if any of the proportions are any particular value. We want to know if being in a particular column is associated with being in a particular row. If the rows and columns are independent, knowledge of which column a patient is in provides no information about which row they are in. Our total number of patients in this study is $N = 10$. How would those observations be distributed under the null (i.e., if the variables were independent)? Well, the probability of having been exposed to radon is $Pr(R = {\rm yes})$, and the probability of having lung cancer is $Pr(LC = {\rm yes})$, so from basic probability we know that the probability of having been exposed to radon and having lung cancer is $Pr(R = {\rm yes})Pr(LC = {\rm yes})$, and the probability of not having been exposed to radon and having lung cancer is $(1-Pr(R = {\rm yes}))Pr(LC = {\rm yes})$, etc. To get the expected count, we can multiply those probabilities by N. A problem here is that we don't know the probabilities of people being exposed to radon or of having lung cancer. We can estimate those probabilities from our data as the number who had been exposed to radon / have lung cancer divided by the total. Thus, we can estimate the component probabilities and ultimately the expected counts under the null. ex = chisq.test(table)$expected; ex # radon # lung.cancer no yes # yes 1.2 1.8 # no 2.8 4.2 When we try to compare the counts we observed to the expected counts we just calculated, we will run into two problems. The first is that the differences will sum to $0$: table-ex # radon # lung.cancer no yes # yes -0.2 0.2 # no 0.2 -0.2 To address that problem, we can square the differences and sum the squares. The second problem is that the magnitude of the differences (or their squares) will tend to increase as a function of the expected count. We can address that by dividing each squared difference by the expected count. So now we have a perfectly simple, intuitive way to test if the variables are independent. Notice, however, that we have just re-created the Pearson's chi-squared test statistic: $$ \chi^2 = \frac{\sum (O - E)^2}{E} $$ All we need to know now is how the test statistic should be distributed under the null. It turns out it is distributed as a chi-squared on $(r-1)(c-1)$ degrees of freedom, where $r$ is the number of rows and $c$ is the number of columns. (Actually, it isn't quite because the chi-squared distribution can take any non-negative real value, whereas the test statistic can only a specific set of values when $N$ is finite; this fact leads to some additional complications that I won't discuss here.) The above should cover questions 1 and 2. For question 3, it may help you to read this excellent CV thread: What is the meaning of p values and t values in statistical tests? To answer your explicit question about $.05$ and $.01$, those numbers are completely arbitrary and come from tradition. As far as I know, their exact origins are shrouded in the mists of time.
Why do we use the chi-squared test to test independence of 2 categorical variables? Instead of asking why the chi-squared test assesses independence, think about how you would test the association of two categorical variables against the null hypothesis of independence. For the sake
35,406
Why do we use the chi-squared test to test independence of 2 categorical variables?
$\chi_1^2$ is the distribution of a random variable $X^2$, where $X \sim N(0,1)$. In the test of independence of two categorical variables, the actual counts are subtracted from the expected counts, and normalized by dividing by the expected counts. Squaring is extremely useful, because we are not interested in the direction of the differences (positive or negative with respect to the expected counts), but rather the magnitude in absolute values. Absolute values are awkward, and squaring fulfills the same role, plus it fits into the $\chi^2$ just right. Next we add these square normalized differences from each cell to produce the $\chi^2$ statistic: $\small\displaystyle \sum_{i=1}^n\frac{(\text{Observed - Expected})^2}{\text{Expected}}$. This, under some minimal conditions will follow a $\chi^2$ distribution. The $\small \text{deg. of freedom}$ will be calculated as $(\small\text{no.rows - 1})\times(\text{no.cols - 1})$. We are running an "omnibus" test to assess the overall deviation from what is expected by adding together the squared differences in each cell, and keeping track of the degrees of freedom. In the test of independence, the margins are considered fixed and the cell expected counts are conditioned on both margins. Alan Agresti has a great example on page 65 of Categorical Data Analysis (Second Edition) based on sampling couples from the population, and assessing whether the sexual satisfaction of the wife is independent of the sexual satisfaction of the husband - intuition would reason that happy couples would reflect in similar assessment of satisfaction for both husband and wife. Each couple is an observational unit, and two categorical variables are recorded for each unit. These concepts are a bit subtle, but important in differentiating the test of independence from the test of homogeneity. I tried summarizing them here. The tabulated data are as follows: husband wife Never Sometimes Often Always Sum Never 7 7 2 3 19 Sometimes 2 8 3 7 20 Often 1 5 4 9 19 Always 2 8 9 14 33 Sum 12 28 18 33 91 Running a chi-square test of independence will yield: chisq.test(sex_satis, correct = T) ## Pearson's Chi-squared test ## ## data: sex_satis ## X-squared = 16.955, df = 9, p-value = 0.04942 Which means that the *probability of encountering a test statistic more extreme than $\small 16.95$ under the null hypothesis (i.e. independence between satisfaction of husbands and wives) is less than $5\%$ (exactly $\small 0.049$), and for many studies this is good enough to reject $\text{H}_0$- indeed, in this case, the intuition of common sense is reaffirmed by data. Now this should answer the question but I want to tie up the point about conditioning on the margins. Because we don't know the proportions in the population, we estimate them based on the sample, and we figure that under the null hypothesis of independence, the expected value of “never/never” is the probability that the wife “never” experiences satisfaction ($19/91$) times (independent of) the probability that the husband “never” experiences pleasure ($12/91$). Based on this resultant probability the expected frequency in the cell will be found by multiplying by the total number of cases ($91$).
Why do we use the chi-squared test to test independence of 2 categorical variables?
$\chi_1^2$ is the distribution of a random variable $X^2$, where $X \sim N(0,1)$. In the test of independence of two categorical variables, the actual counts are subtracted from the expected counts,
Why do we use the chi-squared test to test independence of 2 categorical variables? $\chi_1^2$ is the distribution of a random variable $X^2$, where $X \sim N(0,1)$. In the test of independence of two categorical variables, the actual counts are subtracted from the expected counts, and normalized by dividing by the expected counts. Squaring is extremely useful, because we are not interested in the direction of the differences (positive or negative with respect to the expected counts), but rather the magnitude in absolute values. Absolute values are awkward, and squaring fulfills the same role, plus it fits into the $\chi^2$ just right. Next we add these square normalized differences from each cell to produce the $\chi^2$ statistic: $\small\displaystyle \sum_{i=1}^n\frac{(\text{Observed - Expected})^2}{\text{Expected}}$. This, under some minimal conditions will follow a $\chi^2$ distribution. The $\small \text{deg. of freedom}$ will be calculated as $(\small\text{no.rows - 1})\times(\text{no.cols - 1})$. We are running an "omnibus" test to assess the overall deviation from what is expected by adding together the squared differences in each cell, and keeping track of the degrees of freedom. In the test of independence, the margins are considered fixed and the cell expected counts are conditioned on both margins. Alan Agresti has a great example on page 65 of Categorical Data Analysis (Second Edition) based on sampling couples from the population, and assessing whether the sexual satisfaction of the wife is independent of the sexual satisfaction of the husband - intuition would reason that happy couples would reflect in similar assessment of satisfaction for both husband and wife. Each couple is an observational unit, and two categorical variables are recorded for each unit. These concepts are a bit subtle, but important in differentiating the test of independence from the test of homogeneity. I tried summarizing them here. The tabulated data are as follows: husband wife Never Sometimes Often Always Sum Never 7 7 2 3 19 Sometimes 2 8 3 7 20 Often 1 5 4 9 19 Always 2 8 9 14 33 Sum 12 28 18 33 91 Running a chi-square test of independence will yield: chisq.test(sex_satis, correct = T) ## Pearson's Chi-squared test ## ## data: sex_satis ## X-squared = 16.955, df = 9, p-value = 0.04942 Which means that the *probability of encountering a test statistic more extreme than $\small 16.95$ under the null hypothesis (i.e. independence between satisfaction of husbands and wives) is less than $5\%$ (exactly $\small 0.049$), and for many studies this is good enough to reject $\text{H}_0$- indeed, in this case, the intuition of common sense is reaffirmed by data. Now this should answer the question but I want to tie up the point about conditioning on the margins. Because we don't know the proportions in the population, we estimate them based on the sample, and we figure that under the null hypothesis of independence, the expected value of “never/never” is the probability that the wife “never” experiences satisfaction ($19/91$) times (independent of) the probability that the husband “never” experiences pleasure ($12/91$). Based on this resultant probability the expected frequency in the cell will be found by multiplying by the total number of cases ($91$).
Why do we use the chi-squared test to test independence of 2 categorical variables? $\chi_1^2$ is the distribution of a random variable $X^2$, where $X \sim N(0,1)$. In the test of independence of two categorical variables, the actual counts are subtracted from the expected counts,
35,407
Why do we use the chi-squared test to test independence of 2 categorical variables?
The threshold of p value is usually set at 0.05, which can be traced back to the beginning of statistics. If you want to be more conservative, you can of course use p<0.01. It just shows how unlikely the null hypothesis of independence is, therefore leading to a reasonable rejection of the null hypothesis. An example below is borrowed from https://www.icalcu.com/stat/chisqtest.html "In a final exam, 5 girls and 6 boys got A, 7 girls and 8 boys got A-, 8 girls and 7 boys got B, 6 girls and 5 boys got B-. In order to test whether gender and final exam score are independent, we would input "5 7 8 6" in the first row above for girls, and "6 8 7 5" in the second row above for boys. We get a chi-square value of 0.3151515 with 3 degrees of freedom, and the associated p value is at 0.9571542. As p>0.05, we can not reject the null hypothesis that gender and final exam score are independent."
Why do we use the chi-squared test to test independence of 2 categorical variables?
The threshold of p value is usually set at 0.05, which can be traced back to the beginning of statistics. If you want to be more conservative, you can of course use p<0.01. It just shows how unlikely
Why do we use the chi-squared test to test independence of 2 categorical variables? The threshold of p value is usually set at 0.05, which can be traced back to the beginning of statistics. If you want to be more conservative, you can of course use p<0.01. It just shows how unlikely the null hypothesis of independence is, therefore leading to a reasonable rejection of the null hypothesis. An example below is borrowed from https://www.icalcu.com/stat/chisqtest.html "In a final exam, 5 girls and 6 boys got A, 7 girls and 8 boys got A-, 8 girls and 7 boys got B, 6 girls and 5 boys got B-. In order to test whether gender and final exam score are independent, we would input "5 7 8 6" in the first row above for girls, and "6 8 7 5" in the second row above for boys. We get a chi-square value of 0.3151515 with 3 degrees of freedom, and the associated p value is at 0.9571542. As p>0.05, we can not reject the null hypothesis that gender and final exam score are independent."
Why do we use the chi-squared test to test independence of 2 categorical variables? The threshold of p value is usually set at 0.05, which can be traced back to the beginning of statistics. If you want to be more conservative, you can of course use p<0.01. It just shows how unlikely
35,408
Resources to get started with deep reinforcement learning
A nice introduction deep reinforcement learning by Lex Fridman (2019-01): https://youtu.be/zR11FLZ-O9M 2 complimentary, easy-to-read blog posts to get started on deep reinforcement learning: the first one focuses on policy gradients, the second one focuses on deep Q-learning. Deep Reinforcement Learning: Pong from Pixels (mirror) by Andrej Karpathy (May 31, 2016). Demystifying Deep Reinforcement Learning (mirror) by Tambet Matiise on Nervana (December 21, 2015) Then, two more in-depth resources: 10 videos, ~90 minutes each: Advanced Topics 2015 (COMPM050/COMPGI13) (mirror) on Reinforcement Learning by David Silver (2015) 455-page free book: Reinforcement Learning: An Introduction (2nd Edition) by Richard S. Sutton and Andrew G. Barto (2016) To start coding: Learning Reinforcement Learning (with Code, Exercises and Solutions) (mirror) by Denny Britz (October 2, 2016) Minimal and Clean Reinforcement Learning Examples (2017) Using Keras and Deep Q-Network to Play FlappyBird (mirror, code) by Ben Lau (July 10, 2016) (the code is straightforward to run on Ubuntu) Using Keras and Deep Deterministic Policy Gradient to play TORCS (mirror, code) by Ben Lau (October 11, 2016) (note: installing the gym_torcs requirement to have the code run may take some time, and instructions are only given for Linux). More links: A curated list of resources dedicated to reinforcement learning.
Resources to get started with deep reinforcement learning
A nice introduction deep reinforcement learning by Lex Fridman (2019-01): https://youtu.be/zR11FLZ-O9M 2 complimentary, easy-to-read blog posts to get started on deep reinforcement learning: the firs
Resources to get started with deep reinforcement learning A nice introduction deep reinforcement learning by Lex Fridman (2019-01): https://youtu.be/zR11FLZ-O9M 2 complimentary, easy-to-read blog posts to get started on deep reinforcement learning: the first one focuses on policy gradients, the second one focuses on deep Q-learning. Deep Reinforcement Learning: Pong from Pixels (mirror) by Andrej Karpathy (May 31, 2016). Demystifying Deep Reinforcement Learning (mirror) by Tambet Matiise on Nervana (December 21, 2015) Then, two more in-depth resources: 10 videos, ~90 minutes each: Advanced Topics 2015 (COMPM050/COMPGI13) (mirror) on Reinforcement Learning by David Silver (2015) 455-page free book: Reinforcement Learning: An Introduction (2nd Edition) by Richard S. Sutton and Andrew G. Barto (2016) To start coding: Learning Reinforcement Learning (with Code, Exercises and Solutions) (mirror) by Denny Britz (October 2, 2016) Minimal and Clean Reinforcement Learning Examples (2017) Using Keras and Deep Q-Network to Play FlappyBird (mirror, code) by Ben Lau (July 10, 2016) (the code is straightforward to run on Ubuntu) Using Keras and Deep Deterministic Policy Gradient to play TORCS (mirror, code) by Ben Lau (October 11, 2016) (note: installing the gym_torcs requirement to have the code run may take some time, and instructions are only given for Linux). More links: A curated list of resources dedicated to reinforcement learning.
Resources to get started with deep reinforcement learning A nice introduction deep reinforcement learning by Lex Fridman (2019-01): https://youtu.be/zR11FLZ-O9M 2 complimentary, easy-to-read blog posts to get started on deep reinforcement learning: the firs
35,409
Resources to get started with deep reinforcement learning
You can see many resources on github already including this recent list of Deep RL papers Also checkout some implementations such as Deep Q learning And here is a nice video by David Silver at RLDM videolectures.net deep RL
Resources to get started with deep reinforcement learning
You can see many resources on github already including this recent list of Deep RL papers Also checkout some implementations such as Deep Q learning And here is a nice video by David Silver at RLDM v
Resources to get started with deep reinforcement learning You can see many resources on github already including this recent list of Deep RL papers Also checkout some implementations such as Deep Q learning And here is a nice video by David Silver at RLDM videolectures.net deep RL
Resources to get started with deep reinforcement learning You can see many resources on github already including this recent list of Deep RL papers Also checkout some implementations such as Deep Q learning And here is a nice video by David Silver at RLDM v
35,410
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms?
This is a bit of a necropost, but if you are still interested, here is a set of general tensorflow tutorials that explain how to run things in tensorflow. It includes examples of doing linear and nearest neighbor regressions, so it should help with your original question. https://github.com/aymericdamien/TensorFlow-Examples In addition, here is the original tensorflow tutorial for doing differential equations in tensorflow. Gives you an idea of the flexibility of the tensorflow computation graph. https://www.tensorflow.org/versions/r0.9/tutorials/pdes/index.html
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms
This is a bit of a necropost, but if you are still interested, here is a set of general tensorflow tutorials that explain how to run things in tensorflow. It includes examples of doing linear and near
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms? This is a bit of a necropost, but if you are still interested, here is a set of general tensorflow tutorials that explain how to run things in tensorflow. It includes examples of doing linear and nearest neighbor regressions, so it should help with your original question. https://github.com/aymericdamien/TensorFlow-Examples In addition, here is the original tensorflow tutorial for doing differential equations in tensorflow. Gives you an idea of the flexibility of the tensorflow computation graph. https://www.tensorflow.org/versions/r0.9/tutorials/pdes/index.html
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms This is a bit of a necropost, but if you are still interested, here is a set of general tensorflow tutorials that explain how to run things in tensorflow. It includes examples of doing linear and near
35,411
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms?
With TensorFlow you can implement any machine learning algorithm that relies on gradient descent and backpropagation (chain rule) or can be restated as such. That includes logistic regression, support vector machines and many others. But I wouldn't know how to implement random forest in TensorFlow.
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms
With TensorFlow you can implement any machine learning algorithm that relies on gradient descent and backpropagation (chain rule) or can be restated as such. That includes logistic regression, support
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms? With TensorFlow you can implement any machine learning algorithm that relies on gradient descent and backpropagation (chain rule) or can be restated as such. That includes logistic regression, support vector machines and many others. But I wouldn't know how to implement random forest in TensorFlow.
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms With TensorFlow you can implement any machine learning algorithm that relies on gradient descent and backpropagation (chain rule) or can be restated as such. That includes logistic regression, support
35,412
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms?
A few of numpy operations are mirrored in TensorFlow, so if you can implement it in numpy, porting to TensorFlow can be straightforward. For instance, here's an example of K-means clustering: https://stackoverflow.com/questions/33621643/how-would-i-implement-k-means-with-tensorflow
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms
A few of numpy operations are mirrored in TensorFlow, so if you can implement it in numpy, porting to TensorFlow can be straightforward. For instance, here's an example of K-means clustering: https://
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms? A few of numpy operations are mirrored in TensorFlow, so if you can implement it in numpy, porting to TensorFlow can be straightforward. For instance, here's an example of K-means clustering: https://stackoverflow.com/questions/33621643/how-would-i-implement-k-means-with-tensorflow
In TensorFlow's Computational Model, is it possible to implement general machine learning algorithms A few of numpy operations are mirrored in TensorFlow, so if you can implement it in numpy, porting to TensorFlow can be straightforward. For instance, here's an example of K-means clustering: https://
35,413
Correlation coefficient for a uniform distribution on an ellipse
Let $(X,Y)$ be uniformly distributed on the interior of the ellipse $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$$ where $a$ and $b$ are the semi-axes of the ellipse. Then, $X$ and $Y$ have marginal densities \begin{align} f_X(x) &= \frac{2}{\pi a^2}\sqrt{a^2-x^2}\,\,\mathbf 1_{-a,a}(x),\\ f_X(x) &= \frac{2}{\pi b^2}\sqrt{b^2-y^2}\,\,\mathbf 1_{-b,b}(y), \end{align} and it is easy to see that $E[X] = E[Y] = 0$. Also, \begin{align} \sigma_X^2 = E[X^2] &= \frac{2}{\pi a^2}\int_a^a x^2\sqrt{a^2-x^2}\,\mathrm dx\\ &= \frac{4}{\pi a^2}\int_0^a x^2\sqrt{a^2-x^2}\,\mathrm dx\\ &= \frac{4}{\pi a^2}\times a^4 \frac 12\frac{\Gamma(3/2)\Gamma(3/2)}{\Gamma(3)}\\ &= \frac{a^2}{4}, \end{align} and similarly, $\sigma_Y^2 = \frac{b^2}{4}$. Finally, $X$ and $Y$ are uncorrelated random variables. Let \begin{align} U &= X\cos \theta - Y \sin \theta\\ V &= X\sin \theta + Y \cos \theta \end{align} which is a rotation transformation applied to $(X,Y)$. Then, $(U,V)$ are uniformly distributed on the interior of an ellipse whose axes do not coincide with the $u$ and $v$ axes. But, it is easy to verify that $U$ and $V$ are zero-mean random variables and that their variances are \begin{align} \sigma_U^2 &= \frac{a^2\cos^2\theta + b^2\sin^2\theta}{4}\\ \sigma_V^2 &= \frac{a^2\sin^2\theta + b^2\cos^2\theta}{4} \end{align} Furthermore, $$\operatorname{cov}(U,V) = (\sigma_X^2-\sigma_Y^2)\sin\theta\cos\theta = \frac{a^2-b^2}{8}\sin 2\theta$$ from which we can get the value of $\rho_{U,V}$. Now, the ellipse on whose interior $(U,V)$ is uniformly distributed has equation $$\frac{(u \cos\theta + v\sin \theta)^2}{a^2} + \frac{(-u \sin\theta + v\cos \theta)^2}{b^2} = 1,$$ that is, $$\left(\frac{\cos^2\theta}{a^2} + \frac{\sin^2\theta}{b^2}\right) u^2 + \left(\frac{\sin^2\theta}{a^2} + \frac{\cos^2\theta}{b^2}\right) v^2 + \left(\left(\frac{1}{a^2} - \frac{1}{b^2}\right)\sin 2\theta \right)uv = 1,$$ which can also be expressed as $$\sigma_V^2\cdot u^2 + \sigma_U^2\cdot v^2 -2\rho_{U,V}\sigma_U\sigma_V\cdot uv = \frac{a^2b^2}{4}\tag{1}$$ Setting $u = 0$ in $(1)$ gives $\displaystyle h = \frac{ab}{\sigma_U}$. while implicit differentiation of $(1)$ with respect to $u$ gives $$\sigma_V^2\cdot 2u + \sigma_U^2\cdot 2v\frac{\mathrm dv}{\mathrm du} -2\rho_{U,V}\sigma_U\sigma_V\cdot \left(v + u\frac{\mathrm dv}{\mathrm du}\right) = 0,$$ that is, the tangent to the ellipse $(1)$ is horizontal at the two points $(u,v)$ on the ellipse for which $$\rho_{U,V}\sigma_U\cdot v = \sigma_v\cdot u.$$ The value of $H$ can be figured out from this, and will (in the unlikely event that I have made no mistakes in doing the above calculations) lead to the desired result.
Correlation coefficient for a uniform distribution on an ellipse
Let $(X,Y)$ be uniformly distributed on the interior of the ellipse $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$$ where $a$ and $b$ are the semi-axes of the ellipse. Then, $X$ and $Y$ have marginal densi
Correlation coefficient for a uniform distribution on an ellipse Let $(X,Y)$ be uniformly distributed on the interior of the ellipse $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$$ where $a$ and $b$ are the semi-axes of the ellipse. Then, $X$ and $Y$ have marginal densities \begin{align} f_X(x) &= \frac{2}{\pi a^2}\sqrt{a^2-x^2}\,\,\mathbf 1_{-a,a}(x),\\ f_X(x) &= \frac{2}{\pi b^2}\sqrt{b^2-y^2}\,\,\mathbf 1_{-b,b}(y), \end{align} and it is easy to see that $E[X] = E[Y] = 0$. Also, \begin{align} \sigma_X^2 = E[X^2] &= \frac{2}{\pi a^2}\int_a^a x^2\sqrt{a^2-x^2}\,\mathrm dx\\ &= \frac{4}{\pi a^2}\int_0^a x^2\sqrt{a^2-x^2}\,\mathrm dx\\ &= \frac{4}{\pi a^2}\times a^4 \frac 12\frac{\Gamma(3/2)\Gamma(3/2)}{\Gamma(3)}\\ &= \frac{a^2}{4}, \end{align} and similarly, $\sigma_Y^2 = \frac{b^2}{4}$. Finally, $X$ and $Y$ are uncorrelated random variables. Let \begin{align} U &= X\cos \theta - Y \sin \theta\\ V &= X\sin \theta + Y \cos \theta \end{align} which is a rotation transformation applied to $(X,Y)$. Then, $(U,V)$ are uniformly distributed on the interior of an ellipse whose axes do not coincide with the $u$ and $v$ axes. But, it is easy to verify that $U$ and $V$ are zero-mean random variables and that their variances are \begin{align} \sigma_U^2 &= \frac{a^2\cos^2\theta + b^2\sin^2\theta}{4}\\ \sigma_V^2 &= \frac{a^2\sin^2\theta + b^2\cos^2\theta}{4} \end{align} Furthermore, $$\operatorname{cov}(U,V) = (\sigma_X^2-\sigma_Y^2)\sin\theta\cos\theta = \frac{a^2-b^2}{8}\sin 2\theta$$ from which we can get the value of $\rho_{U,V}$. Now, the ellipse on whose interior $(U,V)$ is uniformly distributed has equation $$\frac{(u \cos\theta + v\sin \theta)^2}{a^2} + \frac{(-u \sin\theta + v\cos \theta)^2}{b^2} = 1,$$ that is, $$\left(\frac{\cos^2\theta}{a^2} + \frac{\sin^2\theta}{b^2}\right) u^2 + \left(\frac{\sin^2\theta}{a^2} + \frac{\cos^2\theta}{b^2}\right) v^2 + \left(\left(\frac{1}{a^2} - \frac{1}{b^2}\right)\sin 2\theta \right)uv = 1,$$ which can also be expressed as $$\sigma_V^2\cdot u^2 + \sigma_U^2\cdot v^2 -2\rho_{U,V}\sigma_U\sigma_V\cdot uv = \frac{a^2b^2}{4}\tag{1}$$ Setting $u = 0$ in $(1)$ gives $\displaystyle h = \frac{ab}{\sigma_U}$. while implicit differentiation of $(1)$ with respect to $u$ gives $$\sigma_V^2\cdot 2u + \sigma_U^2\cdot 2v\frac{\mathrm dv}{\mathrm du} -2\rho_{U,V}\sigma_U\sigma_V\cdot \left(v + u\frac{\mathrm dv}{\mathrm du}\right) = 0,$$ that is, the tangent to the ellipse $(1)$ is horizontal at the two points $(u,v)$ on the ellipse for which $$\rho_{U,V}\sigma_U\cdot v = \sigma_v\cdot u.$$ The value of $H$ can be figured out from this, and will (in the unlikely event that I have made no mistakes in doing the above calculations) lead to the desired result.
Correlation coefficient for a uniform distribution on an ellipse Let $(X,Y)$ be uniformly distributed on the interior of the ellipse $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$$ where $a$ and $b$ are the semi-axes of the ellipse. Then, $X$ and $Y$ have marginal densi
35,414
Covariance of Non-Random Vectors Equal to Zero
"Covariance" is used in many distinct senses. It can be a property of a bivariate population, a property of a bivariate distribution, a property of a paired dataset, or an estimator of (1) or (2) based on a sample. Because any finite collection of ordered pairs $((x_1,y_1), \ldots, (x_n,y_n))$ can be considered an instance of any one of these four things--a population, a distribution, a dataset, or a sample--multiple interpretations of "covariance" are possible. They are not the same. Thus, some non-mathematical information is needed in order to determine in any case what "covariance" means. In light of this, let's revisit three statements made in the two referenced posts: If $u,v$ are random vectors, then $\operatorname{Cov}(u,v)$ is the matrix of elements $\operatorname{Cov}(u_i,v_j).$ This is complicated, because $(u,v)$ can be viewed in two equivalent ways. The context implies $u$ and $v$ are vectors in the same $n$-dimensional real vector space and each is written $u=(u_1,u_2,\ldots,u_n)$, etc. Thus "$(u,v)$" denotes a bivariate distribution (of vectors), as in (2) above, but it can also be considered a collection of pairs $(u_1,v_1), (u_2,v_2), \ldots, (u_n,v_n)$, giving it the structure of a paired dataset, as in (3) above. However, its elements are random variables, not numbers. Regardless, these two points of view allow us to interpret "$\operatorname{Cov}$" ambiguously: would it be $$\operatorname{Cov}(u,v) = \frac{1}{n}\left(\sum_{i=1}^n u_i v_i\right) - \left(\frac{1}{n}\sum_{i=1}^n u_i\right)\left(\frac{1}{n}\sum_{i-1}^n v_i\right),\tag{1}$$ which (as a function of the random variables $u$ and $v$) is a random variable, or would it be the matrix $$\left(\operatorname{Cov}(u,v)\right)_{ij} = \operatorname{Cov}(u_i,v_j) = \mathbb{E}(u_i v_j) - \mathbb{E}(u_i)\mathbb{E}(v_j),\tag{2}$$ which is an $n\times n$ matrix of numbers? Only the context in which such an ambiguous expression appears can tell us which is meant, but the latter may be more common than the former. If $u,v$ are not random vectors, then $\operatorname{Cov}(u,v)$ is the scalar $\Sigma u_i v_i$. Maybe. This assertion understands $u$ and $v$ in the sense of a population or dataset and assumes the averages of the $u_i$ and $v_i$ in that dataset are both zero. More generally, for such a dataset, their covariance would be given by formula $(1)$ above. Another nuance is that in many circumstances $(u,v)$ represent a sample of a bivariate population or distribution. That is, they are considered not as an ordered pair of vectors but as a dataset $(u_1,v_1), (u_2,v_2), \ldots, (u_n,v_n)$ wherein each $(u_i,v_i)$ is an independent realization of a common random variable $(U,V)$. Then, it is likely that "covariance" would refer to an estimate of $\operatorname{Cov}(U,V)$, such as $$\operatorname{Cov}(u,v) = \frac{1}{n-1}\left(\sum_{i=1}^n u_i v_i - \frac{1}{n}\left(\sum_{i=1}^n u_i\right)\left(\sum_{i-1}^n v_i\right)\right).$$ This is the fourth sense of "covariance." If two vectors are not random, then their covariance is zero. This is an unusual interpretation. It must be thinking of "covariance" in the sense of formula $(2)$ above, $$\left(\operatorname{Cov}(u,v)\right)_{ij} = \operatorname{Cov}(u_i,v_j) = 0$$ Each $u_i$ and $v_j$ is considered, in effect, a random variable that happens to be a constant. In a regression context (where vectors, numbers, and random variables all occur together) some of these distinctions are further elaborated in the thread on variance and covariance in the context of deterministic values.
Covariance of Non-Random Vectors Equal to Zero
"Covariance" is used in many distinct senses. It can be a property of a bivariate population, a property of a bivariate distribution, a property of a paired dataset, or an estimator of (1) or (2) ba
Covariance of Non-Random Vectors Equal to Zero "Covariance" is used in many distinct senses. It can be a property of a bivariate population, a property of a bivariate distribution, a property of a paired dataset, or an estimator of (1) or (2) based on a sample. Because any finite collection of ordered pairs $((x_1,y_1), \ldots, (x_n,y_n))$ can be considered an instance of any one of these four things--a population, a distribution, a dataset, or a sample--multiple interpretations of "covariance" are possible. They are not the same. Thus, some non-mathematical information is needed in order to determine in any case what "covariance" means. In light of this, let's revisit three statements made in the two referenced posts: If $u,v$ are random vectors, then $\operatorname{Cov}(u,v)$ is the matrix of elements $\operatorname{Cov}(u_i,v_j).$ This is complicated, because $(u,v)$ can be viewed in two equivalent ways. The context implies $u$ and $v$ are vectors in the same $n$-dimensional real vector space and each is written $u=(u_1,u_2,\ldots,u_n)$, etc. Thus "$(u,v)$" denotes a bivariate distribution (of vectors), as in (2) above, but it can also be considered a collection of pairs $(u_1,v_1), (u_2,v_2), \ldots, (u_n,v_n)$, giving it the structure of a paired dataset, as in (3) above. However, its elements are random variables, not numbers. Regardless, these two points of view allow us to interpret "$\operatorname{Cov}$" ambiguously: would it be $$\operatorname{Cov}(u,v) = \frac{1}{n}\left(\sum_{i=1}^n u_i v_i\right) - \left(\frac{1}{n}\sum_{i=1}^n u_i\right)\left(\frac{1}{n}\sum_{i-1}^n v_i\right),\tag{1}$$ which (as a function of the random variables $u$ and $v$) is a random variable, or would it be the matrix $$\left(\operatorname{Cov}(u,v)\right)_{ij} = \operatorname{Cov}(u_i,v_j) = \mathbb{E}(u_i v_j) - \mathbb{E}(u_i)\mathbb{E}(v_j),\tag{2}$$ which is an $n\times n$ matrix of numbers? Only the context in which such an ambiguous expression appears can tell us which is meant, but the latter may be more common than the former. If $u,v$ are not random vectors, then $\operatorname{Cov}(u,v)$ is the scalar $\Sigma u_i v_i$. Maybe. This assertion understands $u$ and $v$ in the sense of a population or dataset and assumes the averages of the $u_i$ and $v_i$ in that dataset are both zero. More generally, for such a dataset, their covariance would be given by formula $(1)$ above. Another nuance is that in many circumstances $(u,v)$ represent a sample of a bivariate population or distribution. That is, they are considered not as an ordered pair of vectors but as a dataset $(u_1,v_1), (u_2,v_2), \ldots, (u_n,v_n)$ wherein each $(u_i,v_i)$ is an independent realization of a common random variable $(U,V)$. Then, it is likely that "covariance" would refer to an estimate of $\operatorname{Cov}(U,V)$, such as $$\operatorname{Cov}(u,v) = \frac{1}{n-1}\left(\sum_{i=1}^n u_i v_i - \frac{1}{n}\left(\sum_{i=1}^n u_i\right)\left(\sum_{i-1}^n v_i\right)\right).$$ This is the fourth sense of "covariance." If two vectors are not random, then their covariance is zero. This is an unusual interpretation. It must be thinking of "covariance" in the sense of formula $(2)$ above, $$\left(\operatorname{Cov}(u,v)\right)_{ij} = \operatorname{Cov}(u_i,v_j) = 0$$ Each $u_i$ and $v_j$ is considered, in effect, a random variable that happens to be a constant. In a regression context (where vectors, numbers, and random variables all occur together) some of these distinctions are further elaborated in the thread on variance and covariance in the context of deterministic values.
Covariance of Non-Random Vectors Equal to Zero "Covariance" is used in many distinct senses. It can be a property of a bivariate population, a property of a bivariate distribution, a property of a paired dataset, or an estimator of (1) or (2) ba
35,415
Covariance of Non-Random Vectors Equal to Zero
You have a misconception. Using the cov function on a pair of vectors computes the sample covariance of the two vectors. That is, it is assuming X and Y are vectors of observations of two one-dimensional random variables. That is why it doesn't give zero as an answer. What is zero (a matrix filled with zeroes, actually) is the covariance of two nonrandom numeric vectors. It would be silly to try to compute that covariance matrix though ^^ EDIT: Here's an example, silliness and all: x <- matrix(rep(1:3,5), nrow=5, byrow=T) y <- matrix(rep(c(4.3,1.2,999),5), nrow=5, byrow=T) x y cov(x,y) # All zeroes
Covariance of Non-Random Vectors Equal to Zero
You have a misconception. Using the cov function on a pair of vectors computes the sample covariance of the two vectors. That is, it is assuming X and Y are vectors of observations of two one-dimensio
Covariance of Non-Random Vectors Equal to Zero You have a misconception. Using the cov function on a pair of vectors computes the sample covariance of the two vectors. That is, it is assuming X and Y are vectors of observations of two one-dimensional random variables. That is why it doesn't give zero as an answer. What is zero (a matrix filled with zeroes, actually) is the covariance of two nonrandom numeric vectors. It would be silly to try to compute that covariance matrix though ^^ EDIT: Here's an example, silliness and all: x <- matrix(rep(1:3,5), nrow=5, byrow=T) y <- matrix(rep(c(4.3,1.2,999),5), nrow=5, byrow=T) x y cov(x,y) # All zeroes
Covariance of Non-Random Vectors Equal to Zero You have a misconception. Using the cov function on a pair of vectors computes the sample covariance of the two vectors. That is, it is assuming X and Y are vectors of observations of two one-dimensio
35,416
Covariance of Non-Random Vectors Equal to Zero
Simply put a non-random vector has component elements that are constant -- they do not change by definition. Since they do not change, there is no variability in their values. Hence their variances are always zero.
Covariance of Non-Random Vectors Equal to Zero
Simply put a non-random vector has component elements that are constant -- they do not change by definition. Since they do not change, there is no variability in their values. Hence their variances
Covariance of Non-Random Vectors Equal to Zero Simply put a non-random vector has component elements that are constant -- they do not change by definition. Since they do not change, there is no variability in their values. Hence their variances are always zero.
Covariance of Non-Random Vectors Equal to Zero Simply put a non-random vector has component elements that are constant -- they do not change by definition. Since they do not change, there is no variability in their values. Hence their variances
35,417
How to best evaluate a time series prediction algorithm?
What you are proposing is known as a "rolling origin" evaluation in the forecasting literature. And yes, this method of evaluating forecasting algorithms is very widely used. If you find that performance is a bottleneck, you could do subsampling. Don't use every possible origin. Instead, use, e.g., every fifth possible origin. (Make sure you don't introduce unwanted confounding between your subsampled origins and seasonality in the data. For instance, if you use daily data, don't use every seventh day as an origin, because then you are really only assessing forecasting quality on Tuesdays, or only on Thursdays etc.) Then again, you don't really need to train your model again from scratch every time you roll the origin forward. Start out from the last trained model. (For example, in Exponential Smoothing, simply update your components with the new data since the last training.) This should dramatically cut down on your overall training time.
How to best evaluate a time series prediction algorithm?
What you are proposing is known as a "rolling origin" evaluation in the forecasting literature. And yes, this method of evaluating forecasting algorithms is very widely used. If you find that performa
How to best evaluate a time series prediction algorithm? What you are proposing is known as a "rolling origin" evaluation in the forecasting literature. And yes, this method of evaluating forecasting algorithms is very widely used. If you find that performance is a bottleneck, you could do subsampling. Don't use every possible origin. Instead, use, e.g., every fifth possible origin. (Make sure you don't introduce unwanted confounding between your subsampled origins and seasonality in the data. For instance, if you use daily data, don't use every seventh day as an origin, because then you are really only assessing forecasting quality on Tuesdays, or only on Thursdays etc.) Then again, you don't really need to train your model again from scratch every time you roll the origin forward. Start out from the last trained model. (For example, in Exponential Smoothing, simply update your components with the new data since the last training.) This should dramatically cut down on your overall training time.
How to best evaluate a time series prediction algorithm? What you are proposing is known as a "rolling origin" evaluation in the forecasting literature. And yes, this method of evaluating forecasting algorithms is very widely used. If you find that performa
35,418
Estimators independence in simple linear regression
This is tantamount to showing that $\widehat{\boldsymbol{\beta}}$, the vector of estimates, is independent of the residual vector $\mathbf{e}$. I trust that you are familiar with the matrix notation of the model, it makes the proof quite short. Recall that the OLS estimator is given by $\left( \mathbf{X}^{T}\mathbf{X} \right)^{-1}\mathbf{X}^{T}\mathbf{Y}$ and the vector of residuals by $\left(\mathbf{I}-\mathbf{H} \right)\mathbf{Y}$, where $\mathbf{H}$ is the projection matrix given by $\mathbf{X}\left(\mathbf{X}^{T}\mathbf{X} \right)^{-1}\mathbf{X}^{T}$. Assuming that $\mathbf{Y}$ is multivariate normal, which is the assumption you need in order to construct finite-sample tests and confidence intervals, what we want to do is take advantage of the fact that linear combinations of multivariate normal variables are also multivariate normal. Hence we rewrite these two as follows $$\begin{bmatrix} \widehat{\boldsymbol{\beta}} \\ \mathbf{e} \end{bmatrix}=\begin{bmatrix} \left( \mathbf{X}^{T}\mathbf{X} \right)^{-1}\mathbf{X}^{T} \\ \mathbf{I}-\mathbf{H} \end{bmatrix} \mathbf{Y}$$ And now we need to remember that if $\mathbf{X}\sim N_p \left(\boldsymbol{\mu}, \boldsymbol{\Sigma} \right)$, then $\mathbf{AX}\sim N_p \left(\mathbf{A}\boldsymbol{\mu}, \mathbf{A}\boldsymbol{\Sigma}\mathbf{A}^{T} \right)$ (the distribution is closed under affine transformations). We are mainly interested in the new covariance matrix as it being diagonal will indicate that the variables are independent and so we focus on that. It is easy to show-and I leave the details to you- that the covariance matrix is of the form $$ \begin{bmatrix} \sigma^2 \left(\mathbf{X}^{T}\mathbf{X} \right)^{-1} & \mathbf{0} \\ \mathbf{0} & \sigma^2 \left(\mathbf{I}-\mathbf{H} \right) \end{bmatrix} $$ and so we may conclude that the random variables are independent. And since $\widehat{\boldsymbol{\beta}}$ is independent of $\mathbf{e}$, it is also independent of the Mean Squared Error $\frac{\mathbf{e}^{T}\mathbf{e}}{n-k}$, as we wanted to show. Note that in general lack of correlation does not imply independence, this is a special property of the multivariate normal distribution and undoubtedly one of the reasons it is loved so much by statisticians. Hope this helps.
Estimators independence in simple linear regression
This is tantamount to showing that $\widehat{\boldsymbol{\beta}}$, the vector of estimates, is independent of the residual vector $\mathbf{e}$. I trust that you are familiar with the matrix notation o
Estimators independence in simple linear regression This is tantamount to showing that $\widehat{\boldsymbol{\beta}}$, the vector of estimates, is independent of the residual vector $\mathbf{e}$. I trust that you are familiar with the matrix notation of the model, it makes the proof quite short. Recall that the OLS estimator is given by $\left( \mathbf{X}^{T}\mathbf{X} \right)^{-1}\mathbf{X}^{T}\mathbf{Y}$ and the vector of residuals by $\left(\mathbf{I}-\mathbf{H} \right)\mathbf{Y}$, where $\mathbf{H}$ is the projection matrix given by $\mathbf{X}\left(\mathbf{X}^{T}\mathbf{X} \right)^{-1}\mathbf{X}^{T}$. Assuming that $\mathbf{Y}$ is multivariate normal, which is the assumption you need in order to construct finite-sample tests and confidence intervals, what we want to do is take advantage of the fact that linear combinations of multivariate normal variables are also multivariate normal. Hence we rewrite these two as follows $$\begin{bmatrix} \widehat{\boldsymbol{\beta}} \\ \mathbf{e} \end{bmatrix}=\begin{bmatrix} \left( \mathbf{X}^{T}\mathbf{X} \right)^{-1}\mathbf{X}^{T} \\ \mathbf{I}-\mathbf{H} \end{bmatrix} \mathbf{Y}$$ And now we need to remember that if $\mathbf{X}\sim N_p \left(\boldsymbol{\mu}, \boldsymbol{\Sigma} \right)$, then $\mathbf{AX}\sim N_p \left(\mathbf{A}\boldsymbol{\mu}, \mathbf{A}\boldsymbol{\Sigma}\mathbf{A}^{T} \right)$ (the distribution is closed under affine transformations). We are mainly interested in the new covariance matrix as it being diagonal will indicate that the variables are independent and so we focus on that. It is easy to show-and I leave the details to you- that the covariance matrix is of the form $$ \begin{bmatrix} \sigma^2 \left(\mathbf{X}^{T}\mathbf{X} \right)^{-1} & \mathbf{0} \\ \mathbf{0} & \sigma^2 \left(\mathbf{I}-\mathbf{H} \right) \end{bmatrix} $$ and so we may conclude that the random variables are independent. And since $\widehat{\boldsymbol{\beta}}$ is independent of $\mathbf{e}$, it is also independent of the Mean Squared Error $\frac{\mathbf{e}^{T}\mathbf{e}}{n-k}$, as we wanted to show. Note that in general lack of correlation does not imply independence, this is a special property of the multivariate normal distribution and undoubtedly one of the reasons it is loved so much by statisticians. Hope this helps.
Estimators independence in simple linear regression This is tantamount to showing that $\widehat{\boldsymbol{\beta}}$, the vector of estimates, is independent of the residual vector $\mathbf{e}$. I trust that you are familiar with the matrix notation o
35,419
T-test using only summary data in a box plot
Since you have the sample means and your hypothesis relates to population means, I've assumed you'll definitely want to use the sample means in what follows. With some distributional assumptions, you can certainly get somewhere. If the sample sizes are quite large you could assume a distribution in order to scale the IQRs to an estimate of $\sigma$ and just treat it as a z-test. (n=30 isn't really "large" though) e.g. if you assume normality, the population interquartile range is about 1.35$\sigma$, so if the sample is large enough that the population IQR is estimated with little error, you can estimate $\sigma$ and have an effective test at the normal. In this case, if you don't assume equal variances, then you get $\tilde{\sigma_i}=\text{IQR}_i/1.35$, then calculate $\tilde{\sigma}_D^2 = \tilde{\sigma}_1^2/n_1+\tilde{\sigma}_2^2/n_2$ and then take $z^* = \frac{\bar{x}_1-\bar{x}_2}{\tilde{\sigma}_D}$ and look up z-tables. [By way of a check, I just did a simulation where I generated normal samples of size 30 (with equal variance, though I didn't assume it in the calculation), and the test is anticonservative (i.e. the type I error rate is higher than nominal), so when you attempt to do a 5% test it looks like you're actually getting somewhere in the region of 6.8% (the approximation will likely be a bit worse if the variances differ). If you can tolerate that, then that's probably fine. Of course you could lower the significance level to compensate for the anticonservatism but I'd be inclined to bite the bullet and try option 2. Once sample sizes hit 200 or so, though, this works pretty well.] If either sample size is not large, you can still do something, but the distribution of the statistic will depend on the exact method by which the quartiles were computed as well as the particular sample sizes. In particular, you could either a. assume equal variances and use a test statistic akin to an equal-variance t-statistic but with an estimate of $\sigma^2$ based on a weighted average of the squares of the two IQRs; or b. not make an assumption of equal variance and use a test statistic more akin to a Welch-Satterthwaite type statistic. In the first case the distribution of the test statistic could be obtained fairly simply by simulation from the assumed distribution. (In the second case things are a bit more complicated because the distribution will depend on the way the spreads differ -- but something could still be done.) If you're not prepared to make some distributional assumption, you can still bound the sample standard deviation and so get upper and lower bounds on the t-statistic; however, the bounds may not be very narrow. If you hadn't had the sample means, you could use the medians in an analog of the t-test. If you're assuming normality (or even just symmetry and existence of means) then the medians will estimate the respective means; however, since we only need to deal with the difference in means, substantially weaker assumptions will suffice for this to work as a test. In this case you can get critical values (or indeed, p-values) via simulation quite easily, but the null distribution under a normal assumption is pretty close to t-distributed; a quite decent approximation to the p-value can be obtained from t-tables, but suitable degrees of freedom are substantially lower than you'd have from a t-test (close to half!) -- and the test statistic should be scaled as well, since the variances don't exactly correspond. This won't have especially good power at the normal, but it will have good robustness to deviations from normality. As an example, for a statistic of this form: $t^* = \frac{\tilde{x}_1-\tilde{x}_2}{\sqrt{q_1^2/n+q_2^2/n}}$ where $\tilde{x_i}$ is the median of sample $i$ and $q_i$ is the interquartile range of sample $i$ (which is analogous to a particular form of two-sample t-test for equal variance and equal $n$). I simulated 40,000 samples of size 30 and 30. A Q-Q plot of absolute values of $t^*$ vs absolute values of quantiles of $c\cdot t_{40}$ (for $c=1.064$) is plotted below (grey), and the 45 degree line is drawn in green. The second plot shows detail in the region of typical significance levels (including, but not limited to values between 1% and 10%). The approximation is accurate to about 3 figures over most of that range. [Similar plots are obtained for a variety of other degrees of freedom in the vicinity (with suitably chosen $c$) for each. Simulations at a variety of sample sizes suggest that t-distribution approximations work well across a wide range of $n$ for the equal-variance equal-sample-size case. I expect approximation via t-distributions will be adequate for the equal-variance unequal-sample-size case, but the simulations and analysis required would take a more substantial amount of time.]
T-test using only summary data in a box plot
Since you have the sample means and your hypothesis relates to population means, I've assumed you'll definitely want to use the sample means in what follows. With some distributional assumptions, you
T-test using only summary data in a box plot Since you have the sample means and your hypothesis relates to population means, I've assumed you'll definitely want to use the sample means in what follows. With some distributional assumptions, you can certainly get somewhere. If the sample sizes are quite large you could assume a distribution in order to scale the IQRs to an estimate of $\sigma$ and just treat it as a z-test. (n=30 isn't really "large" though) e.g. if you assume normality, the population interquartile range is about 1.35$\sigma$, so if the sample is large enough that the population IQR is estimated with little error, you can estimate $\sigma$ and have an effective test at the normal. In this case, if you don't assume equal variances, then you get $\tilde{\sigma_i}=\text{IQR}_i/1.35$, then calculate $\tilde{\sigma}_D^2 = \tilde{\sigma}_1^2/n_1+\tilde{\sigma}_2^2/n_2$ and then take $z^* = \frac{\bar{x}_1-\bar{x}_2}{\tilde{\sigma}_D}$ and look up z-tables. [By way of a check, I just did a simulation where I generated normal samples of size 30 (with equal variance, though I didn't assume it in the calculation), and the test is anticonservative (i.e. the type I error rate is higher than nominal), so when you attempt to do a 5% test it looks like you're actually getting somewhere in the region of 6.8% (the approximation will likely be a bit worse if the variances differ). If you can tolerate that, then that's probably fine. Of course you could lower the significance level to compensate for the anticonservatism but I'd be inclined to bite the bullet and try option 2. Once sample sizes hit 200 or so, though, this works pretty well.] If either sample size is not large, you can still do something, but the distribution of the statistic will depend on the exact method by which the quartiles were computed as well as the particular sample sizes. In particular, you could either a. assume equal variances and use a test statistic akin to an equal-variance t-statistic but with an estimate of $\sigma^2$ based on a weighted average of the squares of the two IQRs; or b. not make an assumption of equal variance and use a test statistic more akin to a Welch-Satterthwaite type statistic. In the first case the distribution of the test statistic could be obtained fairly simply by simulation from the assumed distribution. (In the second case things are a bit more complicated because the distribution will depend on the way the spreads differ -- but something could still be done.) If you're not prepared to make some distributional assumption, you can still bound the sample standard deviation and so get upper and lower bounds on the t-statistic; however, the bounds may not be very narrow. If you hadn't had the sample means, you could use the medians in an analog of the t-test. If you're assuming normality (or even just symmetry and existence of means) then the medians will estimate the respective means; however, since we only need to deal with the difference in means, substantially weaker assumptions will suffice for this to work as a test. In this case you can get critical values (or indeed, p-values) via simulation quite easily, but the null distribution under a normal assumption is pretty close to t-distributed; a quite decent approximation to the p-value can be obtained from t-tables, but suitable degrees of freedom are substantially lower than you'd have from a t-test (close to half!) -- and the test statistic should be scaled as well, since the variances don't exactly correspond. This won't have especially good power at the normal, but it will have good robustness to deviations from normality. As an example, for a statistic of this form: $t^* = \frac{\tilde{x}_1-\tilde{x}_2}{\sqrt{q_1^2/n+q_2^2/n}}$ where $\tilde{x_i}$ is the median of sample $i$ and $q_i$ is the interquartile range of sample $i$ (which is analogous to a particular form of two-sample t-test for equal variance and equal $n$). I simulated 40,000 samples of size 30 and 30. A Q-Q plot of absolute values of $t^*$ vs absolute values of quantiles of $c\cdot t_{40}$ (for $c=1.064$) is plotted below (grey), and the 45 degree line is drawn in green. The second plot shows detail in the region of typical significance levels (including, but not limited to values between 1% and 10%). The approximation is accurate to about 3 figures over most of that range. [Similar plots are obtained for a variety of other degrees of freedom in the vicinity (with suitably chosen $c$) for each. Simulations at a variety of sample sizes suggest that t-distribution approximations work well across a wide range of $n$ for the equal-variance equal-sample-size case. I expect approximation via t-distributions will be adequate for the equal-variance unequal-sample-size case, but the simulations and analysis required would take a more substantial amount of time.]
T-test using only summary data in a box plot Since you have the sample means and your hypothesis relates to population means, I've assumed you'll definitely want to use the sample means in what follows. With some distributional assumptions, you
35,420
Log vs square root link for Poisson data in R
You're confusing the effect of a data-transformation with the use of a link function in a GLM. If you do a log-transform of the response, it will "straighten the relationship" if $E(Y|x)$ is of the form $\exp(a+bx)$. Similarly, if you take the square root of the response, it will make the variance nearly constant, if the variance is proportional to the mean (as it is with a Poisson, where it's equal to the mean). However, in a GLM, the link function is not used to transform the data. The GLM itself takes into account the fact that the variance of the Poisson increases with the mean; you don't need to do anything about that (as long as the Poisson assumption is suitable). The only thing left it to account for the relationship between the predictor and the response. The link function does specify the form of the relationship between the conditional mean of the response and the predictor. The sqrt link is mainly used for the purpose of comparing with an older analysis where a square root transform was used in order to apply least squares regression. By using the square root link you can fit a model of the same functional form but with full ML estimation of the parameters. If you were considering using the log because of the fact that it linearized the relationship, that's definitely the link you should use. (Generally the log link is easier to interpret, as well.) If you really wanted to entertain both link functions and choose between them you could compare the AICs; or you could compare the deviances (there are other choices of course, but both are provided in the summary output already and they do measure "fit"; whichever you look at, they should lead to the same conclusion). However, unless there's some clear indication that the log-link is inadequate or some other reason to entertain the square root link, I would simply do the log-link. Note that if you do use the data to choose between the link functions, subsequent hypothesis tests of coefficients estimated from the same data points will (among other things) no longer have their nominal properties (standard errors will be too small, confidence intervals too narrow, p-values don't mean the same thing ...) (By the way, those aren't the only two link-function options for a Poisson in R, since there's also the identity link ... and that's not counting what you can do if you move to a quasi-Poisson fit) A warning: if you're modelling a variable over time, you should keep in mind that there's (a) likely to be time dependence in your counts, in a way that would invalidate the GLM assumptions of independence (e.g. your standard errors could easily be wrong); and (b) the notion of spurious regression can as readily apply to a Poisson regression as an ordinary regression (so your parameter estimates could easily be wrong/misleading as well). I doubt that your series will be stationary, so this is potentially a serious threat to your conclusions -- but spurious regression can be a problem even with stationary series (a point that is not so widely understood; I give a reference for that in this answer which answer also illustrates the phenomenon with correlations in the non-stationary case with a simple coin-tossing example).
Log vs square root link for Poisson data in R
You're confusing the effect of a data-transformation with the use of a link function in a GLM. If you do a log-transform of the response, it will "straighten the relationship" if $E(Y|x)$ is of the fo
Log vs square root link for Poisson data in R You're confusing the effect of a data-transformation with the use of a link function in a GLM. If you do a log-transform of the response, it will "straighten the relationship" if $E(Y|x)$ is of the form $\exp(a+bx)$. Similarly, if you take the square root of the response, it will make the variance nearly constant, if the variance is proportional to the mean (as it is with a Poisson, where it's equal to the mean). However, in a GLM, the link function is not used to transform the data. The GLM itself takes into account the fact that the variance of the Poisson increases with the mean; you don't need to do anything about that (as long as the Poisson assumption is suitable). The only thing left it to account for the relationship between the predictor and the response. The link function does specify the form of the relationship between the conditional mean of the response and the predictor. The sqrt link is mainly used for the purpose of comparing with an older analysis where a square root transform was used in order to apply least squares regression. By using the square root link you can fit a model of the same functional form but with full ML estimation of the parameters. If you were considering using the log because of the fact that it linearized the relationship, that's definitely the link you should use. (Generally the log link is easier to interpret, as well.) If you really wanted to entertain both link functions and choose between them you could compare the AICs; or you could compare the deviances (there are other choices of course, but both are provided in the summary output already and they do measure "fit"; whichever you look at, they should lead to the same conclusion). However, unless there's some clear indication that the log-link is inadequate or some other reason to entertain the square root link, I would simply do the log-link. Note that if you do use the data to choose between the link functions, subsequent hypothesis tests of coefficients estimated from the same data points will (among other things) no longer have their nominal properties (standard errors will be too small, confidence intervals too narrow, p-values don't mean the same thing ...) (By the way, those aren't the only two link-function options for a Poisson in R, since there's also the identity link ... and that's not counting what you can do if you move to a quasi-Poisson fit) A warning: if you're modelling a variable over time, you should keep in mind that there's (a) likely to be time dependence in your counts, in a way that would invalidate the GLM assumptions of independence (e.g. your standard errors could easily be wrong); and (b) the notion of spurious regression can as readily apply to a Poisson regression as an ordinary regression (so your parameter estimates could easily be wrong/misleading as well). I doubt that your series will be stationary, so this is potentially a serious threat to your conclusions -- but spurious regression can be a problem even with stationary series (a point that is not so widely understood; I give a reference for that in this answer which answer also illustrates the phenomenon with correlations in the non-stationary case with a simple coin-tossing example).
Log vs square root link for Poisson data in R You're confusing the effect of a data-transformation with the use of a link function in a GLM. If you do a log-transform of the response, it will "straighten the relationship" if $E(Y|x)$ is of the fo
35,421
Log vs square root link for Poisson data in R
If you are fitting a GLiM with a Poisson distribution specified for the response, you do not have to try to stabilize the conditional variance of the response. That is automatically taken care of for you. The Poisson GLiM does not assume constant variance in the sense that a regular linear (Gaussian) regression model does. The effect of the link function will be to change the shape of the regression line in the original data space, and thereby to change the interpretation of the coefficients. If you are worried about whether the shape / amount of curvature will be appropriate, you can always use splines. Thus, you may want to choose which link to use based on the interpretability of your coefficients. In my opinion, that will typically favor the log link. If you only wanted to use your covariates without spline functions, and you wanted to determine which shape better fit your data, you could use cross-validation and examine the out of sample predictive error. Although written in the context of binomial GLiMs (not Poisson), you may still be interested in reading my answer here: Difference between logit and probit models.
Log vs square root link for Poisson data in R
If you are fitting a GLiM with a Poisson distribution specified for the response, you do not have to try to stabilize the conditional variance of the response. That is automatically taken care of for
Log vs square root link for Poisson data in R If you are fitting a GLiM with a Poisson distribution specified for the response, you do not have to try to stabilize the conditional variance of the response. That is automatically taken care of for you. The Poisson GLiM does not assume constant variance in the sense that a regular linear (Gaussian) regression model does. The effect of the link function will be to change the shape of the regression line in the original data space, and thereby to change the interpretation of the coefficients. If you are worried about whether the shape / amount of curvature will be appropriate, you can always use splines. Thus, you may want to choose which link to use based on the interpretability of your coefficients. In my opinion, that will typically favor the log link. If you only wanted to use your covariates without spline functions, and you wanted to determine which shape better fit your data, you could use cross-validation and examine the out of sample predictive error. Although written in the context of binomial GLiMs (not Poisson), you may still be interested in reading my answer here: Difference between logit and probit models.
Log vs square root link for Poisson data in R If you are fitting a GLiM with a Poisson distribution specified for the response, you do not have to try to stabilize the conditional variance of the response. That is automatically taken care of for
35,422
Moment-generating function (MGF) of non-central chi-squared distribution
Let $Z$ have a standard normal distribution, with mean $0$ and variance $1$, then $(Z+\mu)^2$ has a noncentral chi-squared distribution with one degree of freedom. The moment-generating function of $(Z+\mu)^2$ then is \begin{equation} E[e^{t(Z+\mu)^2}] = \int_{-\infty}^{+\infty} e^{t(z+\mu)^2} f_Z(z) \text{d}z \end{equation} with $f_Z(z) = \frac{1}{\sqrt{2\pi}}e^{-z^2/2}$ the density of $Z$. Then, \begin{align*} E[e^{t(Z+\mu)^2}] & = \frac{1}{\sqrt{2\pi}} \int_{-\infty}^{+\infty} e^{t(z+\mu)^2} e^{-z^2/2}\text{d}z\\ & = \frac{1}{\sqrt{2\pi}} \int \exp[-(\frac{1}{2}-t)z^2+2\mu t z +\mu^2 t] \text{d} z\\ & = \frac{1}{\sqrt{2\pi}} \int \exp[-(\frac{1}{2}-t) (z-Q)^2+\mu^2 t + \frac{2\mu^2 t^2}{1-2t}] \text{d} z \qquad\text{with } Q=\frac{2\mu t}{1-2t}\\ & = \exp[\mu^2 t + \frac{2\mu^2t^2}{1-2t}] \frac{1}{\sqrt{2\pi}} \int \exp[-\frac{(z-Q)^2}{2(1-2t)^{-1}}] \text{d}z\\ & = \exp[\mu^2 t + \frac{2\mu^2t^2}{1-2t}] (1-2t)^{-1/2} \times \frac{1}{\sqrt{2\pi}(1-2t)^{-1/2}} \int \exp[-\frac{(z-Q)^2}{2(1-2t)^{-1}}] \text{d}z\\ & = \exp[\mu^2 t + \frac{2\mu^2t^2}{1-2t}] (1-2t)^{-1/2} \times 1\\ & = \exp[\frac{\mu^2 t}{1-2t} ] (1-2t)^{-1/2} \end{align*} By definition, a noncentral chi-squared distributed random variable $\chi^2_{n,\lambda}$ with $n$ df and parameter $\lambda=\sum_{i=1}^n \mu_i^2$ is the sum of the squares of $n$ independent normal variables $X_i=Z_i+\mu_i$, $i=1,\ldots,n$. That is, \begin{equation*} \chi^2_{n,\lambda} = \sum_{i=1}^n X_i^2 = \sum_{i=1}^n (Z_i+\mu_i)^2 \end{equation*} Because all terms are jointly independent and using the above result, we have \begin{align*} E[e^{t\chi^2_{n,\lambda}}] & = E[\prod_i \exp[t(Z_i+\mu_i)^2]]\\ & = \prod_i E[\exp[t(Z_i+\mu_i)^2]]\\ & = \prod_i (1-2t)^{-1/2} \exp[\frac{\mu_i^2t}{1-2t}]\\ & = (1-2t)^{-n/2} \exp[\frac{t}{1-2t}\sum_i \mu_i^2]\\ & = (1-2t)^{-n/2} \exp[\frac{\lambda t}{1-2t}]\\ \end{align*}
Moment-generating function (MGF) of non-central chi-squared distribution
Let $Z$ have a standard normal distribution, with mean $0$ and variance $1$, then $(Z+\mu)^2$ has a noncentral chi-squared distribution with one degree of freedom. The moment-generating function of $(
Moment-generating function (MGF) of non-central chi-squared distribution Let $Z$ have a standard normal distribution, with mean $0$ and variance $1$, then $(Z+\mu)^2$ has a noncentral chi-squared distribution with one degree of freedom. The moment-generating function of $(Z+\mu)^2$ then is \begin{equation} E[e^{t(Z+\mu)^2}] = \int_{-\infty}^{+\infty} e^{t(z+\mu)^2} f_Z(z) \text{d}z \end{equation} with $f_Z(z) = \frac{1}{\sqrt{2\pi}}e^{-z^2/2}$ the density of $Z$. Then, \begin{align*} E[e^{t(Z+\mu)^2}] & = \frac{1}{\sqrt{2\pi}} \int_{-\infty}^{+\infty} e^{t(z+\mu)^2} e^{-z^2/2}\text{d}z\\ & = \frac{1}{\sqrt{2\pi}} \int \exp[-(\frac{1}{2}-t)z^2+2\mu t z +\mu^2 t] \text{d} z\\ & = \frac{1}{\sqrt{2\pi}} \int \exp[-(\frac{1}{2}-t) (z-Q)^2+\mu^2 t + \frac{2\mu^2 t^2}{1-2t}] \text{d} z \qquad\text{with } Q=\frac{2\mu t}{1-2t}\\ & = \exp[\mu^2 t + \frac{2\mu^2t^2}{1-2t}] \frac{1}{\sqrt{2\pi}} \int \exp[-\frac{(z-Q)^2}{2(1-2t)^{-1}}] \text{d}z\\ & = \exp[\mu^2 t + \frac{2\mu^2t^2}{1-2t}] (1-2t)^{-1/2} \times \frac{1}{\sqrt{2\pi}(1-2t)^{-1/2}} \int \exp[-\frac{(z-Q)^2}{2(1-2t)^{-1}}] \text{d}z\\ & = \exp[\mu^2 t + \frac{2\mu^2t^2}{1-2t}] (1-2t)^{-1/2} \times 1\\ & = \exp[\frac{\mu^2 t}{1-2t} ] (1-2t)^{-1/2} \end{align*} By definition, a noncentral chi-squared distributed random variable $\chi^2_{n,\lambda}$ with $n$ df and parameter $\lambda=\sum_{i=1}^n \mu_i^2$ is the sum of the squares of $n$ independent normal variables $X_i=Z_i+\mu_i$, $i=1,\ldots,n$. That is, \begin{equation*} \chi^2_{n,\lambda} = \sum_{i=1}^n X_i^2 = \sum_{i=1}^n (Z_i+\mu_i)^2 \end{equation*} Because all terms are jointly independent and using the above result, we have \begin{align*} E[e^{t\chi^2_{n,\lambda}}] & = E[\prod_i \exp[t(Z_i+\mu_i)^2]]\\ & = \prod_i E[\exp[t(Z_i+\mu_i)^2]]\\ & = \prod_i (1-2t)^{-1/2} \exp[\frac{\mu_i^2t}{1-2t}]\\ & = (1-2t)^{-n/2} \exp[\frac{t}{1-2t}\sum_i \mu_i^2]\\ & = (1-2t)^{-n/2} \exp[\frac{\lambda t}{1-2t}]\\ \end{align*}
Moment-generating function (MGF) of non-central chi-squared distribution Let $Z$ have a standard normal distribution, with mean $0$ and variance $1$, then $(Z+\mu)^2$ has a noncentral chi-squared distribution with one degree of freedom. The moment-generating function of $(
35,423
How exactly are standardized residuals calculated
The statistical tools in Excel have always been black boxes. There's nothing for it but to do some forensic reverse-engineering. By performing a simple regression in Excel 2013, involving the data $x=(1,2,3,4,5,6,7,8,9)$ and $y=(2,1,4,3,6,5,9,8,7)$, and requesting "standardized residuals" in the dialog, I obtained output that states The "Standard Error" is $1.3723\ldots$. There are $9$ observations. The residuals $r_i$ are $(0.5333\ldots, -1.35, \ldots, 0.35, -1.533\ldots)$. The corresponding "Standard Residuals" are $(0.4154\ldots, -1.0516\ldots, \ldots, 0.2726\ldots, -1.1944\ldots)$. Since "standardized" values are typically numbers divided by some estimate of their standard error, I compared these "Standard Residuals" to the residuals and to the "Standard Error." Knowing that various formulas for variances are sums of squares of residuals $r_i$ divided variously by $n$ (the number of data) or $n-p$ (the number of data reduced by the number of variables, in this case two: one for the intercept and a second for the slope), I squared everything in sight. It became immediately obvious that Excel is computing the "Standard Residual" as $$\frac{r_i}{\sqrt{\frac{1}{n-1}\sum_{i=1}^n r_i^2}}.$$ This formula reproduced Excel's output exactly--not even a trace of floating point roundoff error. The denominator is what would be computed by Excel's STDEV function. For residuals from a mean, it is an unbiased estimate of their variance. For residuals in a regression, however, it has no standard meaning or value. It's garbage! But now you know how to compute it... .
How exactly are standardized residuals calculated
The statistical tools in Excel have always been black boxes. There's nothing for it but to do some forensic reverse-engineering. By performing a simple regression in Excel 2013, involving the data $
How exactly are standardized residuals calculated The statistical tools in Excel have always been black boxes. There's nothing for it but to do some forensic reverse-engineering. By performing a simple regression in Excel 2013, involving the data $x=(1,2,3,4,5,6,7,8,9)$ and $y=(2,1,4,3,6,5,9,8,7)$, and requesting "standardized residuals" in the dialog, I obtained output that states The "Standard Error" is $1.3723\ldots$. There are $9$ observations. The residuals $r_i$ are $(0.5333\ldots, -1.35, \ldots, 0.35, -1.533\ldots)$. The corresponding "Standard Residuals" are $(0.4154\ldots, -1.0516\ldots, \ldots, 0.2726\ldots, -1.1944\ldots)$. Since "standardized" values are typically numbers divided by some estimate of their standard error, I compared these "Standard Residuals" to the residuals and to the "Standard Error." Knowing that various formulas for variances are sums of squares of residuals $r_i$ divided variously by $n$ (the number of data) or $n-p$ (the number of data reduced by the number of variables, in this case two: one for the intercept and a second for the slope), I squared everything in sight. It became immediately obvious that Excel is computing the "Standard Residual" as $$\frac{r_i}{\sqrt{\frac{1}{n-1}\sum_{i=1}^n r_i^2}}.$$ This formula reproduced Excel's output exactly--not even a trace of floating point roundoff error. The denominator is what would be computed by Excel's STDEV function. For residuals from a mean, it is an unbiased estimate of their variance. For residuals in a regression, however, it has no standard meaning or value. It's garbage! But now you know how to compute it... .
How exactly are standardized residuals calculated The statistical tools in Excel have always been black boxes. There's nothing for it but to do some forensic reverse-engineering. By performing a simple regression in Excel 2013, involving the data $
35,424
How exactly are standardized residuals calculated
In R : modeGlob <- lm(rnorm(100)~ abs(rnorm(100))) #Your model. hii <- hatvalues(modeGlob) # hat matrix. rst <- modeGlob$residuals / (summary(modeGlob)$sigma * sqrt(1-hii)) # manually calculate standardized residuals. identical(rstandard(modeGlob) , rst) # check, this must be TRUE. plot(rstandard(modeGlob) , rst) # check it graphically.
How exactly are standardized residuals calculated
In R : modeGlob <- lm(rnorm(100)~ abs(rnorm(100))) #Your model. hii <- hatvalues(modeGlob) # hat matrix. rst <- modeGlob$residuals / (summary(modeGlob)$sigma * sqrt(1-hii)) # manually c
How exactly are standardized residuals calculated In R : modeGlob <- lm(rnorm(100)~ abs(rnorm(100))) #Your model. hii <- hatvalues(modeGlob) # hat matrix. rst <- modeGlob$residuals / (summary(modeGlob)$sigma * sqrt(1-hii)) # manually calculate standardized residuals. identical(rstandard(modeGlob) , rst) # check, this must be TRUE. plot(rstandard(modeGlob) , rst) # check it graphically.
How exactly are standardized residuals calculated In R : modeGlob <- lm(rnorm(100)~ abs(rnorm(100))) #Your model. hii <- hatvalues(modeGlob) # hat matrix. rst <- modeGlob$residuals / (summary(modeGlob)$sigma * sqrt(1-hii)) # manually c
35,425
Introductory graduate-level survey sampling textbook?
Sampling: Design and Analysis by Sharon Lohr (quoted in your link) is probably the easiest book. Thomas Lumley's "Survey analysis in R" is even easier, but it doesn't show you the theories. To judge whether you're ok to read the book by Lohr, do you know? Sample mean vs Population mean? Central limit theorem? Normal distribution? Variance vs standard deviation? If you don't, you should start off by reading a general statistic book. If you do, start reading the Lohr book! The Kish book is a classic but old. Not really suitable for beginners. It goes into the theory deeper than the other two books I mention. However, I don't like the notation and the book doesn't explain the concepts as clear as Lohr.
Introductory graduate-level survey sampling textbook?
Sampling: Design and Analysis by Sharon Lohr (quoted in your link) is probably the easiest book. Thomas Lumley's "Survey analysis in R" is even easier, but it doesn't show you the theories. To judge w
Introductory graduate-level survey sampling textbook? Sampling: Design and Analysis by Sharon Lohr (quoted in your link) is probably the easiest book. Thomas Lumley's "Survey analysis in R" is even easier, but it doesn't show you the theories. To judge whether you're ok to read the book by Lohr, do you know? Sample mean vs Population mean? Central limit theorem? Normal distribution? Variance vs standard deviation? If you don't, you should start off by reading a general statistic book. If you do, start reading the Lohr book! The Kish book is a classic but old. Not really suitable for beginners. It goes into the theory deeper than the other two books I mention. However, I don't like the notation and the book doesn't explain the concepts as clear as Lohr.
Introductory graduate-level survey sampling textbook? Sampling: Design and Analysis by Sharon Lohr (quoted in your link) is probably the easiest book. Thomas Lumley's "Survey analysis in R" is even easier, but it doesn't show you the theories. To judge w
35,426
Introductory graduate-level survey sampling textbook?
I was going to recommend Sampling: Design and Analysis by Sharon Lohr, but it was already mentioned. Not much heavy on math, it's an easy intro book that covers most of the basic topics and uses plots and pictures to build on intuition. A more mathy book is Cochran Sampling Techniques. It's more comprehensive and it has a deeper treatment of the topics. It reads as a dry math book: definition, theorem, proofs. Finally, there's Survey Sampling by Kish. I have personally no experience with it, but both Kish and his books are always well regarded. I believe Kish comes from the experimental design field, and the book may look too "spoken" (it relies more on words than formulae).
Introductory graduate-level survey sampling textbook?
I was going to recommend Sampling: Design and Analysis by Sharon Lohr, but it was already mentioned. Not much heavy on math, it's an easy intro book that covers most of the basic topics and uses plots
Introductory graduate-level survey sampling textbook? I was going to recommend Sampling: Design and Analysis by Sharon Lohr, but it was already mentioned. Not much heavy on math, it's an easy intro book that covers most of the basic topics and uses plots and pictures to build on intuition. A more mathy book is Cochran Sampling Techniques. It's more comprehensive and it has a deeper treatment of the topics. It reads as a dry math book: definition, theorem, proofs. Finally, there's Survey Sampling by Kish. I have personally no experience with it, but both Kish and his books are always well regarded. I believe Kish comes from the experimental design field, and the book may look too "spoken" (it relies more on words than formulae).
Introductory graduate-level survey sampling textbook? I was going to recommend Sampling: Design and Analysis by Sharon Lohr, but it was already mentioned. Not much heavy on math, it's an easy intro book that covers most of the basic topics and uses plots
35,427
Why is post treatment bias a bias and not just multicollinearity?
First, let’s clear up a difference between the terms, and then discuss the respective problems that each causes. Multi-collinearity refers to a problematic relationship between multiple right-hand-side variables (usually control variables) caused by their being highly correlated, regardless of causal ordering. Post-treatment bias refers to a problematic relationship between your treatment variable and at least one control variable, based on a hypothesized causal ordering. Furthermore, multi-collinearity and Post-treatment bias causes different problems if they are not avoided. Multi-collinearity generally refers to a high correlation between multiple right-hand-side variables (usually two control variables) in a regression model, which is a problem. If a right-hand-side variable and your outcome variable were highly correlated (conditional on other right-hand-side variables), however, that would not necessarily be a problem; instead it would be suggestive of a strong relationship that might be of interest to the researcher. Multi-collinearity between control variables does not impact the reliability of a model overall. We can still reliably interpret the coefficient and standard errors on our treatment variable. The negative side of multi-collinearity is that we can no longer interpret the coefficient and standard error on the highly correlated control variables. But if we are being strict in conceiving of our regression model as a notioanal experiment, where we want to estimate the effect of one treatment (T) on one outcome (Y), considering the other variables (X) in our model as controls (and not as estimable quantities of causal interest), then regressing on highly correlated variables is fine. Another fact that may be thinking about is that if two variables are perfectly multicollinear, then one will be dropped from any regression model that includes them both. For more, see: See http://en.wikipedia.org/wiki/Multicollinearity Post-treatment bias occurs when the regression model includes a consequence of treatment as a control variable, regardless of how highly correlated the consequence-of-treatment control variable is with the treatment. Although generally the severity of post-treatment bias is increasing in the correlation between the treatment and the consequence-of-treatment control variable. Post-treatment bias is a problem because one of your control variables will mathematically “soak up” some of the effect of your treatment, thus biasing your estimate of the treatment effect. That is, some of the variation in your outcome due to your treatment will be accounted for in the coefficient estimate on the consequence-of-treatment control variable. This is misleading because to estimate the full effect of treatment, you want all of the variation explained by the treatment to be included in the treatment variable's coefficient estimate. As an example, we want to study the impact of race on salary. Imagine that race affects job position, which in turn affects salary, and the full effect of race on salary is due to the way that race changes people’s job position. That is, other than how race affects job position, there is no effect of race on salary. If we regressed salary on race and controlled for job position, we would (correctly, mathematically speaking) find no relationship between race and salary, conditional on job position. To highlight how controlling for a consequence of treatment biases your treatment estimate, consider the difference between a researcher interested in the total effect of a treatment versus the direct effect of a treatment. If we want to study the total impact of race on salary we do not care how that effect is mediated. We care about all pathways linking race and salary. We do not want to control for any variable that mediates the effect of race on salary. If we care about only the direct effect of race on salary (although this research question smacks of pre-Darwinian scientific racism), we want to exclude any "mediated" effects from our treatment estimate. So we would want to control for job position, education, social networks, etc. These change the treatment estimate. If our goal is to estimate the direct effect, then control for the consequences of treatment. If our goal is to estimate the total effect, however, controlling for these consequences of treatment biases our treatment estimate. For more intuition through example, refer to Gelman and Hill (2007) "Data Analysis Using Regression and Multilevel/Hierarchical Models," pages 188-192.
Why is post treatment bias a bias and not just multicollinearity?
First, let’s clear up a difference between the terms, and then discuss the respective problems that each causes. Multi-collinearity refers to a problematic relationship between multiple right-hand-sid
Why is post treatment bias a bias and not just multicollinearity? First, let’s clear up a difference between the terms, and then discuss the respective problems that each causes. Multi-collinearity refers to a problematic relationship between multiple right-hand-side variables (usually control variables) caused by their being highly correlated, regardless of causal ordering. Post-treatment bias refers to a problematic relationship between your treatment variable and at least one control variable, based on a hypothesized causal ordering. Furthermore, multi-collinearity and Post-treatment bias causes different problems if they are not avoided. Multi-collinearity generally refers to a high correlation between multiple right-hand-side variables (usually two control variables) in a regression model, which is a problem. If a right-hand-side variable and your outcome variable were highly correlated (conditional on other right-hand-side variables), however, that would not necessarily be a problem; instead it would be suggestive of a strong relationship that might be of interest to the researcher. Multi-collinearity between control variables does not impact the reliability of a model overall. We can still reliably interpret the coefficient and standard errors on our treatment variable. The negative side of multi-collinearity is that we can no longer interpret the coefficient and standard error on the highly correlated control variables. But if we are being strict in conceiving of our regression model as a notioanal experiment, where we want to estimate the effect of one treatment (T) on one outcome (Y), considering the other variables (X) in our model as controls (and not as estimable quantities of causal interest), then regressing on highly correlated variables is fine. Another fact that may be thinking about is that if two variables are perfectly multicollinear, then one will be dropped from any regression model that includes them both. For more, see: See http://en.wikipedia.org/wiki/Multicollinearity Post-treatment bias occurs when the regression model includes a consequence of treatment as a control variable, regardless of how highly correlated the consequence-of-treatment control variable is with the treatment. Although generally the severity of post-treatment bias is increasing in the correlation between the treatment and the consequence-of-treatment control variable. Post-treatment bias is a problem because one of your control variables will mathematically “soak up” some of the effect of your treatment, thus biasing your estimate of the treatment effect. That is, some of the variation in your outcome due to your treatment will be accounted for in the coefficient estimate on the consequence-of-treatment control variable. This is misleading because to estimate the full effect of treatment, you want all of the variation explained by the treatment to be included in the treatment variable's coefficient estimate. As an example, we want to study the impact of race on salary. Imagine that race affects job position, which in turn affects salary, and the full effect of race on salary is due to the way that race changes people’s job position. That is, other than how race affects job position, there is no effect of race on salary. If we regressed salary on race and controlled for job position, we would (correctly, mathematically speaking) find no relationship between race and salary, conditional on job position. To highlight how controlling for a consequence of treatment biases your treatment estimate, consider the difference between a researcher interested in the total effect of a treatment versus the direct effect of a treatment. If we want to study the total impact of race on salary we do not care how that effect is mediated. We care about all pathways linking race and salary. We do not want to control for any variable that mediates the effect of race on salary. If we care about only the direct effect of race on salary (although this research question smacks of pre-Darwinian scientific racism), we want to exclude any "mediated" effects from our treatment estimate. So we would want to control for job position, education, social networks, etc. These change the treatment estimate. If our goal is to estimate the direct effect, then control for the consequences of treatment. If our goal is to estimate the total effect, however, controlling for these consequences of treatment biases our treatment estimate. For more intuition through example, refer to Gelman and Hill (2007) "Data Analysis Using Regression and Multilevel/Hierarchical Models," pages 188-192.
Why is post treatment bias a bias and not just multicollinearity? First, let’s clear up a difference between the terms, and then discuss the respective problems that each causes. Multi-collinearity refers to a problematic relationship between multiple right-hand-sid
35,428
Estimate number of breakpoints in regression
Some remarks: You need to estimate two parameters in each segment (intercept and slope). Hence breakpoints() requires that there are at least three observations in each segment...otherwise you cannot estimate the parameters (without getting a perfect fit). But three is the minimal value that is technically possible. Whether or not it leads to meaningful results is a different question. Usually, you probably wouldn't use a regression model for just three observations, would you? Therefore the task of identifying 2 breakpoints plus 6 regression coefficients (three intercepts and three slopes) from just 14 observations is really challenging. Without using additional prior knowledge it is probably hard to argue that this does not overfit the data. If you set the minimal segment size to 5 (or higher) you cannot estimate 2 breakpoints on 14 observations. Hence, setting h = 3 or h = 4 are the only options that would allow 2 breakpoints. The reason that the latter prefers only 1 breakpoint is that it is not possible anymore to group the last three observations into their own segment. More documentation than on the manual page are in the third reference in citation("strucchange") discussing practical problems in breakpoint estimation. To compare the 1- and 2-breakpoint solution you can first estimate the breakpoints: bp <- breakpoints(y ~ x, h = 3) And then you can visualize the fits: plot(y ~ x, pch = 19) lines(fitted(bp, breaks = 1) ~ x, col = 4, lwd = 1.5) lines(fitted(bp, breaks = 2) ~ x, col = 2, lwd = 1.5) As remarked above: From a purely data-driven perspective, I would probably consider both models overfitting. But maybe one or the other model has a plausible interpretation for you.
Estimate number of breakpoints in regression
Some remarks: You need to estimate two parameters in each segment (intercept and slope). Hence breakpoints() requires that there are at least three observations in each segment...otherwise you cannot
Estimate number of breakpoints in regression Some remarks: You need to estimate two parameters in each segment (intercept and slope). Hence breakpoints() requires that there are at least three observations in each segment...otherwise you cannot estimate the parameters (without getting a perfect fit). But three is the minimal value that is technically possible. Whether or not it leads to meaningful results is a different question. Usually, you probably wouldn't use a regression model for just three observations, would you? Therefore the task of identifying 2 breakpoints plus 6 regression coefficients (three intercepts and three slopes) from just 14 observations is really challenging. Without using additional prior knowledge it is probably hard to argue that this does not overfit the data. If you set the minimal segment size to 5 (or higher) you cannot estimate 2 breakpoints on 14 observations. Hence, setting h = 3 or h = 4 are the only options that would allow 2 breakpoints. The reason that the latter prefers only 1 breakpoint is that it is not possible anymore to group the last three observations into their own segment. More documentation than on the manual page are in the third reference in citation("strucchange") discussing practical problems in breakpoint estimation. To compare the 1- and 2-breakpoint solution you can first estimate the breakpoints: bp <- breakpoints(y ~ x, h = 3) And then you can visualize the fits: plot(y ~ x, pch = 19) lines(fitted(bp, breaks = 1) ~ x, col = 4, lwd = 1.5) lines(fitted(bp, breaks = 2) ~ x, col = 2, lwd = 1.5) As remarked above: From a purely data-driven perspective, I would probably consider both models overfitting. But maybe one or the other model has a plausible interpretation for you.
Estimate number of breakpoints in regression Some remarks: You need to estimate two parameters in each segment (intercept and slope). Hence breakpoints() requires that there are at least three observations in each segment...otherwise you cannot
35,429
A model for non-negative data with many zeros: pros and cons of Tweedie GLM
You're right to think that a Box-Cox transformation won't deal with the zeros issue (nor indeed would any other transformation). The Tweedie might be suitable, and is sometimes used for data like these*, but the probability of a zero is related to the $p$ (the power in the variance function). *\ another issue to consider -- your data are observed over time, so you must also consider the possibility of time-dependence (such as autocorrelation). A more common solution to the zeros would be a zero-inflated or hurdle model, such as a zero-inflated gamma. There are numerous questions on site on "zero-inflated"/"0-inflated" models and hurdle models. However if your thought was correct and it's only "too small to register", that would indicate censoring. Looking at the plot though, I have some doubts that it's an adequate explanation for what we see: Between the lower two grey lines, there are only three points, but a large number of points either exactly on the line (or very close to it). That big gap would be consistent with your thought, but those three points (circled in red) do not seem consistent with it -- if those points can register, why not others? However, such a banding feature can sometimes be seen in Tweedie distributions as well; the tricky part would be whether it's even possible to get the right mix of parameters to match both the proportion of zeros and the banding at lower values. (Beware interpreting those plots; the spikes at zero are not density but probability, and strictly speaking should not be represented on the same plot as the continuous part. You can draw a cdf but it's less clear what's going on.) However, even more seriously perhaps, the Tweedie definitely cannot reproduce the clumping behaviour at the top end of the plot (for that matter neither can any of the other models I've mentioned).
A model for non-negative data with many zeros: pros and cons of Tweedie GLM
You're right to think that a Box-Cox transformation won't deal with the zeros issue (nor indeed would any other transformation). The Tweedie might be suitable, and is sometimes used for data like thes
A model for non-negative data with many zeros: pros and cons of Tweedie GLM You're right to think that a Box-Cox transformation won't deal with the zeros issue (nor indeed would any other transformation). The Tweedie might be suitable, and is sometimes used for data like these*, but the probability of a zero is related to the $p$ (the power in the variance function). *\ another issue to consider -- your data are observed over time, so you must also consider the possibility of time-dependence (such as autocorrelation). A more common solution to the zeros would be a zero-inflated or hurdle model, such as a zero-inflated gamma. There are numerous questions on site on "zero-inflated"/"0-inflated" models and hurdle models. However if your thought was correct and it's only "too small to register", that would indicate censoring. Looking at the plot though, I have some doubts that it's an adequate explanation for what we see: Between the lower two grey lines, there are only three points, but a large number of points either exactly on the line (or very close to it). That big gap would be consistent with your thought, but those three points (circled in red) do not seem consistent with it -- if those points can register, why not others? However, such a banding feature can sometimes be seen in Tweedie distributions as well; the tricky part would be whether it's even possible to get the right mix of parameters to match both the proportion of zeros and the banding at lower values. (Beware interpreting those plots; the spikes at zero are not density but probability, and strictly speaking should not be represented on the same plot as the continuous part. You can draw a cdf but it's less clear what's going on.) However, even more seriously perhaps, the Tweedie definitely cannot reproduce the clumping behaviour at the top end of the plot (for that matter neither can any of the other models I've mentioned).
A model for non-negative data with many zeros: pros and cons of Tweedie GLM You're right to think that a Box-Cox transformation won't deal with the zeros issue (nor indeed would any other transformation). The Tweedie might be suitable, and is sometimes used for data like thes
35,430
Rank and z-transform instead of Wilcoxon?
(Pulls Conover [1] off the bookshelf...) This idea is quite old; it dates back at least to van der Waerden (1952/1953) [2][3], who suggested a test that corresponds to the Kruskal Wallis but with ranks replaced by normal scores. (The idea of using ordered random normal values rather than an approximation of their expectation or their median - is perhaps even a little older.) According to Conover, Fisher and Yates (1957) [4] suggest replacing observations with expected normal scores (i.e. transformed ranks) in a variety of tests where normality would be assumed. The asymptotic relative efficiency at the normal will be 1, which makes it sound quite attractive ... however, the advantage over say the Wilcoxon-Mann-Whitney (gain in power) -- even at the normal -- is quite small, and if the distribution is heavier tailed than normal (say logistic), it may be disadvantageous to do this. (Some simulation suggests that it is in fact the case: unless the distribution is close to normal already -- in which case there's no benefit to doing the transformation -- such a transformation may actually lose power.) Chernoff & Lehmann [5] calculate asymptotic power for a variety of distributions; where there's at least one very short tail (such as the uniform), the normal scores test can have much better ARE for a shift alternative against the Wilcoxon-Mann-Whitney -- better than the t-test itself does. Their results agree with my simulations for heavier tailed cases. Note that in the two-sample case, as the separation in means becomes large, while the combined sample looks quite normal, the two samples are not normal at all: As a result, not all properties of the normal test will carry over to the normal scores test, and the behaviour at larger separations (with small samples) may be somewhat counterintuitive. The tests obtained by this idea are sometimes collectively called normal scores tests, which search term (via Google, say) turns up a number of references. For example, here, Richard Darlington discusses doing it for the Wilcoxon signed ranks test; he points out there's an advantage over the plain rank test, because it reduces the number of tied values of the test statistic. Before I end up writing pages on it, I'll leave you to search further. Conover lists a number of other references and has a fair bit of discussion, so I'd definitely recommend reading that. Gelman's point, however, seems to be about convenience - not needing to develop a new test each time the situation changes; though if convenience is the main issue there's already the ability to use permutation tests on whatever statistic we like. [With the normal scores approach, the difficulty is we still need a suitable way to rank -- you can't just rank things that aren't comparable under the null and expect the right sort of behaviour. There's a similar problem with the permutation test, since you similarly need exchangeability under the null.] You mention an R function, but you can rank and convert to normal scores easily in R just using functions that already come with R. e.g. using the sleep data in R. you'd do a t-test this way: t.test(extra ~ group, data = sleep) # Welch t.test(extra ~ group, data = sleep, var.equal=TRUE) # equal-variance t.test(qqnorm(extra,plot=FALSE)$x ~ group, data = sleep) # normal scores [1] Conover, W. J. (1980), Practical Nonparameteric Statistics, 2e. Wiley. pp. 316–327. (From the above Wikipedia link it looks like in 3e (1999) the discussion starts on p396) [2] van der Waerden, B.L. (1952), "Order tests for the two-sample problem and their power", Proceedings of the Koninklijke Nederlandse Akademie van Wetenschappen, Serie A 55 (Indagationes Mathematicae 14), 453–458. [3] van der Waerden, B.L. (1953), "Order tests for the two-sample problem. II, III", Proceedings of the Koninklijke Nederlandse Akademie van Wetenschappen, Serie A 56 (Indagationes Mathematicae, 15), 303–310 & 311–316. (there are also corrections to the 1952 paper on p 80 of that volume) [4] Fisher R.A. and Yates F. (1957) Statistical Tables for Biological, Agricultural and Medical Research, 5e, Oliver & Boyd, Edinburgh. [5] Hodges, J. L.; Lehmann, E. L. (1961), "Comparison of the Normal Scores and Wilcoxon Tests," Proceedings of the Fourth Berkeley Symposium on Mathematical Statistics and Probability, Volume 1: Contributions to the Theory of Statistics, 307--317, University of California Press, Berkeley, Calif. http://projecteuclid.org/euclid.bsmsp/1200512171.
Rank and z-transform instead of Wilcoxon?
(Pulls Conover [1] off the bookshelf...) This idea is quite old; it dates back at least to van der Waerden (1952/1953) [2][3], who suggested a test that corresponds to the Kruskal Wallis but with rank
Rank and z-transform instead of Wilcoxon? (Pulls Conover [1] off the bookshelf...) This idea is quite old; it dates back at least to van der Waerden (1952/1953) [2][3], who suggested a test that corresponds to the Kruskal Wallis but with ranks replaced by normal scores. (The idea of using ordered random normal values rather than an approximation of their expectation or their median - is perhaps even a little older.) According to Conover, Fisher and Yates (1957) [4] suggest replacing observations with expected normal scores (i.e. transformed ranks) in a variety of tests where normality would be assumed. The asymptotic relative efficiency at the normal will be 1, which makes it sound quite attractive ... however, the advantage over say the Wilcoxon-Mann-Whitney (gain in power) -- even at the normal -- is quite small, and if the distribution is heavier tailed than normal (say logistic), it may be disadvantageous to do this. (Some simulation suggests that it is in fact the case: unless the distribution is close to normal already -- in which case there's no benefit to doing the transformation -- such a transformation may actually lose power.) Chernoff & Lehmann [5] calculate asymptotic power for a variety of distributions; where there's at least one very short tail (such as the uniform), the normal scores test can have much better ARE for a shift alternative against the Wilcoxon-Mann-Whitney -- better than the t-test itself does. Their results agree with my simulations for heavier tailed cases. Note that in the two-sample case, as the separation in means becomes large, while the combined sample looks quite normal, the two samples are not normal at all: As a result, not all properties of the normal test will carry over to the normal scores test, and the behaviour at larger separations (with small samples) may be somewhat counterintuitive. The tests obtained by this idea are sometimes collectively called normal scores tests, which search term (via Google, say) turns up a number of references. For example, here, Richard Darlington discusses doing it for the Wilcoxon signed ranks test; he points out there's an advantage over the plain rank test, because it reduces the number of tied values of the test statistic. Before I end up writing pages on it, I'll leave you to search further. Conover lists a number of other references and has a fair bit of discussion, so I'd definitely recommend reading that. Gelman's point, however, seems to be about convenience - not needing to develop a new test each time the situation changes; though if convenience is the main issue there's already the ability to use permutation tests on whatever statistic we like. [With the normal scores approach, the difficulty is we still need a suitable way to rank -- you can't just rank things that aren't comparable under the null and expect the right sort of behaviour. There's a similar problem with the permutation test, since you similarly need exchangeability under the null.] You mention an R function, but you can rank and convert to normal scores easily in R just using functions that already come with R. e.g. using the sleep data in R. you'd do a t-test this way: t.test(extra ~ group, data = sleep) # Welch t.test(extra ~ group, data = sleep, var.equal=TRUE) # equal-variance t.test(qqnorm(extra,plot=FALSE)$x ~ group, data = sleep) # normal scores [1] Conover, W. J. (1980), Practical Nonparameteric Statistics, 2e. Wiley. pp. 316–327. (From the above Wikipedia link it looks like in 3e (1999) the discussion starts on p396) [2] van der Waerden, B.L. (1952), "Order tests for the two-sample problem and their power", Proceedings of the Koninklijke Nederlandse Akademie van Wetenschappen, Serie A 55 (Indagationes Mathematicae 14), 453–458. [3] van der Waerden, B.L. (1953), "Order tests for the two-sample problem. II, III", Proceedings of the Koninklijke Nederlandse Akademie van Wetenschappen, Serie A 56 (Indagationes Mathematicae, 15), 303–310 & 311–316. (there are also corrections to the 1952 paper on p 80 of that volume) [4] Fisher R.A. and Yates F. (1957) Statistical Tables for Biological, Agricultural and Medical Research, 5e, Oliver & Boyd, Edinburgh. [5] Hodges, J. L.; Lehmann, E. L. (1961), "Comparison of the Normal Scores and Wilcoxon Tests," Proceedings of the Fourth Berkeley Symposium on Mathematical Statistics and Probability, Volume 1: Contributions to the Theory of Statistics, 307--317, University of California Press, Berkeley, Calif. http://projecteuclid.org/euclid.bsmsp/1200512171.
Rank and z-transform instead of Wilcoxon? (Pulls Conover [1] off the bookshelf...) This idea is quite old; it dates back at least to van der Waerden (1952/1953) [2][3], who suggested a test that corresponds to the Kruskal Wallis but with rank
35,431
Exact definition of Maxout
None of the above; maxout networks don't follow the architecture you assumed. From the beginning of the "description of maxout" section in the paper you linked, which defined maxout: Given an input $x \in \mathbb{R}^d$ ($x$ may be $v$, or may be a hidden layer’s state), a maxout hidden layer implements the function $$h_i = \max_{j \in [1, k]} z_{ij}$$ where $z_{ij} = x^T W_{ij} + b_{ij}$, and $W \in \mathbb{R}^{d \times m \times k}$ and $b ∈ R^{m \times k}$ are learned parameters. So, each unit of the $m$ units has $k$ different affine combinations of the previous layer, and outputs the max of those $k$ affine functions. Imagine each layer being conected to the previous layer with $k$ different-colored connections, and taking the max of the colors. Alternatively, you can think of a maxout unit as actually being two layers: each of the previous layer's units is connected to each of $k$ units with the identity activation function, and then a single unit connects those $k$ linear units with a max-pooling activation. This means that the unit, viewed as a function from $\mathbb R^d$ to $\mathbb R$, is the piecewise max of affine functions. The paper's Figure 1 gives some examples of different functions it might look like: Each of the dashed lines represents a $W^T x + b$. You can represent any convex function in this way, which is pretty nice.
Exact definition of Maxout
None of the above; maxout networks don't follow the architecture you assumed. From the beginning of the "description of maxout" section in the paper you linked, which defined maxout: Given an input $
Exact definition of Maxout None of the above; maxout networks don't follow the architecture you assumed. From the beginning of the "description of maxout" section in the paper you linked, which defined maxout: Given an input $x \in \mathbb{R}^d$ ($x$ may be $v$, or may be a hidden layer’s state), a maxout hidden layer implements the function $$h_i = \max_{j \in [1, k]} z_{ij}$$ where $z_{ij} = x^T W_{ij} + b_{ij}$, and $W \in \mathbb{R}^{d \times m \times k}$ and $b ∈ R^{m \times k}$ are learned parameters. So, each unit of the $m$ units has $k$ different affine combinations of the previous layer, and outputs the max of those $k$ affine functions. Imagine each layer being conected to the previous layer with $k$ different-colored connections, and taking the max of the colors. Alternatively, you can think of a maxout unit as actually being two layers: each of the previous layer's units is connected to each of $k$ units with the identity activation function, and then a single unit connects those $k$ linear units with a max-pooling activation. This means that the unit, viewed as a function from $\mathbb R^d$ to $\mathbb R$, is the piecewise max of affine functions. The paper's Figure 1 gives some examples of different functions it might look like: Each of the dashed lines represents a $W^T x + b$. You can represent any convex function in this way, which is pretty nice.
Exact definition of Maxout None of the above; maxout networks don't follow the architecture you assumed. From the beginning of the "description of maxout" section in the paper you linked, which defined maxout: Given an input $
35,432
My Test accuracy is pretty bad compared to cross-validation accuracy
Hastie et al discuss this precise issue in their book, The Elements of Statistical Learning. They conclude that cross-validation is NOT an estimate of test-error conditional on the training set. Rather, they believe it is an estimate of the unconditional test error. In other words, this is the expected test error if you are also randomizing over the world of possible training sets, rather than the precise training set you've been given.
My Test accuracy is pretty bad compared to cross-validation accuracy
Hastie et al discuss this precise issue in their book, The Elements of Statistical Learning. They conclude that cross-validation is NOT an estimate of test-error conditional on the training set. Rat
My Test accuracy is pretty bad compared to cross-validation accuracy Hastie et al discuss this precise issue in their book, The Elements of Statistical Learning. They conclude that cross-validation is NOT an estimate of test-error conditional on the training set. Rather, they believe it is an estimate of the unconditional test error. In other words, this is the expected test error if you are also randomizing over the world of possible training sets, rather than the precise training set you've been given.
My Test accuracy is pretty bad compared to cross-validation accuracy Hastie et al discuss this precise issue in their book, The Elements of Statistical Learning. They conclude that cross-validation is NOT an estimate of test-error conditional on the training set. Rat
35,433
My Test accuracy is pretty bad compared to cross-validation accuracy
I'd suspect something is wrong with how you created the hold out set. Ie either it wasn't randomized or needed to be done with stratified sampling. This sort of thing can also happen if you did feature selection or engineering outside of the CV loop as you'll produce features that look good across the cv folds but don't generalize. It can also happen if you tuned model hyperparameters using the CV loop. How did the other model's do on the hold out set? SVMs can be quite prone to this while RF's tend to be less prone so i'd wonder about that in particular. Other strategies for dealing with this include an inner CV loop and fixing the regularization parameters to limit the amount of overfitting you can do. Finally if this is highly dimensional data with lots of variance unrelated to the target (like genetic data) it is quite possible there exist models that works well in the cv data but not the hold out data by random chance. This phenomena has been described as "anti learning", again RF's tend to be more robust against this (because of the internal bagging) though it begins to effect them as well as the dimensionality grows.
My Test accuracy is pretty bad compared to cross-validation accuracy
I'd suspect something is wrong with how you created the hold out set. Ie either it wasn't randomized or needed to be done with stratified sampling. This sort of thing can also happen if you did featur
My Test accuracy is pretty bad compared to cross-validation accuracy I'd suspect something is wrong with how you created the hold out set. Ie either it wasn't randomized or needed to be done with stratified sampling. This sort of thing can also happen if you did feature selection or engineering outside of the CV loop as you'll produce features that look good across the cv folds but don't generalize. It can also happen if you tuned model hyperparameters using the CV loop. How did the other model's do on the hold out set? SVMs can be quite prone to this while RF's tend to be less prone so i'd wonder about that in particular. Other strategies for dealing with this include an inner CV loop and fixing the regularization parameters to limit the amount of overfitting you can do. Finally if this is highly dimensional data with lots of variance unrelated to the target (like genetic data) it is quite possible there exist models that works well in the cv data but not the hold out data by random chance. This phenomena has been described as "anti learning", again RF's tend to be more robust against this (because of the internal bagging) though it begins to effect them as well as the dimensionality grows.
My Test accuracy is pretty bad compared to cross-validation accuracy I'd suspect something is wrong with how you created the hold out set. Ie either it wasn't randomized or needed to be done with stratified sampling. This sort of thing can also happen if you did featur
35,434
PDF of a sum of dependent variables
Find the pdf of: $\quad A+D+\sqrt{(A-D)^2+4BC}, \quad $ where $A,B,C,D$ are iid $Uniform(0,1)$ Let $U = 4 BC$, where $U$ has pdf: $\quad g(u) = \frac{1}{4} \log \left(\frac{4}{u}\right) \quad \text{for } 0<u<4$. This reduces the problem from 4 to 3 independent random variables. Then, by independence, the joint pdf of $(A,D,U)$ is $f(a,d,u)$: Let $Z = A+D+\sqrt{(A-D)^2+4BC}$. The cdf of $Z$ is $P(Z<z)$: where I am using the Prob function from the mathStatica package for Mathematica to automate the nitty-gritties. The pdf of $Z$ is simply the derivative of the latter wrt $z$, which yields the solution: All done. Here is a plot of the exact theoretical pdf of $Z$: Monte Carlo check The following diagram compares an empirical Monte Carlo approximation of the pdf (squiggly blue) to the theoretical pdf derived above (red dashed). Looks fine.
PDF of a sum of dependent variables
Find the pdf of: $\quad A+D+\sqrt{(A-D)^2+4BC}, \quad $ where $A,B,C,D$ are iid $Uniform(0,1)$ Let $U = 4 BC$, where $U$ has pdf: $\quad g(u) = \frac{1}{4} \log \left(\frac{4}{u}\right) \quad \tex
PDF of a sum of dependent variables Find the pdf of: $\quad A+D+\sqrt{(A-D)^2+4BC}, \quad $ where $A,B,C,D$ are iid $Uniform(0,1)$ Let $U = 4 BC$, where $U$ has pdf: $\quad g(u) = \frac{1}{4} \log \left(\frac{4}{u}\right) \quad \text{for } 0<u<4$. This reduces the problem from 4 to 3 independent random variables. Then, by independence, the joint pdf of $(A,D,U)$ is $f(a,d,u)$: Let $Z = A+D+\sqrt{(A-D)^2+4BC}$. The cdf of $Z$ is $P(Z<z)$: where I am using the Prob function from the mathStatica package for Mathematica to automate the nitty-gritties. The pdf of $Z$ is simply the derivative of the latter wrt $z$, which yields the solution: All done. Here is a plot of the exact theoretical pdf of $Z$: Monte Carlo check The following diagram compares an empirical Monte Carlo approximation of the pdf (squiggly blue) to the theoretical pdf derived above (red dashed). Looks fine.
PDF of a sum of dependent variables Find the pdf of: $\quad A+D+\sqrt{(A-D)^2+4BC}, \quad $ where $A,B,C,D$ are iid $Uniform(0,1)$ Let $U = 4 BC$, where $U$ has pdf: $\quad g(u) = \frac{1}{4} \log \left(\frac{4}{u}\right) \quad \tex
35,435
PDF of a sum of dependent variables
Just after reading wolfies answer I understood I could calculate the final distribution from the very beginning without all the mid-point steps: M[x_] := M[x] = Evaluate@FullSimplify@ Integrate[ Boole[a + d + Sqrt[(a - d)^2 + 4 b c] <= x], {a, 0, 1}, {b, 0, 1}, {c, 0, 1}, {d, 0, 1}] gives the CDF and m[x_] := m[x] = Evaluate@FullSimplify@D[M[x], x] gives the PDF that works perfect with my simulation: This uses directly the approach of an answer to my previous question.
PDF of a sum of dependent variables
Just after reading wolfies answer I understood I could calculate the final distribution from the very beginning without all the mid-point steps: M[x_] := M[x] = Evaluate@FullSimplify@ Integrate
PDF of a sum of dependent variables Just after reading wolfies answer I understood I could calculate the final distribution from the very beginning without all the mid-point steps: M[x_] := M[x] = Evaluate@FullSimplify@ Integrate[ Boole[a + d + Sqrt[(a - d)^2 + 4 b c] <= x], {a, 0, 1}, {b, 0, 1}, {c, 0, 1}, {d, 0, 1}] gives the CDF and m[x_] := m[x] = Evaluate@FullSimplify@D[M[x], x] gives the PDF that works perfect with my simulation: This uses directly the approach of an answer to my previous question.
PDF of a sum of dependent variables Just after reading wolfies answer I understood I could calculate the final distribution from the very beginning without all the mid-point steps: M[x_] := M[x] = Evaluate@FullSimplify@ Integrate
35,436
Likelihood Ratio for the Bivariate Normal distribution
As has been made clear in the comments, the OP is interested in the Likelihood ratio when the common variance is also estimated, and not known. The joint density of one pair of $\{X_i, Y_i$}, given also the maintained assumptions on the parameter values is $$ f(x_i,y_i) = \frac{1}{2 \pi \sigma^2\sqrt{3/4}} \ \exp\left\{ -\frac{2}{3}\left[ \frac{(x_i-\mu_x)^2}{\sigma^2} + \frac{(y_i-\mu_y)^2}{\sigma^2} - \frac{(x_i-\mu_x)(y_i-\mu_y)}{\sigma^2} \right] \right\}$$ So the joint Likelihood of the sample (not log likelihood) is $$ L(\mu_x, \mu_y, \sigma^2 \mid, \mathbf x, \mathbf y, \rho=1/2) = \left(\frac{1}{2 \pi \sigma^2\sqrt{3/4}}\right)^n \\ \times \exp\left\{ -\frac{2}{3\sigma^2}\left[ \sum_{i=1}^n(x_i -\mu_x)^2 +\sum_{i=1}^n(y_i -\mu_y)^2 - \sum_{i=1}^n(x_i-\mu_x)(y_i-\mu_y) \right] \right\}$$ Denote $L_1$ the maximized likelihood with the sample means (MLEs for the true means), and $L_0$ the likelihood with the means set equal to zero. Then the Likelihood Ratio (not the log such) is $$ LR \equiv \frac {L_0}{L_1} = \frac {\hat \sigma^{2n}_1\cdot \exp\left\{ -(2/3\hat \sigma^2_0)\cdot\left[ \sum_{i=1}^nx_i^2 +\sum_{i=1}^ny_i^2 - \sum_{i=1}^nx_iy_i \right] \right\}}{\hat \sigma^{2n}_0 \cdot\exp\left\{ -(2/3\hat \sigma^2_1)\cdot\left[ \sum_{i=1}^nx_i^2 -n\bar x^2 +\sum_{i=1}^ny_i^2 -n\bar y^2 - \sum_{i=1}^nx_iy_i+n\bar x\bar y \right] \right\}}$$ where $\hat \sigma^2_1$ is the estimate with unconstrained means and $\hat \sigma^2_0$ is the estimate with the means constrained to zero. The OP has (correctly) calculated the MLEs for the common variance as $$\hat \sigma^2_1 = \frac{2}{3n} \sum_{i=1}^n \left[ \left(x_i-\bar{x}\right)^2+\left(y_i-\bar{y} \right)^2-\left(x_i-\bar{x}\right)\left(y_i-\bar{y} \right) \right]$$ $$\hat \sigma^2_0 = \frac{2}{3n} \sum_{i=1}^n \left( x_i^2+y_i^2-x_iy_i \right)$$ If we plug these into the LR, inside the exponential, both in the numerator and the denominator, things cancel out and we are left simply with $$ LR = \frac {\hat \sigma^{2n}_1}{\hat \sigma^{2n}_0 } $$ Our goal is not to derive the LR per se -it is to find a statistic to run the test we are interested in. So let's consider the quantity (which is the reciprocal of quantity presented in the question) $$\left(LR\right)^{-1/n} = \frac {\hat \sigma^{2}_0}{\hat \sigma^{2}_1}$$ $$ = \frac{2}{3n} \frac{\sum_{i=1}^{n}x_i^2+\sum_{i=1}^{n}y_i^2-\sum_{i=1}^n x_iy_i }{\hat \sigma^{2}_1}$$ $$= \frac {1}{3n}\cdot\left[\sum_{i=1}^n\left(\frac {x_i}{\hat \sigma_1}\right)^2 + \sum_{i=1}^n\left(\frac {y_i}{\hat \sigma_1}\right)^2 + \sum_{i=1}^n\left(\frac {x_i-y_i}{\hat \sigma_1}\right)^2\right]$$ Note that $\hat \sigma^{2}_1$ is a consistent estimator of the true variance, irrespective of whether the true means are zero or not. Also (given equal variances and $\rho =1/2$), $$Z_i = X_i - Y_i \sim N(\mu_x-\mu_y, \sigma^2)$$ Under the null of zero means, then, all $(x_i/\hat \sigma_1)^2$, $(y_i/\hat \sigma_1)^2$ and $(z_i/\hat \sigma_1)^2$ are chi-squares with one degree of freedom (and i.i.d., per sum). Each sum (denote the three sums for compactness $S_x, S_y, S_z$) has expected value $n$ and standard deviation $\sqrt {2n}$ (under the null). So subtract $n$ 3 times and add $n$ 3 times, and also divide and multiply by $\sqrt {2n}$ and re-arrange to get $$\sqrt {n}\left(LR\right)^{-1/n} = \frac {\sqrt 2}{3}\cdot\left[\frac {S_x - E(S_x)}{SD(S_x)} + \frac {S_y - E(S_x)}{SD(S_x)} + \frac {S_z - E(S_z)}{SD(S_z)}\right] + 1$$ The three terms inside the bracket, are the subject matter of the Central Limit Theorem, and so each element converges to a standard normal. Therefore we have arrived (due to initial bi-variate normality) at $$\frac {3}{\sqrt 2} \left[\sqrt{n}\left(LR\right)^{-1/n} -1\right] \xrightarrow{d} N(0, AV)$$ Of course in order to actually use the left-hand side as a statistic in a test, we need to derive the asymptotic variance -but for the moment, I do not feel up to the task. I just note that one should determine whether the three $S$'s are asymptotically independent or not.
Likelihood Ratio for the Bivariate Normal distribution
As has been made clear in the comments, the OP is interested in the Likelihood ratio when the common variance is also estimated, and not known. The joint density of one pair of $\{X_i, Y_i$}, given al
Likelihood Ratio for the Bivariate Normal distribution As has been made clear in the comments, the OP is interested in the Likelihood ratio when the common variance is also estimated, and not known. The joint density of one pair of $\{X_i, Y_i$}, given also the maintained assumptions on the parameter values is $$ f(x_i,y_i) = \frac{1}{2 \pi \sigma^2\sqrt{3/4}} \ \exp\left\{ -\frac{2}{3}\left[ \frac{(x_i-\mu_x)^2}{\sigma^2} + \frac{(y_i-\mu_y)^2}{\sigma^2} - \frac{(x_i-\mu_x)(y_i-\mu_y)}{\sigma^2} \right] \right\}$$ So the joint Likelihood of the sample (not log likelihood) is $$ L(\mu_x, \mu_y, \sigma^2 \mid, \mathbf x, \mathbf y, \rho=1/2) = \left(\frac{1}{2 \pi \sigma^2\sqrt{3/4}}\right)^n \\ \times \exp\left\{ -\frac{2}{3\sigma^2}\left[ \sum_{i=1}^n(x_i -\mu_x)^2 +\sum_{i=1}^n(y_i -\mu_y)^2 - \sum_{i=1}^n(x_i-\mu_x)(y_i-\mu_y) \right] \right\}$$ Denote $L_1$ the maximized likelihood with the sample means (MLEs for the true means), and $L_0$ the likelihood with the means set equal to zero. Then the Likelihood Ratio (not the log such) is $$ LR \equiv \frac {L_0}{L_1} = \frac {\hat \sigma^{2n}_1\cdot \exp\left\{ -(2/3\hat \sigma^2_0)\cdot\left[ \sum_{i=1}^nx_i^2 +\sum_{i=1}^ny_i^2 - \sum_{i=1}^nx_iy_i \right] \right\}}{\hat \sigma^{2n}_0 \cdot\exp\left\{ -(2/3\hat \sigma^2_1)\cdot\left[ \sum_{i=1}^nx_i^2 -n\bar x^2 +\sum_{i=1}^ny_i^2 -n\bar y^2 - \sum_{i=1}^nx_iy_i+n\bar x\bar y \right] \right\}}$$ where $\hat \sigma^2_1$ is the estimate with unconstrained means and $\hat \sigma^2_0$ is the estimate with the means constrained to zero. The OP has (correctly) calculated the MLEs for the common variance as $$\hat \sigma^2_1 = \frac{2}{3n} \sum_{i=1}^n \left[ \left(x_i-\bar{x}\right)^2+\left(y_i-\bar{y} \right)^2-\left(x_i-\bar{x}\right)\left(y_i-\bar{y} \right) \right]$$ $$\hat \sigma^2_0 = \frac{2}{3n} \sum_{i=1}^n \left( x_i^2+y_i^2-x_iy_i \right)$$ If we plug these into the LR, inside the exponential, both in the numerator and the denominator, things cancel out and we are left simply with $$ LR = \frac {\hat \sigma^{2n}_1}{\hat \sigma^{2n}_0 } $$ Our goal is not to derive the LR per se -it is to find a statistic to run the test we are interested in. So let's consider the quantity (which is the reciprocal of quantity presented in the question) $$\left(LR\right)^{-1/n} = \frac {\hat \sigma^{2}_0}{\hat \sigma^{2}_1}$$ $$ = \frac{2}{3n} \frac{\sum_{i=1}^{n}x_i^2+\sum_{i=1}^{n}y_i^2-\sum_{i=1}^n x_iy_i }{\hat \sigma^{2}_1}$$ $$= \frac {1}{3n}\cdot\left[\sum_{i=1}^n\left(\frac {x_i}{\hat \sigma_1}\right)^2 + \sum_{i=1}^n\left(\frac {y_i}{\hat \sigma_1}\right)^2 + \sum_{i=1}^n\left(\frac {x_i-y_i}{\hat \sigma_1}\right)^2\right]$$ Note that $\hat \sigma^{2}_1$ is a consistent estimator of the true variance, irrespective of whether the true means are zero or not. Also (given equal variances and $\rho =1/2$), $$Z_i = X_i - Y_i \sim N(\mu_x-\mu_y, \sigma^2)$$ Under the null of zero means, then, all $(x_i/\hat \sigma_1)^2$, $(y_i/\hat \sigma_1)^2$ and $(z_i/\hat \sigma_1)^2$ are chi-squares with one degree of freedom (and i.i.d., per sum). Each sum (denote the three sums for compactness $S_x, S_y, S_z$) has expected value $n$ and standard deviation $\sqrt {2n}$ (under the null). So subtract $n$ 3 times and add $n$ 3 times, and also divide and multiply by $\sqrt {2n}$ and re-arrange to get $$\sqrt {n}\left(LR\right)^{-1/n} = \frac {\sqrt 2}{3}\cdot\left[\frac {S_x - E(S_x)}{SD(S_x)} + \frac {S_y - E(S_x)}{SD(S_x)} + \frac {S_z - E(S_z)}{SD(S_z)}\right] + 1$$ The three terms inside the bracket, are the subject matter of the Central Limit Theorem, and so each element converges to a standard normal. Therefore we have arrived (due to initial bi-variate normality) at $$\frac {3}{\sqrt 2} \left[\sqrt{n}\left(LR\right)^{-1/n} -1\right] \xrightarrow{d} N(0, AV)$$ Of course in order to actually use the left-hand side as a statistic in a test, we need to derive the asymptotic variance -but for the moment, I do not feel up to the task. I just note that one should determine whether the three $S$'s are asymptotically independent or not.
Likelihood Ratio for the Bivariate Normal distribution As has been made clear in the comments, the OP is interested in the Likelihood ratio when the common variance is also estimated, and not known. The joint density of one pair of $\{X_i, Y_i$}, given al
35,437
Likelihood Ratio for the Bivariate Normal distribution
I would like to suggest this way to simplify the likelihood ratio $\Lambda$. I am not a native English speaker so feel free to correct my grammar errors. Let me introduce these statistics $U, V$ which are given by linear combination of X and Y as $\begin{pmatrix} U \\ V \end{pmatrix} =\begin{pmatrix} 1 & -{1 \over 2} \\ 0 & { \sqrt3 \over 2} \end{pmatrix}\begin{pmatrix} X \\ Y \end{pmatrix} $ where $(X, Y)' \sim N_2((\mu_1,\mu_2)',\begin{pmatrix} \sigma^2 & {\sigma^2\over 2} \\ {\sigma^2\over 2} & \sigma^2 \end{pmatrix})$ as given in the problem. We know that the distribution of $U$ and $V$ is $$(U, V)' \sim N_2((\mu_1-{\mu_2\over2},{\sqrt3 \mu_2\over2})',\begin{pmatrix} {3 \sigma^2\over 4} & 0 \\ 0 &{3 \sigma^2\over 4} \end{pmatrix})$$ We can tell that $U$ and $V$ are independent of each other. Now we can express $\Lambda^{-1/n}$ with these statistics like this: $$\frac{\sum_{i=1}^{n}X_i^2+\sum_{i=1}^{n}Y_i^2-\sum_{i=1}^n X_iY_i }{ \sum_{i=1}^{n} \left(X_i-\bar{X} \right)^2+\sum_{i=1}^{n} \left(Y_i-\bar{Y} \right)^2-\sum_{i=1}^{n} \left(Y_i-\bar{Y} \right) \left(X_i-\bar{X} \right) } = \frac{\sum_{i=1}^{n}U_i^2+\sum_{i=1}^{n}V_i^2 } { \sum_{i=1}^{n} \left(U_i-\bar{U} \right)^2+\sum_{i=1}^{n} \left(V_i-\bar{V} \right)^2 } $$ $$=1+\frac{n \bar{U}^2+n \bar{V}^2 } { \sum_{i=1}^{n} \left(U_i-\bar{U} \right)^2+\sum_{i=1}^{n} \left(V_i-\bar{V} \right)^2 }$$ We know that $S_U^2$ the sample variance of U and $S_V^2$ the sample variance of V are independent of $\bar U$ and $\bar V$ respectively. So these four statistics are independent of each other. And we also know their distributions under null hypothesis : $${n\bar U^2 \over 3\sigma^2/4 } \sim \chi^2 (1) $$ $${n\bar V^2 \over 3\sigma^2/4 } \sim \chi^2 (1) $$ $${{(n-1)S_U^2\over 3\sigma^2/4 } } \sim \chi^2 (n-1) $$ $${ {(n-1)S_V^2\over 3\sigma^2/4 }} \sim \chi^2 (n-1) $$ Let's use these statistics then, $$\Lambda^{-1/n}= 1+\frac{{n\bar U^2 \over 3 \sigma^2 /4}+{n\bar U^2 \over 3\sigma^2 /4}}{{(n-1)S_U^2\over 3 \sigma^2 /4}+{(n-1)S_V^2\over 3 \sigma^2 /4}}$$ Look at the right term. The numerator has $\chi^2(2)$ distribution and the denominator has $\chi^2(2n-2)$ distribution. We can adopt F distribution here like this: $$\Lambda^{-1/n}=1+\frac {Q} {n-1}$$ where Q has a F distribution with dof 2 and 2n-2. Further more, I guess it would have non central F distribution under alternative hypothesis. Thank you for reading. edit Interestingly $\lim_{n->\infty} \Lambda = e^{-Q}$. Could we interpret this? I am being curious. edit Well, according to this document :http://www.math.wm.edu/~leemis/chart/UDR/PDFs/FChisquare.pdf I think Q will converge to the distribution $\Gamma(1,1)$ that is $f_{Q_\infty}(q)=e^{-q}$ which means that the limit of the likelihood ratio $\Lambda_{\infty}$ is likely to have uniform distribution, since $f_{\Lambda_{\infty}}=1$ and $0\leq \Lambda_{\infty} \leq 1$ Am I right? I am not sure about this.
Likelihood Ratio for the Bivariate Normal distribution
I would like to suggest this way to simplify the likelihood ratio $\Lambda$. I am not a native English speaker so feel free to correct my grammar errors. Let me introduce these statistics $U, V$ which
Likelihood Ratio for the Bivariate Normal distribution I would like to suggest this way to simplify the likelihood ratio $\Lambda$. I am not a native English speaker so feel free to correct my grammar errors. Let me introduce these statistics $U, V$ which are given by linear combination of X and Y as $\begin{pmatrix} U \\ V \end{pmatrix} =\begin{pmatrix} 1 & -{1 \over 2} \\ 0 & { \sqrt3 \over 2} \end{pmatrix}\begin{pmatrix} X \\ Y \end{pmatrix} $ where $(X, Y)' \sim N_2((\mu_1,\mu_2)',\begin{pmatrix} \sigma^2 & {\sigma^2\over 2} \\ {\sigma^2\over 2} & \sigma^2 \end{pmatrix})$ as given in the problem. We know that the distribution of $U$ and $V$ is $$(U, V)' \sim N_2((\mu_1-{\mu_2\over2},{\sqrt3 \mu_2\over2})',\begin{pmatrix} {3 \sigma^2\over 4} & 0 \\ 0 &{3 \sigma^2\over 4} \end{pmatrix})$$ We can tell that $U$ and $V$ are independent of each other. Now we can express $\Lambda^{-1/n}$ with these statistics like this: $$\frac{\sum_{i=1}^{n}X_i^2+\sum_{i=1}^{n}Y_i^2-\sum_{i=1}^n X_iY_i }{ \sum_{i=1}^{n} \left(X_i-\bar{X} \right)^2+\sum_{i=1}^{n} \left(Y_i-\bar{Y} \right)^2-\sum_{i=1}^{n} \left(Y_i-\bar{Y} \right) \left(X_i-\bar{X} \right) } = \frac{\sum_{i=1}^{n}U_i^2+\sum_{i=1}^{n}V_i^2 } { \sum_{i=1}^{n} \left(U_i-\bar{U} \right)^2+\sum_{i=1}^{n} \left(V_i-\bar{V} \right)^2 } $$ $$=1+\frac{n \bar{U}^2+n \bar{V}^2 } { \sum_{i=1}^{n} \left(U_i-\bar{U} \right)^2+\sum_{i=1}^{n} \left(V_i-\bar{V} \right)^2 }$$ We know that $S_U^2$ the sample variance of U and $S_V^2$ the sample variance of V are independent of $\bar U$ and $\bar V$ respectively. So these four statistics are independent of each other. And we also know their distributions under null hypothesis : $${n\bar U^2 \over 3\sigma^2/4 } \sim \chi^2 (1) $$ $${n\bar V^2 \over 3\sigma^2/4 } \sim \chi^2 (1) $$ $${{(n-1)S_U^2\over 3\sigma^2/4 } } \sim \chi^2 (n-1) $$ $${ {(n-1)S_V^2\over 3\sigma^2/4 }} \sim \chi^2 (n-1) $$ Let's use these statistics then, $$\Lambda^{-1/n}= 1+\frac{{n\bar U^2 \over 3 \sigma^2 /4}+{n\bar U^2 \over 3\sigma^2 /4}}{{(n-1)S_U^2\over 3 \sigma^2 /4}+{(n-1)S_V^2\over 3 \sigma^2 /4}}$$ Look at the right term. The numerator has $\chi^2(2)$ distribution and the denominator has $\chi^2(2n-2)$ distribution. We can adopt F distribution here like this: $$\Lambda^{-1/n}=1+\frac {Q} {n-1}$$ where Q has a F distribution with dof 2 and 2n-2. Further more, I guess it would have non central F distribution under alternative hypothesis. Thank you for reading. edit Interestingly $\lim_{n->\infty} \Lambda = e^{-Q}$. Could we interpret this? I am being curious. edit Well, according to this document :http://www.math.wm.edu/~leemis/chart/UDR/PDFs/FChisquare.pdf I think Q will converge to the distribution $\Gamma(1,1)$ that is $f_{Q_\infty}(q)=e^{-q}$ which means that the limit of the likelihood ratio $\Lambda_{\infty}$ is likely to have uniform distribution, since $f_{\Lambda_{\infty}}=1$ and $0\leq \Lambda_{\infty} \leq 1$ Am I right? I am not sure about this.
Likelihood Ratio for the Bivariate Normal distribution I would like to suggest this way to simplify the likelihood ratio $\Lambda$. I am not a native English speaker so feel free to correct my grammar errors. Let me introduce these statistics $U, V$ which
35,438
Likelihood Ratio for the Bivariate Normal distribution
It is my understanding that there are likelihood ratios and log likelihood ratios, the latter being the log of the quotient as opposed to the quotient of logs. I think this is where you have gone wrong. Best of luck!
Likelihood Ratio for the Bivariate Normal distribution
It is my understanding that there are likelihood ratios and log likelihood ratios, the latter being the log of the quotient as opposed to the quotient of logs. I think this is where you have gone wro
Likelihood Ratio for the Bivariate Normal distribution It is my understanding that there are likelihood ratios and log likelihood ratios, the latter being the log of the quotient as opposed to the quotient of logs. I think this is where you have gone wrong. Best of luck!
Likelihood Ratio for the Bivariate Normal distribution It is my understanding that there are likelihood ratios and log likelihood ratios, the latter being the log of the quotient as opposed to the quotient of logs. I think this is where you have gone wro
35,439
Likelihood Ratio for the Bivariate Normal distribution
I am fairly confident that it reduces to a statistic with an F distribution. The numerator of the likelihood ratio you have provided is a chi-squared distribution multiplied by a constant (having 2*(n-1)) under HO. Also, under HO, X == Y, therefore the denominator can also be written as a chi-squared variable (having 2n df).
Likelihood Ratio for the Bivariate Normal distribution
I am fairly confident that it reduces to a statistic with an F distribution. The numerator of the likelihood ratio you have provided is a chi-squared distribution multiplied by a constant (having 2*(
Likelihood Ratio for the Bivariate Normal distribution I am fairly confident that it reduces to a statistic with an F distribution. The numerator of the likelihood ratio you have provided is a chi-squared distribution multiplied by a constant (having 2*(n-1)) under HO. Also, under HO, X == Y, therefore the denominator can also be written as a chi-squared variable (having 2n df).
Likelihood Ratio for the Bivariate Normal distribution I am fairly confident that it reduces to a statistic with an F distribution. The numerator of the likelihood ratio you have provided is a chi-squared distribution multiplied by a constant (having 2*(
35,440
Likelihood Ratio for the Bivariate Normal distribution
I am fairly confident that it reduces to a statistic with an F distribution too. The numerator of the likelihood ratio you have provided is a chi-squared distribution multiplied by a constant, and the same holds for the denominator. The cross product XY is the sum of two independent chi-squared variables since var (x) = var (y) and XY may be rewritten in the form .25*(X+Y)^2 -.25*(X-Y)^2 which is of the chi-squared form.
Likelihood Ratio for the Bivariate Normal distribution
I am fairly confident that it reduces to a statistic with an F distribution too. The numerator of the likelihood ratio you have provided is a chi-squared distribution multiplied by a constant, and the
Likelihood Ratio for the Bivariate Normal distribution I am fairly confident that it reduces to a statistic with an F distribution too. The numerator of the likelihood ratio you have provided is a chi-squared distribution multiplied by a constant, and the same holds for the denominator. The cross product XY is the sum of two independent chi-squared variables since var (x) = var (y) and XY may be rewritten in the form .25*(X+Y)^2 -.25*(X-Y)^2 which is of the chi-squared form.
Likelihood Ratio for the Bivariate Normal distribution I am fairly confident that it reduces to a statistic with an F distribution too. The numerator of the likelihood ratio you have provided is a chi-squared distribution multiplied by a constant, and the
35,441
Choice between different robust regressions in R
In the notation I will use, $p$ will be the number of design variables (including the constant term), $n$ the number of observations with $n\geq2p+1$ (if this last condition was not met, the package would not have returned a fit but an error, so I assume it is met). I will denote by $\hat{\boldsymbol\beta}_{FLTS}$ the vector of coefficients estimated by FLTS (ltsReg) and $\hat{\boldsymbol\beta}_{MM}$ the coefficients estimated by MM (lmrob). I will also write: $$r^2_i(\hat{\boldsymbol\beta})=(y_i-\boldsymbol x_i^\top\hat{\boldsymbol\beta})^2$$ (these are the squared residuals, not the standardized ones!) The rlm function fits an 'M' estimate of regression and, like @Frank Harrell's proposal made in the comments to your question, it is not robust to outliers on the design space. Ordinal regression has a breakdown point (the proportion of your data that needs to be replaced by outliers to pull the fitted coefficients to arbitrary values) of essentially $1/n$ meaning that a single outlier (regardless of $n$!) suffice to render the fit meaningless. For regression M estimates (e.g. Huber M regression) the breakdown point is essentially $1/(p+1)$. This is somewhat higher but in practice still uncomfortably close to 0 (because often $p$ will be large). The only conclusion that can be drawn from rlm finding a different fit than the other two methods is that it has been swayed by design outliers and that there must be more than $p+1$ of these in your data set. In contrast, the other two algorithms are much more robust: their breakdown point is just below $1/2$ and more importantly, doesn't shrink as $p$ gets large. When fitting a linear model using a robust method, you assume that at least $h=\lfloor(n+p+1)/2\rfloor+1$ observations in your data are uncontaminated. The task of these two algorithms is to find those observations and fit them as well as possible. More precisely, if we denote: \begin{align} H_{FLTS} &= \{i:r^2_i(\hat{\boldsymbol\beta}_{FLTS})\leq q_{h/n}(r^2_i(\hat{\boldsymbol\beta}_{FLTS}))\} \\ H_{MM} &= \{i:r^2_i(\hat{\boldsymbol\beta}_{MM})\leq q_{h/n}(r^2_i(\hat{\boldsymbol\beta}_{MM}))\} \end{align} (where $q_{h/n}(r^2_i(\hat{\boldsymbol\beta}_{MM}))$ is the $h/n$ quantile of the vector $r^2_i(\hat{\boldsymbol\beta}_{MM})$) then $\hat{\boldsymbol\beta}_{MM}$ ($\hat{\boldsymbol\beta}_{FLTS}$) tries to fit the observations with indices in $H_{MM}$ ($H_{FLTS}$). The fact that there are large differences between $\hat{\boldsymbol\beta}_{FLTS}$ and $\hat{\boldsymbol\beta}_{MM}$ indicates that the two algorithms do not identify the same set of observations as outliers. This means that at least one of them is swayed by the outliers. In this case, using the (adjusted) $R^2$ or any one statistics from either of the two fits to decide which to use, though intuitive, is a terrible idea: contaminated fits typically have smaller residuals than clean ones (but since knowledge of this is the reason one uses robust statistics in the first place, I assume that the OP is well aware of this fact and that I don't need to expand on this). The two robust fits give conflicting results and the question is which is correct? One way to solve this is to consider the set: $$H^+=H_{MM}\cap H_{FLTS}$$ because $h\geq[n/2]$, $\#\{H^+\}\geq p$. Furthermore, if either of $H_{MM}$ or $H_{FLTS}$ is free of outliers, so is $H^+$. The solution I propose exploits this fact. Compute: $$D(H^+,\hat{\boldsymbol\beta}_{FLTS},\hat{\boldsymbol\beta}_{MM})=\sum_{i\in H^+}\left(r^2_i(\hat{\boldsymbol\beta}_{FLTS})-r^2_i(\hat{\boldsymbol\beta}_{MM})\right)$$ For example, if $D(H^+,\hat{\boldsymbol\beta}_{FLTS},\hat{\boldsymbol\beta}_{MM})<0$, then, $\hat{\boldsymbol\beta}_{FLTS}$ fits the good observations better than $\hat{\boldsymbol\beta}_{MM}$ and so I would trust $\hat{\boldsymbol\beta}_{FLTS}$ more. And vice versa.
Choice between different robust regressions in R
In the notation I will use, $p$ will be the number of design variables (including the constant term), $n$ the number of observations with $n\geq2p+1$ (if this last condition was not met, the package w
Choice between different robust regressions in R In the notation I will use, $p$ will be the number of design variables (including the constant term), $n$ the number of observations with $n\geq2p+1$ (if this last condition was not met, the package would not have returned a fit but an error, so I assume it is met). I will denote by $\hat{\boldsymbol\beta}_{FLTS}$ the vector of coefficients estimated by FLTS (ltsReg) and $\hat{\boldsymbol\beta}_{MM}$ the coefficients estimated by MM (lmrob). I will also write: $$r^2_i(\hat{\boldsymbol\beta})=(y_i-\boldsymbol x_i^\top\hat{\boldsymbol\beta})^2$$ (these are the squared residuals, not the standardized ones!) The rlm function fits an 'M' estimate of regression and, like @Frank Harrell's proposal made in the comments to your question, it is not robust to outliers on the design space. Ordinal regression has a breakdown point (the proportion of your data that needs to be replaced by outliers to pull the fitted coefficients to arbitrary values) of essentially $1/n$ meaning that a single outlier (regardless of $n$!) suffice to render the fit meaningless. For regression M estimates (e.g. Huber M regression) the breakdown point is essentially $1/(p+1)$. This is somewhat higher but in practice still uncomfortably close to 0 (because often $p$ will be large). The only conclusion that can be drawn from rlm finding a different fit than the other two methods is that it has been swayed by design outliers and that there must be more than $p+1$ of these in your data set. In contrast, the other two algorithms are much more robust: their breakdown point is just below $1/2$ and more importantly, doesn't shrink as $p$ gets large. When fitting a linear model using a robust method, you assume that at least $h=\lfloor(n+p+1)/2\rfloor+1$ observations in your data are uncontaminated. The task of these two algorithms is to find those observations and fit them as well as possible. More precisely, if we denote: \begin{align} H_{FLTS} &= \{i:r^2_i(\hat{\boldsymbol\beta}_{FLTS})\leq q_{h/n}(r^2_i(\hat{\boldsymbol\beta}_{FLTS}))\} \\ H_{MM} &= \{i:r^2_i(\hat{\boldsymbol\beta}_{MM})\leq q_{h/n}(r^2_i(\hat{\boldsymbol\beta}_{MM}))\} \end{align} (where $q_{h/n}(r^2_i(\hat{\boldsymbol\beta}_{MM}))$ is the $h/n$ quantile of the vector $r^2_i(\hat{\boldsymbol\beta}_{MM})$) then $\hat{\boldsymbol\beta}_{MM}$ ($\hat{\boldsymbol\beta}_{FLTS}$) tries to fit the observations with indices in $H_{MM}$ ($H_{FLTS}$). The fact that there are large differences between $\hat{\boldsymbol\beta}_{FLTS}$ and $\hat{\boldsymbol\beta}_{MM}$ indicates that the two algorithms do not identify the same set of observations as outliers. This means that at least one of them is swayed by the outliers. In this case, using the (adjusted) $R^2$ or any one statistics from either of the two fits to decide which to use, though intuitive, is a terrible idea: contaminated fits typically have smaller residuals than clean ones (but since knowledge of this is the reason one uses robust statistics in the first place, I assume that the OP is well aware of this fact and that I don't need to expand on this). The two robust fits give conflicting results and the question is which is correct? One way to solve this is to consider the set: $$H^+=H_{MM}\cap H_{FLTS}$$ because $h\geq[n/2]$, $\#\{H^+\}\geq p$. Furthermore, if either of $H_{MM}$ or $H_{FLTS}$ is free of outliers, so is $H^+$. The solution I propose exploits this fact. Compute: $$D(H^+,\hat{\boldsymbol\beta}_{FLTS},\hat{\boldsymbol\beta}_{MM})=\sum_{i\in H^+}\left(r^2_i(\hat{\boldsymbol\beta}_{FLTS})-r^2_i(\hat{\boldsymbol\beta}_{MM})\right)$$ For example, if $D(H^+,\hat{\boldsymbol\beta}_{FLTS},\hat{\boldsymbol\beta}_{MM})<0$, then, $\hat{\boldsymbol\beta}_{FLTS}$ fits the good observations better than $\hat{\boldsymbol\beta}_{MM}$ and so I would trust $\hat{\boldsymbol\beta}_{FLTS}$ more. And vice versa.
Choice between different robust regressions in R In the notation I will use, $p$ will be the number of design variables (including the constant term), $n$ the number of observations with $n\geq2p+1$ (if this last condition was not met, the package w
35,442
Convert hazards ratio to odds ratio
If there was an extremely low proportion of subjects with an event in all experiments (let's say <10%) and the hazard and odds ratios are vey close to 1, then hazard, odds and relative risk ratios will be relatively close to each other. If that is not the case the fundamental differences between these measures will be more and more noticable. For a given trial duration, particular distribution for event occurence and a particular drop-out pattern, there is a correspondence of hazard ratio to odds ratio to relative risk ratio. If all your experiments in your meta-analysis are similar in these respects, it might be possible to convert them. Once you have experiments with different durations, different drop-out patterns or different event time distributions, a hazard ratio might be constant across experiments and is probably the better relative risk measure, but an odds or risk ratio will essentially never be (even if the hazard ratio is, while the same odds ratio would correspond to different hazard ratios across experiments).
Convert hazards ratio to odds ratio
If there was an extremely low proportion of subjects with an event in all experiments (let's say <10%) and the hazard and odds ratios are vey close to 1, then hazard, odds and relative risk ratios wil
Convert hazards ratio to odds ratio If there was an extremely low proportion of subjects with an event in all experiments (let's say <10%) and the hazard and odds ratios are vey close to 1, then hazard, odds and relative risk ratios will be relatively close to each other. If that is not the case the fundamental differences between these measures will be more and more noticable. For a given trial duration, particular distribution for event occurence and a particular drop-out pattern, there is a correspondence of hazard ratio to odds ratio to relative risk ratio. If all your experiments in your meta-analysis are similar in these respects, it might be possible to convert them. Once you have experiments with different durations, different drop-out patterns or different event time distributions, a hazard ratio might be constant across experiments and is probably the better relative risk measure, but an odds or risk ratio will essentially never be (even if the hazard ratio is, while the same odds ratio would correspond to different hazard ratios across experiments).
Convert hazards ratio to odds ratio If there was an extremely low proportion of subjects with an event in all experiments (let's say <10%) and the hazard and odds ratios are vey close to 1, then hazard, odds and relative risk ratios wil
35,443
Convert hazards ratio to odds ratio
$$\text{RR} = (1 - e^{\text{HR}\ln(1-r)})/r$$ where HR is the hazard ratio and r is the rate for the reference group. If r is not reported, it is probably reported elsewhere (e.g. baseline death rate). See Shor et al. (2017) doi: 10.1016/j.socscimed.2017.05.049 Zhang and Yu (1998), doi: 10.1001/jama.280.19.1690 provide an approximate of RR based on the odds ratio (OR). $$\text{RR} = \frac{\text{OR}}{(1-P_o)+(P_o\cdot \text{OR})}$$ where Po is the incidence of the outcome of interest in the non-exposed group. You can then calculate OR.
Convert hazards ratio to odds ratio
$$\text{RR} = (1 - e^{\text{HR}\ln(1-r)})/r$$ where HR is the hazard ratio and r is the rate for the reference group. If r is not reported, it is probably reported elsewhere (e.g. baseline death rate
Convert hazards ratio to odds ratio $$\text{RR} = (1 - e^{\text{HR}\ln(1-r)})/r$$ where HR is the hazard ratio and r is the rate for the reference group. If r is not reported, it is probably reported elsewhere (e.g. baseline death rate). See Shor et al. (2017) doi: 10.1016/j.socscimed.2017.05.049 Zhang and Yu (1998), doi: 10.1001/jama.280.19.1690 provide an approximate of RR based on the odds ratio (OR). $$\text{RR} = \frac{\text{OR}}{(1-P_o)+(P_o\cdot \text{OR})}$$ where Po is the incidence of the outcome of interest in the non-exposed group. You can then calculate OR.
Convert hazards ratio to odds ratio $$\text{RR} = (1 - e^{\text{HR}\ln(1-r)})/r$$ where HR is the hazard ratio and r is the rate for the reference group. If r is not reported, it is probably reported elsewhere (e.g. baseline death rate
35,444
Convert hazards ratio to odds ratio
Exploiting the assumption that hazard ratios are asymptotically similar to relative risks, you can use exploit the formula recommendeed by Grant et al, BMJ 2014: RR = OR / (1 - p + (p * OR) where RR is the relative risk, OR is the odds ratio, and p is the control event rate, which leads to the following: OR = ((1 - p) * RR) / (1 - RR * p). Thus, for instance, a RR of 2.0 with a p of 0.1 would lead to an OR of 2.25, whereas if p increases to 0.2 it would lead to an OR of 2.67.
Convert hazards ratio to odds ratio
Exploiting the assumption that hazard ratios are asymptotically similar to relative risks, you can use exploit the formula recommendeed by Grant et al, BMJ 2014: RR = OR / (1 - p + (p * OR) where RR
Convert hazards ratio to odds ratio Exploiting the assumption that hazard ratios are asymptotically similar to relative risks, you can use exploit the formula recommendeed by Grant et al, BMJ 2014: RR = OR / (1 - p + (p * OR) where RR is the relative risk, OR is the odds ratio, and p is the control event rate, which leads to the following: OR = ((1 - p) * RR) / (1 - RR * p). Thus, for instance, a RR of 2.0 with a p of 0.1 would lead to an OR of 2.25, whereas if p increases to 0.2 it would lead to an OR of 2.67.
Convert hazards ratio to odds ratio Exploiting the assumption that hazard ratios are asymptotically similar to relative risks, you can use exploit the formula recommendeed by Grant et al, BMJ 2014: RR = OR / (1 - p + (p * OR) where RR
35,445
Convert hazards ratio to odds ratio
See also this paper on the relation between OR, RR, and HR Stare, J. & Maucort-Boulch, D. Odds ratio, hazard ratio and relative risk. Advances in Methodology and Statistics 13, 59–67 (2016). Available in https://mz.mf.uni-lj.si/article/view/159/262
Convert hazards ratio to odds ratio
See also this paper on the relation between OR, RR, and HR Stare, J. & Maucort-Boulch, D. Odds ratio, hazard ratio and relative risk. Advances in Methodology and Statistics 13, 59–67 (2016). Available
Convert hazards ratio to odds ratio See also this paper on the relation between OR, RR, and HR Stare, J. & Maucort-Boulch, D. Odds ratio, hazard ratio and relative risk. Advances in Methodology and Statistics 13, 59–67 (2016). Available in https://mz.mf.uni-lj.si/article/view/159/262
Convert hazards ratio to odds ratio See also this paper on the relation between OR, RR, and HR Stare, J. & Maucort-Boulch, D. Odds ratio, hazard ratio and relative risk. Advances in Methodology and Statistics 13, 59–67 (2016). Available
35,446
Are time series methods only good for forecasting?
Usually you want to forecast the behaviour of a system to improve your reaction to and interaction with that system. But at the end of the day, forecasting is only a last resort, if it is not feasible to control the system. Moreover, forecasting with nothing but time series is something you usually only do if your system is so complex that you cannot incorporate any useful other knowledge about it into your forecasts. Time-series analysis gives you a lot of methods to understand the inner workings of a system, which in turn may be the first step to controlling it. For example, it may yield the following information: What are the internal rhythms of the system and what is their relevance to my observable? To what extent is my system noise-dominated and how does that noise look like? Is the system stationary or not – the latter being an indicator for long-term changes of external conditions influencing the system. If I regard my system as a dynamical system, what are the features of the underlying dynamics: Is it chaotic or regular? How does it react to perturbations? How does its phase space look like? For a system with multiple components: Which components interact with each other? How do I model my system if I want my model to do more than just reproduce certain features of observed time series, such as yielding an understanding of the system, properly describing situations that are not comparable to anything that has been observed in the past at all, e.g., when I actively manipulate the system or an extreme event happens (such as in a disaster simulation). All of the above points can play into this and moreover, time-series analysis can be used to verify a model by comparing the time series of the original and the model. Some practical examples: Climate research employs a lot of time-series analysis but is not only good for forecasting climate but also tries to answers the important question of how we influence our climate. If you have a time series related to the illness of an individual female patient and you find a strong frequency component of roughly one month, this is a strong hint to the menstrual cycle being somehow involved. Even if you fail to understand this relation, and can only treat the symptoms by giving some medication at the right time, you can benefit from taking the actual menstrual cycle of that patient into account (this is an example were you forecast with more than just time series).
Are time series methods only good for forecasting?
Usually you want to forecast the behaviour of a system to improve your reaction to and interaction with that system. But at the end of the day, forecasting is only a last resort, if it is not feasible
Are time series methods only good for forecasting? Usually you want to forecast the behaviour of a system to improve your reaction to and interaction with that system. But at the end of the day, forecasting is only a last resort, if it is not feasible to control the system. Moreover, forecasting with nothing but time series is something you usually only do if your system is so complex that you cannot incorporate any useful other knowledge about it into your forecasts. Time-series analysis gives you a lot of methods to understand the inner workings of a system, which in turn may be the first step to controlling it. For example, it may yield the following information: What are the internal rhythms of the system and what is their relevance to my observable? To what extent is my system noise-dominated and how does that noise look like? Is the system stationary or not – the latter being an indicator for long-term changes of external conditions influencing the system. If I regard my system as a dynamical system, what are the features of the underlying dynamics: Is it chaotic or regular? How does it react to perturbations? How does its phase space look like? For a system with multiple components: Which components interact with each other? How do I model my system if I want my model to do more than just reproduce certain features of observed time series, such as yielding an understanding of the system, properly describing situations that are not comparable to anything that has been observed in the past at all, e.g., when I actively manipulate the system or an extreme event happens (such as in a disaster simulation). All of the above points can play into this and moreover, time-series analysis can be used to verify a model by comparing the time series of the original and the model. Some practical examples: Climate research employs a lot of time-series analysis but is not only good for forecasting climate but also tries to answers the important question of how we influence our climate. If you have a time series related to the illness of an individual female patient and you find a strong frequency component of roughly one month, this is a strong hint to the menstrual cycle being somehow involved. Even if you fail to understand this relation, and can only treat the symptoms by giving some medication at the right time, you can benefit from taking the actual menstrual cycle of that patient into account (this is an example were you forecast with more than just time series).
Are time series methods only good for forecasting? Usually you want to forecast the behaviour of a system to improve your reaction to and interaction with that system. But at the end of the day, forecasting is only a last resort, if it is not feasible
35,447
Are time series methods only good for forecasting?
I would say no. Time series methods can reveal something about the structure of the problem in hand, not just about some forecasts done only with series own history. For example state-space model form can be used to model time varying regression with several varieties. And also structural time series can be casted into state space form. Zellner and Palm wrote an article about the combining structural and time series modeling. ftp://ftp.uic.edu/pub/depts/econ/hhstokes/e537/zellner_palm_je74.pdf
Are time series methods only good for forecasting?
I would say no. Time series methods can reveal something about the structure of the problem in hand, not just about some forecasts done only with series own history. For example state-space model for
Are time series methods only good for forecasting? I would say no. Time series methods can reveal something about the structure of the problem in hand, not just about some forecasts done only with series own history. For example state-space model form can be used to model time varying regression with several varieties. And also structural time series can be casted into state space form. Zellner and Palm wrote an article about the combining structural and time series modeling. ftp://ftp.uic.edu/pub/depts/econ/hhstokes/e537/zellner_palm_je74.pdf
Are time series methods only good for forecasting? I would say no. Time series methods can reveal something about the structure of the problem in hand, not just about some forecasts done only with series own history. For example state-space model for
35,448
Are time series methods only good for forecasting?
No. I'll give you one use of time series, which is not related to forecasting: spectral analysis. FFT is the work horse in spectral analysis, but it works best when your series are essentially infinite, or very long. Analyzing sound waves is a good application for FFT. However, in social sciences the series are usually not very long. Usually we have a few dozen observations at most. So in these cases you can use Yule-Walker equations to obtain a periodogram of the series, e.g. see MATLAB pyulear function.
Are time series methods only good for forecasting?
No. I'll give you one use of time series, which is not related to forecasting: spectral analysis. FFT is the work horse in spectral analysis, but it works best when your series are essentially infini
Are time series methods only good for forecasting? No. I'll give you one use of time series, which is not related to forecasting: spectral analysis. FFT is the work horse in spectral analysis, but it works best when your series are essentially infinite, or very long. Analyzing sound waves is a good application for FFT. However, in social sciences the series are usually not very long. Usually we have a few dozen observations at most. So in these cases you can use Yule-Walker equations to obtain a periodogram of the series, e.g. see MATLAB pyulear function.
Are time series methods only good for forecasting? No. I'll give you one use of time series, which is not related to forecasting: spectral analysis. FFT is the work horse in spectral analysis, but it works best when your series are essentially infini
35,449
Applied statistics vs Mathematical statistics
There are not only mathematical statistics and applied statistics, but also statistics (in general). You could say that statistics is about why and applied statistics is about how. Mathematical statistics is a branch of mathematics and generally a scientific discipline (the same as statistics). Applied statistics, on the other hand, is a term commonly used to name courses for non-mathematically oriented audience, that teach you how to apply statistical tools for the purpose of data analysis. You can find multiple applied statistics handbooks named like: "Discovering Statistics Using SPSS", "Statistics for Social Science" etc. Applied statistics is often applied by non-statisticians, e.g. researchers doing their projects. However, this doesn't mean that statisticians do not apply statistics, but rather it's applied statistics that is not interested in researching statistical theory, but rather it's applications. Statistics is concerned about statistical problems, while applied statistics about using statistics for solving other problems. There are journals on applied statistics that promote development of statistical tools (see below). Examples that could give you a scope on what applied statistics is: Journal of Applied Statistics provides a forum for communication between both applied statisticians and users of applied statistical techniques across a wide range of disciplines. These areas include business, computing, economics, ecology, education, management, medicine, operational research and sociology, but papers from other areas are also considered. The editorial policy is to publish rigorous but clear and accessible papers on applied techniques. Purely theoretical papers are avoided but those on theoretical developments which clearly demonstrate significant applied potential are welcomed. The Journal aims for a balance of methodological innovation, thorough evaluation of existing techniques, case studies,speculative articles, book reviews and letters. (source) or: The Journal of the Royal Statistical Society, Series C (Applied Statistics) (...) is concerned with papers which deal with novel solutions to real life statistical problems by adapting or developing methodology, or by demonstrating the proper application of new or existing statistical methods to them. (...) A deep understanding of statistical methodology is not necessary to appreciate the content. Although papers describing developments in statistical computing driven by practical examples are within its scope, the journal is not concerned with simply numerical illustrations or simulation studies. The emphasis of Series C is on case-studies of statistical analyses in practice. (source) or aims of applied statistics courses: The MSc in Applied Statistics will aim to train you to solve real-world statistical problems. When completing the course you should be able to choose an appropriate statistical method to solve a given problem of data analysis and communicate your results clearly and succinctly. The course aims to equip you with the computational skills to carry through the analysis and answer the problem as presented. (...) (source) I didn't give here a broad review on what statistics or mathematical statistics are, but it should be self-explanatory since I given you examples on how does applied statistics differ from them.
Applied statistics vs Mathematical statistics
There are not only mathematical statistics and applied statistics, but also statistics (in general). You could say that statistics is about why and applied statistics is about how. Mathematical statis
Applied statistics vs Mathematical statistics There are not only mathematical statistics and applied statistics, but also statistics (in general). You could say that statistics is about why and applied statistics is about how. Mathematical statistics is a branch of mathematics and generally a scientific discipline (the same as statistics). Applied statistics, on the other hand, is a term commonly used to name courses for non-mathematically oriented audience, that teach you how to apply statistical tools for the purpose of data analysis. You can find multiple applied statistics handbooks named like: "Discovering Statistics Using SPSS", "Statistics for Social Science" etc. Applied statistics is often applied by non-statisticians, e.g. researchers doing their projects. However, this doesn't mean that statisticians do not apply statistics, but rather it's applied statistics that is not interested in researching statistical theory, but rather it's applications. Statistics is concerned about statistical problems, while applied statistics about using statistics for solving other problems. There are journals on applied statistics that promote development of statistical tools (see below). Examples that could give you a scope on what applied statistics is: Journal of Applied Statistics provides a forum for communication between both applied statisticians and users of applied statistical techniques across a wide range of disciplines. These areas include business, computing, economics, ecology, education, management, medicine, operational research and sociology, but papers from other areas are also considered. The editorial policy is to publish rigorous but clear and accessible papers on applied techniques. Purely theoretical papers are avoided but those on theoretical developments which clearly demonstrate significant applied potential are welcomed. The Journal aims for a balance of methodological innovation, thorough evaluation of existing techniques, case studies,speculative articles, book reviews and letters. (source) or: The Journal of the Royal Statistical Society, Series C (Applied Statistics) (...) is concerned with papers which deal with novel solutions to real life statistical problems by adapting or developing methodology, or by demonstrating the proper application of new or existing statistical methods to them. (...) A deep understanding of statistical methodology is not necessary to appreciate the content. Although papers describing developments in statistical computing driven by practical examples are within its scope, the journal is not concerned with simply numerical illustrations or simulation studies. The emphasis of Series C is on case-studies of statistical analyses in practice. (source) or aims of applied statistics courses: The MSc in Applied Statistics will aim to train you to solve real-world statistical problems. When completing the course you should be able to choose an appropriate statistical method to solve a given problem of data analysis and communicate your results clearly and succinctly. The course aims to equip you with the computational skills to carry through the analysis and answer the problem as presented. (...) (source) I didn't give here a broad review on what statistics or mathematical statistics are, but it should be self-explanatory since I given you examples on how does applied statistics differ from them.
Applied statistics vs Mathematical statistics There are not only mathematical statistics and applied statistics, but also statistics (in general). You could say that statistics is about why and applied statistics is about how. Mathematical statis
35,450
Applied statistics vs Mathematical statistics
If you're simply taking a book on techniques and learning how to plug things into R/SAS/STATA, you're really not doing applied statistics, imo. The best applied statistics courses/programs involve a healthy dose of theory. The difference between the two really is one of emphasis. In an applied course, you're learning to use techniques, whereas in "pure" stats courses you're learning to develop or prove things. So in a good applied regression class, you'll see the proof that, say, the coefficients in OLS regression are the MLE, assuming the errors are Gaussian. You might remember this, along with the implication that this means the coefficients are efficient estimators, as reasons that OLS is "good." But aside from remembering this (maybe you get a question on the test worth a few points as to why OLS is "good," and you'll have to write down this fact), and maybe a homework question asking you to prove some implication of this fact, you're unlikely to use that proof again. In a "pure" stats class, however, the proof is the class. You might not even see how this fact is used in the "real world." You're more interested in how the proof works, because at some point in the future you might want to prove that the estimator you're developing is an MLE. Put differently, at my university, the graduate Applied Regression course uses a fair amount of proofs in class, and you have a hard time passing if you don't know calculus and linear algebra. But the homeworks and exams are mostly about interpreting data. In the PhD-level GLM course, however, they never so much as download a dataset.
Applied statistics vs Mathematical statistics
If you're simply taking a book on techniques and learning how to plug things into R/SAS/STATA, you're really not doing applied statistics, imo. The best applied statistics courses/programs involve a h
Applied statistics vs Mathematical statistics If you're simply taking a book on techniques and learning how to plug things into R/SAS/STATA, you're really not doing applied statistics, imo. The best applied statistics courses/programs involve a healthy dose of theory. The difference between the two really is one of emphasis. In an applied course, you're learning to use techniques, whereas in "pure" stats courses you're learning to develop or prove things. So in a good applied regression class, you'll see the proof that, say, the coefficients in OLS regression are the MLE, assuming the errors are Gaussian. You might remember this, along with the implication that this means the coefficients are efficient estimators, as reasons that OLS is "good." But aside from remembering this (maybe you get a question on the test worth a few points as to why OLS is "good," and you'll have to write down this fact), and maybe a homework question asking you to prove some implication of this fact, you're unlikely to use that proof again. In a "pure" stats class, however, the proof is the class. You might not even see how this fact is used in the "real world." You're more interested in how the proof works, because at some point in the future you might want to prove that the estimator you're developing is an MLE. Put differently, at my university, the graduate Applied Regression course uses a fair amount of proofs in class, and you have a hard time passing if you don't know calculus and linear algebra. But the homeworks and exams are mostly about interpreting data. In the PhD-level GLM course, however, they never so much as download a dataset.
Applied statistics vs Mathematical statistics If you're simply taking a book on techniques and learning how to plug things into R/SAS/STATA, you're really not doing applied statistics, imo. The best applied statistics courses/programs involve a h
35,451
Adding a value to each element of a column in R [closed]
Here you have every possibility: x <- matrix(1:9, 3, 3) add 5 to column 1: x[, 1] + 5 add 5 to row 1: x[1, ] + 5 add 1 to the first row, 2 to second, 3 to third: x + 1:3 the same with columns: t(t(x) + 1:3) add 5 to all the cells: x + 5
Adding a value to each element of a column in R [closed]
Here you have every possibility: x <- matrix(1:9, 3, 3) add 5 to column 1: x[, 1] + 5 add 5 to row 1: x[1, ] + 5 add 1 to the first row, 2 to second, 3 to third: x + 1:3 the same with columns: t(
Adding a value to each element of a column in R [closed] Here you have every possibility: x <- matrix(1:9, 3, 3) add 5 to column 1: x[, 1] + 5 add 5 to row 1: x[1, ] + 5 add 1 to the first row, 2 to second, 3 to third: x + 1:3 the same with columns: t(t(x) + 1:3) add 5 to all the cells: x + 5
Adding a value to each element of a column in R [closed] Here you have every possibility: x <- matrix(1:9, 3, 3) add 5 to column 1: x[, 1] + 5 add 5 to row 1: x[1, ] + 5 add 1 to the first row, 2 to second, 3 to third: x + 1:3 the same with columns: t(
35,452
Adding a value to each element of a column in R [closed]
R vectorizes operations (here: addition) automatically. > c(1,2,3,4,5)+5 [1] 6 7 8 9 10 (Such questions are better at StackOverflow in the R tag.)
Adding a value to each element of a column in R [closed]
R vectorizes operations (here: addition) automatically. > c(1,2,3,4,5)+5 [1] 6 7 8 9 10 (Such questions are better at StackOverflow in the R tag.)
Adding a value to each element of a column in R [closed] R vectorizes operations (here: addition) automatically. > c(1,2,3,4,5)+5 [1] 6 7 8 9 10 (Such questions are better at StackOverflow in the R tag.)
Adding a value to each element of a column in R [closed] R vectorizes operations (here: addition) automatically. > c(1,2,3,4,5)+5 [1] 6 7 8 9 10 (Such questions are better at StackOverflow in the R tag.)
35,453
Under which conditions do PCA and FA yield similar results?
This is an excellent question, but unfortunately (or maybe fortunately?) I have only recently written a very long answer in a related thread, addressing your question almost exactly. I would kindly ask you to look there and see if that answers your question. Very briefly, if we just focus on PCA and FA loadings $\mathbf W$, then the difference is that PCA finds $\mathbf W$ to reconstruct the sample covariance (or correlation) matrix $\mathbf C$ as close as possible: $$\mathbf C \approx \mathbf W \mathbf W^\top,$$ whereas FA finds $\mathbf W$ to reconstruct the off-diagonal part of the covariance (or correlation) matrix only: $$\mathrm{offdiag}\{\mathbf C\} \approx \mathbf W \mathbf W^\top.$$ By this I mean that FA does not care what values $\mathbf W \mathbf W^\top$ has on the diagonal, it only cares about the off-diagonal part. With this in mind, the answer to your question becomes easy to see. If the number $n$ of variables (size of $\mathbf C$) is large, then the off-diagonal part of $\mathbf C$ is almost the whole matrix (diagonal has size $n$ and the whole matrix size $n^2$, so the contribution of the diagonal is only $1/n \to 0$), and so we can expect that PCA approximates FA well. If the diagonal values are rather small, then again they don't play much role for PCA, and PCA ends up being close to FA, exactly as @ttnphns said above. If, on the other hand, $\mathbf C$ is either small or strongly dominated by the diagonal (in particular if it has very different values on the diagonal), then PCA will have to bias $\mathbf W$ towards reproducing the diagonal as well, and so will end up being quite different from FA. One example is given in this thread: Why do PCA and Factor Analysis return different results in this example?
Under which conditions do PCA and FA yield similar results?
This is an excellent question, but unfortunately (or maybe fortunately?) I have only recently written a very long answer in a related thread, addressing your question almost exactly. I would kindly as
Under which conditions do PCA and FA yield similar results? This is an excellent question, but unfortunately (or maybe fortunately?) I have only recently written a very long answer in a related thread, addressing your question almost exactly. I would kindly ask you to look there and see if that answers your question. Very briefly, if we just focus on PCA and FA loadings $\mathbf W$, then the difference is that PCA finds $\mathbf W$ to reconstruct the sample covariance (or correlation) matrix $\mathbf C$ as close as possible: $$\mathbf C \approx \mathbf W \mathbf W^\top,$$ whereas FA finds $\mathbf W$ to reconstruct the off-diagonal part of the covariance (or correlation) matrix only: $$\mathrm{offdiag}\{\mathbf C\} \approx \mathbf W \mathbf W^\top.$$ By this I mean that FA does not care what values $\mathbf W \mathbf W^\top$ has on the diagonal, it only cares about the off-diagonal part. With this in mind, the answer to your question becomes easy to see. If the number $n$ of variables (size of $\mathbf C$) is large, then the off-diagonal part of $\mathbf C$ is almost the whole matrix (diagonal has size $n$ and the whole matrix size $n^2$, so the contribution of the diagonal is only $1/n \to 0$), and so we can expect that PCA approximates FA well. If the diagonal values are rather small, then again they don't play much role for PCA, and PCA ends up being close to FA, exactly as @ttnphns said above. If, on the other hand, $\mathbf C$ is either small or strongly dominated by the diagonal (in particular if it has very different values on the diagonal), then PCA will have to bias $\mathbf W$ towards reproducing the diagonal as well, and so will end up being quite different from FA. One example is given in this thread: Why do PCA and Factor Analysis return different results in this example?
Under which conditions do PCA and FA yield similar results? This is an excellent question, but unfortunately (or maybe fortunately?) I have only recently written a very long answer in a related thread, addressing your question almost exactly. I would kindly as
35,454
Testing whether data follows T-Distribution
Here's how to run KS-test on $t$-distribution. Suppose you have a sample which you suspect is from $t$-distribution, and has size = $n$ Estimate the t-distribution parameters from the sample. Generate $M$ samples of size $n$ from the estimated distribution. For each sample obtain KS statistics using the estimated distribution as theoretical Build empirical nonparametric distribution from obtained statistics, e.g. using kernel density estimators Obtain KS statistics for the original sample and the estimated distribution Obtain $p$-value for the KS-stat using the empirical distribution of statistics Make decision based on confidence level In your case d.f. is a given, so you can fit $t$-distribution with a given $N$ instead of estimating it like in my example here in MATLAB ('nu' variable is d.f.). % True T-distribution true_pd = makedist('tlocationscale','mu',0,'sigma',1,'nu',2); % plot true distribution x=0:0.01:1; plot(icdf(true_pd,x),x); hold on; plot(norminv(x),x); legend({'t' 'normal'},'Location','Best') title 'CDF' rng(0) % obtain a sample n=100; sample = random(true_pd,n,1); subplot(2,1,1) histfit(sample,20,'normal'); title 'Sample from t(2,1,0) fit with Nromal' subplot(2,1,2) qqplot(sample); % estimate H_0: T-distribution from this sample disp 'H_0:' null_pd = fitdist(sample,'tlocationscale') [~,~,ksstat] = kstest(sample,'CDF',null_pd); % get KS-test critical values by parametric bootstrapping from estimated m=999; r=random(null_pd,n,m); stats = zeros(m,1); % store test statistics est_pd = makedist('tlocationscale'); opts = statset(statset('tlsfit'),'MaxIter',1000); opts = statset(opts,'MaxFun',2000); for i=1:m bsample = r(:,i); [~,~,stats(i)] = kstest(bsample,'CDF',est_pd.fit(bsample,'options',opts)); end p = (sum(stats>ksstat)+1) / (m+1); mcErr = sqrt(p*(1-p)/m); fprintf('KS stat: %f, p-value: %f, Monte Carlo error: %f\n',ksstat, p , mcErr); % get the empirical distribution of KS test statistics epd = ProbDistUnivKernel(stats); % popular critical values disp 'Crit. values for \alpha= 0.1, 0.05 and 0.01' icdf(epd,[ 0.9 0.95 0.99]) figure plot(icdf(epd,x),x) grid on title 'KS-test statistics simulated distribution' OUTPUT: H_0: null_pd = tLocationScaleDistribution t Location-Scale distribution mu = 0.161093 [-0.117585, 0.439771] sigma = 1.06958 [0.799248, 1.43136] nu = 1.58744 [1.02505, 2.45837] KS stat: 0.041646, p-value: 0.865000, Monte Carlo error: 0.010812 Crit. values for \alpha= 0.1, 0.05 and 0.01 ans = 0.0720 0.0791 0.0931 In this case based on $p$-value we can not reject that the sample comes from the t-distribution. You can compare the critical values with the standard critical values here. You can replace the lines of code where I define and estimate $t$-distribution by the standard normal distribution, and see that the critical values match the table in my link. If you don't like my method, you can follow this paper, which describes bootstrapping in detail: Jogesh Babu, G., and C. R. Rao. "Goodness-of-fit tests when parameters are estimated." Sankhya: The Indian Journal of Statistics 66 (2004): 63-74. If you want to see what @Glen_b is talking about when saying that the distribution must be know and not estimated see item #3 here in the NIST Handbook. It's not a very powerful test if your sample is normal and you have to estimate d.f. It's very difficult to distinguish between normal and $t$-distribution in small sample sizes, because $t$-distribution converges to normal when d.f. N$\to\infty$. In your case N is given, so the test should work fine.
Testing whether data follows T-Distribution
Here's how to run KS-test on $t$-distribution. Suppose you have a sample which you suspect is from $t$-distribution, and has size = $n$ Estimate the t-distribution parameters from the sample. Genera
Testing whether data follows T-Distribution Here's how to run KS-test on $t$-distribution. Suppose you have a sample which you suspect is from $t$-distribution, and has size = $n$ Estimate the t-distribution parameters from the sample. Generate $M$ samples of size $n$ from the estimated distribution. For each sample obtain KS statistics using the estimated distribution as theoretical Build empirical nonparametric distribution from obtained statistics, e.g. using kernel density estimators Obtain KS statistics for the original sample and the estimated distribution Obtain $p$-value for the KS-stat using the empirical distribution of statistics Make decision based on confidence level In your case d.f. is a given, so you can fit $t$-distribution with a given $N$ instead of estimating it like in my example here in MATLAB ('nu' variable is d.f.). % True T-distribution true_pd = makedist('tlocationscale','mu',0,'sigma',1,'nu',2); % plot true distribution x=0:0.01:1; plot(icdf(true_pd,x),x); hold on; plot(norminv(x),x); legend({'t' 'normal'},'Location','Best') title 'CDF' rng(0) % obtain a sample n=100; sample = random(true_pd,n,1); subplot(2,1,1) histfit(sample,20,'normal'); title 'Sample from t(2,1,0) fit with Nromal' subplot(2,1,2) qqplot(sample); % estimate H_0: T-distribution from this sample disp 'H_0:' null_pd = fitdist(sample,'tlocationscale') [~,~,ksstat] = kstest(sample,'CDF',null_pd); % get KS-test critical values by parametric bootstrapping from estimated m=999; r=random(null_pd,n,m); stats = zeros(m,1); % store test statistics est_pd = makedist('tlocationscale'); opts = statset(statset('tlsfit'),'MaxIter',1000); opts = statset(opts,'MaxFun',2000); for i=1:m bsample = r(:,i); [~,~,stats(i)] = kstest(bsample,'CDF',est_pd.fit(bsample,'options',opts)); end p = (sum(stats>ksstat)+1) / (m+1); mcErr = sqrt(p*(1-p)/m); fprintf('KS stat: %f, p-value: %f, Monte Carlo error: %f\n',ksstat, p , mcErr); % get the empirical distribution of KS test statistics epd = ProbDistUnivKernel(stats); % popular critical values disp 'Crit. values for \alpha= 0.1, 0.05 and 0.01' icdf(epd,[ 0.9 0.95 0.99]) figure plot(icdf(epd,x),x) grid on title 'KS-test statistics simulated distribution' OUTPUT: H_0: null_pd = tLocationScaleDistribution t Location-Scale distribution mu = 0.161093 [-0.117585, 0.439771] sigma = 1.06958 [0.799248, 1.43136] nu = 1.58744 [1.02505, 2.45837] KS stat: 0.041646, p-value: 0.865000, Monte Carlo error: 0.010812 Crit. values for \alpha= 0.1, 0.05 and 0.01 ans = 0.0720 0.0791 0.0931 In this case based on $p$-value we can not reject that the sample comes from the t-distribution. You can compare the critical values with the standard critical values here. You can replace the lines of code where I define and estimate $t$-distribution by the standard normal distribution, and see that the critical values match the table in my link. If you don't like my method, you can follow this paper, which describes bootstrapping in detail: Jogesh Babu, G., and C. R. Rao. "Goodness-of-fit tests when parameters are estimated." Sankhya: The Indian Journal of Statistics 66 (2004): 63-74. If you want to see what @Glen_b is talking about when saying that the distribution must be know and not estimated see item #3 here in the NIST Handbook. It's not a very powerful test if your sample is normal and you have to estimate d.f. It's very difficult to distinguish between normal and $t$-distribution in small sample sizes, because $t$-distribution converges to normal when d.f. N$\to\infty$. In your case N is given, so the test should work fine.
Testing whether data follows T-Distribution Here's how to run KS-test on $t$-distribution. Suppose you have a sample which you suspect is from $t$-distribution, and has size = $n$ Estimate the t-distribution parameters from the sample. Genera
35,455
Testing whether data follows T-Distribution
Unless you have prespecified the mean and variance before you see the data, a straight Kolmogorov-Smirnov test is not suitable - indeed once you estimate parameters it's no longer distribution free. Your p-values will be quite wrong - your actual significance level will be much lower than your nominal rate and power will be correspondingly low. If you want to do a Kolmogorov-Smirnov-like test, you need the t-distribution version of a Lilliefors test (essentially, a K-S test with fitted parameters). One might do better with an adapted version of a Shapiro-Francia type test, based off the squared correlation between the observed values and approximate expected order statistics for a $t_N$ distribution. This will correspond directly to the correlation in a suitable Q-Q plot. Distributions under the null can be simulated for either of the above tests. Another alternative if sample sizes are not small is the Anderson-Darling test. It has the same issue as the K-S but the impact seems to drop off relatively rapidly with sample size. See the discussion in D'Agostino and Stephens "Goodness of fit Techniques" [If you have a specific alternative in mind, (one in which the $t_N$ might be a special case, such as testing against a t with a different df) you may be able to make a likelihood ratio statistic.] There are tests for unimodality and symmetry, as well.
Testing whether data follows T-Distribution
Unless you have prespecified the mean and variance before you see the data, a straight Kolmogorov-Smirnov test is not suitable - indeed once you estimate parameters it's no longer distribution free.
Testing whether data follows T-Distribution Unless you have prespecified the mean and variance before you see the data, a straight Kolmogorov-Smirnov test is not suitable - indeed once you estimate parameters it's no longer distribution free. Your p-values will be quite wrong - your actual significance level will be much lower than your nominal rate and power will be correspondingly low. If you want to do a Kolmogorov-Smirnov-like test, you need the t-distribution version of a Lilliefors test (essentially, a K-S test with fitted parameters). One might do better with an adapted version of a Shapiro-Francia type test, based off the squared correlation between the observed values and approximate expected order statistics for a $t_N$ distribution. This will correspond directly to the correlation in a suitable Q-Q plot. Distributions under the null can be simulated for either of the above tests. Another alternative if sample sizes are not small is the Anderson-Darling test. It has the same issue as the K-S but the impact seems to drop off relatively rapidly with sample size. See the discussion in D'Agostino and Stephens "Goodness of fit Techniques" [If you have a specific alternative in mind, (one in which the $t_N$ might be a special case, such as testing against a t with a different df) you may be able to make a likelihood ratio statistic.] There are tests for unimodality and symmetry, as well.
Testing whether data follows T-Distribution Unless you have prespecified the mean and variance before you see the data, a straight Kolmogorov-Smirnov test is not suitable - indeed once you estimate parameters it's no longer distribution free.
35,456
Why does a goodness of fit test use the chi square distribution rather than the hypothesised distribution? [duplicate]
There are two different distributions in play - the distribution of your data (or strictly speaking, the hypothesised distribution of the population they are drawn from), and the distribution of your test statistic under the assumption that the null hypothesis is correct. This is a little subtlety that I find can catch people out when they are new to the concept, but in fact it is usually the case that the null distribution of your test statistic is quite different to the (hypothesised or actual) distribution of your data.* Using a chi squared goodness of fit test means that if your null hypothesis is true, then your test statistic, $\chi^2 = \sum_{i=1}^n {\frac{(O_i - E_i)}{E_i}^2}$, would follow a chi square distribution (at least, approximately - you may hear it called "asymptotic", i.e. for large samples it should be close enough to chi square for practical purposes). This is why you use the chi square distribution tables. Remember that $\chi^2$ is larger if your data is a bad fit to the hypothesised distribution, since in this case the square of the difference between expected and observed frequencies, the $(O_i - E_i)^2$ in the numerators, is large. So if $\chi^2$ is larger than the critical value in the tables, you have significant evidence against the null hypothesis, in the sense that a $\chi^2$ value that large, and hence a fit that poor, would be unlikely if the hypothesised model were true. None of this means that your data is chi squared distributed, or that you expect it to be so. The expected frequencies $E_i$ used in the $\chi^2$ calculation are premised on the population having whatever distribution is specified according to $H_0$. We can look at this in more detail. Supposing that $H_0$ is true so the expected frequencies are "correct" (they may not match the observed frequencies precisely, but if we were to take hundreds of samples and tabulate each one, then in each category the average of our observed frequencies should be very close to the expected one), then the quantity $\frac{O_i - E_i}{\sqrt{E_i}}$ will behave approximately like a z-score for that cell. The sum over all the cells of $\sum_{i=1}^n {\frac{(O_i - E_i)}{E_i}^2}$ is then, roughly, the sum of squared z-scores. Perhaps you already know that the random chi-squared variable with $\nu$ degrees of freedom, $\chi^2_\nu$, is the sum of the squares of $\nu$ independent standard normal variables. You may now be able to see that, so long as your data were drawn from a population whose distribution matched your null model, your test statistic will approximately follow a chi-squared distribution. Things are actually slightly more complicated - since the total of the expected frequencies equals the total of the observed frequencies, the total of $O_i - E_i$ must be zero. Hence the value of $O_i - E_i$ in the last cell is completely determined by what happened in the previous cells, so our "z-scores" weren't quite independent. Fortunately we can compensate for this by subtracting one from the degrees of freedom, which explains why in your case, with 5 cells in your table and hence 5 values of $\frac{(O_i - E_i)^2}{E_i}$ in your sum, you'd compare your test statistic to the critical value listed in the tables for $\chi^2_4$. If your test statistic is above the critical value, this tells you the sum of squared z-scores would be unlikely to be so high. Were your null hypothesis true, then your test statistic should behave like the sum of squared z-scores, so the fact it came out so high constitutes evidence against the null hypothesis - i.e. it suggests your population did not follow the hypothesised distribution. $*$ The very first hypothesis test that many people learn is the Z test for the mean, where the data are sampled from a normal distribution of known variance $\sigma^2$ and the null hypothesis is $H_0: \mu = \mu_0$ . In this case, all three of the population distribution, the sample mean and the z-score (the test statistic for this test) are normally distributed. But this is rarely true for hypothesis tests in general. Moreover, for the Z test, assuming the null hypothesis is true, their distributions are $X \sim \mathcal{N}(\mu_0, \sigma^2)$, $\bar{X} \sim \mathcal{N}(\mu_0, \frac{\sigma^2}{n})$ and $Z \sim \mathcal{N}(0, 1)$. So on closer inspection we see that, even here, the distributions of the data and the test statistic are quite different after all.
Why does a goodness of fit test use the chi square distribution rather than the hypothesised distrib
There are two different distributions in play - the distribution of your data (or strictly speaking, the hypothesised distribution of the population they are drawn from), and the distribution of your
Why does a goodness of fit test use the chi square distribution rather than the hypothesised distribution? [duplicate] There are two different distributions in play - the distribution of your data (or strictly speaking, the hypothesised distribution of the population they are drawn from), and the distribution of your test statistic under the assumption that the null hypothesis is correct. This is a little subtlety that I find can catch people out when they are new to the concept, but in fact it is usually the case that the null distribution of your test statistic is quite different to the (hypothesised or actual) distribution of your data.* Using a chi squared goodness of fit test means that if your null hypothesis is true, then your test statistic, $\chi^2 = \sum_{i=1}^n {\frac{(O_i - E_i)}{E_i}^2}$, would follow a chi square distribution (at least, approximately - you may hear it called "asymptotic", i.e. for large samples it should be close enough to chi square for practical purposes). This is why you use the chi square distribution tables. Remember that $\chi^2$ is larger if your data is a bad fit to the hypothesised distribution, since in this case the square of the difference between expected and observed frequencies, the $(O_i - E_i)^2$ in the numerators, is large. So if $\chi^2$ is larger than the critical value in the tables, you have significant evidence against the null hypothesis, in the sense that a $\chi^2$ value that large, and hence a fit that poor, would be unlikely if the hypothesised model were true. None of this means that your data is chi squared distributed, or that you expect it to be so. The expected frequencies $E_i$ used in the $\chi^2$ calculation are premised on the population having whatever distribution is specified according to $H_0$. We can look at this in more detail. Supposing that $H_0$ is true so the expected frequencies are "correct" (they may not match the observed frequencies precisely, but if we were to take hundreds of samples and tabulate each one, then in each category the average of our observed frequencies should be very close to the expected one), then the quantity $\frac{O_i - E_i}{\sqrt{E_i}}$ will behave approximately like a z-score for that cell. The sum over all the cells of $\sum_{i=1}^n {\frac{(O_i - E_i)}{E_i}^2}$ is then, roughly, the sum of squared z-scores. Perhaps you already know that the random chi-squared variable with $\nu$ degrees of freedom, $\chi^2_\nu$, is the sum of the squares of $\nu$ independent standard normal variables. You may now be able to see that, so long as your data were drawn from a population whose distribution matched your null model, your test statistic will approximately follow a chi-squared distribution. Things are actually slightly more complicated - since the total of the expected frequencies equals the total of the observed frequencies, the total of $O_i - E_i$ must be zero. Hence the value of $O_i - E_i$ in the last cell is completely determined by what happened in the previous cells, so our "z-scores" weren't quite independent. Fortunately we can compensate for this by subtracting one from the degrees of freedom, which explains why in your case, with 5 cells in your table and hence 5 values of $\frac{(O_i - E_i)^2}{E_i}$ in your sum, you'd compare your test statistic to the critical value listed in the tables for $\chi^2_4$. If your test statistic is above the critical value, this tells you the sum of squared z-scores would be unlikely to be so high. Were your null hypothesis true, then your test statistic should behave like the sum of squared z-scores, so the fact it came out so high constitutes evidence against the null hypothesis - i.e. it suggests your population did not follow the hypothesised distribution. $*$ The very first hypothesis test that many people learn is the Z test for the mean, where the data are sampled from a normal distribution of known variance $\sigma^2$ and the null hypothesis is $H_0: \mu = \mu_0$ . In this case, all three of the population distribution, the sample mean and the z-score (the test statistic for this test) are normally distributed. But this is rarely true for hypothesis tests in general. Moreover, for the Z test, assuming the null hypothesis is true, their distributions are $X \sim \mathcal{N}(\mu_0, \sigma^2)$, $\bar{X} \sim \mathcal{N}(\mu_0, \frac{\sigma^2}{n})$ and $Z \sim \mathcal{N}(0, 1)$. So on closer inspection we see that, even here, the distributions of the data and the test statistic are quite different after all.
Why does a goodness of fit test use the chi square distribution rather than the hypothesised distrib There are two different distributions in play - the distribution of your data (or strictly speaking, the hypothesised distribution of the population they are drawn from), and the distribution of your
35,457
Finding peaks in power spectrum of a signal in R
You can think of it as a problem of analytically locating the local maxima that are graphically observed. The code below locates those maxima by means of a one-dimensional optimization algorithm that is applied across overlapping intervals that cover the entire x-axis. At each interval the objective function is defined by spline interpolation of the sample periodrogram. I think there is a more complete implementation of this idea somewhere in a package or post, but I could not find it. As an example, I take the sample periodogram for the logs of the "AirPassengers" data: sp <- spectrum(log(AirPassengers), span = c(3, 5)) Next I define the objective function, the intervals that are checked for the presence of local maxima and some thresholds for the gradient and Hessian that will be used to decide whether or not to accept the solution as a local maximum. # objective function, spline interpolation of the sample spectrum f <- function(x, q, d) spline(q, d, xout = x)$y x <- sp$freq y <- log(sp$spec) nb <- 10 # choose number of intervals iv <- embed(seq(floor(min(x)), ceiling(max(x)), len = nb), 2)[,c(2,1)] # make overlapping intervals to avoid problems if the peak is close to # the ends of the intervals (two modes could be found in each interval) iv[-1,1] <- iv[-nrow(iv),2] - 2 # The function "f" is maximized at each of these intervals iv # [,1] [,2] # [1,] 0.0000000 0.6666667 # [2,] -1.3333333 1.3333333 # [3,] -0.6666667 2.0000000 # [4,] 0.0000000 2.6666667 # [5,] 0.6666667 3.3333333 # [6,] 1.3333333 4.0000000 # [7,] 2.0000000 4.6666667 # [8,] 2.6666667 5.3333333 # [9,] 3.3333333 6.0000000 # choose thresholds for the gradient and Hessian to accept # the solution is a local maximum gr.thr <- 0.001 hes.thr <- 0.03 Now run the optimization algorithm for each interval. The gradient and Hessian are computed numerically by means of the functions grad and hessian from package numDeriv. require("numDeriv") vals <- matrix(nrow = nrow(iv), ncol = 3) grd <- hes <- rep(NA, nrow(vals)) for (j in seq(1, nrow(iv))) { opt <- optimize(f = f, maximum = TRUE, interval = iv[j,], q = x, d = y) vals[j,1] <- opt$max vals[j,3] <- exp(opt$obj) grd[j] <- grad(func = f, x = vals[j,1], q = x, d = y) hes[j] <- hessian(func = f, x = vals[j,1], q = x, d = y) if (abs(grd[j]) < gr.thr && abs(hes[j]) > hes.thr) vals[j,2] <- 1 } # it is convenient to round the located peaks in order to avoid # several local maxima that essentially the same point vals[,1] <- round(vals[,1], 2) if (anyNA(vals[,2])) { peaks <- unique(vals[-which(is.na(vals[,2])),1]) } else peaks <- unique(vals[,1]) The located peaks in this case are the following: peaks # [1] 0.06 1.00 2.01 2.99 4.00 4.98 Graphically we can see that in this example they match well with the peaks observed in the plot of the periodogram: plot(sp$freq, sp$spec, log = "y", type = "l") abline(v = peaks, lty = 2)
Finding peaks in power spectrum of a signal in R
You can think of it as a problem of analytically locating the local maxima that are graphically observed. The code below locates those maxima by means of a one-dimensional optimization algorithm that
Finding peaks in power spectrum of a signal in R You can think of it as a problem of analytically locating the local maxima that are graphically observed. The code below locates those maxima by means of a one-dimensional optimization algorithm that is applied across overlapping intervals that cover the entire x-axis. At each interval the objective function is defined by spline interpolation of the sample periodrogram. I think there is a more complete implementation of this idea somewhere in a package or post, but I could not find it. As an example, I take the sample periodogram for the logs of the "AirPassengers" data: sp <- spectrum(log(AirPassengers), span = c(3, 5)) Next I define the objective function, the intervals that are checked for the presence of local maxima and some thresholds for the gradient and Hessian that will be used to decide whether or not to accept the solution as a local maximum. # objective function, spline interpolation of the sample spectrum f <- function(x, q, d) spline(q, d, xout = x)$y x <- sp$freq y <- log(sp$spec) nb <- 10 # choose number of intervals iv <- embed(seq(floor(min(x)), ceiling(max(x)), len = nb), 2)[,c(2,1)] # make overlapping intervals to avoid problems if the peak is close to # the ends of the intervals (two modes could be found in each interval) iv[-1,1] <- iv[-nrow(iv),2] - 2 # The function "f" is maximized at each of these intervals iv # [,1] [,2] # [1,] 0.0000000 0.6666667 # [2,] -1.3333333 1.3333333 # [3,] -0.6666667 2.0000000 # [4,] 0.0000000 2.6666667 # [5,] 0.6666667 3.3333333 # [6,] 1.3333333 4.0000000 # [7,] 2.0000000 4.6666667 # [8,] 2.6666667 5.3333333 # [9,] 3.3333333 6.0000000 # choose thresholds for the gradient and Hessian to accept # the solution is a local maximum gr.thr <- 0.001 hes.thr <- 0.03 Now run the optimization algorithm for each interval. The gradient and Hessian are computed numerically by means of the functions grad and hessian from package numDeriv. require("numDeriv") vals <- matrix(nrow = nrow(iv), ncol = 3) grd <- hes <- rep(NA, nrow(vals)) for (j in seq(1, nrow(iv))) { opt <- optimize(f = f, maximum = TRUE, interval = iv[j,], q = x, d = y) vals[j,1] <- opt$max vals[j,3] <- exp(opt$obj) grd[j] <- grad(func = f, x = vals[j,1], q = x, d = y) hes[j] <- hessian(func = f, x = vals[j,1], q = x, d = y) if (abs(grd[j]) < gr.thr && abs(hes[j]) > hes.thr) vals[j,2] <- 1 } # it is convenient to round the located peaks in order to avoid # several local maxima that essentially the same point vals[,1] <- round(vals[,1], 2) if (anyNA(vals[,2])) { peaks <- unique(vals[-which(is.na(vals[,2])),1]) } else peaks <- unique(vals[,1]) The located peaks in this case are the following: peaks # [1] 0.06 1.00 2.01 2.99 4.00 4.98 Graphically we can see that in this example they match well with the peaks observed in the plot of the periodogram: plot(sp$freq, sp$spec, log = "y", type = "l") abline(v = peaks, lty = 2)
Finding peaks in power spectrum of a signal in R You can think of it as a problem of analytically locating the local maxima that are graphically observed. The code below locates those maxima by means of a one-dimensional optimization algorithm that
35,458
Confidence Interval on a random quantity?
Geometric view of the problem and distributions of $\vec{b}\cdot \vec{a}$ and $|\vec{b}|^2$ Below is geometrical view of the problem. The direction of $\vec{a}$ doesn't really matter and we can just use the lengths of these vectors $|\vec{a}|$ and $|\vec{b}|$ which give all neccesary information. The distribution of the length of the vector projection of $\vec{b}$ onto $\vec{a}$ will be $\vec{b} \cdot \vec{a}/{\vert \vec{a} \vert} \sim N(\vert \vec{a} \vert,1)$ which is related to the quantity that you are looking for $$\vec{b} \cdot {\vec{a}} \sim N(\vert \vec{a} \vert^2,\vert \vec{a} \vert^2)$$ We can further deduce that the squared lenght of the samples vector $|\vec{b}|^2$ has the distribution a non-central chi-squared distribution, with the degrees of freedom $p$ and the noncentrality parameter $ \sum_{k=1}^p \mu_k^2 = \vert \vec{a} \vert^2$ $$\vert \vec{b} \vert^2 \sim \chi^2_{p,\vert \vec{a} \vert^2}$$ furthermore $$\left(|\vec{b}|^2 - \frac{(\vec{b} \cdot\vec{a})^2}{\vert \vec{a} \vert^2}\right)_{\text{conditional on ${\vec{b} \cdot \vec{a}}$ and $|\vec{a}|^2$}} \sim \chi^2_{p-1}$$ This last expression shows that the interval estimate for $\vec{b}\cdot\vec{a}$ may, from a certain viewpoint, be seen as a confidence interval, because $\vec{b}\cdot\vec{a}$ can be seen as a parameter in the distribution of $|\vec{b}|^2$. But it is complicated because there is a nuisance parameter $|\vec{a}|^2$, and also the parameter $\vec{b}\cdot\vec{a}$ is itselve a random variable, relating to $|\vec{a}|^2$. Plots of distributions and some method to define a $c(\vec{b},p,\alpha)$ In the image above we plotted for a 95% region by using the right $\beta_1$ part of the distribution of $ N(\vert \vec{a} \vert^2,\vert \vec{a} \vert^2)$ and the top $\beta_2$ part of the shifted distribution of $ \chi^2_{p-1}$ such that $\beta_1 \cdot \beta_2 = 0.05$ Now the big trick is to draw some line $c(|\vec{\beta}|^2,p,\alpha)$ which bounds the points such that for any $\vec{a}$ there are a fraction $1-\alpha$ of the points (at least) that are below the line. Below the line is where the region succeeds and and we want to have this happen at least fraction $1-\alpha$ of the time. (see also The basic logic of constructing a confidence interval and Can we reject a null hypothesis with confidence intervals produced via sampling rather than the null hypothesis? for analogous reasoning but in a simpler setting). It might be doubtfull that we can succeed to get the situation: $$\forall \, |\vec{a}| \,: \quad Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)) = \alpha$$ But we should always be able to get some result like $$\forall \, |\vec{a}| \,: \quad Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)) \leq \alpha$$ or more strictly the least upper bound of all the $Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha))$ is equal to $\alpha$ $$\text{sup} \lbrace Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)): |\vec{a}| \geq 0 \rbrace = \alpha$$ For the line in the image with the multiple $|\vec{a}|$ we use the line that touches the peaks of the single regions to define the function $c(|\vec{b}|,p,\alpha)$. By using these peaks we do get that the original regions, which were intended to be like $\alpha = \beta_1 \beta_2$ are not optimally covered. Instead, less points fall below the line (so $\alpha > \beta_1 \beta_2$). For small $|\vec{a}|$ these will be the top part, and for large $|\vec{a}|$ this will be the right part. So you will get: $$\begin{array}{} |\vec{a}| << 1: \quad Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)) \approx \beta_2 \\ |\vec{a}| >> 1 : \quad Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)) \approx \beta_1 \end{array}$$ and $$\text{sup} \lbrace Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)): |\vec{a}| \geq 0 \rbrace \approx \max(\beta_1,\beta_2)$$ So this is still a bit work in progress. One possible ways to solve the situation could be to have some parametric function that you keep improving itteratively by trial and error such that the line is more constant (but it would not be very insightfull). Or possibly one could describe some differential function for the line/function. # find limiting 'a' and a 'b dot a' as function of b² f <- function(b2,p,beta1,beta2) { offset <- qchisq(1-beta2,p-1) qma <- qnorm(1-beta1,0,1) if (b2 <= qma^2+offset) { xma = -10^5 } else { ysup <- b2 - offset - qma^2 alim <- -qma + sqrt(qma^2+ysup) xma <- alim^2+qma*alim } xma } fv <- Vectorize(f) # plot boundary b2 <- seq(0,1500,0.1) lines(fv(b2,p=25,sqrt(0.05),sqrt(0.05)),b2) # check it via simulations dosims <- function(a,testfunc,nrep=10000,beta1=sqrt(0.05),beta2=sqrt(0.05)) { p <- length(a) replicate(nrep,{ bee <- a + rnorm(p) bnd <- testfunc(sum(bee^2),p,beta1,beta2) bta <- sum(bee * a) bta <= bnd }) } mean(dosims(c(1,rep(0,7)),fv)) ### plotting # vectors of |a| to be tried las2 <- 2^seq(-10,10,0.5) # different values of beta1 and beta2 y1 <- sapply(las2,FUN = function(las2) mean(dosims(c(las2,rep(0,24)),fv,nrep=50000,beta1=0.2,beta2=0.2))) y2 <- sapply(las2,FUN = function(las2) mean(dosims(c(las2,rep(0,24)),fv,nrep=50000,beta1=0.4,beta2=0.1))) y3 <- sapply(las2,FUN = function(las2) mean(dosims(c(las2,rep(0,24)),fv,nrep=50000,beta1=0.1,beta2=0.4))) plot(-10,-10, xlim=c(10^-3,10^3),ylim=c(0,0.5),log="x", xlab = expression("|a|"), ylab = expression(paste("effective ", alpha))) points(las2,y1, cex=0.5, col=1,bg=1, pch=21) points(las2,y2, cex=0.5, col=2,bg=2, pch=21) points(las2,y3, cex=0.5, col=3,bg=3, pch=21) text(0.001,0.4,expression(paste(beta[2], " = 0.4 ", beta[1], " = 0.1")),pos=4) text(0.001,0.25,expression(paste(beta[2], " = 0.2 ", beta[1], " = 0.2")),pos=4) text(0.001,0.15,expression(paste(beta[2], " = 0.1 ", beta[1], " = 0.4")),pos=4) title(expression(paste("different effective ", alpha, " for different |a|")))
Confidence Interval on a random quantity?
Geometric view of the problem and distributions of $\vec{b}\cdot \vec{a}$ and $|\vec{b}|^2$ Below is geometrical view of the problem. The direction of $\vec{a}$ doesn't really matter and we can just u
Confidence Interval on a random quantity? Geometric view of the problem and distributions of $\vec{b}\cdot \vec{a}$ and $|\vec{b}|^2$ Below is geometrical view of the problem. The direction of $\vec{a}$ doesn't really matter and we can just use the lengths of these vectors $|\vec{a}|$ and $|\vec{b}|$ which give all neccesary information. The distribution of the length of the vector projection of $\vec{b}$ onto $\vec{a}$ will be $\vec{b} \cdot \vec{a}/{\vert \vec{a} \vert} \sim N(\vert \vec{a} \vert,1)$ which is related to the quantity that you are looking for $$\vec{b} \cdot {\vec{a}} \sim N(\vert \vec{a} \vert^2,\vert \vec{a} \vert^2)$$ We can further deduce that the squared lenght of the samples vector $|\vec{b}|^2$ has the distribution a non-central chi-squared distribution, with the degrees of freedom $p$ and the noncentrality parameter $ \sum_{k=1}^p \mu_k^2 = \vert \vec{a} \vert^2$ $$\vert \vec{b} \vert^2 \sim \chi^2_{p,\vert \vec{a} \vert^2}$$ furthermore $$\left(|\vec{b}|^2 - \frac{(\vec{b} \cdot\vec{a})^2}{\vert \vec{a} \vert^2}\right)_{\text{conditional on ${\vec{b} \cdot \vec{a}}$ and $|\vec{a}|^2$}} \sim \chi^2_{p-1}$$ This last expression shows that the interval estimate for $\vec{b}\cdot\vec{a}$ may, from a certain viewpoint, be seen as a confidence interval, because $\vec{b}\cdot\vec{a}$ can be seen as a parameter in the distribution of $|\vec{b}|^2$. But it is complicated because there is a nuisance parameter $|\vec{a}|^2$, and also the parameter $\vec{b}\cdot\vec{a}$ is itselve a random variable, relating to $|\vec{a}|^2$. Plots of distributions and some method to define a $c(\vec{b},p,\alpha)$ In the image above we plotted for a 95% region by using the right $\beta_1$ part of the distribution of $ N(\vert \vec{a} \vert^2,\vert \vec{a} \vert^2)$ and the top $\beta_2$ part of the shifted distribution of $ \chi^2_{p-1}$ such that $\beta_1 \cdot \beta_2 = 0.05$ Now the big trick is to draw some line $c(|\vec{\beta}|^2,p,\alpha)$ which bounds the points such that for any $\vec{a}$ there are a fraction $1-\alpha$ of the points (at least) that are below the line. Below the line is where the region succeeds and and we want to have this happen at least fraction $1-\alpha$ of the time. (see also The basic logic of constructing a confidence interval and Can we reject a null hypothesis with confidence intervals produced via sampling rather than the null hypothesis? for analogous reasoning but in a simpler setting). It might be doubtfull that we can succeed to get the situation: $$\forall \, |\vec{a}| \,: \quad Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)) = \alpha$$ But we should always be able to get some result like $$\forall \, |\vec{a}| \,: \quad Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)) \leq \alpha$$ or more strictly the least upper bound of all the $Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha))$ is equal to $\alpha$ $$\text{sup} \lbrace Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)): |\vec{a}| \geq 0 \rbrace = \alpha$$ For the line in the image with the multiple $|\vec{a}|$ we use the line that touches the peaks of the single regions to define the function $c(|\vec{b}|,p,\alpha)$. By using these peaks we do get that the original regions, which were intended to be like $\alpha = \beta_1 \beta_2$ are not optimally covered. Instead, less points fall below the line (so $\alpha > \beta_1 \beta_2$). For small $|\vec{a}|$ these will be the top part, and for large $|\vec{a}|$ this will be the right part. So you will get: $$\begin{array}{} |\vec{a}| << 1: \quad Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)) \approx \beta_2 \\ |\vec{a}| >> 1 : \quad Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)) \approx \beta_1 \end{array}$$ and $$\text{sup} \lbrace Pr(\vec{b} \cdot \vec{a} \leq c(\vec{b},p,\alpha)): |\vec{a}| \geq 0 \rbrace \approx \max(\beta_1,\beta_2)$$ So this is still a bit work in progress. One possible ways to solve the situation could be to have some parametric function that you keep improving itteratively by trial and error such that the line is more constant (but it would not be very insightfull). Or possibly one could describe some differential function for the line/function. # find limiting 'a' and a 'b dot a' as function of b² f <- function(b2,p,beta1,beta2) { offset <- qchisq(1-beta2,p-1) qma <- qnorm(1-beta1,0,1) if (b2 <= qma^2+offset) { xma = -10^5 } else { ysup <- b2 - offset - qma^2 alim <- -qma + sqrt(qma^2+ysup) xma <- alim^2+qma*alim } xma } fv <- Vectorize(f) # plot boundary b2 <- seq(0,1500,0.1) lines(fv(b2,p=25,sqrt(0.05),sqrt(0.05)),b2) # check it via simulations dosims <- function(a,testfunc,nrep=10000,beta1=sqrt(0.05),beta2=sqrt(0.05)) { p <- length(a) replicate(nrep,{ bee <- a + rnorm(p) bnd <- testfunc(sum(bee^2),p,beta1,beta2) bta <- sum(bee * a) bta <= bnd }) } mean(dosims(c(1,rep(0,7)),fv)) ### plotting # vectors of |a| to be tried las2 <- 2^seq(-10,10,0.5) # different values of beta1 and beta2 y1 <- sapply(las2,FUN = function(las2) mean(dosims(c(las2,rep(0,24)),fv,nrep=50000,beta1=0.2,beta2=0.2))) y2 <- sapply(las2,FUN = function(las2) mean(dosims(c(las2,rep(0,24)),fv,nrep=50000,beta1=0.4,beta2=0.1))) y3 <- sapply(las2,FUN = function(las2) mean(dosims(c(las2,rep(0,24)),fv,nrep=50000,beta1=0.1,beta2=0.4))) plot(-10,-10, xlim=c(10^-3,10^3),ylim=c(0,0.5),log="x", xlab = expression("|a|"), ylab = expression(paste("effective ", alpha))) points(las2,y1, cex=0.5, col=1,bg=1, pch=21) points(las2,y2, cex=0.5, col=2,bg=2, pch=21) points(las2,y3, cex=0.5, col=3,bg=3, pch=21) text(0.001,0.4,expression(paste(beta[2], " = 0.4 ", beta[1], " = 0.1")),pos=4) text(0.001,0.25,expression(paste(beta[2], " = 0.2 ", beta[1], " = 0.2")),pos=4) text(0.001,0.15,expression(paste(beta[2], " = 0.1 ", beta[1], " = 0.4")),pos=4) title(expression(paste("different effective ", alpha, " for different |a|")))
Confidence Interval on a random quantity? Geometric view of the problem and distributions of $\vec{b}\cdot \vec{a}$ and $|\vec{b}|^2$ Below is geometrical view of the problem. The direction of $\vec{a}$ doesn't really matter and we can just u
35,459
Confidence Interval on a random quantity?
I will switch notation to something more familiar. I hope it is not confusing. I don't see how one could estimate the $c$-function with a completely unbiased estimator. But I will provide an unbiased estimator for "part" of the $c$-function, and provide a formula for the remaining bias, so that it can be assessed by simulation. We assume that we have a jointly normal $p$-dimensional random (column) vector $$\mathbf x \sim N\left (\mathbf μ, \frac 1n \mathbf I_p\right),\;\;\;\mathbf μ = (\mu_1,...,\mu_p)'$$ By the specification of the covariance matrix, the elements of the random vector are independent. We are interested in the univariate random variable $Y = \mathbf x'\mathbf μ$. Due to joint normality, this variable has also a normal distribution $$Y\sim N\left(\mathbf μ'\mathbf μ, \frac 1n \mathbf μ'\mathbf μ\right)$$ Therefore $$P\left(\sqrt n\frac {Y-\mathbf μ'\mathbf μ}{\sqrt {\mathbf μ'\mathbf μ}} \leq \sqrt n\frac {c-\mathbf μ'\mathbf μ}{\sqrt {\mathbf μ'\mathbf μ}}\right)=\Phi\left(\sqrt n\frac {c-\mathbf μ'\mathbf μ}{\sqrt {\mathbf μ'\mathbf μ}}\right)$$ where $\Phi()$ is the standard normal CDF, and $$\Phi\left(\sqrt n\frac {c-\mathbf μ'\mathbf μ}{\sqrt {\mathbf μ'\mathbf μ}}\right) = \alpha \Rightarrow \sqrt n\frac {c-\mathbf μ'\mathbf μ}{\sqrt {\mathbf μ'\mathbf μ}} = \Phi^{-1}(\alpha)=z_{\alpha} $$ $$\Rightarrow c = \frac {\sqrt {\mathbf μ'\mathbf μ}}{\sqrt n} z_a + \mathbf μ'\mathbf μ \tag{1}$$ We need therefore to obtain estimates for $\mathbf μ'\mathbf μ$ and its square root. For each element of the vector $\mathbf x$, say $X_k$ we have $n$ available i.i.d. observations, $\{x_{k1},...,x_{kn}\}$. So for each element of $\mathbf μ'\mathbf μ = (\mu_1^2,...,\mu_p^2)'$ let's try the estimator $$ \text{Est}(\mu_k^2) = \frac 1n\sum_{i=1}^nX^2_{ki}$$ This estimator has expected value $$E\left(\frac 1n\sum_{i=1}^nX^2_{ki}\right) = \frac 1n \sum_{i=1}^nE(X^2_{ki}) =\frac 1n \sum_{i=1}^n\left(\text{Var}(X_{ki})+[E(X_{ki})]^2\right)$$ $$\Rightarrow E\left(\hat {\mu_k^2}\right) = \frac 1n\sum_{i=1}^n\left(\frac 1n+\mu_k^2\right) = \frac 1{n} + \mu_k^2$$ So an unbiased estimator for $\mu_{ki}^2 $ is $$\hat {\mu_k^2} = \frac 1n\sum_{i=1}^nX^2_{ki} -\frac 1{n}$$ implying that $$E\left[\sum_{k=1}^p\left(\frac 1n\sum_{i=1}^nX^2_{ki} -\frac 1{n}\right)\right] =\frac 1n E\left(\sum_{k=1}^p\sum_{i=1}^nX^2_{ki}\right) -\frac p{n} =\mathbf μ'\mathbf μ$$ and so that $$\hat \theta \equiv \frac 1n\sum_{k=1}^p\sum_{i=1}^nX^2_{ki} -\frac p{n} \tag{2}$$ is an unbiased estimator of $\mathbf μ'\mathbf μ$. But an unbiased estimator for $\sqrt {\mathbf μ'\mathbf μ}$ does not seem to exist (one that is solely based on the known quantities, that is). So assume that we go on and estimate $c$ by $$ \hat c = \frac {\sqrt {\hat \theta}}{\sqrt n} z_a + \hat \theta \tag{3}$$ The bias of this estimator is $$B(\hat c) = E(\hat c - c) = \frac {z_{\alpha}}{\sqrt n}\cdot \left[E\left(\sqrt {\hat \theta}\right) - \sqrt {\mathbf μ'\mathbf μ}\right] >0$$ the "positive bias" result due to Jensen's Inequality. In this approach, the size $n$ of the sample is critical, since it reduces bias for any given value of $\mathbf μ$. What are the consequences of this overestimation bias? Assume that we are given $n$,$p$, and we are told to calculate the critical value for $Y$ for probability $\alpha$, $P(Y\leq c) = \alpha$. Given a sequence of samples, we will provide an estimate $\hat c$ for which, "on average" $\hat c > c$. In other words $$P(Y\leq E(\hat c)) = \alpha^* > \alpha = P(Y\leq c)$$ One could assess by simulation the magnitude of the bias for various values of $\mathbf μ$, and how, and how much, it distorts results.
Confidence Interval on a random quantity?
I will switch notation to something more familiar. I hope it is not confusing. I don't see how one could estimate the $c$-function with a completely unbiased estimator. But I will provide an unbiased
Confidence Interval on a random quantity? I will switch notation to something more familiar. I hope it is not confusing. I don't see how one could estimate the $c$-function with a completely unbiased estimator. But I will provide an unbiased estimator for "part" of the $c$-function, and provide a formula for the remaining bias, so that it can be assessed by simulation. We assume that we have a jointly normal $p$-dimensional random (column) vector $$\mathbf x \sim N\left (\mathbf μ, \frac 1n \mathbf I_p\right),\;\;\;\mathbf μ = (\mu_1,...,\mu_p)'$$ By the specification of the covariance matrix, the elements of the random vector are independent. We are interested in the univariate random variable $Y = \mathbf x'\mathbf μ$. Due to joint normality, this variable has also a normal distribution $$Y\sim N\left(\mathbf μ'\mathbf μ, \frac 1n \mathbf μ'\mathbf μ\right)$$ Therefore $$P\left(\sqrt n\frac {Y-\mathbf μ'\mathbf μ}{\sqrt {\mathbf μ'\mathbf μ}} \leq \sqrt n\frac {c-\mathbf μ'\mathbf μ}{\sqrt {\mathbf μ'\mathbf μ}}\right)=\Phi\left(\sqrt n\frac {c-\mathbf μ'\mathbf μ}{\sqrt {\mathbf μ'\mathbf μ}}\right)$$ where $\Phi()$ is the standard normal CDF, and $$\Phi\left(\sqrt n\frac {c-\mathbf μ'\mathbf μ}{\sqrt {\mathbf μ'\mathbf μ}}\right) = \alpha \Rightarrow \sqrt n\frac {c-\mathbf μ'\mathbf μ}{\sqrt {\mathbf μ'\mathbf μ}} = \Phi^{-1}(\alpha)=z_{\alpha} $$ $$\Rightarrow c = \frac {\sqrt {\mathbf μ'\mathbf μ}}{\sqrt n} z_a + \mathbf μ'\mathbf μ \tag{1}$$ We need therefore to obtain estimates for $\mathbf μ'\mathbf μ$ and its square root. For each element of the vector $\mathbf x$, say $X_k$ we have $n$ available i.i.d. observations, $\{x_{k1},...,x_{kn}\}$. So for each element of $\mathbf μ'\mathbf μ = (\mu_1^2,...,\mu_p^2)'$ let's try the estimator $$ \text{Est}(\mu_k^2) = \frac 1n\sum_{i=1}^nX^2_{ki}$$ This estimator has expected value $$E\left(\frac 1n\sum_{i=1}^nX^2_{ki}\right) = \frac 1n \sum_{i=1}^nE(X^2_{ki}) =\frac 1n \sum_{i=1}^n\left(\text{Var}(X_{ki})+[E(X_{ki})]^2\right)$$ $$\Rightarrow E\left(\hat {\mu_k^2}\right) = \frac 1n\sum_{i=1}^n\left(\frac 1n+\mu_k^2\right) = \frac 1{n} + \mu_k^2$$ So an unbiased estimator for $\mu_{ki}^2 $ is $$\hat {\mu_k^2} = \frac 1n\sum_{i=1}^nX^2_{ki} -\frac 1{n}$$ implying that $$E\left[\sum_{k=1}^p\left(\frac 1n\sum_{i=1}^nX^2_{ki} -\frac 1{n}\right)\right] =\frac 1n E\left(\sum_{k=1}^p\sum_{i=1}^nX^2_{ki}\right) -\frac p{n} =\mathbf μ'\mathbf μ$$ and so that $$\hat \theta \equiv \frac 1n\sum_{k=1}^p\sum_{i=1}^nX^2_{ki} -\frac p{n} \tag{2}$$ is an unbiased estimator of $\mathbf μ'\mathbf μ$. But an unbiased estimator for $\sqrt {\mathbf μ'\mathbf μ}$ does not seem to exist (one that is solely based on the known quantities, that is). So assume that we go on and estimate $c$ by $$ \hat c = \frac {\sqrt {\hat \theta}}{\sqrt n} z_a + \hat \theta \tag{3}$$ The bias of this estimator is $$B(\hat c) = E(\hat c - c) = \frac {z_{\alpha}}{\sqrt n}\cdot \left[E\left(\sqrt {\hat \theta}\right) - \sqrt {\mathbf μ'\mathbf μ}\right] >0$$ the "positive bias" result due to Jensen's Inequality. In this approach, the size $n$ of the sample is critical, since it reduces bias for any given value of $\mathbf μ$. What are the consequences of this overestimation bias? Assume that we are given $n$,$p$, and we are told to calculate the critical value for $Y$ for probability $\alpha$, $P(Y\leq c) = \alpha$. Given a sequence of samples, we will provide an estimate $\hat c$ for which, "on average" $\hat c > c$. In other words $$P(Y\leq E(\hat c)) = \alpha^* > \alpha = P(Y\leq c)$$ One could assess by simulation the magnitude of the bias for various values of $\mathbf μ$, and how, and how much, it distorts results.
Confidence Interval on a random quantity? I will switch notation to something more familiar. I hope it is not confusing. I don't see how one could estimate the $c$-function with a completely unbiased estimator. But I will provide an unbiased
35,460
Confidence Interval on a random quantity?
An approach that almost works is as follows: Note that $\left(\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a}\right) / \sqrt{\vec{b}^{\top}\vec{b}}$ 'looks like' $\vec{z}^{\top} \vec{c}$, where $\vec{c}$ is a unit-length vector (it is actually $\vec{b}$ scaled to unit length), and $\vec{z} = \vec{b} - \vec{a} \sim \mathcal{N}\left(0,I\right)$. If it were the case that $\vec{c}$ were independent of $\vec{z}$, then one could claim that $\vec{b}^{\top}\vec{b} + Z_{\alpha} \sqrt{\vec{b}^{\top}\vec{b}}$ was a $\alpha$ confidence bound, where $Z_{\alpha}$ is the $\alpha$ quantile of the normal. However, $\vec{c}$ is not independent of $\vec{z}$. It tends to be 'aligned with' $\vec{z}$. Now, when $\vec{a}^{\top}\vec{a} \gg 1$, $\vec{c}$ is essentially independent, and the confidence bound above gives proper coverage. When $0 < \vec{a}^{\top}\vec{a} \ll 1$, however, $\vec{z}^{\top}\vec{c}$ is more like a shifted, scaled, non-central chi-square random variable. A little R simulation shows the effects of $\vec{a}^{\top}\vec{a}$ on normality of the quantity $\left(\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a}\right) / \sqrt{\vec{b}^{\top}\vec{b}}$: z.sim <- function(p,eff.size,nsim=1e5) { a <- matrix(eff.size * rnorm(p),nrow=p) b <- rep(a,nsim) + matrix(rnorm(p*nsim),nrow=p) atb <- as.matrix(t(a) %*% b) btb <- matrix(colSums(b * b),nrow=1) isZ <- (btb - atb) / sqrt(btb) } set.seed(99) isZ <- z.sim(6,1e3) jpeg("isZ.jpg") qqnorm(isZ) qqline(isZ) dev.off() jpeg("isChi.jpg") isZ <- z.sim(6,1e-3) qqnorm(isZ) qqline(isZ) dev.off()
Confidence Interval on a random quantity?
An approach that almost works is as follows: Note that $\left(\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a}\right) / \sqrt{\vec{b}^{\top}\vec{b}}$ 'looks like' $\vec{z}^{\top} \vec{c}$, where $\vec{c}
Confidence Interval on a random quantity? An approach that almost works is as follows: Note that $\left(\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a}\right) / \sqrt{\vec{b}^{\top}\vec{b}}$ 'looks like' $\vec{z}^{\top} \vec{c}$, where $\vec{c}$ is a unit-length vector (it is actually $\vec{b}$ scaled to unit length), and $\vec{z} = \vec{b} - \vec{a} \sim \mathcal{N}\left(0,I\right)$. If it were the case that $\vec{c}$ were independent of $\vec{z}$, then one could claim that $\vec{b}^{\top}\vec{b} + Z_{\alpha} \sqrt{\vec{b}^{\top}\vec{b}}$ was a $\alpha$ confidence bound, where $Z_{\alpha}$ is the $\alpha$ quantile of the normal. However, $\vec{c}$ is not independent of $\vec{z}$. It tends to be 'aligned with' $\vec{z}$. Now, when $\vec{a}^{\top}\vec{a} \gg 1$, $\vec{c}$ is essentially independent, and the confidence bound above gives proper coverage. When $0 < \vec{a}^{\top}\vec{a} \ll 1$, however, $\vec{z}^{\top}\vec{c}$ is more like a shifted, scaled, non-central chi-square random variable. A little R simulation shows the effects of $\vec{a}^{\top}\vec{a}$ on normality of the quantity $\left(\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a}\right) / \sqrt{\vec{b}^{\top}\vec{b}}$: z.sim <- function(p,eff.size,nsim=1e5) { a <- matrix(eff.size * rnorm(p),nrow=p) b <- rep(a,nsim) + matrix(rnorm(p*nsim),nrow=p) atb <- as.matrix(t(a) %*% b) btb <- matrix(colSums(b * b),nrow=1) isZ <- (btb - atb) / sqrt(btb) } set.seed(99) isZ <- z.sim(6,1e3) jpeg("isZ.jpg") qqnorm(isZ) qqline(isZ) dev.off() jpeg("isChi.jpg") isZ <- z.sim(6,1e-3) qqnorm(isZ) qqline(isZ) dev.off()
Confidence Interval on a random quantity? An approach that almost works is as follows: Note that $\left(\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a}\right) / \sqrt{\vec{b}^{\top}\vec{b}}$ 'looks like' $\vec{z}^{\top} \vec{c}$, where $\vec{c}
35,461
Confidence Interval on a random quantity?
For the case $p=1$, we can find a two sided interval. In this case we can assume that $0 < a$ is the population parameter, and we observe $b=\mathcal{N}\left(a,1\right).$ We wish to bound $ab$ in probability with some function of $|b|$ (We may only use absolute value of $b$ as it is the one dimensional analogue of $\sqrt{\vec{b}^{\top}\vec{b}}$ for the $p>1$ case.) Let $\phi$ be the normal density function, and let $z_{\alpha/2}$ be the $\alpha/2$ quantile of the normal. Then, trivially $$ \int_{-\infty}^{\infty} \phi\left(b-a\right) I\left\{|a-b| \ge -z_{\alpha/2}\right\} \mathrm{d}b = \alpha. $$ Now note that $|a-b|$ is invariant with respect to multiplication of the inside by $\pm 1$, so we can multiply by $\operatorname{sign}\left(b\right)$. That is $|a-b| = \left|a\operatorname{sign}\left(b\right) - |b| \right|.$ Using this, then multiplying the quantities by $|b|$ we have: \begin{align} \alpha &= \mathcal{P}\left( \left|a\operatorname{sign}\left(b\right) - |b| \right| \ge -z_{\alpha/2} \right),\\ &= \mathcal{P}\left( \left|ab - b^2 \right| \ge -z_{\alpha/2} |b| \right),\\ &= \mathcal{P}\left( ab \not\in \left[b^2 + z_{\alpha/2} |b|,b^2 - z_{\alpha/2} |b|\right] \right). \end{align} Thus the symmetric interval $\left[b^2 + z_{\alpha/2} |b|,b^2 - z_{\alpha/2} |b|\right]$ has $1-\alpha$ coverage of $ab$. Let's test with code: test_ci <- function(a,nsim=100000,alpha=0.05) { b <- rnorm(nsim,mean=a,sd=1) b_lo <- b^2 + abs(b) * qnorm(alpha/2) b_hi <- b^2 + abs(b) * qnorm(alpha/2,lower.tail=FALSE) ab <- a*b isout <- ab < b_lo | ab > b_hi mean(isout) } # try twice, with a 'small' and with a 'large' set.seed(1234) test_ci(a=0.01) set.seed(4321) test_ci(a=3.00) I get the nominal 0.05 type I rate: [1] 0.04983 [1] 0.04998 It's not clear how to turn this into a solution for the $p>1$ case, but I assume some trigonometry and use of the $t$ distribution will apply.
Confidence Interval on a random quantity?
For the case $p=1$, we can find a two sided interval. In this case we can assume that $0 < a$ is the population parameter, and we observe $b=\mathcal{N}\left(a,1\right).$ We wish to bound $ab$ in prob
Confidence Interval on a random quantity? For the case $p=1$, we can find a two sided interval. In this case we can assume that $0 < a$ is the population parameter, and we observe $b=\mathcal{N}\left(a,1\right).$ We wish to bound $ab$ in probability with some function of $|b|$ (We may only use absolute value of $b$ as it is the one dimensional analogue of $\sqrt{\vec{b}^{\top}\vec{b}}$ for the $p>1$ case.) Let $\phi$ be the normal density function, and let $z_{\alpha/2}$ be the $\alpha/2$ quantile of the normal. Then, trivially $$ \int_{-\infty}^{\infty} \phi\left(b-a\right) I\left\{|a-b| \ge -z_{\alpha/2}\right\} \mathrm{d}b = \alpha. $$ Now note that $|a-b|$ is invariant with respect to multiplication of the inside by $\pm 1$, so we can multiply by $\operatorname{sign}\left(b\right)$. That is $|a-b| = \left|a\operatorname{sign}\left(b\right) - |b| \right|.$ Using this, then multiplying the quantities by $|b|$ we have: \begin{align} \alpha &= \mathcal{P}\left( \left|a\operatorname{sign}\left(b\right) - |b| \right| \ge -z_{\alpha/2} \right),\\ &= \mathcal{P}\left( \left|ab - b^2 \right| \ge -z_{\alpha/2} |b| \right),\\ &= \mathcal{P}\left( ab \not\in \left[b^2 + z_{\alpha/2} |b|,b^2 - z_{\alpha/2} |b|\right] \right). \end{align} Thus the symmetric interval $\left[b^2 + z_{\alpha/2} |b|,b^2 - z_{\alpha/2} |b|\right]$ has $1-\alpha$ coverage of $ab$. Let's test with code: test_ci <- function(a,nsim=100000,alpha=0.05) { b <- rnorm(nsim,mean=a,sd=1) b_lo <- b^2 + abs(b) * qnorm(alpha/2) b_hi <- b^2 + abs(b) * qnorm(alpha/2,lower.tail=FALSE) ab <- a*b isout <- ab < b_lo | ab > b_hi mean(isout) } # try twice, with a 'small' and with a 'large' set.seed(1234) test_ci(a=0.01) set.seed(4321) test_ci(a=3.00) I get the nominal 0.05 type I rate: [1] 0.04983 [1] 0.04998 It's not clear how to turn this into a solution for the $p>1$ case, but I assume some trigonometry and use of the $t$ distribution will apply.
Confidence Interval on a random quantity? For the case $p=1$, we can find a two sided interval. In this case we can assume that $0 < a$ is the population parameter, and we observe $b=\mathcal{N}\left(a,1\right).$ We wish to bound $ab$ in prob
35,462
Confidence Interval on a random quantity?
Again, the question is to find function $c()$ such that, if you fixed $\vec{a}$, then under $m$ independent draws of $\vec{b_i} = \vec{a} + \vec{z_i}$, the proportion of $i$ such that $\vec{b_i}^{\top}\vec{a} \le c\left(\vec{b_i},p,\alpha\right)$ should go to $\alpha$ as $m \to \infty$. I will give a broken solution to illustrate how this should work in code. First note that $\vec{b}^{\top}\vec{b}$ is a non-central chi-square with non-centrality parameter $\lambda=\vec{a}^{\top}\vec{a}$ and d.f. $p$. So we have $$ E\left[\vec{b}^{\top}\vec{b}\right] = p + \vec{a}^{\top}\vec{a}. $$ Now note that $\vec{b}^{\top}\vec{a} \sim \mathcal{N}\left(\vec{a}^{\top}\vec{a},\vec{a}^{\top}\vec{a}\right)$. So in particular, $$ E\left[\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a} - p\right] = 0. $$ Ignoring the covariance of $\vec{b}^{\top}\vec{a}$ and $\vec{b}^{\top}\vec{b}$ (at my own peril), I can mistakenly claim that the variance of this quantity is $$ \operatorname{Var}\left[\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a} - p\right] = \vec{a}^{\top}\vec{a} + 2\left(p + 2 \vec{a}^{\top}\vec{a}\right) = 2p + 5\vec{a}^{\top}\vec{a}.$$ Putting these together I can make the outlandish and ludicrous claim that the $\alpha$ quantile of $\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a} - p$ is around $$ Z_{\alpha}\sqrt{2p+5\vec{a}^{\top}\vec{a}}. $$ I then might incorrectly conclude that $$ Pr\left(\vec{b}^{\top}\vec{a} \le \vec{b}^{\top}\vec{b} - p + Z_{\alpha}\sqrt{2p+5\vec{a}^{\top}\vec{a}}\right) \approx \alpha. $$ Since I do not know $\vec{a}$, I could then further substitute in the expectation of $\vec{b}^{\top}\vec{b}$ to arrive at $$ c\left(\vec{b},p,\alpha\right) = \vec{b}^{\top}\vec{b} - p + Z_{\alpha}\sqrt{0 \vee \left(5\vec{b}^{\top}\vec{b}-3p\right)}, $$ taking care of course to avoid estimating a negative standard deviation. This is certainly not going to work because we ignored the covariance term. However, the point is to demonstrate some code: # my broken 'c' function cfunc <- function(bee,p=length(bee),alpha=0.05) { lam <- sum(bee^2) sig <- sqrt(max(0,5*lam - 3*p)) lam - p + qnorm(alpha) * sig } # check it via simulations dosims <- function(a,testfunc,nrep=10000,alpha=0.05) { p <- length(a) replicate(nrep,{ bee <- a + rnorm(p) bnd <- testfunc(bee,p,alpha) bta <- sum(bee * a) bta <= bnd }) } options(digits=5) set.seed(1234) mean(dosims(rep(0.01,8),cfunc)) mean(dosims(rep(0.1,8),cfunc)) mean(dosims(rep(1,8),cfunc)) I get nothing like the nominal $0.05$ coverage: [1] 0.0011 [1] 0.0018 [1] 0.001 You should be able to plug in a working confidence bound for the testfunc.
Confidence Interval on a random quantity?
Again, the question is to find function $c()$ such that, if you fixed $\vec{a}$, then under $m$ independent draws of $\vec{b_i} = \vec{a} + \vec{z_i}$, the proportion of $i$ such that $\vec{b_i}^{\top
Confidence Interval on a random quantity? Again, the question is to find function $c()$ such that, if you fixed $\vec{a}$, then under $m$ independent draws of $\vec{b_i} = \vec{a} + \vec{z_i}$, the proportion of $i$ such that $\vec{b_i}^{\top}\vec{a} \le c\left(\vec{b_i},p,\alpha\right)$ should go to $\alpha$ as $m \to \infty$. I will give a broken solution to illustrate how this should work in code. First note that $\vec{b}^{\top}\vec{b}$ is a non-central chi-square with non-centrality parameter $\lambda=\vec{a}^{\top}\vec{a}$ and d.f. $p$. So we have $$ E\left[\vec{b}^{\top}\vec{b}\right] = p + \vec{a}^{\top}\vec{a}. $$ Now note that $\vec{b}^{\top}\vec{a} \sim \mathcal{N}\left(\vec{a}^{\top}\vec{a},\vec{a}^{\top}\vec{a}\right)$. So in particular, $$ E\left[\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a} - p\right] = 0. $$ Ignoring the covariance of $\vec{b}^{\top}\vec{a}$ and $\vec{b}^{\top}\vec{b}$ (at my own peril), I can mistakenly claim that the variance of this quantity is $$ \operatorname{Var}\left[\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a} - p\right] = \vec{a}^{\top}\vec{a} + 2\left(p + 2 \vec{a}^{\top}\vec{a}\right) = 2p + 5\vec{a}^{\top}\vec{a}.$$ Putting these together I can make the outlandish and ludicrous claim that the $\alpha$ quantile of $\vec{b}^{\top}\vec{b} - \vec{b}^{\top}\vec{a} - p$ is around $$ Z_{\alpha}\sqrt{2p+5\vec{a}^{\top}\vec{a}}. $$ I then might incorrectly conclude that $$ Pr\left(\vec{b}^{\top}\vec{a} \le \vec{b}^{\top}\vec{b} - p + Z_{\alpha}\sqrt{2p+5\vec{a}^{\top}\vec{a}}\right) \approx \alpha. $$ Since I do not know $\vec{a}$, I could then further substitute in the expectation of $\vec{b}^{\top}\vec{b}$ to arrive at $$ c\left(\vec{b},p,\alpha\right) = \vec{b}^{\top}\vec{b} - p + Z_{\alpha}\sqrt{0 \vee \left(5\vec{b}^{\top}\vec{b}-3p\right)}, $$ taking care of course to avoid estimating a negative standard deviation. This is certainly not going to work because we ignored the covariance term. However, the point is to demonstrate some code: # my broken 'c' function cfunc <- function(bee,p=length(bee),alpha=0.05) { lam <- sum(bee^2) sig <- sqrt(max(0,5*lam - 3*p)) lam - p + qnorm(alpha) * sig } # check it via simulations dosims <- function(a,testfunc,nrep=10000,alpha=0.05) { p <- length(a) replicate(nrep,{ bee <- a + rnorm(p) bnd <- testfunc(bee,p,alpha) bta <- sum(bee * a) bta <= bnd }) } options(digits=5) set.seed(1234) mean(dosims(rep(0.01,8),cfunc)) mean(dosims(rep(0.1,8),cfunc)) mean(dosims(rep(1,8),cfunc)) I get nothing like the nominal $0.05$ coverage: [1] 0.0011 [1] 0.0018 [1] 0.001 You should be able to plug in a working confidence bound for the testfunc.
Confidence Interval on a random quantity? Again, the question is to find function $c()$ such that, if you fixed $\vec{a}$, then under $m$ independent draws of $\vec{b_i} = \vec{a} + \vec{z_i}$, the proportion of $i$ such that $\vec{b_i}^{\top
35,463
AB testing vs testing the null hypothesis
Is there a difference? Yes. A null hypothesis test produces a test statistic and a p-value, the probability of a test statistic as extreme as the that of the data, under the assumption that the null hypothesis is true. In your example, prop.test tests the assumption that the $p_A$ and $p_B$ are equal. This is distinct from the probability described in your link, $Pr(p_B \gt p_A)$: On your data, prop.test produces a p-value of 0.6291; we interpret this to mean that if $p_A = p_B$, we would expect to see data this extreme in roughly 63% of experiments. But this isn't directly interpretable as the probability that the alternative outperforms the control. Using the linked post's formula, one arrives at $Pr(p_B \gt p_A) \approx 0.726$, which is directly interpretable as such. (Python code after the break.) To gain a little intuition about this, observe the two posterior densities for $p_A, p_B$. The mode of $p_B$ is clearly to the right of the mode of $p_A$. In other words, our point estimate for $p_B$ is higher. Expected, since $\frac{55}{50000} \gt \frac{100}{100000}$. The posterior for $p_B$ is more dispersed. Intuitively satisfying: since we've observed A twice as many times, we're more confident in a narrower posterior. There's still plenty of overlap—it's conceivable that the two treatments just don't meaningfully differ. For one last intuitive aid, we can plot the distribution of the difference of the posteriors, and observe that roughly three-quarters of its area lies to the right of $0$: To reiterate, the p-value only tells us that the data fail to reach the extremity at which we'd be convinced a difference exists. Is one preferable? That question is an instance of the broader Bayesian v. Frequentist choice, and often veers into matters of opinion. In general, I believe the answer depends on many factors, including application, audience, and analyst preference. Here are a few ways to view the difference between the two, which will hopefully help show when one might be preferable. One nice introduction to Bayesian A/B testing puts it like so: Which of these two statements is more appealing: (1) "We rejected the null hypothesis that A=B with a p-value of 0.043." (2) "There is an 85% chance that A has a 5% lift over B." Bayesian modeling can answer questions like (2) directly. For another take, theoretical statistician Larry Wasserman nicely describes the two schools of thought: But first, I should say that Bayesian and Frequentist inference are defined by their goals not their methods. The Goal of Frequentist Inference: Construct procedure with frequency guarantees. (For example, confidence intervals.) The Goal of Bayesian Inference: Quantify and manipulate your degrees of beliefs. In other words, Bayesian inference is the Analysis of Beliefs. >>> from scipy.special import betaln as lbeta def probability_B_beats_A(a_A, b_A, a_B, b_B): ... total = 0.0 ... for i in range(a_B): ... total += exp(lbeta(a_A+i, b_B+b_A) - log(b_B+i) - lbeta(1+i, b_B) - lbeta(a_A, b_A)) ... return total >>> probability_B_beats_A(101, 100001 - 100, 56, 50001 - 55) 0.72594700264280843
AB testing vs testing the null hypothesis
Is there a difference? Yes. A null hypothesis test produces a test statistic and a p-value, the probability of a test statistic as extreme as the that of the data, under the assumption that the null
AB testing vs testing the null hypothesis Is there a difference? Yes. A null hypothesis test produces a test statistic and a p-value, the probability of a test statistic as extreme as the that of the data, under the assumption that the null hypothesis is true. In your example, prop.test tests the assumption that the $p_A$ and $p_B$ are equal. This is distinct from the probability described in your link, $Pr(p_B \gt p_A)$: On your data, prop.test produces a p-value of 0.6291; we interpret this to mean that if $p_A = p_B$, we would expect to see data this extreme in roughly 63% of experiments. But this isn't directly interpretable as the probability that the alternative outperforms the control. Using the linked post's formula, one arrives at $Pr(p_B \gt p_A) \approx 0.726$, which is directly interpretable as such. (Python code after the break.) To gain a little intuition about this, observe the two posterior densities for $p_A, p_B$. The mode of $p_B$ is clearly to the right of the mode of $p_A$. In other words, our point estimate for $p_B$ is higher. Expected, since $\frac{55}{50000} \gt \frac{100}{100000}$. The posterior for $p_B$ is more dispersed. Intuitively satisfying: since we've observed A twice as many times, we're more confident in a narrower posterior. There's still plenty of overlap—it's conceivable that the two treatments just don't meaningfully differ. For one last intuitive aid, we can plot the distribution of the difference of the posteriors, and observe that roughly three-quarters of its area lies to the right of $0$: To reiterate, the p-value only tells us that the data fail to reach the extremity at which we'd be convinced a difference exists. Is one preferable? That question is an instance of the broader Bayesian v. Frequentist choice, and often veers into matters of opinion. In general, I believe the answer depends on many factors, including application, audience, and analyst preference. Here are a few ways to view the difference between the two, which will hopefully help show when one might be preferable. One nice introduction to Bayesian A/B testing puts it like so: Which of these two statements is more appealing: (1) "We rejected the null hypothesis that A=B with a p-value of 0.043." (2) "There is an 85% chance that A has a 5% lift over B." Bayesian modeling can answer questions like (2) directly. For another take, theoretical statistician Larry Wasserman nicely describes the two schools of thought: But first, I should say that Bayesian and Frequentist inference are defined by their goals not their methods. The Goal of Frequentist Inference: Construct procedure with frequency guarantees. (For example, confidence intervals.) The Goal of Bayesian Inference: Quantify and manipulate your degrees of beliefs. In other words, Bayesian inference is the Analysis of Beliefs. >>> from scipy.special import betaln as lbeta def probability_B_beats_A(a_A, b_A, a_B, b_B): ... total = 0.0 ... for i in range(a_B): ... total += exp(lbeta(a_A+i, b_B+b_A) - log(b_B+i) - lbeta(1+i, b_B) - lbeta(a_A, b_A)) ... return total >>> probability_B_beats_A(101, 100001 - 100, 56, 50001 - 55) 0.72594700264280843
AB testing vs testing the null hypothesis Is there a difference? Yes. A null hypothesis test produces a test statistic and a p-value, the probability of a test statistic as extreme as the that of the data, under the assumption that the null
35,464
Hyper-volume of the $\alpha$ contour of a multivariate Gaussian
Ok, this question seems to come up from time to time so I though I'll give a general answer. In [1], the authors show that if $\pmb x_i\sim \mathcal{N}_p(\pmb \mu,\pmb \varSigma),i=1,\ldots,n$ with $\varSigma$ symmetric positive definite, and $S_{\alpha}$ $$S_{\alpha}=\{i: (\pmb x_i-\pmb\mu)'\varSigma^{-1}(\pmb x_i-\pmb\mu)\leqslant q_{\alpha}\}\label{a}\tag{0}$$ for $q_{\alpha}=\chi^2_{p}(\alpha),\;0<\alpha\leqslant 1$ and $$C_{\alpha}=\mbox{cov}_{i\in S_{\alpha}}\pmb x_i\label{b}\tag{1}$$ Then, asymptotically, $C_{\alpha}$ converges to $l_{\alpha}\varSigma$ where $$l_{\alpha}=\frac{ F_{\chi^2_{p+2}(q_{\alpha})} }{\alpha}\label{c}\tag{2}$$ This approximation is really good (here for alpha=60/70): library(MASS) alpha<-60/70 p<-2 n<-1000000 radius<-sqrt(qchisq(alpha,df=p)) x0<-mvrnorm(n,rep(0,p),diag(p),empirical=TRUE) Id<-which(rowSums(x0*x0)<=radius**2) cov(x0[Id,]) qalpa<-qchisq(alpha,p) diag(1/(alpha/(pchisq(qalpa,p+2))),p) So, finally, to answer the question, the $\log$ determinant of the covariance matrix of the $[\alpha n]$ observations with smallest Eucledian norm to the origin (this is the particular case where $\varSigma=\pmb I_p$ and $\pmb \mu=\pmb 0_p$) is given by: $$p\log F_{\chi^2_{p+2}(q_{\alpha})}-p\log\alpha\label{d}\tag{3}$$ Croux C., Haesbroeck G. (1999). Influence function and efficiency of the minimum covariance determinant scatter matrix estimator. Journal of Multivariate Analysis. 71. 161--190.
Hyper-volume of the $\alpha$ contour of a multivariate Gaussian
Ok, this question seems to come up from time to time so I though I'll give a general answer. In [1], the authors show that if $\pmb x_i\sim \mathcal{N}_p(\pmb \mu,\pmb \varSigma),i=1,\ldots,n$ with
Hyper-volume of the $\alpha$ contour of a multivariate Gaussian Ok, this question seems to come up from time to time so I though I'll give a general answer. In [1], the authors show that if $\pmb x_i\sim \mathcal{N}_p(\pmb \mu,\pmb \varSigma),i=1,\ldots,n$ with $\varSigma$ symmetric positive definite, and $S_{\alpha}$ $$S_{\alpha}=\{i: (\pmb x_i-\pmb\mu)'\varSigma^{-1}(\pmb x_i-\pmb\mu)\leqslant q_{\alpha}\}\label{a}\tag{0}$$ for $q_{\alpha}=\chi^2_{p}(\alpha),\;0<\alpha\leqslant 1$ and $$C_{\alpha}=\mbox{cov}_{i\in S_{\alpha}}\pmb x_i\label{b}\tag{1}$$ Then, asymptotically, $C_{\alpha}$ converges to $l_{\alpha}\varSigma$ where $$l_{\alpha}=\frac{ F_{\chi^2_{p+2}(q_{\alpha})} }{\alpha}\label{c}\tag{2}$$ This approximation is really good (here for alpha=60/70): library(MASS) alpha<-60/70 p<-2 n<-1000000 radius<-sqrt(qchisq(alpha,df=p)) x0<-mvrnorm(n,rep(0,p),diag(p),empirical=TRUE) Id<-which(rowSums(x0*x0)<=radius**2) cov(x0[Id,]) qalpa<-qchisq(alpha,p) diag(1/(alpha/(pchisq(qalpa,p+2))),p) So, finally, to answer the question, the $\log$ determinant of the covariance matrix of the $[\alpha n]$ observations with smallest Eucledian norm to the origin (this is the particular case where $\varSigma=\pmb I_p$ and $\pmb \mu=\pmb 0_p$) is given by: $$p\log F_{\chi^2_{p+2}(q_{\alpha})}-p\log\alpha\label{d}\tag{3}$$ Croux C., Haesbroeck G. (1999). Influence function and efficiency of the minimum covariance determinant scatter matrix estimator. Journal of Multivariate Analysis. 71. 161--190.
Hyper-volume of the $\alpha$ contour of a multivariate Gaussian Ok, this question seems to come up from time to time so I though I'll give a general answer. In [1], the authors show that if $\pmb x_i\sim \mathcal{N}_p(\pmb \mu,\pmb \varSigma),i=1,\ldots,n$ with
35,465
Hyper-volume of the $\alpha$ contour of a multivariate Gaussian
Say $X\sim N_n(0,\Sigma)$, where $\Sigma$ is positive definite with $n$ eigenvalues $\lambda_1,\lambda_2,\dots,\lambda_n$. Then the constant-density contours are ellipsoids with $i$th principal axis of $r_i = \sqrt{\chi^2_{\alpha,n}\lambda_i}$, and therefore the volume of the hyper-ellipsoid can be found as $$ \big( \prod_{i=1}^nr_i \big)\pi^{n/2} \Big/ \Gamma\big(1+\dfrac{n}{2}\big). $$
Hyper-volume of the $\alpha$ contour of a multivariate Gaussian
Say $X\sim N_n(0,\Sigma)$, where $\Sigma$ is positive definite with $n$ eigenvalues $\lambda_1,\lambda_2,\dots,\lambda_n$. Then the constant-density contours are ellipsoids with $i$th principal axis o
Hyper-volume of the $\alpha$ contour of a multivariate Gaussian Say $X\sim N_n(0,\Sigma)$, where $\Sigma$ is positive definite with $n$ eigenvalues $\lambda_1,\lambda_2,\dots,\lambda_n$. Then the constant-density contours are ellipsoids with $i$th principal axis of $r_i = \sqrt{\chi^2_{\alpha,n}\lambda_i}$, and therefore the volume of the hyper-ellipsoid can be found as $$ \big( \prod_{i=1}^nr_i \big)\pi^{n/2} \Big/ \Gamma\big(1+\dfrac{n}{2}\big). $$
Hyper-volume of the $\alpha$ contour of a multivariate Gaussian Say $X\sim N_n(0,\Sigma)$, where $\Sigma$ is positive definite with $n$ eigenvalues $\lambda_1,\lambda_2,\dots,\lambda_n$. Then the constant-density contours are ellipsoids with $i$th principal axis o
35,466
Calculating effect sizes and standard errors for the difference between two standardized mean differences
I can certainly give you an answer to the first part of your question. Using your notation, let $d_{var_1}$ and $d_{var_2}$ denote the two d values (computed for the same two groups) based on two different dependent variables and let $v_{var_1}$ and $v_{var_2}$ denote the corresponding sampling variances, which are typically computed/estimated with: $$v_{var_1} = \frac{1}{n_1} + \frac{1}{n_2} + \frac{d_{var_1}^2}{2(n_1 + n_2)}$$ and $$v_{var_2} = \frac{1}{n_1} + \frac{1}{n_2} + \frac{d_{var_2}^2}{2(n_1 + n_2)},$$ where $n_1$ and $n_2$ are the two group sizes. Let $r = cor(var_1, var_2)$ denote the correlation between the two variables. Then the covariance between the two d values can be estimated with: $$cov(d_{var_1}, d_{var_2}) = \left(\frac{1}{n_1} + \frac{1}{n_2}\right)r + \left(\frac{d_{var_1}d_{var_2}}{2(n_1 + n_2)} \right)r^2.$$ See equation (19.27) in the chapter on stochastically dependent effect sizes by Gleser and Olkin (2009) in The handbook of research synthesis and meta-analysis (2nd ed.). Therefore, the sampling variance of $$d_{diff} = d_{var_1} - d_{var_2}$$ can be computed/estimated with: $$v_{d_{diff}} = v_{var_1} + v_{var_2} - 2 cov(d_{var_1}, d_{var_2}).$$ The chapter by Gleser and Olkin also partly addresses your second question. Essentially, you have what the authors call a 'multiple-treatment study' and they provide equations for the covariance in that case as well (see Expectation of correlated variables). However, your case is actually a combination of the 'multiple-treatment' and 'multiple-endpoint' case. Deriving the necessary covariance equations would require some additional work.
Calculating effect sizes and standard errors for the difference between two standardized mean differ
I can certainly give you an answer to the first part of your question. Using your notation, let $d_{var_1}$ and $d_{var_2}$ denote the two d values (computed for the same two groups) based on two diff
Calculating effect sizes and standard errors for the difference between two standardized mean differences I can certainly give you an answer to the first part of your question. Using your notation, let $d_{var_1}$ and $d_{var_2}$ denote the two d values (computed for the same two groups) based on two different dependent variables and let $v_{var_1}$ and $v_{var_2}$ denote the corresponding sampling variances, which are typically computed/estimated with: $$v_{var_1} = \frac{1}{n_1} + \frac{1}{n_2} + \frac{d_{var_1}^2}{2(n_1 + n_2)}$$ and $$v_{var_2} = \frac{1}{n_1} + \frac{1}{n_2} + \frac{d_{var_2}^2}{2(n_1 + n_2)},$$ where $n_1$ and $n_2$ are the two group sizes. Let $r = cor(var_1, var_2)$ denote the correlation between the two variables. Then the covariance between the two d values can be estimated with: $$cov(d_{var_1}, d_{var_2}) = \left(\frac{1}{n_1} + \frac{1}{n_2}\right)r + \left(\frac{d_{var_1}d_{var_2}}{2(n_1 + n_2)} \right)r^2.$$ See equation (19.27) in the chapter on stochastically dependent effect sizes by Gleser and Olkin (2009) in The handbook of research synthesis and meta-analysis (2nd ed.). Therefore, the sampling variance of $$d_{diff} = d_{var_1} - d_{var_2}$$ can be computed/estimated with: $$v_{d_{diff}} = v_{var_1} + v_{var_2} - 2 cov(d_{var_1}, d_{var_2}).$$ The chapter by Gleser and Olkin also partly addresses your second question. Essentially, you have what the authors call a 'multiple-treatment study' and they provide equations for the covariance in that case as well (see Expectation of correlated variables). However, your case is actually a combination of the 'multiple-treatment' and 'multiple-endpoint' case. Deriving the necessary covariance equations would require some additional work.
Calculating effect sizes and standard errors for the difference between two standardized mean differ I can certainly give you an answer to the first part of your question. Using your notation, let $d_{var_1}$ and $d_{var_2}$ denote the two d values (computed for the same two groups) based on two diff
35,467
Calculating effect sizes and standard errors for the difference between two standardized mean differences
This question can be answered by using a structural equation modeling (SEM) approach. It can be used as long as the effect sizes are functions of the parameters, such as means, correlations, and standard deviations. The sampling covariance matrix is numerically derived by the use of Delta method automatically in SEM. Chapter 3 of Cheung (2015) provides an introduction and examples in this approach. One of the examples used in the book is the multiple treatment multiple-endpoint studies. Here are the syntax and output in R. ################################################### ### code chunk number 8: ME_MT ################################################### ## Load the library for SEM library(lavaan) ## Covariance matrix of the control group for variables 1 and 2 lower <- '11 5, 10' ## Convert a lower triangle data into a covariance matrix Cov1 <- getCov(lower, diag=TRUE, names=c("x1", "x2")) ## Covariance matrix of the treatment group 1 for variables 1 and 2 lower <- '12 6, 11' Cov2 <- getCov(lower, diag=TRUE, names=c("x1", "x2")) ## Covariance matrix of the treatment group 2 for variables 1 and 2 lower <- '13 7, 12' Cov3 <- getCov(lower, diag=TRUE, names=c("x1", "x2")) ## Convert covariance matrices into a list Cov <- list(Cov1, Cov2, Cov3) ## Means for the three groups ## 10 and 11 are the means for variables 1 and 2 Mean <- list(c(10,11), c(12,13), c(13,14)) ## Sample sizes for the groups N <- c(50, 50, 50) ## Assuming homogeneity of covariance matrices ## You can free this constraint by using different labels model5 <- 'eta1 =~ c("sd1", "sd1", "sd1")*x1 eta2 =~ c("sd2", "sd2", "sd2")*x2 eta1 ~~ c("r", "r", "r")*eta2 ## The subscripts 0, 1 and 2 represent the means ## of the control and two treatment groups x1 ~ c("m1_0", "m1_1", "m1_2")*1 x2 ~ c("m2_0", "m2_1", "m2_2")*1 ## The measurement errors are fixed at 0 x1 ~~ 0*x1 x2 ~~ 0*x2 ## Multiple endpoint effect size 1 for treatment group 1 ES1_1 := (m1_1 - m1_0)/sd1 ## Multiple endpoint effect size 2 for treatment group 1 ES2_1 := (m2_1 - m2_0)/sd2 ## Multiple endpoint effect size 1 for treatment group 2 ES1_2 := (m1_2 - m1_0)/sd1 ## Multiple endpoint effect size 2 for treatment group 2 ES2_2 := (m2_2 - m2_0)/sd2' fit5 <- sem(model5, sample.cov=Cov, sample.mean=Mean, sample.nobs=N, std.lv=TRUE, sample.cov.rescale=FALSE) ## Obtain the free parameters in the model ( x <- fit5@Fit@x ) ## [1] 3.464102 3.316625 0.522233 10.000000 11.000000 12.000000 13.000000 ## [8] 13.000000 14.000000 ## Obtain the sampling covariance matrix of the parameter estimates VCOV <- vcov(fit5) ## Compute the multivariate effect sizes ( ES <- fit5@Model@def.function(x=x) ) ## ES1_1 ES2_1 ES1_2 ES2_2 ## 0.5773503 0.6030227 0.8660254 0.9045340 ## Compute the jacobian for 'defined parameters' JAC <- lavaan:::lavJacobianD(func=fit5@Model@def.function, x=x) ## Compute the sampling covariance matrix using delta method ES.VCOV <- JAC %*% VCOV %*% t(JAC) ## Add the variable names for ease of reference dimnames(ES.VCOV) <- list(names(ES), names(ES)) ES.VCOV ## ES1_1 ES2_1 ES1_2 ES2_2 ## ES1_1 0.04111111 0.02120582 0.02166667 0.01091942 ## ES2_1 0.02120582 0.04121212 0.01091942 0.02181818 ## ES1_2 0.02166667 0.01091942 0.04250000 0.02160145 ## ES2_2 0.01091942 0.02181818 0.02160145 0.04272727 In this example, the estimated vector of effect sizes are their sampling covariance matrix are ES and ES.VCOV, respectively. ES1_1 and ES2_1 are the effect sizes for group 1 comparing against the control group, while ES1_2 and ES2_2 are the effect sizes group 2 comparing against the control group. Reference Cheung, M. W.-L. (2015). Meta-analysis: A structural equation modeling approach. Chichester, West Sussex: John Wiley & Sons, Inc..
Calculating effect sizes and standard errors for the difference between two standardized mean differ
This question can be answered by using a structural equation modeling (SEM) approach. It can be used as long as the effect sizes are functions of the parameters, such as means, correlations, and stand
Calculating effect sizes and standard errors for the difference between two standardized mean differences This question can be answered by using a structural equation modeling (SEM) approach. It can be used as long as the effect sizes are functions of the parameters, such as means, correlations, and standard deviations. The sampling covariance matrix is numerically derived by the use of Delta method automatically in SEM. Chapter 3 of Cheung (2015) provides an introduction and examples in this approach. One of the examples used in the book is the multiple treatment multiple-endpoint studies. Here are the syntax and output in R. ################################################### ### code chunk number 8: ME_MT ################################################### ## Load the library for SEM library(lavaan) ## Covariance matrix of the control group for variables 1 and 2 lower <- '11 5, 10' ## Convert a lower triangle data into a covariance matrix Cov1 <- getCov(lower, diag=TRUE, names=c("x1", "x2")) ## Covariance matrix of the treatment group 1 for variables 1 and 2 lower <- '12 6, 11' Cov2 <- getCov(lower, diag=TRUE, names=c("x1", "x2")) ## Covariance matrix of the treatment group 2 for variables 1 and 2 lower <- '13 7, 12' Cov3 <- getCov(lower, diag=TRUE, names=c("x1", "x2")) ## Convert covariance matrices into a list Cov <- list(Cov1, Cov2, Cov3) ## Means for the three groups ## 10 and 11 are the means for variables 1 and 2 Mean <- list(c(10,11), c(12,13), c(13,14)) ## Sample sizes for the groups N <- c(50, 50, 50) ## Assuming homogeneity of covariance matrices ## You can free this constraint by using different labels model5 <- 'eta1 =~ c("sd1", "sd1", "sd1")*x1 eta2 =~ c("sd2", "sd2", "sd2")*x2 eta1 ~~ c("r", "r", "r")*eta2 ## The subscripts 0, 1 and 2 represent the means ## of the control and two treatment groups x1 ~ c("m1_0", "m1_1", "m1_2")*1 x2 ~ c("m2_0", "m2_1", "m2_2")*1 ## The measurement errors are fixed at 0 x1 ~~ 0*x1 x2 ~~ 0*x2 ## Multiple endpoint effect size 1 for treatment group 1 ES1_1 := (m1_1 - m1_0)/sd1 ## Multiple endpoint effect size 2 for treatment group 1 ES2_1 := (m2_1 - m2_0)/sd2 ## Multiple endpoint effect size 1 for treatment group 2 ES1_2 := (m1_2 - m1_0)/sd1 ## Multiple endpoint effect size 2 for treatment group 2 ES2_2 := (m2_2 - m2_0)/sd2' fit5 <- sem(model5, sample.cov=Cov, sample.mean=Mean, sample.nobs=N, std.lv=TRUE, sample.cov.rescale=FALSE) ## Obtain the free parameters in the model ( x <- fit5@Fit@x ) ## [1] 3.464102 3.316625 0.522233 10.000000 11.000000 12.000000 13.000000 ## [8] 13.000000 14.000000 ## Obtain the sampling covariance matrix of the parameter estimates VCOV <- vcov(fit5) ## Compute the multivariate effect sizes ( ES <- fit5@Model@def.function(x=x) ) ## ES1_1 ES2_1 ES1_2 ES2_2 ## 0.5773503 0.6030227 0.8660254 0.9045340 ## Compute the jacobian for 'defined parameters' JAC <- lavaan:::lavJacobianD(func=fit5@Model@def.function, x=x) ## Compute the sampling covariance matrix using delta method ES.VCOV <- JAC %*% VCOV %*% t(JAC) ## Add the variable names for ease of reference dimnames(ES.VCOV) <- list(names(ES), names(ES)) ES.VCOV ## ES1_1 ES2_1 ES1_2 ES2_2 ## ES1_1 0.04111111 0.02120582 0.02166667 0.01091942 ## ES2_1 0.02120582 0.04121212 0.01091942 0.02181818 ## ES1_2 0.02166667 0.01091942 0.04250000 0.02160145 ## ES2_2 0.01091942 0.02181818 0.02160145 0.04272727 In this example, the estimated vector of effect sizes are their sampling covariance matrix are ES and ES.VCOV, respectively. ES1_1 and ES2_1 are the effect sizes for group 1 comparing against the control group, while ES1_2 and ES2_2 are the effect sizes group 2 comparing against the control group. Reference Cheung, M. W.-L. (2015). Meta-analysis: A structural equation modeling approach. Chichester, West Sussex: John Wiley & Sons, Inc..
Calculating effect sizes and standard errors for the difference between two standardized mean differ This question can be answered by using a structural equation modeling (SEM) approach. It can be used as long as the effect sizes are functions of the parameters, such as means, correlations, and stand
35,468
Calculating effect sizes and standard errors for the difference between two standardized mean differences
I am not completely certain how this solution was derived, but I thought I would post it anyway so that other people could evaluate it. I also thought that this information was worth posting as a full answer rather than leaving it buried in the comments of the answer provided by @Wolfgang. According to a response that Ian White supplied in correspondence with me, given groups $g_1$, $g_2$, and $g_3$, and assuming that the standard deviation used to calculate one's effect sizes was pooled across $g_1$, $g_2$, and $g_3$, $$cov(d_{diff_{g_1 - g_2}}, d_{diff_{g_1 - g_3}}) = \frac{r}{n_1} + \frac{d_{diff_{g_1 - g_2}} * d_{diff_{g_1 - g_3}} * r^2}{(2 * (n_1 + n_2 + n_3))}$$ Again, I'm not entirely certain how this solution was derived, and I would be grateful for any insight that others could provide.
Calculating effect sizes and standard errors for the difference between two standardized mean differ
I am not completely certain how this solution was derived, but I thought I would post it anyway so that other people could evaluate it. I also thought that this information was worth posting as a ful
Calculating effect sizes and standard errors for the difference between two standardized mean differences I am not completely certain how this solution was derived, but I thought I would post it anyway so that other people could evaluate it. I also thought that this information was worth posting as a full answer rather than leaving it buried in the comments of the answer provided by @Wolfgang. According to a response that Ian White supplied in correspondence with me, given groups $g_1$, $g_2$, and $g_3$, and assuming that the standard deviation used to calculate one's effect sizes was pooled across $g_1$, $g_2$, and $g_3$, $$cov(d_{diff_{g_1 - g_2}}, d_{diff_{g_1 - g_3}}) = \frac{r}{n_1} + \frac{d_{diff_{g_1 - g_2}} * d_{diff_{g_1 - g_3}} * r^2}{(2 * (n_1 + n_2 + n_3))}$$ Again, I'm not entirely certain how this solution was derived, and I would be grateful for any insight that others could provide.
Calculating effect sizes and standard errors for the difference between two standardized mean differ I am not completely certain how this solution was derived, but I thought I would post it anyway so that other people could evaluate it. I also thought that this information was worth posting as a ful
35,469
Iterative process for removing extreme samples
The problem with your approach is that you start assuming that your data is normally distributed, when you already know it is not. Some outlier detection techniques are similar (it is sound) but make the same assumption. Rather than using the mean and the standard deviation, you may prefer the MAD (median absolute deviation) estimate, because is a more robust estimate of the deviation to use for thresholding your data. Another possibility is Tukey's outlier detection algorithm. Still, most importantly, you point out that your data may be bimodal (users and bots). I am mostly familiar with the standard unimodal approach. For such case, you may need some technique like GMM or kernel density estimation. I googled a bit, and came across this paper which seems really interesting and fit your problem quite well. Finally there are techniques for outlier detection, like SVMs which are distribution agnostic, and may work "out of the box", provided enough data.
Iterative process for removing extreme samples
The problem with your approach is that you start assuming that your data is normally distributed, when you already know it is not. Some outlier detection techniques are similar (it is sound) but make
Iterative process for removing extreme samples The problem with your approach is that you start assuming that your data is normally distributed, when you already know it is not. Some outlier detection techniques are similar (it is sound) but make the same assumption. Rather than using the mean and the standard deviation, you may prefer the MAD (median absolute deviation) estimate, because is a more robust estimate of the deviation to use for thresholding your data. Another possibility is Tukey's outlier detection algorithm. Still, most importantly, you point out that your data may be bimodal (users and bots). I am mostly familiar with the standard unimodal approach. For such case, you may need some technique like GMM or kernel density estimation. I googled a bit, and came across this paper which seems really interesting and fit your problem quite well. Finally there are techniques for outlier detection, like SVMs which are distribution agnostic, and may work "out of the box", provided enough data.
Iterative process for removing extreme samples The problem with your approach is that you start assuming that your data is normally distributed, when you already know it is not. Some outlier detection techniques are similar (it is sound) but make
35,470
Iterative process for removing extreme samples
Just a heed of warning! be very careful of the way you implement the algorithm you have mentioned. Personally, I am a little skeptical of it. The reason is the curse of dimensionality. In a high dimensional problem, since all points lie on the boundary, they all look like outliers. As a simple counterexample to your algorithm, say you throw away 10 points in the first run (with the metric being 4 standard deviations (s.d.)). On the second run, your standard deviation will shrink because you have tossed out the extreme points. Now the 4.s.d. value for the second iteration will be smaller and hence you end up tossing more points. If the distribution looks something like a sinusoid decaying away from the origin, you might end up throwing away most of the points under the pretext of extremeness. If you think my analysis is wrong (which it very well might be) I would appreciate your take on why I am thinking of this incorrectly
Iterative process for removing extreme samples
Just a heed of warning! be very careful of the way you implement the algorithm you have mentioned. Personally, I am a little skeptical of it. The reason is the curse of dimensionality. In a high dim
Iterative process for removing extreme samples Just a heed of warning! be very careful of the way you implement the algorithm you have mentioned. Personally, I am a little skeptical of it. The reason is the curse of dimensionality. In a high dimensional problem, since all points lie on the boundary, they all look like outliers. As a simple counterexample to your algorithm, say you throw away 10 points in the first run (with the metric being 4 standard deviations (s.d.)). On the second run, your standard deviation will shrink because you have tossed out the extreme points. Now the 4.s.d. value for the second iteration will be smaller and hence you end up tossing more points. If the distribution looks something like a sinusoid decaying away from the origin, you might end up throwing away most of the points under the pretext of extremeness. If you think my analysis is wrong (which it very well might be) I would appreciate your take on why I am thinking of this incorrectly
Iterative process for removing extreme samples Just a heed of warning! be very careful of the way you implement the algorithm you have mentioned. Personally, I am a little skeptical of it. The reason is the curse of dimensionality. In a high dim
35,471
Computing inverse probability weights -- conditional (multivariate) density estimation?
The basic idea As per Chen, Linton, and Robinson (2001), the "default" technique for conditional univariate kernel density estimation is to find, for bandwidths $a,b,c$, $$\frac{\hat{f}_{ab}(y,z)}{\hat{f}_c(z)}=\hat{f}_{abc}(y|z)$$ Then, with numerator bandwidth $(a,b)$ and denominator bandwidth $c$ and $a=b=c$, the following central limit result holds under certain independence and consistency assumptions (which are only really restrictive when $y=x_t,z=x_{t-1}$): $$ \sqrt{na^2}\left(\hat{f}_{abc=aaa}(y|z)-f(y|z)\right)\xrightarrow{d}N(0,V) $$ where $$\begin{align} \hat{V}&=\left(\int K(u)^2du\right)^2\cdot\frac{\hat{f}_{aaa}(y|z)}{\hat{f}_a(z)}\\&=\left(\int K(u)^2du\right)^2\cdot\hat{f}_{aa }(y,z) \end{align}$$ Although I've never see a frequentist weighted model (even intro-stats WLS) make an attempt to account for the variance of the estimated weights. For now I'm going to follow that convention but if I get results here I'll see if I can work it into a fully Bayesian model that will propagate uncertainty more honestly. So yes, estimating the conditional density by estimating the joint and marginal densities is standard procedure. Applicability to my case It's not explicitly clear from that paper is how this generalizes to the case when when $y=x_t$ and $z=\left(x_s\right)_{s=1}^{t-1}$, and $x_s=\left(\begin{smallmatrix} x_{s,1}\\ \ddots \\x_{s,D} \end{smallmatrix}\right)$. But I guess this is really just the same thing as one big long sequence $x=\left(\left(x_{s,d}\right)_{d=1}^{D}\right)_{s=1}^{t-1}$ which seems perfectly manageable according to Robinson (1983) (cited in Chen, et al). Again, using Bayes' rule to estimate the conditional density seems perfectly acceptable. Bandwidth The final issue is bandwidth selection. Bandwidth is now a block matrix of the form $$ B=\left(\begin{matrix} B^{numerator}&0\\0&B^{denominator} \end{matrix}\right)=\left(\begin{matrix} \left(\begin{matrix}a_{1,1}&&B^{num}_1\\&\ddots&\\B^{num}_2&&a_{t,D}\end{matrix}\right)&0\\0&\left(\begin{matrix}c_{1,1}&&B^{denom}_1\\&\ddots&\\B^{denom}_2&&c_{t-1,D}\end{matrix}\right) \end{matrix}\right) $$ which is a mess. When bandwidth $H=hH_0$ such that $|H_0|=1$, then $b^*\sim\sqrt[4+D]{N}$, but this result would apply separately to $B^{num}$ and $B^{denom}$ rather than to $B$ as a whole (source, someone's lecture notes). Chen et al find an optimal bandwidth $a=b=c$ (in their 2-d case) for a given level of $z$ that looks like it generalizes to the case when $y$ and $z$ are multivariate. They suggest setting $z=\mu$ where $\mu$ is the theoretical mean that would be induced under joint normality, and they derive $\hat{a}(\mu)$. A more general version of the same result is in another section of those lecture notes, called "rule-of-thumb" bandwidth. They also derive optimal bandwidth as a function of a general cross-validation procedure. Computation I have a 7-dimensional treatment over 3 time periods, so I have up to a 21-dimensional density to estimate. And I forgot about baseline covariates. I have something like 30 baseline covariates, so I would end up trying to estimate a 51-dimensional distribution, a 44-dimensional distribution, and a 37-dimensional distribution. And that's not to mention that the extreme dimensionality will require an impossibly large sample. Scott & Wand (1991) report that a sample size of 50 in one dimension is equivalent to well over 1 million in 8 dimensions... no mention of 30. No amount of these can express how I feel right now. Conclusion So I just wasted a week of my life on this. Oh well. Instead, I'm going to use MCMC to fit parametric treatment and outcome models simultaneously, so that the IPT weights end up being a function of the posterior predictive densities from the treatment model. Then I'll step through linear, quadratic, and cubic forms for the treatment model and see which one fits the best.
Computing inverse probability weights -- conditional (multivariate) density estimation?
The basic idea As per Chen, Linton, and Robinson (2001), the "default" technique for conditional univariate kernel density estimation is to find, for bandwidths $a,b,c$, $$\frac{\hat{f}_{ab}(y,z)}{\ha
Computing inverse probability weights -- conditional (multivariate) density estimation? The basic idea As per Chen, Linton, and Robinson (2001), the "default" technique for conditional univariate kernel density estimation is to find, for bandwidths $a,b,c$, $$\frac{\hat{f}_{ab}(y,z)}{\hat{f}_c(z)}=\hat{f}_{abc}(y|z)$$ Then, with numerator bandwidth $(a,b)$ and denominator bandwidth $c$ and $a=b=c$, the following central limit result holds under certain independence and consistency assumptions (which are only really restrictive when $y=x_t,z=x_{t-1}$): $$ \sqrt{na^2}\left(\hat{f}_{abc=aaa}(y|z)-f(y|z)\right)\xrightarrow{d}N(0,V) $$ where $$\begin{align} \hat{V}&=\left(\int K(u)^2du\right)^2\cdot\frac{\hat{f}_{aaa}(y|z)}{\hat{f}_a(z)}\\&=\left(\int K(u)^2du\right)^2\cdot\hat{f}_{aa }(y,z) \end{align}$$ Although I've never see a frequentist weighted model (even intro-stats WLS) make an attempt to account for the variance of the estimated weights. For now I'm going to follow that convention but if I get results here I'll see if I can work it into a fully Bayesian model that will propagate uncertainty more honestly. So yes, estimating the conditional density by estimating the joint and marginal densities is standard procedure. Applicability to my case It's not explicitly clear from that paper is how this generalizes to the case when when $y=x_t$ and $z=\left(x_s\right)_{s=1}^{t-1}$, and $x_s=\left(\begin{smallmatrix} x_{s,1}\\ \ddots \\x_{s,D} \end{smallmatrix}\right)$. But I guess this is really just the same thing as one big long sequence $x=\left(\left(x_{s,d}\right)_{d=1}^{D}\right)_{s=1}^{t-1}$ which seems perfectly manageable according to Robinson (1983) (cited in Chen, et al). Again, using Bayes' rule to estimate the conditional density seems perfectly acceptable. Bandwidth The final issue is bandwidth selection. Bandwidth is now a block matrix of the form $$ B=\left(\begin{matrix} B^{numerator}&0\\0&B^{denominator} \end{matrix}\right)=\left(\begin{matrix} \left(\begin{matrix}a_{1,1}&&B^{num}_1\\&\ddots&\\B^{num}_2&&a_{t,D}\end{matrix}\right)&0\\0&\left(\begin{matrix}c_{1,1}&&B^{denom}_1\\&\ddots&\\B^{denom}_2&&c_{t-1,D}\end{matrix}\right) \end{matrix}\right) $$ which is a mess. When bandwidth $H=hH_0$ such that $|H_0|=1$, then $b^*\sim\sqrt[4+D]{N}$, but this result would apply separately to $B^{num}$ and $B^{denom}$ rather than to $B$ as a whole (source, someone's lecture notes). Chen et al find an optimal bandwidth $a=b=c$ (in their 2-d case) for a given level of $z$ that looks like it generalizes to the case when $y$ and $z$ are multivariate. They suggest setting $z=\mu$ where $\mu$ is the theoretical mean that would be induced under joint normality, and they derive $\hat{a}(\mu)$. A more general version of the same result is in another section of those lecture notes, called "rule-of-thumb" bandwidth. They also derive optimal bandwidth as a function of a general cross-validation procedure. Computation I have a 7-dimensional treatment over 3 time periods, so I have up to a 21-dimensional density to estimate. And I forgot about baseline covariates. I have something like 30 baseline covariates, so I would end up trying to estimate a 51-dimensional distribution, a 44-dimensional distribution, and a 37-dimensional distribution. And that's not to mention that the extreme dimensionality will require an impossibly large sample. Scott & Wand (1991) report that a sample size of 50 in one dimension is equivalent to well over 1 million in 8 dimensions... no mention of 30. No amount of these can express how I feel right now. Conclusion So I just wasted a week of my life on this. Oh well. Instead, I'm going to use MCMC to fit parametric treatment and outcome models simultaneously, so that the IPT weights end up being a function of the posterior predictive densities from the treatment model. Then I'll step through linear, quadratic, and cubic forms for the treatment model and see which one fits the best.
Computing inverse probability weights -- conditional (multivariate) density estimation? The basic idea As per Chen, Linton, and Robinson (2001), the "default" technique for conditional univariate kernel density estimation is to find, for bandwidths $a,b,c$, $$\frac{\hat{f}_{ab}(y,z)}{\ha
35,472
Clustering algorithms for extremely sparse data
For text vectors, there are good known similarities - cosine, and the variations used e.g. in Lucene for text retrieval. k-means, however, may be a bad fit. Because the means computed will not have a realistic sparsity, but will be much more dense. Anyway, there exist some k-means variations for text, such as spherical k-means. You may want to try CLUTO, which seems to be a more popular tool for clustering text. Hierarchical clustering is probably a good candidate, too. But it does not scale to large data sets, as the usual implementations are $O(n^3)$. For 80000 documents, this will take quite some time.
Clustering algorithms for extremely sparse data
For text vectors, there are good known similarities - cosine, and the variations used e.g. in Lucene for text retrieval. k-means, however, may be a bad fit. Because the means computed will not have a
Clustering algorithms for extremely sparse data For text vectors, there are good known similarities - cosine, and the variations used e.g. in Lucene for text retrieval. k-means, however, may be a bad fit. Because the means computed will not have a realistic sparsity, but will be much more dense. Anyway, there exist some k-means variations for text, such as spherical k-means. You may want to try CLUTO, which seems to be a more popular tool for clustering text. Hierarchical clustering is probably a good candidate, too. But it does not scale to large data sets, as the usual implementations are $O(n^3)$. For 80000 documents, this will take quite some time.
Clustering algorithms for extremely sparse data For text vectors, there are good known similarities - cosine, and the variations used e.g. in Lucene for text retrieval. k-means, however, may be a bad fit. Because the means computed will not have a
35,473
Fast missing data imputation in R for big data that is more sophisticated than simply imputing the means?
I used mice (multiple imputation by chained equation). It's fairly fast, and quite simple. I used it on 3000 obs. for c.a. 10 variables. Done in 10min on an old computer. Further, I believe it is one of the best multiple-imputation packages out there. It can use regression to impute, among other methods. You need to create a dataframe with the variable you want to impute, and include every variable that might predict values of that variable (so every var. in your model + possibly other var. as well). The mice package will impute every missing value in that dataframe. Simplest way of imputing. Gives you a dataframe Datimp that has five imputed data + the original data. library(mice) #m=5 number of multiple imputations #maxit=10 number of iterations. 10-20 is sufficient. imp <- mice(Dat1, m=5, maxit=10, printFlag=TRUE) Datimp <- complete(imp, "long", include=TRUE) write.table(Datimp, "C:/.../impute1.txt", sep="\t", dec=",", row.names=FALSE) A better way to do this is: library(mice) Dat1 <- subset(Dat, select=c(id, faculty, gender, age, job, salary)) #create subset #of variables you would like to either impute or use as predictors for imputation. ini <- mice(Dat1, maxit=0, pri=F) pred <- ini$pred pred[,c("id", "faculty")] <- 0 #variables you do not want to use as predictors (but #want to have in the dataset, can't add them later. meth <- ini$meth meth[c("id", "faculty", "gender", "age", "job")] <- "" #choose a prediction method #for imputing your variables. Here I don't want these variables to be imputed, so I #choose "" (empty, no mehod). imp <- mice(Dat1, m=5, maxit=10, printFlag=TRUE, pred=pred, meth=meth, seed=2345) Datimp <- complete(imp, "long", include=TRUE) write.table(Datimp, "C:/.../impute1.txt", sep="\t", dec=",", row.names=FALSE) See if your imputations were any good: library(lattice) com <- complete(imp, "long", inc=T) col <- rep(c("blue","red")[1+as.numeric(is.na(imp$salary))],6) stripplot(salary~.imp, data=com, jit=TRUE, fac=0.8, col=col, pch=20, xlab="Imputation number",cex=0.25) densityplot(salary~.imp, data=com, jit=TRUE, fac=0.8, col=col, pch=20, xlab="Imputation number",cex=0.25) long <- complete(imp,"long") levels(long$.imp) <- paste("Imputation",1:22) long <- cbind(long, salary.na=is.na(imp$data$salary)) densityplot(~salary|.imp, data=long, group=salary, plot.points=FALSE, ref=TRUE, xlab="Salary",scales=list(y=list(draw=F)), par.settings=simpleTheme(col.line=rep(c("blue","red"))), auto.key = list(columns=2,text=c("Observed","Imputed"))) Finally, and importantly. You can't just save your new dataset and use your imputed values as normal observed values. You use pooled regression or pooled lmer ...So the uncertainty of the imputed values is taken into account. fit1 <- with(imp, lm(salary ~ gender, na.action=na.omit)) summary(est <- pool(fit1)) pool.r.squared(fit1,adjusted=FALSE)
Fast missing data imputation in R for big data that is more sophisticated than simply imputing the m
I used mice (multiple imputation by chained equation). It's fairly fast, and quite simple. I used it on 3000 obs. for c.a. 10 variables. Done in 10min on an old computer. Further, I believe it is one
Fast missing data imputation in R for big data that is more sophisticated than simply imputing the means? I used mice (multiple imputation by chained equation). It's fairly fast, and quite simple. I used it on 3000 obs. for c.a. 10 variables. Done in 10min on an old computer. Further, I believe it is one of the best multiple-imputation packages out there. It can use regression to impute, among other methods. You need to create a dataframe with the variable you want to impute, and include every variable that might predict values of that variable (so every var. in your model + possibly other var. as well). The mice package will impute every missing value in that dataframe. Simplest way of imputing. Gives you a dataframe Datimp that has five imputed data + the original data. library(mice) #m=5 number of multiple imputations #maxit=10 number of iterations. 10-20 is sufficient. imp <- mice(Dat1, m=5, maxit=10, printFlag=TRUE) Datimp <- complete(imp, "long", include=TRUE) write.table(Datimp, "C:/.../impute1.txt", sep="\t", dec=",", row.names=FALSE) A better way to do this is: library(mice) Dat1 <- subset(Dat, select=c(id, faculty, gender, age, job, salary)) #create subset #of variables you would like to either impute or use as predictors for imputation. ini <- mice(Dat1, maxit=0, pri=F) pred <- ini$pred pred[,c("id", "faculty")] <- 0 #variables you do not want to use as predictors (but #want to have in the dataset, can't add them later. meth <- ini$meth meth[c("id", "faculty", "gender", "age", "job")] <- "" #choose a prediction method #for imputing your variables. Here I don't want these variables to be imputed, so I #choose "" (empty, no mehod). imp <- mice(Dat1, m=5, maxit=10, printFlag=TRUE, pred=pred, meth=meth, seed=2345) Datimp <- complete(imp, "long", include=TRUE) write.table(Datimp, "C:/.../impute1.txt", sep="\t", dec=",", row.names=FALSE) See if your imputations were any good: library(lattice) com <- complete(imp, "long", inc=T) col <- rep(c("blue","red")[1+as.numeric(is.na(imp$salary))],6) stripplot(salary~.imp, data=com, jit=TRUE, fac=0.8, col=col, pch=20, xlab="Imputation number",cex=0.25) densityplot(salary~.imp, data=com, jit=TRUE, fac=0.8, col=col, pch=20, xlab="Imputation number",cex=0.25) long <- complete(imp,"long") levels(long$.imp) <- paste("Imputation",1:22) long <- cbind(long, salary.na=is.na(imp$data$salary)) densityplot(~salary|.imp, data=long, group=salary, plot.points=FALSE, ref=TRUE, xlab="Salary",scales=list(y=list(draw=F)), par.settings=simpleTheme(col.line=rep(c("blue","red"))), auto.key = list(columns=2,text=c("Observed","Imputed"))) Finally, and importantly. You can't just save your new dataset and use your imputed values as normal observed values. You use pooled regression or pooled lmer ...So the uncertainty of the imputed values is taken into account. fit1 <- with(imp, lm(salary ~ gender, na.action=na.omit)) summary(est <- pool(fit1)) pool.r.squared(fit1,adjusted=FALSE)
Fast missing data imputation in R for big data that is more sophisticated than simply imputing the m I used mice (multiple imputation by chained equation). It's fairly fast, and quite simple. I used it on 3000 obs. for c.a. 10 variables. Done in 10min on an old computer. Further, I believe it is one
35,474
Fast missing data imputation in R for big data that is more sophisticated than simply imputing the means?
The Hmisc package can probably do this with the imputation function (aregImpute). Agree that columns are plenty, but rows are few. Should probably be handled by Hisc...
Fast missing data imputation in R for big data that is more sophisticated than simply imputing the m
The Hmisc package can probably do this with the imputation function (aregImpute). Agree that columns are plenty, but rows are few. Should probably be handled by Hisc...
Fast missing data imputation in R for big data that is more sophisticated than simply imputing the means? The Hmisc package can probably do this with the imputation function (aregImpute). Agree that columns are plenty, but rows are few. Should probably be handled by Hisc...
Fast missing data imputation in R for big data that is more sophisticated than simply imputing the m The Hmisc package can probably do this with the imputation function (aregImpute). Agree that columns are plenty, but rows are few. Should probably be handled by Hisc...
35,475
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form
$\textbf{X}$ is of dimension $\textbf{N}\times\textbf{K}$ and $\textbf{X}'$ of dimension $\textbf{K}\times\textbf{N}$, the product $(\textbf{X}'\textbf{X})$ is consequently of dimension $\textbf{K}\times\textbf{K}$. Taking the invers of $\textbf{N}\times\textbf{N}$ does not change the dimension of the matrix. Consequently the multiplication of $(\textbf{X}'\textbf{X})\textbf{X}'$ is a multiplication of a matrix of dimension $\textbf{K}\times\textbf{K}$ with a matrix of dimension $\textbf{K}\times\textbf{N}$. There product is a matrix of dimension $\textbf{K}\times\textbf{N}$. $\textbf{y}$ is a vector of $\textbf{N}\times1$. Multiplying $(\textbf{X}'\textbf{X})\textbf{X}'$, which is of dimension $\textbf{K}\times\textbf{N}$ with the vector $\textbf{y}$, which is of dimension $\textbf{N}\times1$ gives us a vector of $\textbf{K}\times1$ dimension. I hope this sheds some light on you problem. Otherwise you should check out how the least squares estimator is derived. An explanation in a simple way can be found under http://economictheoryblog.com/2015/02/19/ols_estimator/
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form
$\textbf{X}$ is of dimension $\textbf{N}\times\textbf{K}$ and $\textbf{X}'$ of dimension $\textbf{K}\times\textbf{N}$, the product $(\textbf{X}'\textbf{X})$ is consequently of dimension $\textbf{K}\t
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form $\textbf{X}$ is of dimension $\textbf{N}\times\textbf{K}$ and $\textbf{X}'$ of dimension $\textbf{K}\times\textbf{N}$, the product $(\textbf{X}'\textbf{X})$ is consequently of dimension $\textbf{K}\times\textbf{K}$. Taking the invers of $\textbf{N}\times\textbf{N}$ does not change the dimension of the matrix. Consequently the multiplication of $(\textbf{X}'\textbf{X})\textbf{X}'$ is a multiplication of a matrix of dimension $\textbf{K}\times\textbf{K}$ with a matrix of dimension $\textbf{K}\times\textbf{N}$. There product is a matrix of dimension $\textbf{K}\times\textbf{N}$. $\textbf{y}$ is a vector of $\textbf{N}\times1$. Multiplying $(\textbf{X}'\textbf{X})\textbf{X}'$, which is of dimension $\textbf{K}\times\textbf{N}$ with the vector $\textbf{y}$, which is of dimension $\textbf{N}\times1$ gives us a vector of $\textbf{K}\times1$ dimension. I hope this sheds some light on you problem. Otherwise you should check out how the least squares estimator is derived. An explanation in a simple way can be found under http://economictheoryblog.com/2015/02/19/ols_estimator/
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form $\textbf{X}$ is of dimension $\textbf{N}\times\textbf{K}$ and $\textbf{X}'$ of dimension $\textbf{K}\times\textbf{N}$, the product $(\textbf{X}'\textbf{X})$ is consequently of dimension $\textbf{K}\t
35,476
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form
It appears that you're simply confused by the notation. Here ${\bf x}_{i}$ is the column vector ${\bf x}_{i} = \left[\begin{array}{c} x_{i,1} \\ x_{i,2} \\ \vdots \\ x_{i,n} \end{array} \right].$ It is somewhat confusing that the author has chosen to take the $i$th row of the matrix ${\bf X}$ and call its transpose ${\bf x}_{i}$. Next, when you compute the outer product ${\bf x}_{i}{\bf x}_{i}'$, you get an $n$ by $n$ matrix: ${\bf x}_{i}{\bf x}_{i}'=\left[\begin{array}{ccccc} {\it x}_{i,1}x_{i,1} & x_{i,1}x_{i,2} & x_{i,1}x_{i,3} & \ldots & x_{i,1}x_{i,n} \\ x_{i,2}x_{i,1} & x_{i,2}x_{i,2} & x_{i,2}x_{i,3} & \ldots & x_{i,2}x_{i,n} \\ \vdots & \vdots & \vdots & \vdots & \vdots \\ x_{i,n}x_{i,1} & x_{i,n}x_{i,2} & x_{i,n}x_{i,3} & \ldots & x_{i,n}x_{i,n} \\ \end{array} \right].$ Finally, you need to be aware of the sum of outer products form of matrix multiplication, which gives ${\bf X}'{\bf X}=\sum_{i=1}^{n}{\bf x}_{i}{\bf x}_{i}'.$
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form
It appears that you're simply confused by the notation. Here ${\bf x}_{i}$ is the column vector ${\bf x}_{i} = \left[\begin{array}{c} x_{i,1} \\ x_{i,2} \\ \vdots \\ x_{i,n} \end{array} \right].$
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form It appears that you're simply confused by the notation. Here ${\bf x}_{i}$ is the column vector ${\bf x}_{i} = \left[\begin{array}{c} x_{i,1} \\ x_{i,2} \\ \vdots \\ x_{i,n} \end{array} \right].$ It is somewhat confusing that the author has chosen to take the $i$th row of the matrix ${\bf X}$ and call its transpose ${\bf x}_{i}$. Next, when you compute the outer product ${\bf x}_{i}{\bf x}_{i}'$, you get an $n$ by $n$ matrix: ${\bf x}_{i}{\bf x}_{i}'=\left[\begin{array}{ccccc} {\it x}_{i,1}x_{i,1} & x_{i,1}x_{i,2} & x_{i,1}x_{i,3} & \ldots & x_{i,1}x_{i,n} \\ x_{i,2}x_{i,1} & x_{i,2}x_{i,2} & x_{i,2}x_{i,3} & \ldots & x_{i,2}x_{i,n} \\ \vdots & \vdots & \vdots & \vdots & \vdots \\ x_{i,n}x_{i,1} & x_{i,n}x_{i,2} & x_{i,n}x_{i,3} & \ldots & x_{i,n}x_{i,n} \\ \end{array} \right].$ Finally, you need to be aware of the sum of outer products form of matrix multiplication, which gives ${\bf X}'{\bf X}=\sum_{i=1}^{n}{\bf x}_{i}{\bf x}_{i}'.$
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form It appears that you're simply confused by the notation. Here ${\bf x}_{i}$ is the column vector ${\bf x}_{i} = \left[\begin{array}{c} x_{i,1} \\ x_{i,2} \\ \vdots \\ x_{i,n} \end{array} \right].$
35,477
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form
You are referring to Cameron & Trivedi, page 16, aren't you? There they say that "vectors are defined as column vectors". This is why in $y_i=\mathbf{x}_i'\boldsymbol{\beta}+u_i$ (same page) $\mathbf{x}_i$ is the column vector that contains... the $i$th row of the $N\times K$ $\mathbf{X}$ matrix. So $\mathbf{x}_i'\boldsymbol{\beta}$ is a scalar, $\mathbf{x}_i\mathbf{x}_i'$ is a matrix. Wooldridge writes $y_i=\mathbf{x}_i\boldsymbol{\beta}$ and $\sum_{i=1}^N\mathbf{x}_i'\mathbf{x}_i$. It's just a different convention.
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form
You are referring to Cameron & Trivedi, page 16, aren't you? There they say that "vectors are defined as column vectors". This is why in $y_i=\mathbf{x}_i'\boldsymbol{\beta}+u_i$ (same page) $\mathbf{
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form You are referring to Cameron & Trivedi, page 16, aren't you? There they say that "vectors are defined as column vectors". This is why in $y_i=\mathbf{x}_i'\boldsymbol{\beta}+u_i$ (same page) $\mathbf{x}_i$ is the column vector that contains... the $i$th row of the $N\times K$ $\mathbf{X}$ matrix. So $\mathbf{x}_i'\boldsymbol{\beta}$ is a scalar, $\mathbf{x}_i\mathbf{x}_i'$ is a matrix. Wooldridge writes $y_i=\mathbf{x}_i\boldsymbol{\beta}$ and $\sum_{i=1}^N\mathbf{x}_i'\mathbf{x}_i$. It's just a different convention.
OLS Coefficient estimator; Transformation from Matrix to sum of matrices form You are referring to Cameron & Trivedi, page 16, aren't you? There they say that "vectors are defined as column vectors". This is why in $y_i=\mathbf{x}_i'\boldsymbol{\beta}+u_i$ (same page) $\mathbf{
35,478
What does this residuals versus fitted plot mean about my model?
The first plot (Normal Q-Q plot) checks if residuals follow a normal distribution, which is an assumption of linear regression. If dots are over the line y=x it means the residuals are normally distributed. Your plot seems OK in this aspect. The Residuals _versus_ Fitted plot is useful to illustrate if a linear model presents: non-linear relationship between the response variable and predictors. A horizontal trend line in the plot indicates absence of nonlinear patterns between response and predictors, which is what is expected in a linear model. heteroscedasticity (aka heterogeneity of variance). A model will exhibit heteroscedasticity when the residuals are not equally spread along the fitted values. However, as suggested by @BenBolker, a better alternative for visualizing homo/heteroscedasticity is the Scale-Location plot (it uses the Standardized Residuals vs Fitted values) for the reasons written in: Trying to understand the fitted vs residual plot? But why heteroscedasticity is bad? According to the Wikipedia article: ...the presence of heteroscedasticity can invalidate statistical tests of significance that assume that the modelling errors are uncorrelated and normally distributed and that their variances do not vary with the effects being modelled. In other words, if one had observed heteroskedasticity, the parameters' standard errors (calculated through t tests) would not make much sense. Your plot seems to be OK, though. A nice complementary article is Understanding Diagnostic Plots for Linear Regression Analysis from Bommae Kim, University of Virginia.
What does this residuals versus fitted plot mean about my model?
The first plot (Normal Q-Q plot) checks if residuals follow a normal distribution, which is an assumption of linear regression. If dots are over the line y=x it means the residuals are normally distri
What does this residuals versus fitted plot mean about my model? The first plot (Normal Q-Q plot) checks if residuals follow a normal distribution, which is an assumption of linear regression. If dots are over the line y=x it means the residuals are normally distributed. Your plot seems OK in this aspect. The Residuals _versus_ Fitted plot is useful to illustrate if a linear model presents: non-linear relationship between the response variable and predictors. A horizontal trend line in the plot indicates absence of nonlinear patterns between response and predictors, which is what is expected in a linear model. heteroscedasticity (aka heterogeneity of variance). A model will exhibit heteroscedasticity when the residuals are not equally spread along the fitted values. However, as suggested by @BenBolker, a better alternative for visualizing homo/heteroscedasticity is the Scale-Location plot (it uses the Standardized Residuals vs Fitted values) for the reasons written in: Trying to understand the fitted vs residual plot? But why heteroscedasticity is bad? According to the Wikipedia article: ...the presence of heteroscedasticity can invalidate statistical tests of significance that assume that the modelling errors are uncorrelated and normally distributed and that their variances do not vary with the effects being modelled. In other words, if one had observed heteroskedasticity, the parameters' standard errors (calculated through t tests) would not make much sense. Your plot seems to be OK, though. A nice complementary article is Understanding Diagnostic Plots for Linear Regression Analysis from Bommae Kim, University of Virginia.
What does this residuals versus fitted plot mean about my model? The first plot (Normal Q-Q plot) checks if residuals follow a normal distribution, which is an assumption of linear regression. If dots are over the line y=x it means the residuals are normally distri
35,479
What are "second-order dependencies" and "higher order dependencies" in the data?
PCA is based on variances and covariances, $\mathrm E[x_i x_j]$ (assuming mean-free variables). These are measures of second-order dependencies because the data enter in the form of terms of order 2. After PCA, the principal components have 0 covariance between them, so second-order dependencies have been removed. However, it is still possible that higher-order dependencies exist, e.g. that $\mathrm E[x_i x_j x_k] \neq 0$ for some $i$, $j$, and $k$. By removing second-order dependencies by applying a linear transform, PCA in a way "reveals" second-order dependencies in the form of that transform, but it does not "reveal" higher-order dependencies.
What are "second-order dependencies" and "higher order dependencies" in the data?
PCA is based on variances and covariances, $\mathrm E[x_i x_j]$ (assuming mean-free variables). These are measures of second-order dependencies because the data enter in the form of terms of order 2.
What are "second-order dependencies" and "higher order dependencies" in the data? PCA is based on variances and covariances, $\mathrm E[x_i x_j]$ (assuming mean-free variables). These are measures of second-order dependencies because the data enter in the form of terms of order 2. After PCA, the principal components have 0 covariance between them, so second-order dependencies have been removed. However, it is still possible that higher-order dependencies exist, e.g. that $\mathrm E[x_i x_j x_k] \neq 0$ for some $i$, $j$, and $k$. By removing second-order dependencies by applying a linear transform, PCA in a way "reveals" second-order dependencies in the form of that transform, but it does not "reveal" higher-order dependencies.
What are "second-order dependencies" and "higher order dependencies" in the data? PCA is based on variances and covariances, $\mathrm E[x_i x_j]$ (assuming mean-free variables). These are measures of second-order dependencies because the data enter in the form of terms of order 2.
35,480
What are "second-order dependencies" and "higher order dependencies" in the data?
In the context of this paper, it appears as if they are using to ‘second order dependencies’ to refer to cases where $X$ and $Y$ are orthogonal to each other, and higher order dependencies when $X$ and $Y$ are not. Finding orthogonal axes is the basis for the principal component analysis, because you are trying to find what orthogonal axes exist that can explain the maximum amount of variation. Their point is that for some more complicated data sets, looking for orthogonal axes does not really make sense because it may systematically explain too little of the information. I think it’s easiest to explain this with a (terrible) MS Paint picture: Taking their Figure 6 and butchering it, their point is that if you have an orthogonal $X$ and $Y$ then there are only 4 positions on the ferris wheel that this system can explain. There are many other positions in between where you have $Y$ and some combo of $Y$ and $X$ (or $X$ and some combo of $Y$ and $X$) required to explain it, which is sort of like needing $Y^2$ and $X$ to explain the information (aka, a higher-order dependency). In this case if you were aware that your data described a circular path, the rational solution would be to use $\Theta$ to describe it and avoid PCA (which is their first suggested solution - to use $a$ $priori$ information). But you can't always predict higher order relationships.
What are "second-order dependencies" and "higher order dependencies" in the data?
In the context of this paper, it appears as if they are using to ‘second order dependencies’ to refer to cases where $X$ and $Y$ are orthogonal to each other, and higher order dependencies when $X$ an
What are "second-order dependencies" and "higher order dependencies" in the data? In the context of this paper, it appears as if they are using to ‘second order dependencies’ to refer to cases where $X$ and $Y$ are orthogonal to each other, and higher order dependencies when $X$ and $Y$ are not. Finding orthogonal axes is the basis for the principal component analysis, because you are trying to find what orthogonal axes exist that can explain the maximum amount of variation. Their point is that for some more complicated data sets, looking for orthogonal axes does not really make sense because it may systematically explain too little of the information. I think it’s easiest to explain this with a (terrible) MS Paint picture: Taking their Figure 6 and butchering it, their point is that if you have an orthogonal $X$ and $Y$ then there are only 4 positions on the ferris wheel that this system can explain. There are many other positions in between where you have $Y$ and some combo of $Y$ and $X$ (or $X$ and some combo of $Y$ and $X$) required to explain it, which is sort of like needing $Y^2$ and $X$ to explain the information (aka, a higher-order dependency). In this case if you were aware that your data described a circular path, the rational solution would be to use $\Theta$ to describe it and avoid PCA (which is their first suggested solution - to use $a$ $priori$ information). But you can't always predict higher order relationships.
What are "second-order dependencies" and "higher order dependencies" in the data? In the context of this paper, it appears as if they are using to ‘second order dependencies’ to refer to cases where $X$ and $Y$ are orthogonal to each other, and higher order dependencies when $X$ an
35,481
$\phi$-divergence?
Ok found it myself. It was part of the following paper: Jiménez-Gamero, María-Dolores, et al. "Minimum $\phi$-divergence estimation in misspecified multinomial models." Computational Statistics & Data Analysis 55.12 (2011): 3365-3378. $\phi: [0,\infty) \to \mathbb{R}$ is a strictly convex function, twice continuously differentiable in $(0,\infty)$. For arbitrary $Q = (q_1,q_2, ... .,q_m)^t,P = (p_1,p_2, . . . ,p_m)^t ∈ \Delta_m$, the $\phi$-divergence between $Q$ and $P$ is defined by (Csiszár, 1967) $$D_\phi(Q,P) =\sum\limits_{i=1}^{m}p_i\phi(\frac{q_i}{p_i}).$$
$\phi$-divergence?
Ok found it myself. It was part of the following paper: Jiménez-Gamero, María-Dolores, et al. "Minimum $\phi$-divergence estimation in misspecified multinomial models." Computational Statistics & Data
$\phi$-divergence? Ok found it myself. It was part of the following paper: Jiménez-Gamero, María-Dolores, et al. "Minimum $\phi$-divergence estimation in misspecified multinomial models." Computational Statistics & Data Analysis 55.12 (2011): 3365-3378. $\phi: [0,\infty) \to \mathbb{R}$ is a strictly convex function, twice continuously differentiable in $(0,\infty)$. For arbitrary $Q = (q_1,q_2, ... .,q_m)^t,P = (p_1,p_2, . . . ,p_m)^t ∈ \Delta_m$, the $\phi$-divergence between $Q$ and $P$ is defined by (Csiszár, 1967) $$D_\phi(Q,P) =\sum\limits_{i=1}^{m}p_i\phi(\frac{q_i}{p_i}).$$
$\phi$-divergence? Ok found it myself. It was part of the following paper: Jiménez-Gamero, María-Dolores, et al. "Minimum $\phi$-divergence estimation in misspecified multinomial models." Computational Statistics & Data
35,482
$\phi$-divergence?
This paper by Love and Bayraksan gives this introduction: '$\phi$-divergences are used in statistics to measure the "distance" between two distributions,' and this formal definition: $I_{\phi}(p,q) = \sum_{\omega = 1}^{n}{q_\omega\phi(\frac{p_\omega}{q_\omega})}$ where $p, q$ are probability vectors and $\phi$ is a function on $t > 0$. It cites as examples Kullback-Leibler divergence and $\chi^2$ distance. The introduction begins on p. 5, examples given on p. 7.
$\phi$-divergence?
This paper by Love and Bayraksan gives this introduction: '$\phi$-divergences are used in statistics to measure the "distance" between two distributions,' and this formal definition: $I_{\phi}(p,q) =
$\phi$-divergence? This paper by Love and Bayraksan gives this introduction: '$\phi$-divergences are used in statistics to measure the "distance" between two distributions,' and this formal definition: $I_{\phi}(p,q) = \sum_{\omega = 1}^{n}{q_\omega\phi(\frac{p_\omega}{q_\omega})}$ where $p, q$ are probability vectors and $\phi$ is a function on $t > 0$. It cites as examples Kullback-Leibler divergence and $\chi^2$ distance. The introduction begins on p. 5, examples given on p. 7.
$\phi$-divergence? This paper by Love and Bayraksan gives this introduction: '$\phi$-divergences are used in statistics to measure the "distance" between two distributions,' and this formal definition: $I_{\phi}(p,q) =
35,483
$\phi$-divergence?
According to Jager and Wellner this term was invented by I. Csiszar (1963), but his paper is in german. Jager and Wellner use it to construct goodness-of-fit tests and they give the following definition: $K(u,v) = v \phi(\frac{u}{v}) + (1-v)\phi(\frac{1-u}{1-v})$
$\phi$-divergence?
According to Jager and Wellner this term was invented by I. Csiszar (1963), but his paper is in german. Jager and Wellner use it to construct goodness-of-fit tests and they give the following definiti
$\phi$-divergence? According to Jager and Wellner this term was invented by I. Csiszar (1963), but his paper is in german. Jager and Wellner use it to construct goodness-of-fit tests and they give the following definition: $K(u,v) = v \phi(\frac{u}{v}) + (1-v)\phi(\frac{1-u}{1-v})$
$\phi$-divergence? According to Jager and Wellner this term was invented by I. Csiszar (1963), but his paper is in german. Jager and Wellner use it to construct goodness-of-fit tests and they give the following definiti
35,484
Hierarchical clustering of correlation matrix
To apply most hierarchical clustering/heatmap tools you'll need to convert your correlation matrix into a distance matrix (ie 0 is close together, higher is further apart). This blog post covers some simple methods with R code. However, a more computationally efficient method is to convert the correlation matrix to a graph, apply a cutoff so that it is sparse and apply graph partitioning methods. A colleague and I actually have a project, Inspectra, that uses spectral graph analysis to compare graphs derived from correlation matrixes. We are developing it for cancer data and it is still a prototype but won best poster at biovis last year and you are welcome to try it and contact one of us via github if you have questions.
Hierarchical clustering of correlation matrix
To apply most hierarchical clustering/heatmap tools you'll need to convert your correlation matrix into a distance matrix (ie 0 is close together, higher is further apart). This blog post covers some
Hierarchical clustering of correlation matrix To apply most hierarchical clustering/heatmap tools you'll need to convert your correlation matrix into a distance matrix (ie 0 is close together, higher is further apart). This blog post covers some simple methods with R code. However, a more computationally efficient method is to convert the correlation matrix to a graph, apply a cutoff so that it is sparse and apply graph partitioning methods. A colleague and I actually have a project, Inspectra, that uses spectral graph analysis to compare graphs derived from correlation matrixes. We are developing it for cancer data and it is still a prototype but won best poster at biovis last year and you are welcome to try it and contact one of us via github if you have questions.
Hierarchical clustering of correlation matrix To apply most hierarchical clustering/heatmap tools you'll need to convert your correlation matrix into a distance matrix (ie 0 is close together, higher is further apart). This blog post covers some
35,485
R: multiple linear regression model and prediction model
newdata should contain a column for each of your predictive variables, alt and sdist. (Any variables except the one you're predicting.) For example: newdata = data.frame(alt = newAltVector, sdist = newSdistVector) predictions = predict.lm(model, newdata) predictions will then contain a fitted y value for each new x. In the below, black dots represent training data, and the blue dots represent predicted values. Whether that's the right way to predict temp depends on how well a linear model approximates the relationship between variables. Try this intro to evaluating a linear model in R.
R: multiple linear regression model and prediction model
newdata should contain a column for each of your predictive variables, alt and sdist. (Any variables except the one you're predicting.) For example: newdata = data.frame(alt = newAltVector, sdist = ne
R: multiple linear regression model and prediction model newdata should contain a column for each of your predictive variables, alt and sdist. (Any variables except the one you're predicting.) For example: newdata = data.frame(alt = newAltVector, sdist = newSdistVector) predictions = predict.lm(model, newdata) predictions will then contain a fitted y value for each new x. In the below, black dots represent training data, and the blue dots represent predicted values. Whether that's the right way to predict temp depends on how well a linear model approximates the relationship between variables. Try this intro to evaluating a linear model in R.
R: multiple linear regression model and prediction model newdata should contain a column for each of your predictive variables, alt and sdist. (Any variables except the one you're predicting.) For example: newdata = data.frame(alt = newAltVector, sdist = ne
35,486
Connecting the dots in a graph
There are a variety of reasons to connect the points in a graph. If you're only showing one category of values (i.e. if there is a line there would only be one) then the rule of continuous versus discrete is generally good to abide by. However, even discrete or categorical values can be connected when multiple lines might be required in order to make it easy to follow pattern variation across the x-axis. The point is to make a coherent story, and if a line makes the story more sensible or easier to follow then add it. If it detracts then remove it. In your case a graph with a point for each lot and hours on the x-axis I would very much be inclined to plot lines connecting the hours for each lot. And, while you have means at hours, the x-axis values are interval measured and theoretically continuous (all continuous might be argued to be interval measured), so there is further justification there. As for bars, as other posters mentioned. I almost always avoid them. A point is usually better even for kinds of data typically thought to be filled by bars. Also consider that, unless the parking lots are the same size the number of cars is misleading. A graph with fixed area and typical bars implies that each bar is representing the same filling of items in the space equally. You only partially solve that problem with proportions of cars in the lots. An alternative when there is only one time period would be to have empty bars indicating the sizes of the lots and then fill them up with the number of cars. But this would be overly complex when demonstrating multiple lots. Line graphs of proportion of fill connected over hours with a line for each lot is the best way to go here.
Connecting the dots in a graph
There are a variety of reasons to connect the points in a graph. If you're only showing one category of values (i.e. if there is a line there would only be one) then the rule of continuous versus disc
Connecting the dots in a graph There are a variety of reasons to connect the points in a graph. If you're only showing one category of values (i.e. if there is a line there would only be one) then the rule of continuous versus discrete is generally good to abide by. However, even discrete or categorical values can be connected when multiple lines might be required in order to make it easy to follow pattern variation across the x-axis. The point is to make a coherent story, and if a line makes the story more sensible or easier to follow then add it. If it detracts then remove it. In your case a graph with a point for each lot and hours on the x-axis I would very much be inclined to plot lines connecting the hours for each lot. And, while you have means at hours, the x-axis values are interval measured and theoretically continuous (all continuous might be argued to be interval measured), so there is further justification there. As for bars, as other posters mentioned. I almost always avoid them. A point is usually better even for kinds of data typically thought to be filled by bars. Also consider that, unless the parking lots are the same size the number of cars is misleading. A graph with fixed area and typical bars implies that each bar is representing the same filling of items in the space equally. You only partially solve that problem with proportions of cars in the lots. An alternative when there is only one time period would be to have empty bars indicating the sizes of the lots and then fill them up with the number of cars. But this would be overly complex when demonstrating multiple lots. Line graphs of proportion of fill connected over hours with a line for each lot is the best way to go here.
Connecting the dots in a graph There are a variety of reasons to connect the points in a graph. If you're only showing one category of values (i.e. if there is a line there would only be one) then the rule of continuous versus disc
35,487
Connecting the dots in a graph
IMHO, whoever first omitted the precise timing of changes in number of cars is the first one responsible for any misleading results. If you had this information (even if measured with error), time would be a proper continuous variable, not a grouped continuous variable (see Anderson, 1984) necessarily. You'd be free to group observations into hour-based bins if you really wanted to, at which point you'd assume responsibility for deriving any misleading results. Otherwise, by preserving precise times of arrival, you could graph your number of cars time-series over continuous time accurately. Anyway, assuming you're stuck with number of cars per hour, I agree with @John, you should draw a line connecting your hourly observations. If you lack information about when each incremental change occurred, it's rather hard to say you're misleading anyone unless you fail to describe the limits of the information graphed. Similarly, if you graph your hourly data with a simple bar chart without a line connecting the bins, you're not really guilty of misleading anyone if you don't claim that the changes between hourly observations occur precisely as depicted, on the hour, all at once. If someone misunderstands (as will probably occur with any sufficiently publicized statistic or data), it won't be the case that you misled them, especially if you describe your data and collection procedure in sufficient detail. This much should not be hard to do. Given basic clarity and thoroughness of data and graph descriptions, there should be no disadvantage of drawing a line to connect your bins. The advantage of connecting your bins is in fact what you seem to think is the disadvantage: drawing those lines mimics a halfway decent equation for the number of cars as a function of continuous time, even though it's based on discrete, hourly observations. You can use a straight line between observations to represent a fairly reasonable assumption that change occurs linearly over each hour, not all at once. Based on such an assumption, any reader can make a decent guess of which minute after a given hour's measurement will see the next car arrive or leave by this fairly common-sense four-step procedure: Find the point on the line where number of cars $=1+$ the previous hour's observation Draw a line straight down from this point to find where it intersects with the hour axis Measure the distance of this point on the hour axis from the point of the previous observation distance $\div$ distance between observations $\times60=$ minute after the hour of the next car's arrival. Of course, one can estimate the next car's arrival down to the precise second too, and you can't stop readers from doing this by not providing the line – drawing the line just becomes the first of five steps. Thus if someone actually wants to know how many cars were there in the meantime...well, they can't, because the info isn't available, but they can estimate. If you knock a step off the process for them, I imagine they'll be grateful. Doing this for your readers with simple, straight lines only implies your comfort with the assumption that change occurs linearly between hourly observations, or more pejoratively stated, your disinterest in any inaccuracies in this assumption. Inaccuracies aren't hard to imagine. First, change necessarily occurs as a nonlinear, zero-inflated function of time. It's nonlinear because the change event is ternary: either a car arrives, leaves, or neither – cars don't arrive or leave in fractional increments. It's zero-inflated because most moments in time won't see a car arrive or leave. You can get around this by treating the line as describing the probability that cars will arrive or leave in any given moment to reach the nearest whole number. Yet another inaccuracy of the assumption behind straight lines between hourly observations remains. You might expect the rate of change (in terms of probability as above) to change more smoothly over time than your straight lines drawn separately between points imply. In more mathematical terms, you might want the derivative of your number of cars(hour) function to be continuous across hours. You might be able to do this by fitting a polynomial function to your data, but if your purpose is predictive, beware of overfitting. Another advantage of lines over histogram-style bars (i.e., with no intermediate spacing for adjacent values of hour...let alone charts with bars that don't "touch" each other) arises from your polytomous lot variable. You can superimpose your separate time series for each lot on the same graph to facilitate comparisons, which will help you see whether your lot variable is interesting. Here's a demonstration with some made-up data: Kudos to McCown! I'm not even going to try to figure out how to do that coherently with bars; I'll leave that to @ChristianStade-Schuldt ;) To be fair, it's even easier to not connect these points as he suggested, but adding the lines helps disambiguate the points corresponding to separate time series from one another. In the end, it's still going to be a little subjective, so judge for yourself: I for one find myself drawing the lines in my mind anyway. BTW, if you feel the lines in the first figure detract anything from the visual impact of the exact points, don't forget that you can always increase the size of the points, change their shape, or present their values numerically in a separate table. Reference Anderson, J. A. (1984). Regression and ordered categorical variables. Journal of the Royal Statistical Society B, 46, 1–30.
Connecting the dots in a graph
IMHO, whoever first omitted the precise timing of changes in number of cars is the first one responsible for any misleading results. If you had this information (even if measured with error), time wou
Connecting the dots in a graph IMHO, whoever first omitted the precise timing of changes in number of cars is the first one responsible for any misleading results. If you had this information (even if measured with error), time would be a proper continuous variable, not a grouped continuous variable (see Anderson, 1984) necessarily. You'd be free to group observations into hour-based bins if you really wanted to, at which point you'd assume responsibility for deriving any misleading results. Otherwise, by preserving precise times of arrival, you could graph your number of cars time-series over continuous time accurately. Anyway, assuming you're stuck with number of cars per hour, I agree with @John, you should draw a line connecting your hourly observations. If you lack information about when each incremental change occurred, it's rather hard to say you're misleading anyone unless you fail to describe the limits of the information graphed. Similarly, if you graph your hourly data with a simple bar chart without a line connecting the bins, you're not really guilty of misleading anyone if you don't claim that the changes between hourly observations occur precisely as depicted, on the hour, all at once. If someone misunderstands (as will probably occur with any sufficiently publicized statistic or data), it won't be the case that you misled them, especially if you describe your data and collection procedure in sufficient detail. This much should not be hard to do. Given basic clarity and thoroughness of data and graph descriptions, there should be no disadvantage of drawing a line to connect your bins. The advantage of connecting your bins is in fact what you seem to think is the disadvantage: drawing those lines mimics a halfway decent equation for the number of cars as a function of continuous time, even though it's based on discrete, hourly observations. You can use a straight line between observations to represent a fairly reasonable assumption that change occurs linearly over each hour, not all at once. Based on such an assumption, any reader can make a decent guess of which minute after a given hour's measurement will see the next car arrive or leave by this fairly common-sense four-step procedure: Find the point on the line where number of cars $=1+$ the previous hour's observation Draw a line straight down from this point to find where it intersects with the hour axis Measure the distance of this point on the hour axis from the point of the previous observation distance $\div$ distance between observations $\times60=$ minute after the hour of the next car's arrival. Of course, one can estimate the next car's arrival down to the precise second too, and you can't stop readers from doing this by not providing the line – drawing the line just becomes the first of five steps. Thus if someone actually wants to know how many cars were there in the meantime...well, they can't, because the info isn't available, but they can estimate. If you knock a step off the process for them, I imagine they'll be grateful. Doing this for your readers with simple, straight lines only implies your comfort with the assumption that change occurs linearly between hourly observations, or more pejoratively stated, your disinterest in any inaccuracies in this assumption. Inaccuracies aren't hard to imagine. First, change necessarily occurs as a nonlinear, zero-inflated function of time. It's nonlinear because the change event is ternary: either a car arrives, leaves, or neither – cars don't arrive or leave in fractional increments. It's zero-inflated because most moments in time won't see a car arrive or leave. You can get around this by treating the line as describing the probability that cars will arrive or leave in any given moment to reach the nearest whole number. Yet another inaccuracy of the assumption behind straight lines between hourly observations remains. You might expect the rate of change (in terms of probability as above) to change more smoothly over time than your straight lines drawn separately between points imply. In more mathematical terms, you might want the derivative of your number of cars(hour) function to be continuous across hours. You might be able to do this by fitting a polynomial function to your data, but if your purpose is predictive, beware of overfitting. Another advantage of lines over histogram-style bars (i.e., with no intermediate spacing for adjacent values of hour...let alone charts with bars that don't "touch" each other) arises from your polytomous lot variable. You can superimpose your separate time series for each lot on the same graph to facilitate comparisons, which will help you see whether your lot variable is interesting. Here's a demonstration with some made-up data: Kudos to McCown! I'm not even going to try to figure out how to do that coherently with bars; I'll leave that to @ChristianStade-Schuldt ;) To be fair, it's even easier to not connect these points as he suggested, but adding the lines helps disambiguate the points corresponding to separate time series from one another. In the end, it's still going to be a little subjective, so judge for yourself: I for one find myself drawing the lines in my mind anyway. BTW, if you feel the lines in the first figure detract anything from the visual impact of the exact points, don't forget that you can always increase the size of the points, change their shape, or present their values numerically in a separate table. Reference Anderson, J. A. (1984). Regression and ordered categorical variables. Journal of the Royal Statistical Society B, 46, 1–30.
Connecting the dots in a graph IMHO, whoever first omitted the precise timing of changes in number of cars is the first one responsible for any misleading results. If you had this information (even if measured with error), time wou
35,488
Connecting the dots in a graph
A continuous line indicates a continuum. If averages should be plotted, I would consider either using a bar diagram or a stair-step diagram. Plotting individual points is also possible, and when averages are concerned, you can probably add standard deviation information as necessary.
Connecting the dots in a graph
A continuous line indicates a continuum. If averages should be plotted, I would consider either using a bar diagram or a stair-step diagram. Plotting individual points is also possible, and when avera
Connecting the dots in a graph A continuous line indicates a continuum. If averages should be plotted, I would consider either using a bar diagram or a stair-step diagram. Plotting individual points is also possible, and when averages are concerned, you can probably add standard deviation information as necessary.
Connecting the dots in a graph A continuous line indicates a continuum. If averages should be plotted, I would consider either using a bar diagram or a stair-step diagram. Plotting individual points is also possible, and when avera
35,489
Connecting the dots in a graph
I would not connect those points because those are discrete values. Depending on the amount of data points you could either use a column/bar chart or just points.
Connecting the dots in a graph
I would not connect those points because those are discrete values. Depending on the amount of data points you could either use a column/bar chart or just points.
Connecting the dots in a graph I would not connect those points because those are discrete values. Depending on the amount of data points you could either use a column/bar chart or just points.
Connecting the dots in a graph I would not connect those points because those are discrete values. Depending on the amount of data points you could either use a column/bar chart or just points.
35,490
How to model football (soccer) scores
The state of the art for football prediction - that can be found in the academic literature - is Dixon and Robinson (1998) "A Birth Process Model for Association Football Matches", available without a pay wall here: http://www2.imperial.ac.uk/~ejm/M3S4/Problems/football.pdf Their model of interacting non-homogeneous Poisson processes accounts for these two key phenomena which independent Poisson distributions cannot: Rising goal rates. More goals are scored at the end of matches than at the start Scoreline dependent goal rates. Teams have a tendency to be motivated or demotivated depending on the scoreline. Such effects are different for the home and away teams It is this second point which you are referring to whereby teams with a comfortable lead have a drop off in their rate of scoring goals.
How to model football (soccer) scores
The state of the art for football prediction - that can be found in the academic literature - is Dixon and Robinson (1998) "A Birth Process Model for Association Football Matches", available without a
How to model football (soccer) scores The state of the art for football prediction - that can be found in the academic literature - is Dixon and Robinson (1998) "A Birth Process Model for Association Football Matches", available without a pay wall here: http://www2.imperial.ac.uk/~ejm/M3S4/Problems/football.pdf Their model of interacting non-homogeneous Poisson processes accounts for these two key phenomena which independent Poisson distributions cannot: Rising goal rates. More goals are scored at the end of matches than at the start Scoreline dependent goal rates. Teams have a tendency to be motivated or demotivated depending on the scoreline. Such effects are different for the home and away teams It is this second point which you are referring to whereby teams with a comfortable lead have a drop off in their rate of scoring goals.
How to model football (soccer) scores The state of the art for football prediction - that can be found in the academic literature - is Dixon and Robinson (1998) "A Birth Process Model for Association Football Matches", available without a
35,491
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior?
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior? Generally speaking, you do need to - it's just that sometimes it's so easy that you might not notice you did it. With 'textbook' problems you can often take $\pi(x|\theta) \propto L_x(\theta)\pi(\theta)$, then play about with the result and recognize the density function, at which point you've computed what the normalizing constant must have been - the thing required to scale your $L_x(\theta)\pi(\theta)$ so it integrates to 1. Since it's a pdf you know it integrates to 1, and since it's proportional to $ L_x(\theta)\pi(\theta)$, you know you have divided by the integral of that. With cases where that doesn't work there are often a few choices. One is numerical integration - you can integrate $ L_x(\theta)\pi(\theta)$ to work out the normalizing constant. So then you can compute expectations, and so on. Another is sampling; maybe you can't find the integral but you can bound it and use rejection smapling, or approximate it and use Metropolis-Hastings etc. With a sample from the posterior, you can again find means or other quantities as needed, or get a good approximation to the density or the cdf. There are other approaches.
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior? Generally speaking, you do need to - it's just that sometimes it's so easy that you mig
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior? Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior? Generally speaking, you do need to - it's just that sometimes it's so easy that you might not notice you did it. With 'textbook' problems you can often take $\pi(x|\theta) \propto L_x(\theta)\pi(\theta)$, then play about with the result and recognize the density function, at which point you've computed what the normalizing constant must have been - the thing required to scale your $L_x(\theta)\pi(\theta)$ so it integrates to 1. Since it's a pdf you know it integrates to 1, and since it's proportional to $ L_x(\theta)\pi(\theta)$, you know you have divided by the integral of that. With cases where that doesn't work there are often a few choices. One is numerical integration - you can integrate $ L_x(\theta)\pi(\theta)$ to work out the normalizing constant. So then you can compute expectations, and so on. Another is sampling; maybe you can't find the integral but you can bound it and use rejection smapling, or approximate it and use Metropolis-Hastings etc. With a sample from the posterior, you can again find means or other quantities as needed, or get a good approximation to the density or the cdf. There are other approaches.
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior? Generally speaking, you do need to - it's just that sometimes it's so easy that you mig
35,492
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior?
Your problem is equivalent to the following: Suppose you have a function $f(x)$ such that $\int f(x) dx < \infty$, and you are looking for a constant $c$ such that $\int cf(x) dx = 1$. Clearly, $c = 1/ \int f(x) dx$ would work, but perhaps it isn't easy to compute $\int f(x) dx$. In your quest to find $c$, perhaps you find a probability density function $g(x)$ (integrates to $1$) that shares the same "form" as $f(x)$. That is $g(x) = d f(x)$ for some constant $d$. Then $1 = \int g(x) dx = \int d f(x) dx$ and hence $c = d$. In other words, multiplying $f(x)$ by $c$ gives us the density function $g(x)$. This is the same logic that allows us to find the posterior distribution by recognizing the functional form of the density.
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian
Your problem is equivalent to the following: Suppose you have a function $f(x)$ such that $\int f(x) dx < \infty$, and you are looking for a constant $c$ such that $\int cf(x) dx = 1$. Clearly, $c = 1
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior? Your problem is equivalent to the following: Suppose you have a function $f(x)$ such that $\int f(x) dx < \infty$, and you are looking for a constant $c$ such that $\int cf(x) dx = 1$. Clearly, $c = 1/ \int f(x) dx$ would work, but perhaps it isn't easy to compute $\int f(x) dx$. In your quest to find $c$, perhaps you find a probability density function $g(x)$ (integrates to $1$) that shares the same "form" as $f(x)$. That is $g(x) = d f(x)$ for some constant $d$. Then $1 = \int g(x) dx = \int d f(x) dx$ and hence $c = d$. In other words, multiplying $f(x)$ by $c$ gives us the density function $g(x)$. This is the same logic that allows us to find the posterior distribution by recognizing the functional form of the density.
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian Your problem is equivalent to the following: Suppose you have a function $f(x)$ such that $\int f(x) dx < \infty$, and you are looking for a constant $c$ such that $\int cf(x) dx = 1$. Clearly, $c = 1
35,493
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior?
The "formal proof" you are looking for is called Bayes' Theorem (see also Posterior probability) which states that: $$\pi(\theta\vert{\bf x}) = \dfrac{f({\bf x}\vert\theta)\pi(\theta)}{\pi({\bf x})}.$$ The left-hand side represents the posterior distribution and IT IS a distribution as long as the prior is proper. From this expression you can identify $f({\bf x}\vert\theta)$ as the likelihood function $L(\theta;{\bf x})$ and you can also see that $\pi({\bf x})$ does not depend upon $\theta$. Therefore $$\pi(\theta\vert{\bf x}) \propto L(\theta;{\bf x})\pi(\theta).$$ Also, note that it should be $\theta\vert{\bf x}$ and not the other way round. $f({\bf x}\vert \theta)$ is the likelihood function, which is not a distribution as a function of $\theta$, tipically. Discussion: In Bayesian statistics it is impossible, for non trivial examples, to identify what sort of distribution is this (e.g. normal, student-t ...). Then, the use of MCMC methods is often necessary to sample from the posterior and to conduct a Bayesian data analysis. MCMC methods require the evaluation of the posterior up to a proportionality constant. For this reason, it is not necessary to calculate $\pi({\bf x})$. However, for Bayesian model comparison you need to obtain a numerical approximation of this quantity, given that the Bayes factors are defined in terms of the normalising constant.
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian
The "formal proof" you are looking for is called Bayes' Theorem (see also Posterior probability) which states that: $$\pi(\theta\vert{\bf x}) = \dfrac{f({\bf x}\vert\theta)\pi(\theta)}{\pi({\bf x})}.$
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior? The "formal proof" you are looking for is called Bayes' Theorem (see also Posterior probability) which states that: $$\pi(\theta\vert{\bf x}) = \dfrac{f({\bf x}\vert\theta)\pi(\theta)}{\pi({\bf x})}.$$ The left-hand side represents the posterior distribution and IT IS a distribution as long as the prior is proper. From this expression you can identify $f({\bf x}\vert\theta)$ as the likelihood function $L(\theta;{\bf x})$ and you can also see that $\pi({\bf x})$ does not depend upon $\theta$. Therefore $$\pi(\theta\vert{\bf x}) \propto L(\theta;{\bf x})\pi(\theta).$$ Also, note that it should be $\theta\vert{\bf x}$ and not the other way round. $f({\bf x}\vert \theta)$ is the likelihood function, which is not a distribution as a function of $\theta$, tipically. Discussion: In Bayesian statistics it is impossible, for non trivial examples, to identify what sort of distribution is this (e.g. normal, student-t ...). Then, the use of MCMC methods is often necessary to sample from the posterior and to conduct a Bayesian data analysis. MCMC methods require the evaluation of the posterior up to a proportionality constant. For this reason, it is not necessary to calculate $\pi({\bf x})$. However, for Bayesian model comparison you need to obtain a numerical approximation of this quantity, given that the Bayes factors are defined in terms of the normalising constant.
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian The "formal proof" you are looking for is called Bayes' Theorem (see also Posterior probability) which states that: $$\pi(\theta\vert{\bf x}) = \dfrac{f({\bf x}\vert\theta)\pi(\theta)}{\pi({\bf x})}.$
35,494
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior?
$$π(θ|x)=[f(x|θ)π(θ)]/π(x)$$ In simple terms, the denominator, or the marginal distribution of the RHS of your Bayes theorem is just a constant that is used to make the RHS numerator a pdf. If you know what kind of distribution your RHS numerator, i.e, the Likelihood function * prior distribution follows, then you can find out the denominator(marginal) easily. For example, if your prior is uniform and your likelihood function is a Binomial, then your posterior will be proportional to a Beta distribution. You can now easily find out the constants for a Beta Distribution.
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian
$$π(θ|x)=[f(x|θ)π(θ)]/π(x)$$ In simple terms, the denominator, or the marginal distribution of the RHS of your Bayes theorem is just a constant that is used to make the RHS numerator a pdf. If you kno
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian posterior? $$π(θ|x)=[f(x|θ)π(θ)]/π(x)$$ In simple terms, the denominator, or the marginal distribution of the RHS of your Bayes theorem is just a constant that is used to make the RHS numerator a pdf. If you know what kind of distribution your RHS numerator, i.e, the Likelihood function * prior distribution follows, then you can find out the denominator(marginal) easily. For example, if your prior is uniform and your likelihood function is a Binomial, then your posterior will be proportional to a Beta distribution. You can now easily find out the constants for a Beta Distribution.
Theoretically, why do we not need to compute a marginal distribution constant for finding a Bayesian $$π(θ|x)=[f(x|θ)π(θ)]/π(x)$$ In simple terms, the denominator, or the marginal distribution of the RHS of your Bayes theorem is just a constant that is used to make the RHS numerator a pdf. If you kno
35,495
Robust monotonic regression in R
I note that after you delete the last point, you only have seven values of which two (28.6%!) are outliers. Many robust methods don't have a breakdown point quite that high (e.g., Theil regression breaks down right at that point for n=7, though at large $n$ it goes to 29.3%), but if you must have such a high breakdown that it can manage so many outliers, you need to choose some approach that actually has that higher breakdown point. There are some available in R; the rlm function in MASS (M-estimation) should deal with this particular case (it has high breakdown against y-outliers), but it won't have robustness to influential outliers. Function lqs in the same package should deal with influential outliers, or there are a number of good packages for robust regression on CRAN. You may find Fox and Weisberg's Robust Regression in R (pdf) a useful resource on several robust regression concepts. All this is just dealing with robust linear regression and is ignoring the monotonicity constraint, but I imagine that will be less of a problem if you get the breakdown issue sorted. If you're still getting negative slope after performing high-breakdown robust regression, but want a nondecreasing line, you would set the line to have slope zero - i.e. choose a robust location estimate and set the line to be constant there. (If you want robust nonlinear-but-monotonic regression, you should mention that specifically.) In response to the edit: You seem to have interpreted my example of the Theil regression as a comment about the breakdown point of line. It was not; it was simply the first example of a robust line that came to me which broke down at a smaller proportion of contamination. As whuber already explained, we can't easily tell which of several lines is being used by line. The reason why line breaks down as it does depends on which of several possible robust estimators that Tukey mentions and line might use. For example, if it's the line that goes 'split data into three groups and for the slope use the slope of the line joining the medians of the outer two thirds' (sometimes called the three-group resistant line, or the median-median line), then its breakdown point is asymptotically 1/6, and its behavior in small samples depends on exactly how the points are allocated to the groups when $n$ is not a multiple of 3. Please note that I am not saying it is the three group resistant line that is implemented in line - in fact I think it isn't - but simply that whatever they have implemented in line may well have a breakdown point such that the resulting line cannot deal with 2 odd points out of 8, if they're in the 'right' positions. In fact the line that is implemented in line has some bizarre behavior - so odd that I wonder if it might have a bug - if you do this: x = y = 1:9 #all points lie on a line with slope 1 plot(x,y) abline(line(x,y),col=2) Then the line line has slope 1.2: Off the top of my head, I don't recall any of Tukey's lines having that behavior. Added much later: I reported this problem to the developers some time ago; it took a couple of releases before it was fixed but now line (which did turn out to be a form of Tukey's three group line) no longer has this bug; it now seems to behave as I'd expect it to in all instances I have tried.
Robust monotonic regression in R
I note that after you delete the last point, you only have seven values of which two (28.6%!) are outliers. Many robust methods don't have a breakdown point quite that high (e.g., Theil regression bre
Robust monotonic regression in R I note that after you delete the last point, you only have seven values of which two (28.6%!) are outliers. Many robust methods don't have a breakdown point quite that high (e.g., Theil regression breaks down right at that point for n=7, though at large $n$ it goes to 29.3%), but if you must have such a high breakdown that it can manage so many outliers, you need to choose some approach that actually has that higher breakdown point. There are some available in R; the rlm function in MASS (M-estimation) should deal with this particular case (it has high breakdown against y-outliers), but it won't have robustness to influential outliers. Function lqs in the same package should deal with influential outliers, or there are a number of good packages for robust regression on CRAN. You may find Fox and Weisberg's Robust Regression in R (pdf) a useful resource on several robust regression concepts. All this is just dealing with robust linear regression and is ignoring the monotonicity constraint, but I imagine that will be less of a problem if you get the breakdown issue sorted. If you're still getting negative slope after performing high-breakdown robust regression, but want a nondecreasing line, you would set the line to have slope zero - i.e. choose a robust location estimate and set the line to be constant there. (If you want robust nonlinear-but-monotonic regression, you should mention that specifically.) In response to the edit: You seem to have interpreted my example of the Theil regression as a comment about the breakdown point of line. It was not; it was simply the first example of a robust line that came to me which broke down at a smaller proportion of contamination. As whuber already explained, we can't easily tell which of several lines is being used by line. The reason why line breaks down as it does depends on which of several possible robust estimators that Tukey mentions and line might use. For example, if it's the line that goes 'split data into three groups and for the slope use the slope of the line joining the medians of the outer two thirds' (sometimes called the three-group resistant line, or the median-median line), then its breakdown point is asymptotically 1/6, and its behavior in small samples depends on exactly how the points are allocated to the groups when $n$ is not a multiple of 3. Please note that I am not saying it is the three group resistant line that is implemented in line - in fact I think it isn't - but simply that whatever they have implemented in line may well have a breakdown point such that the resulting line cannot deal with 2 odd points out of 8, if they're in the 'right' positions. In fact the line that is implemented in line has some bizarre behavior - so odd that I wonder if it might have a bug - if you do this: x = y = 1:9 #all points lie on a line with slope 1 plot(x,y) abline(line(x,y),col=2) Then the line line has slope 1.2: Off the top of my head, I don't recall any of Tukey's lines having that behavior. Added much later: I reported this problem to the developers some time ago; it took a couple of releases before it was fixed but now line (which did turn out to be a form of Tukey's three group line) no longer has this bug; it now seems to behave as I'd expect it to in all instances I have tried.
Robust monotonic regression in R I note that after you delete the last point, you only have seven values of which two (28.6%!) are outliers. Many robust methods don't have a breakdown point quite that high (e.g., Theil regression bre
35,496
What's the activation function used in the nodes of hidden layer from nnet library in R?
This is the implemented function (extracted from the C-sources; filennet.c, lines 156-165): static double sigmoid(double sum) { if (sum < -15.0) return (0.0); else if (sum > 15.0) return (1.0); else return (1.0 / (1.0 + exp(-sum))); }
What's the activation function used in the nodes of hidden layer from nnet library in R?
This is the implemented function (extracted from the C-sources; filennet.c, lines 156-165): static double sigmoid(double sum) { if (sum < -15.0) return (0.0); else if (sum > 15.0) retu
What's the activation function used in the nodes of hidden layer from nnet library in R? This is the implemented function (extracted from the C-sources; filennet.c, lines 156-165): static double sigmoid(double sum) { if (sum < -15.0) return (0.0); else if (sum > 15.0) return (1.0); else return (1.0 / (1.0 + exp(-sum))); }
What's the activation function used in the nodes of hidden layer from nnet library in R? This is the implemented function (extracted from the C-sources; filennet.c, lines 156-165): static double sigmoid(double sum) { if (sum < -15.0) return (0.0); else if (sum > 15.0) retu
35,497
High concordance in cox PH model even though PH assumption is violated
In reverse order: 3) The concordance is simply the proportion of pairs of cases in which the case with the higher-risk predictor had an event before the case with the lower-risk predictor. With a single numeric predictor, the concordance will be the same for any monotone transformation of the predictor even though the Cox model fits may be substantially different. Crudely put, concordance shows your ability to predict who of a pair will die sooner, but not necessarily how much sooner or what proportion of the variance of event times is explained by the model. Concordance for a multivariate model uses the combined linear predictor from the Cox regression as the numeric predictor for each case. So if variables with non-proportional hazards have small-magnitude coefficients compared with other variables, or if their relations to outcome are strong enough despite non-proportionality, the rankings of combined linear predictors may be well correlated with the rankings of event times--which is all that concordance tells you. 2) Absent the PH assumption, HRs aren't strictly valid and can be highly misleading. Think about the corresponding case of a linear-regression fit of data that are not linearly related. 1) Main consequence is that you should examine variables that don't meet the PH assumption in more detail. Consider stratifying by those variables, or devising time-dependent models.
High concordance in cox PH model even though PH assumption is violated
In reverse order: 3) The concordance is simply the proportion of pairs of cases in which the case with the higher-risk predictor had an event before the case with the lower-risk predictor. With a sing
High concordance in cox PH model even though PH assumption is violated In reverse order: 3) The concordance is simply the proportion of pairs of cases in which the case with the higher-risk predictor had an event before the case with the lower-risk predictor. With a single numeric predictor, the concordance will be the same for any monotone transformation of the predictor even though the Cox model fits may be substantially different. Crudely put, concordance shows your ability to predict who of a pair will die sooner, but not necessarily how much sooner or what proportion of the variance of event times is explained by the model. Concordance for a multivariate model uses the combined linear predictor from the Cox regression as the numeric predictor for each case. So if variables with non-proportional hazards have small-magnitude coefficients compared with other variables, or if their relations to outcome are strong enough despite non-proportionality, the rankings of combined linear predictors may be well correlated with the rankings of event times--which is all that concordance tells you. 2) Absent the PH assumption, HRs aren't strictly valid and can be highly misleading. Think about the corresponding case of a linear-regression fit of data that are not linearly related. 1) Main consequence is that you should examine variables that don't meet the PH assumption in more detail. Consider stratifying by those variables, or devising time-dependent models.
High concordance in cox PH model even though PH assumption is violated In reverse order: 3) The concordance is simply the proportion of pairs of cases in which the case with the higher-risk predictor had an event before the case with the lower-risk predictor. With a sing
35,498
Is the residual, e, an estimator of the error, $\epsilon$?
Certainly the residuals are some sort of estimators of $\epsilon$ (to be clear, the definition of the residual is the estimator, the observed residual is an estimate). If the model is correct, then they may sometimes be a fairly good estimate. Indeed $e = y - \hat y = X\beta + \epsilon - X(X'X)^{-1} X'(X\beta + \epsilon) = (I - H)\epsilon$, where $H = X(X'X)^{-1} X'$ is the hat-matrix (because it 'puts the hat on' $y$) -- also sometimes called the projection matrix. http://en.wikipedia.org/wiki/Hat_matrix That is, the $e$'s are each a linear combination of the $\epsilon$'s; if $1-h_{ii}$ is reasonably big relative to $\sum_{j\neq i}h_{ij}$ (if $H$ is 'small' relative to I), then most of the weight is on the $i^\textrm{th}$ error (this is frequently not the case, though). Note that $e_i/\sqrt{1-h_{ii}}$ will have the same expectation and variance as $\epsilon_i$ and if the elements of $H$ are small, in the manner just described, will be highly correlated with it -- in fact, if I have done my algebra right, the correlation between $e_i$ and $\epsilon_i$ is actually: $\text{corr}(e_i,\epsilon_i) = \sqrt{1-h_{ii}}$.
Is the residual, e, an estimator of the error, $\epsilon$?
Certainly the residuals are some sort of estimators of $\epsilon$ (to be clear, the definition of the residual is the estimator, the observed residual is an estimate). If the model is correct, then t
Is the residual, e, an estimator of the error, $\epsilon$? Certainly the residuals are some sort of estimators of $\epsilon$ (to be clear, the definition of the residual is the estimator, the observed residual is an estimate). If the model is correct, then they may sometimes be a fairly good estimate. Indeed $e = y - \hat y = X\beta + \epsilon - X(X'X)^{-1} X'(X\beta + \epsilon) = (I - H)\epsilon$, where $H = X(X'X)^{-1} X'$ is the hat-matrix (because it 'puts the hat on' $y$) -- also sometimes called the projection matrix. http://en.wikipedia.org/wiki/Hat_matrix That is, the $e$'s are each a linear combination of the $\epsilon$'s; if $1-h_{ii}$ is reasonably big relative to $\sum_{j\neq i}h_{ij}$ (if $H$ is 'small' relative to I), then most of the weight is on the $i^\textrm{th}$ error (this is frequently not the case, though). Note that $e_i/\sqrt{1-h_{ii}}$ will have the same expectation and variance as $\epsilon_i$ and if the elements of $H$ are small, in the manner just described, will be highly correlated with it -- in fact, if I have done my algebra right, the correlation between $e_i$ and $\epsilon_i$ is actually: $\text{corr}(e_i,\epsilon_i) = \sqrt{1-h_{ii}}$.
Is the residual, e, an estimator of the error, $\epsilon$? Certainly the residuals are some sort of estimators of $\epsilon$ (to be clear, the definition of the residual is the estimator, the observed residual is an estimate). If the model is correct, then t
35,499
Is a large control sample better than a balanced sample size when the treatment group is small?
Your colleagues are incorrect. It's possible that they're basing their suggestion on the fact that the robustness of typical parametric tests, like a t-test, to violations of assumptions is severely compromised with imbalanced N's. But if you don't violate them then a higher N is better, even if unbalanced. And you can always examine the effect of any violations through simulation. An easy way to imagine why sampling 8 of the 100 control subjects is a bad idea, is to picture two graphs of your data that differ by the control group. Each has the patient and control brain volume measures and a confidence interval (CI) around each measure. In each graph the CI around the test group is going to be the same. But the CI around the control group will be much smaller with the full set of 100 than it will be around a sample of 8. Which graph would you like to present? Other questions to ask yourself when deciding whether to use all 100 control samples or only 8 include: Which do you think has a better estimate of the control mean? Which would have a better estimate of the control variance? Which is more representative of the population? The answer to all of these questions is the larger group. And relating accurate estimates of your parameters is substantially more important than issues you may have with a particular test. NOTE: It's remotely possible that the control sample of 8 CI could be smaller than the one for the full control group. However, that would likely mean that your control sample of 8 is a terrible sample and further highlights why you want to stick with the full data set.
Is a large control sample better than a balanced sample size when the treatment group is small?
Your colleagues are incorrect. It's possible that they're basing their suggestion on the fact that the robustness of typical parametric tests, like a t-test, to violations of assumptions is severely
Is a large control sample better than a balanced sample size when the treatment group is small? Your colleagues are incorrect. It's possible that they're basing their suggestion on the fact that the robustness of typical parametric tests, like a t-test, to violations of assumptions is severely compromised with imbalanced N's. But if you don't violate them then a higher N is better, even if unbalanced. And you can always examine the effect of any violations through simulation. An easy way to imagine why sampling 8 of the 100 control subjects is a bad idea, is to picture two graphs of your data that differ by the control group. Each has the patient and control brain volume measures and a confidence interval (CI) around each measure. In each graph the CI around the test group is going to be the same. But the CI around the control group will be much smaller with the full set of 100 than it will be around a sample of 8. Which graph would you like to present? Other questions to ask yourself when deciding whether to use all 100 control samples or only 8 include: Which do you think has a better estimate of the control mean? Which would have a better estimate of the control variance? Which is more representative of the population? The answer to all of these questions is the larger group. And relating accurate estimates of your parameters is substantially more important than issues you may have with a particular test. NOTE: It's remotely possible that the control sample of 8 CI could be smaller than the one for the full control group. However, that would likely mean that your control sample of 8 is a terrible sample and further highlights why you want to stick with the full data set.
Is a large control sample better than a balanced sample size when the treatment group is small? Your colleagues are incorrect. It's possible that they're basing their suggestion on the fact that the robustness of typical parametric tests, like a t-test, to violations of assumptions is severely
35,500
Non-random small sample - What conclusions can I get?
whuber is right that, technically, statistical inference will not be accurate if randomization was not used. However, in practice, random sampling is often impossible, so it is common (and inevitable and unfortunate) practice that people use inference on non-random samples and generalize the results to the entire population from which the sample was drawn. The actual conclusions that you can confidently make is to simply describe the sample without generalizing the results to others in the population. For example, let's say group 1 had a higher average score on a certain test than group 2. You can conclude that, among the children you measured, group 1 scored higher on the test than group 2. In this case, you are only comparing the 5 children in group1 with the 5 in group 2, and inference is not used (i.e., p-vaues and confidence intervals would not make sense). Simply calculate descriptive statistics such as mean, median, population standard deviation, etc. to describe your data. Keep in mind that you can still run various tests or calculate effect sizes without using inference. For example, you can calculate Cohen's d between group 1 and 2 on a test. You can use ANCOVA and find the mean difference of test score between the groups while controlling for the effect of age and gender. I think some people do not realize that things like ANOVA or multiple regression can be used for descriptive statistics.
Non-random small sample - What conclusions can I get?
whuber is right that, technically, statistical inference will not be accurate if randomization was not used. However, in practice, random sampling is often impossible, so it is common (and inevitable
Non-random small sample - What conclusions can I get? whuber is right that, technically, statistical inference will not be accurate if randomization was not used. However, in practice, random sampling is often impossible, so it is common (and inevitable and unfortunate) practice that people use inference on non-random samples and generalize the results to the entire population from which the sample was drawn. The actual conclusions that you can confidently make is to simply describe the sample without generalizing the results to others in the population. For example, let's say group 1 had a higher average score on a certain test than group 2. You can conclude that, among the children you measured, group 1 scored higher on the test than group 2. In this case, you are only comparing the 5 children in group1 with the 5 in group 2, and inference is not used (i.e., p-vaues and confidence intervals would not make sense). Simply calculate descriptive statistics such as mean, median, population standard deviation, etc. to describe your data. Keep in mind that you can still run various tests or calculate effect sizes without using inference. For example, you can calculate Cohen's d between group 1 and 2 on a test. You can use ANCOVA and find the mean difference of test score between the groups while controlling for the effect of age and gender. I think some people do not realize that things like ANOVA or multiple regression can be used for descriptive statistics.
Non-random small sample - What conclusions can I get? whuber is right that, technically, statistical inference will not be accurate if randomization was not used. However, in practice, random sampling is often impossible, so it is common (and inevitable