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
45,401
simulate dirichlet process in R
With certainty, realizations of a Dirichlet Process are probability measures with countable support, as proved by D. Blackwell, The Annals of Statistics 1 (1973), no. 2, 356--358. You can sample realizations from a Dirichlet Process using the constructive stick-breaking representation introduced by J. Sethuraman, Statistica Sinica, 4, 639 (1994). For a Dirichlet process with concentration parameter $c>0$ and centered at some distribution function $\mathbb{G}_0$, you must draw independent random variables $$ B_i\sim \mathrm{Beta}(1,c)\,, $$ and compute $$ P_1=B_1 \, , \qquad P_i=B_i \prod_{j=1}^{i-1}(1-B_j)\, , \qquad i>1 \, , $$ until for some $n\geq 1$ you have $\sum_{i=1}^n P_i\geq 1-\epsilon$, for some $0<\epsilon<1$. Then, drawing independent $Y_i\sim\mathbb{G}_0$, for $i=1,\dots,n$, the (truncated) approximate realization of the Dirichlet Process is the distribution function $$ H(t) = \sum_{i=1}^n P_i\,I_{[Y_i,\infty)}(t) \, . $$ To sample the $\theta_i$'s from this approximate realization of the Dirichlet Process use R's sample with replacement from the $Y_i$'s with probabilities given by the $P_i$'s. Memory is so cheap nowadays that a more practical way to do the truncation is by taking $n$ "big enough". Here is an example with $c=2$ and $\mathbb{G}_0$ equal to the $\mathrm{N}(0,10)$ distribution function. c <- 2 G_0 <- function(n) rnorm(n, 0, 10) n <- 100 b <- rbeta(n, 1, c) p <- numeric(n) p[1] <- b[1] p[2:n] <- sapply(2:n, function(i) b[i] * prod(1 - b[1:(i-1)])) y <- G_0(n) theta <- sample(y, prob = p, replace = TRUE)
simulate dirichlet process in R
With certainty, realizations of a Dirichlet Process are probability measures with countable support, as proved by D. Blackwell, The Annals of Statistics 1 (1973), no. 2, 356--358. You can sample reali
simulate dirichlet process in R With certainty, realizations of a Dirichlet Process are probability measures with countable support, as proved by D. Blackwell, The Annals of Statistics 1 (1973), no. 2, 356--358. You can sample realizations from a Dirichlet Process using the constructive stick-breaking representation introduced by J. Sethuraman, Statistica Sinica, 4, 639 (1994). For a Dirichlet process with concentration parameter $c>0$ and centered at some distribution function $\mathbb{G}_0$, you must draw independent random variables $$ B_i\sim \mathrm{Beta}(1,c)\,, $$ and compute $$ P_1=B_1 \, , \qquad P_i=B_i \prod_{j=1}^{i-1}(1-B_j)\, , \qquad i>1 \, , $$ until for some $n\geq 1$ you have $\sum_{i=1}^n P_i\geq 1-\epsilon$, for some $0<\epsilon<1$. Then, drawing independent $Y_i\sim\mathbb{G}_0$, for $i=1,\dots,n$, the (truncated) approximate realization of the Dirichlet Process is the distribution function $$ H(t) = \sum_{i=1}^n P_i\,I_{[Y_i,\infty)}(t) \, . $$ To sample the $\theta_i$'s from this approximate realization of the Dirichlet Process use R's sample with replacement from the $Y_i$'s with probabilities given by the $P_i$'s. Memory is so cheap nowadays that a more practical way to do the truncation is by taking $n$ "big enough". Here is an example with $c=2$ and $\mathbb{G}_0$ equal to the $\mathrm{N}(0,10)$ distribution function. c <- 2 G_0 <- function(n) rnorm(n, 0, 10) n <- 100 b <- rbeta(n, 1, c) p <- numeric(n) p[1] <- b[1] p[2:n] <- sapply(2:n, function(i) b[i] * prod(1 - b[1:(i-1)])) y <- G_0(n) theta <- sample(y, prob = p, replace = TRUE)
simulate dirichlet process in R With certainty, realizations of a Dirichlet Process are probability measures with countable support, as proved by D. Blackwell, The Annals of Statistics 1 (1973), no. 2, 356--358. You can sample reali
45,402
simulate dirichlet process in R
Check out the package DPackage in R. It has a lot of functionality for simulating from the Dirichlet Process. Here is a link to the documentation: DPackage. Zen's answer above is pretty good info as well.
simulate dirichlet process in R
Check out the package DPackage in R. It has a lot of functionality for simulating from the Dirichlet Process. Here is a link to the documentation: DPackage. Zen's answer above is pretty good info as w
simulate dirichlet process in R Check out the package DPackage in R. It has a lot of functionality for simulating from the Dirichlet Process. Here is a link to the documentation: DPackage. Zen's answer above is pretty good info as well.
simulate dirichlet process in R Check out the package DPackage in R. It has a lot of functionality for simulating from the Dirichlet Process. Here is a link to the documentation: DPackage. Zen's answer above is pretty good info as w
45,403
simulate dirichlet process in R
Not sure why sample(y, prob = p, replace = TRUE) from zen's answer is necessary. library(tidyverse) ##concentration parameter c <- 1000 ##base distribution G_0 <- function(n) rnorm(n, 0, 1) ##finite approximate realization of Dirichlet Process n <- 1000 b <- rbeta(n, 1, c) p <- numeric(n) p[1] <- b[1] p[2:n] <- sapply(2:n, function(i) b[i] * prod(1 - b[1:(i-1)])) ##check summation of p must be 1 sum(p) ##P(theta_i)=p_i where theta follows i.i.d G_0 theta <- G_0(n) ##plot is similar to https://en.wikipedia.org/wiki/File:Dirichlet_process_draws.svg df1 <- data.frame(theta = theta, p = p) df1 %>% ggplot(aes(x = theta , y = p)) + geom_col(color = "black") + xlim(-4,4)
simulate dirichlet process in R
Not sure why sample(y, prob = p, replace = TRUE) from zen's answer is necessary. library(tidyverse) ##concentration parameter c <- 1000 ##base distribution G_0 <- function(n) rnorm(n, 0, 1) ##finite
simulate dirichlet process in R Not sure why sample(y, prob = p, replace = TRUE) from zen's answer is necessary. library(tidyverse) ##concentration parameter c <- 1000 ##base distribution G_0 <- function(n) rnorm(n, 0, 1) ##finite approximate realization of Dirichlet Process n <- 1000 b <- rbeta(n, 1, c) p <- numeric(n) p[1] <- b[1] p[2:n] <- sapply(2:n, function(i) b[i] * prod(1 - b[1:(i-1)])) ##check summation of p must be 1 sum(p) ##P(theta_i)=p_i where theta follows i.i.d G_0 theta <- G_0(n) ##plot is similar to https://en.wikipedia.org/wiki/File:Dirichlet_process_draws.svg df1 <- data.frame(theta = theta, p = p) df1 %>% ggplot(aes(x = theta , y = p)) + geom_col(color = "black") + xlim(-4,4)
simulate dirichlet process in R Not sure why sample(y, prob = p, replace = TRUE) from zen's answer is necessary. library(tidyverse) ##concentration parameter c <- 1000 ##base distribution G_0 <- function(n) rnorm(n, 0, 1) ##finite
45,404
Bayes Decision Boundary and classifier
Yes, Bayes Classifier is the one which produces the lowest possible test error rate. This is I think best illustrated through an example. To simplify things a bit, let's say we have a simple two class classification problem. For example, we survey a group of students and collect their age, SAT scores and current GPA and want to predict whether they are going to fail a course or not. So in R it would be something like fail ~ age + sat.score + current.GPA Bayes classifier works by just looking at the probabilities for each combination of the features and assigning each instance to the class which has the probability bigger than 50%. Imagine that we do survey all the students that exist. Then in that case, the classifier would know correct probabilities for failing or not for all possible combination of features, and then it will give the best possible classification accuracy. However, this does not mean that it will be able to classify all instances correctly (i.e., to have 0% error rate) as this is impossible in most of the cases. In our example, it is very likely that some of the students would have the same values for all three features and yet some of them will fail while others won't. There is no single classifier which will give you 100% correct answer to this problem, as there is no way to differentiate between the students who failed or not (for a classifier, they look the same). Adding new features for example, previous knowledge or IQ etc might help, but then the problem definition would changed and that might improve the classification accuracy. Thus, if for example for a given combination of features 80% of students pass and only 20% fail, well, then the Bayesian classifier will predict that the students with that combination of features will pass the course, as that is more likely. This minimal possible error rate of the Bayesian classifier is called irreducible error and all classifiers exhibit it. Other classifiers besides this type of error also exhibit reducible error which can be described as resulting from good, but not perfect estimates of those probabilities. Given that most of the times we don't have this perfect information, the idea of different classification models is to make different assumption which will be good enough to produce high enough classification accuracy while not requiring to collect the data about the whole population. Read the full explanation in the "Introduction to statistical learning" by Hastie and Tibshiani http://www-bcf.usc.edu/~gareth/ISL/ (Page 38)
Bayes Decision Boundary and classifier
Yes, Bayes Classifier is the one which produces the lowest possible test error rate. This is I think best illustrated through an example. To simplify things a bit, let's say we have a simple two clas
Bayes Decision Boundary and classifier Yes, Bayes Classifier is the one which produces the lowest possible test error rate. This is I think best illustrated through an example. To simplify things a bit, let's say we have a simple two class classification problem. For example, we survey a group of students and collect their age, SAT scores and current GPA and want to predict whether they are going to fail a course or not. So in R it would be something like fail ~ age + sat.score + current.GPA Bayes classifier works by just looking at the probabilities for each combination of the features and assigning each instance to the class which has the probability bigger than 50%. Imagine that we do survey all the students that exist. Then in that case, the classifier would know correct probabilities for failing or not for all possible combination of features, and then it will give the best possible classification accuracy. However, this does not mean that it will be able to classify all instances correctly (i.e., to have 0% error rate) as this is impossible in most of the cases. In our example, it is very likely that some of the students would have the same values for all three features and yet some of them will fail while others won't. There is no single classifier which will give you 100% correct answer to this problem, as there is no way to differentiate between the students who failed or not (for a classifier, they look the same). Adding new features for example, previous knowledge or IQ etc might help, but then the problem definition would changed and that might improve the classification accuracy. Thus, if for example for a given combination of features 80% of students pass and only 20% fail, well, then the Bayesian classifier will predict that the students with that combination of features will pass the course, as that is more likely. This minimal possible error rate of the Bayesian classifier is called irreducible error and all classifiers exhibit it. Other classifiers besides this type of error also exhibit reducible error which can be described as resulting from good, but not perfect estimates of those probabilities. Given that most of the times we don't have this perfect information, the idea of different classification models is to make different assumption which will be good enough to produce high enough classification accuracy while not requiring to collect the data about the whole population. Read the full explanation in the "Introduction to statistical learning" by Hastie and Tibshiani http://www-bcf.usc.edu/~gareth/ISL/ (Page 38)
Bayes Decision Boundary and classifier Yes, Bayes Classifier is the one which produces the lowest possible test error rate. This is I think best illustrated through an example. To simplify things a bit, let's say we have a simple two clas
45,405
How to select tuning parameter for regularized regressions for interpretation?
I'd like to try answer your main question, here are two options: Use the one-standard-error (1SE) rule When cross-validating for selection purposes, it can help to use the 1SE rule. The standard error of the CV estimate is calculated for each fold. Instead of selecting the model corresponding to the minimum CV error, use the most parsimonious model where the CV error is within one standard error of the minimum. The R package glmnet does this automatically - select lambda.1se instead of lambda.min. The 1SE rule can help select the correct model using LASSO but the estimates could suffer large bias. Usually a large tuning parameter is necessary to set coefficients to zero (especially if there are many that are zero). LASSO shrinks coefficients equally, so the large tuning parameter can overshrink large coefficients and this causes the large bias. Shrinkage is supposed to introduce slight bias but with a substantial decrease in variance, which causes lower prediction error. In this case, the bias is large! Edit: Some authors propose overcoming the bias by using the LASSO for variable selection and then estimating the parameters of the selected subset using least squares - see for example the LARS-OLS Hybrid, or thresholding the LASSO discussed by Bühlmann and van de Geer (2011) Use the adaptive LASSO or relaxed LASSO The LASSO often includes too many variables when selecting the tuning parameter for prediction (minimum CV error). But, with high probability, the true model is a subset of these variables. This suggests using a secondary stage of estimation. The adaptive LASSO and relaxed LASSO both achieve this and control the bias of the LASSO estimate. Using either method, the prediction-optimal tuning parameter leads to consistent selection. The R package relaxo implements relaxed LASSO. For adaptive LASSO, you need an initial estimate, either least squares, ridge or even LASSO estimates, to calculate weights. Then you can implement it using the same function that you would for LASSO by scaling the X matrix: w <- abs(beta.init) x2 <- scale(x, center=FALSE, scale=1/w) Select tuning parameter and estimate coefficients (coef) using x2 coef <- coef*w Edit: I've come across a few other criteria which can be used for variable selection with the LASSO: Wang, et al (2009) proposed a modified BIC criterion and show that it is consistent. Basically a factor $C_{n}$ is multiplied to the BIC penalty. They chose $C_{n}=log(log(p))$ when $p$ varies with $n$. For fixed $p$, Chand (2012) showed consistency using $C_{n}=\sqrt n/p$. Fan and Tang (2013) proposed a generalized version for use when $p>n$. Roberts and Nowak (2014) propose using percentile CV, repeatedly performing cross-validation to yield a vector of tuning parameter estimates and then selecting the optimal one as the 95% percentile of that vector. Sun, et al (2013) propose using Cohen's kappa coefficient which measures the agreement between two sets. Fang, et al (2013) take the ratio of the average kappa coefficient and the average CV error, which they call PASS. These two methods can be implemented using the R package pass. In my conference paper I have done simulations studies to compare the performance of tuning parameter selection methods for the LASSO, both for prediction and variable selection purposes. For variable selection, I implemented the 1SE rule with 5 fold- and 10 fold CV, percentile CV, kappa, PASS, BIC and the modified BIC. The results show that most of these methods do perform better variable selection than prediction methods such as k fold CV, LOOCV, GCV, Cp and AIC.
How to select tuning parameter for regularized regressions for interpretation?
I'd like to try answer your main question, here are two options: Use the one-standard-error (1SE) rule When cross-validating for selection purposes, it can help to use the 1SE rule. The standard er
How to select tuning parameter for regularized regressions for interpretation? I'd like to try answer your main question, here are two options: Use the one-standard-error (1SE) rule When cross-validating for selection purposes, it can help to use the 1SE rule. The standard error of the CV estimate is calculated for each fold. Instead of selecting the model corresponding to the minimum CV error, use the most parsimonious model where the CV error is within one standard error of the minimum. The R package glmnet does this automatically - select lambda.1se instead of lambda.min. The 1SE rule can help select the correct model using LASSO but the estimates could suffer large bias. Usually a large tuning parameter is necessary to set coefficients to zero (especially if there are many that are zero). LASSO shrinks coefficients equally, so the large tuning parameter can overshrink large coefficients and this causes the large bias. Shrinkage is supposed to introduce slight bias but with a substantial decrease in variance, which causes lower prediction error. In this case, the bias is large! Edit: Some authors propose overcoming the bias by using the LASSO for variable selection and then estimating the parameters of the selected subset using least squares - see for example the LARS-OLS Hybrid, or thresholding the LASSO discussed by Bühlmann and van de Geer (2011) Use the adaptive LASSO or relaxed LASSO The LASSO often includes too many variables when selecting the tuning parameter for prediction (minimum CV error). But, with high probability, the true model is a subset of these variables. This suggests using a secondary stage of estimation. The adaptive LASSO and relaxed LASSO both achieve this and control the bias of the LASSO estimate. Using either method, the prediction-optimal tuning parameter leads to consistent selection. The R package relaxo implements relaxed LASSO. For adaptive LASSO, you need an initial estimate, either least squares, ridge or even LASSO estimates, to calculate weights. Then you can implement it using the same function that you would for LASSO by scaling the X matrix: w <- abs(beta.init) x2 <- scale(x, center=FALSE, scale=1/w) Select tuning parameter and estimate coefficients (coef) using x2 coef <- coef*w Edit: I've come across a few other criteria which can be used for variable selection with the LASSO: Wang, et al (2009) proposed a modified BIC criterion and show that it is consistent. Basically a factor $C_{n}$ is multiplied to the BIC penalty. They chose $C_{n}=log(log(p))$ when $p$ varies with $n$. For fixed $p$, Chand (2012) showed consistency using $C_{n}=\sqrt n/p$. Fan and Tang (2013) proposed a generalized version for use when $p>n$. Roberts and Nowak (2014) propose using percentile CV, repeatedly performing cross-validation to yield a vector of tuning parameter estimates and then selecting the optimal one as the 95% percentile of that vector. Sun, et al (2013) propose using Cohen's kappa coefficient which measures the agreement between two sets. Fang, et al (2013) take the ratio of the average kappa coefficient and the average CV error, which they call PASS. These two methods can be implemented using the R package pass. In my conference paper I have done simulations studies to compare the performance of tuning parameter selection methods for the LASSO, both for prediction and variable selection purposes. For variable selection, I implemented the 1SE rule with 5 fold- and 10 fold CV, percentile CV, kappa, PASS, BIC and the modified BIC. The results show that most of these methods do perform better variable selection than prediction methods such as k fold CV, LOOCV, GCV, Cp and AIC.
How to select tuning parameter for regularized regressions for interpretation? I'd like to try answer your main question, here are two options: Use the one-standard-error (1SE) rule When cross-validating for selection purposes, it can help to use the 1SE rule. The standard er
45,406
How to select tuning parameter for regularized regressions for interpretation?
Not sure whether this helps, but potentially you can create (using e.g. the caret package) a plot akin How to interpret the lasso selection plot , and subsequently choose a cross-validated tuning value that restricts the parameter space sufficiently to allow interpretability?
How to select tuning parameter for regularized regressions for interpretation?
Not sure whether this helps, but potentially you can create (using e.g. the caret package) a plot akin How to interpret the lasso selection plot , and subsequently choose a cross-validated tuning valu
How to select tuning parameter for regularized regressions for interpretation? Not sure whether this helps, but potentially you can create (using e.g. the caret package) a plot akin How to interpret the lasso selection plot , and subsequently choose a cross-validated tuning value that restricts the parameter space sufficiently to allow interpretability?
How to select tuning parameter for regularized regressions for interpretation? Not sure whether this helps, but potentially you can create (using e.g. the caret package) a plot akin How to interpret the lasso selection plot , and subsequently choose a cross-validated tuning valu
45,407
Can machine learning find all sort of crazy connections?
If you try a real thoroughly won't a computer find all sort of silly patterns? Yes. (With emphasis on "silly") this is often referred to as overfitting. If you have a huge (and growing amount) of information, would things start to match in a meaningless way? The answer depends on how exactly the amount of information is growing, and how exactly you look for matches. Data is usually regarded with respect to cases and variates. Variates are properties, and cases are sets of observed properties that belong together. Example: patients are cases, and the variates are e.g. expression level of a number of genes or height, weight, eye color, shoe size, blood pressure, etc. If "more information" means that you measure more variates, e.g. expression levels for more genes of the same patients, then chances increase to find chance patterns across the constant set of patients. If "more information" means that you measure the expression levels of the same variates, e.g. a constant set of genes for more patients, then chances decrease. This is known as the curse of dimensionality, and the Elements of Statistical Learning give a very nice explanation in chapter 2. How much of a problem this is also depends on what kind of match you are are looking for: finding a distinction (classification problem) between groups of cases is easier (more degrees of freedom; thus more prone to overfitting!) than finding a function through all points (regression) A different formulation: If you look for any match (any two persons at the party having the same birthday) chances increase with having more information/cases. If you ask for matches between all cases (everyone having the same bithday), chances decrease with adding new cases. But the chance to find (spurious) What safe-guards do you put in place to get rid of these associations? Possibly the most important safe-guard is you can test (validate) the found pattern (or predictive rule) on completely new cases (preferrably in a blinded or even double-blind way). Unfortunately, this is very costly and so it is done far too seldom (look up debates about reproducibility in current biomedical research). You can also calculate confidence intervals for the predictions (before going for an expensive validation study). If they are ridiculously wide (which they are if you calculate them honestly and you have too few cases), this means that you need to tone down your conclusions accordingly. Another safeguard during the model set-up is that you restrict the model to the low complexity you can afford given the always too small* number of cases you have available. You can and should do sanity checks based on the knowledge you have about the application and data. Even if the ability to predict correctly and the possibility to interpret the model do not always come together, it is IMHO often an important safeguard to keep to an interpretable model if you are in the risk of overfitting. If then the trained model contradicts basic e.g. physical properties, that can be a symptom of overfitting. Example: I work with vibrational spectra of biological tissues. The spectra have the physical property that they should be smooth (and I can be very certain of that because there are 100 years of physics and chemistry both in theory and experiments behind that expectation - even if my measurements of the spectra are noisy). Linear models produce coefficients for each of the dimensions. If those coefficients are noisy (= not smooth) this is a sign of overfitting: the coefficients picked up noise from the measurements, my training algorithm failed to separate the true signal from the noise. A completely different kind of safeguard is that you have to be very clear in thinking: It is often easy to get the right answer to the wrong question. When doing statistical hypothesis tests, it is often easy to find out how likely I am to falsely conclude that there is some pattern given that there is none or how likely I am to overlook a pattern given that there realy is some. However, what I want to know is the inverse: given that I found a pattern, how likely is this to be true? (this is close to @Ben Ogorek's false discovery rate). The link between these inverse questions is the percentage of true patterns among all possible combinations (hypotheses) I look at. And unfortunately, that is unknown. If I'm a good researcher, I'll have a better "nose" for true patterns, and this ratio will be large in the small number of tests I conduct. Blindly testing all possible combinations will have a very small ratio of true hypotheses among all tested hypotheses. To stay in your bible example: As example for an informed and careful formulation of hypotheses ("good nose"), assume I predict from the old testament that the ten commandments are important, I can "validate" this "prediction" against the new testament. Conclusion would be e.g. success for the no murder, adultery, stealing/kidnapping commandmentments, mixed evidence on the sabbath. If on the other hand I blindly test all possible combinations of characters from the old testament against all known messages from ET (plus possibly all kinds of quotes from Shakespeare over Gödel to Steven King and Barack Obama) I'll likely find some elaborate method to produce some such quote(s) from the old testament. But the proportion of true pattern producing rules among all possible transformations of characters is minute. I therefore expect that "sucesses" are likely false positives. I still expect that "validating" the transformation rule that produced the pattern for the old testament will fail to produce sensible patterns on the new testament (showing that the patterns were false positives and the pattern-producing transformation was overfit). I'd say it is so unlikely that if it is found to work also on the new testament I have to rule out dishonesty (e.g. sneak preview on the new testament during model parameter tuning) before accepting that validation (compare to plausibility in one of @Ben's links). * I'm told there are fields where enough cases are available. However, personally I have not yet had that pleasure. You may be interested in reading up about no free lunch theorems. One consequence of the NFL-theorem(s) is that the important "ingredient" that makes one algorithm (heuristic) more successful than another is that is better matched to the problem. Thus, including (correct) knowledge about the problem/application and the type of data into the algorithm* can make a difference. However, these choices also include hyperparameters that tune or steer the overall behaviour of the training algorithm. Good choice there will be possible depending on the experience of the data analyst with the method in question. * or choosing an algorithm according to its suitability to this type of problem and this type of data (and with which the data analyst has sufficient experience to conclude a good set of hyperparameters).
Can machine learning find all sort of crazy connections?
If you try a real thoroughly won't a computer find all sort of silly patterns? Yes. (With emphasis on "silly") this is often referred to as overfitting. If you have a huge (and growing amount) of i
Can machine learning find all sort of crazy connections? If you try a real thoroughly won't a computer find all sort of silly patterns? Yes. (With emphasis on "silly") this is often referred to as overfitting. If you have a huge (and growing amount) of information, would things start to match in a meaningless way? The answer depends on how exactly the amount of information is growing, and how exactly you look for matches. Data is usually regarded with respect to cases and variates. Variates are properties, and cases are sets of observed properties that belong together. Example: patients are cases, and the variates are e.g. expression level of a number of genes or height, weight, eye color, shoe size, blood pressure, etc. If "more information" means that you measure more variates, e.g. expression levels for more genes of the same patients, then chances increase to find chance patterns across the constant set of patients. If "more information" means that you measure the expression levels of the same variates, e.g. a constant set of genes for more patients, then chances decrease. This is known as the curse of dimensionality, and the Elements of Statistical Learning give a very nice explanation in chapter 2. How much of a problem this is also depends on what kind of match you are are looking for: finding a distinction (classification problem) between groups of cases is easier (more degrees of freedom; thus more prone to overfitting!) than finding a function through all points (regression) A different formulation: If you look for any match (any two persons at the party having the same birthday) chances increase with having more information/cases. If you ask for matches between all cases (everyone having the same bithday), chances decrease with adding new cases. But the chance to find (spurious) What safe-guards do you put in place to get rid of these associations? Possibly the most important safe-guard is you can test (validate) the found pattern (or predictive rule) on completely new cases (preferrably in a blinded or even double-blind way). Unfortunately, this is very costly and so it is done far too seldom (look up debates about reproducibility in current biomedical research). You can also calculate confidence intervals for the predictions (before going for an expensive validation study). If they are ridiculously wide (which they are if you calculate them honestly and you have too few cases), this means that you need to tone down your conclusions accordingly. Another safeguard during the model set-up is that you restrict the model to the low complexity you can afford given the always too small* number of cases you have available. You can and should do sanity checks based on the knowledge you have about the application and data. Even if the ability to predict correctly and the possibility to interpret the model do not always come together, it is IMHO often an important safeguard to keep to an interpretable model if you are in the risk of overfitting. If then the trained model contradicts basic e.g. physical properties, that can be a symptom of overfitting. Example: I work with vibrational spectra of biological tissues. The spectra have the physical property that they should be smooth (and I can be very certain of that because there are 100 years of physics and chemistry both in theory and experiments behind that expectation - even if my measurements of the spectra are noisy). Linear models produce coefficients for each of the dimensions. If those coefficients are noisy (= not smooth) this is a sign of overfitting: the coefficients picked up noise from the measurements, my training algorithm failed to separate the true signal from the noise. A completely different kind of safeguard is that you have to be very clear in thinking: It is often easy to get the right answer to the wrong question. When doing statistical hypothesis tests, it is often easy to find out how likely I am to falsely conclude that there is some pattern given that there is none or how likely I am to overlook a pattern given that there realy is some. However, what I want to know is the inverse: given that I found a pattern, how likely is this to be true? (this is close to @Ben Ogorek's false discovery rate). The link between these inverse questions is the percentage of true patterns among all possible combinations (hypotheses) I look at. And unfortunately, that is unknown. If I'm a good researcher, I'll have a better "nose" for true patterns, and this ratio will be large in the small number of tests I conduct. Blindly testing all possible combinations will have a very small ratio of true hypotheses among all tested hypotheses. To stay in your bible example: As example for an informed and careful formulation of hypotheses ("good nose"), assume I predict from the old testament that the ten commandments are important, I can "validate" this "prediction" against the new testament. Conclusion would be e.g. success for the no murder, adultery, stealing/kidnapping commandmentments, mixed evidence on the sabbath. If on the other hand I blindly test all possible combinations of characters from the old testament against all known messages from ET (plus possibly all kinds of quotes from Shakespeare over Gödel to Steven King and Barack Obama) I'll likely find some elaborate method to produce some such quote(s) from the old testament. But the proportion of true pattern producing rules among all possible transformations of characters is minute. I therefore expect that "sucesses" are likely false positives. I still expect that "validating" the transformation rule that produced the pattern for the old testament will fail to produce sensible patterns on the new testament (showing that the patterns were false positives and the pattern-producing transformation was overfit). I'd say it is so unlikely that if it is found to work also on the new testament I have to rule out dishonesty (e.g. sneak preview on the new testament during model parameter tuning) before accepting that validation (compare to plausibility in one of @Ben's links). * I'm told there are fields where enough cases are available. However, personally I have not yet had that pleasure. You may be interested in reading up about no free lunch theorems. One consequence of the NFL-theorem(s) is that the important "ingredient" that makes one algorithm (heuristic) more successful than another is that is better matched to the problem. Thus, including (correct) knowledge about the problem/application and the type of data into the algorithm* can make a difference. However, these choices also include hyperparameters that tune or steer the overall behaviour of the training algorithm. Good choice there will be possible depending on the experience of the data analyst with the method in question. * or choosing an algorithm according to its suitability to this type of problem and this type of data (and with which the data analyst has sufficient experience to conclude a good set of hyperparameters).
Can machine learning find all sort of crazy connections? If you try a real thoroughly won't a computer find all sort of silly patterns? Yes. (With emphasis on "silly") this is often referred to as overfitting. If you have a huge (and growing amount) of i
45,408
Can machine learning find all sort of crazy connections?
I would say there are two categories of safeguards. Statistical Safeguards to give you a "fishing license" of sorts. Without them, you're sure to find spurious associations from chance alone as you sift through thousands of hypotheses. Here is general information on the Multiple Comparisons Problem. I prefer False Discovery Rate control. These are available using p.adjust in R. Causal Safeguards. I admire Judea Pearl's attempt to separate statistical language from causal language (see page 7 from this presentation). Pearl states the rule - "No causes in - no causes out." To make causal assertions from observational data, a priori assumptions are required about how all relevant variables might fit into the picture. How you (manually) draw the cause and effect arrows on a sheet of paper will determine how you run your regressions. Not exactly something you can data mine your way out of. For practicality, I often seek advice from a field that must make causal assertions without experimentation - Epidemiology. Here are a set of criteria called the Bradford Hill criteria. Of these, data mining can get you strength, consistency, and maybe even temporality, but it's not going to get you plausibility or coherence.
Can machine learning find all sort of crazy connections?
I would say there are two categories of safeguards. Statistical Safeguards to give you a "fishing license" of sorts. Without them, you're sure to find spurious associations from chance alone as you s
Can machine learning find all sort of crazy connections? I would say there are two categories of safeguards. Statistical Safeguards to give you a "fishing license" of sorts. Without them, you're sure to find spurious associations from chance alone as you sift through thousands of hypotheses. Here is general information on the Multiple Comparisons Problem. I prefer False Discovery Rate control. These are available using p.adjust in R. Causal Safeguards. I admire Judea Pearl's attempt to separate statistical language from causal language (see page 7 from this presentation). Pearl states the rule - "No causes in - no causes out." To make causal assertions from observational data, a priori assumptions are required about how all relevant variables might fit into the picture. How you (manually) draw the cause and effect arrows on a sheet of paper will determine how you run your regressions. Not exactly something you can data mine your way out of. For practicality, I often seek advice from a field that must make causal assertions without experimentation - Epidemiology. Here are a set of criteria called the Bradford Hill criteria. Of these, data mining can get you strength, consistency, and maybe even temporality, but it's not going to get you plausibility or coherence.
Can machine learning find all sort of crazy connections? I would say there are two categories of safeguards. Statistical Safeguards to give you a "fishing license" of sorts. Without them, you're sure to find spurious associations from chance alone as you s
45,409
Why are Random Forests splitted based on m random features?
Just as fitting each tree in the forest with a random subset sample (a bootstrap sample) of the available data adds stochasticity to improve the out-of-sample fit (by reducing the variance component of the error), so does selecting $m$ variables within which to search for each fit add stochasticity. The extra stochasticity makes each tree a poorer model than it would be without the random selection of variables and this is how the Random Forest achieves lower error over a single tree or bagging, which is Random Forests without the random selection of $m$ variables.
Why are Random Forests splitted based on m random features?
Just as fitting each tree in the forest with a random subset sample (a bootstrap sample) of the available data adds stochasticity to improve the out-of-sample fit (by reducing the variance component o
Why are Random Forests splitted based on m random features? Just as fitting each tree in the forest with a random subset sample (a bootstrap sample) of the available data adds stochasticity to improve the out-of-sample fit (by reducing the variance component of the error), so does selecting $m$ variables within which to search for each fit add stochasticity. The extra stochasticity makes each tree a poorer model than it would be without the random selection of variables and this is how the Random Forest achieves lower error over a single tree or bagging, which is Random Forests without the random selection of $m$ variables.
Why are Random Forests splitted based on m random features? Just as fitting each tree in the forest with a random subset sample (a bootstrap sample) of the available data adds stochasticity to improve the out-of-sample fit (by reducing the variance component o
45,410
Why are Random Forests splitted based on m random features?
Actually, an earlier paper (predating the "random forest" terminology) from Leo Breiman considered all features as you suggest [Breiman 1996]. Below are some relevant excerpts from this article. First, some notation: A learning set of $\mathcal{L}$ consists of data $\left\{ (y_n,x_n),n=1,...,N\right\}$ where the $y$'s are either class labels or a numerical response. Assume we have a procedure for using this learning set to form a predictor $\varphi(\textbf{x},\mathcal{L})$ -- if the input is $\textbf{x}$ we predict $y$ by $\varphi(\textbf{x},\mathcal{L})$ The idea behind bagging (and, by extension, random forests) is to stochastically construct many different predictors $\varphi$ and aggregate this population predictors into a single predictor, denoted $\varphi_B$, which generally has superior performance to any of the individual predictors. Stochasticity is added by constructing each predictor on a bootstrap sample of the original training set, rather than the entirety of $\mathcal{L}$. As Gavin Simpson mentioned, selecting a random subset of features adds even more stochasticity to the construction of individual predictors. Breiman (1996) writes: A critical factor in whether bagging will improve accuracy is the stability of the procedure for constructing $\varphi$. If changes in $\mathcal{L}$, i.e. a [bootstrap] replicate of $\mathcal{L}$, produces small changes in $\varphi$, then $\varphi_B$ will be close to $\varphi$. Improvement will occur for unstable procedures where a small change in $\mathcal{L}$ can result in large changes in $\varphi$ . . . The evidence, both experimental and theoretical, is that bagging can push a good but unstable procedures a significant step towards optimality. On the other hand, it can slightly degrade the performance of stable procedures. [Emphasis Added] The paper then goes on to provide said theoretical and experimental evidence. Breiman's seminal description of random forests (Breiman, 1999) credits Tim Kam Ho for developing "the random subspace method" which adds additional instability by selecting $m$ random features to grow each tree (rather than each node). The original publication (Ho, 1998) appears to be behind a paywall unfortunately. One final note -- one interesting question is what to choose for $m$? That is, how many random features should we select to split on for each node? There is a section in Breiman (1999) devoted to this question. The basic conclusion is that the choice does not matter substantially, as long as $m$ is relatively small compared to the total number of features.
Why are Random Forests splitted based on m random features?
Actually, an earlier paper (predating the "random forest" terminology) from Leo Breiman considered all features as you suggest [Breiman 1996]. Below are some relevant excerpts from this article. First
Why are Random Forests splitted based on m random features? Actually, an earlier paper (predating the "random forest" terminology) from Leo Breiman considered all features as you suggest [Breiman 1996]. Below are some relevant excerpts from this article. First, some notation: A learning set of $\mathcal{L}$ consists of data $\left\{ (y_n,x_n),n=1,...,N\right\}$ where the $y$'s are either class labels or a numerical response. Assume we have a procedure for using this learning set to form a predictor $\varphi(\textbf{x},\mathcal{L})$ -- if the input is $\textbf{x}$ we predict $y$ by $\varphi(\textbf{x},\mathcal{L})$ The idea behind bagging (and, by extension, random forests) is to stochastically construct many different predictors $\varphi$ and aggregate this population predictors into a single predictor, denoted $\varphi_B$, which generally has superior performance to any of the individual predictors. Stochasticity is added by constructing each predictor on a bootstrap sample of the original training set, rather than the entirety of $\mathcal{L}$. As Gavin Simpson mentioned, selecting a random subset of features adds even more stochasticity to the construction of individual predictors. Breiman (1996) writes: A critical factor in whether bagging will improve accuracy is the stability of the procedure for constructing $\varphi$. If changes in $\mathcal{L}$, i.e. a [bootstrap] replicate of $\mathcal{L}$, produces small changes in $\varphi$, then $\varphi_B$ will be close to $\varphi$. Improvement will occur for unstable procedures where a small change in $\mathcal{L}$ can result in large changes in $\varphi$ . . . The evidence, both experimental and theoretical, is that bagging can push a good but unstable procedures a significant step towards optimality. On the other hand, it can slightly degrade the performance of stable procedures. [Emphasis Added] The paper then goes on to provide said theoretical and experimental evidence. Breiman's seminal description of random forests (Breiman, 1999) credits Tim Kam Ho for developing "the random subspace method" which adds additional instability by selecting $m$ random features to grow each tree (rather than each node). The original publication (Ho, 1998) appears to be behind a paywall unfortunately. One final note -- one interesting question is what to choose for $m$? That is, how many random features should we select to split on for each node? There is a section in Breiman (1999) devoted to this question. The basic conclusion is that the choice does not matter substantially, as long as $m$ is relatively small compared to the total number of features.
Why are Random Forests splitted based on m random features? Actually, an earlier paper (predating the "random forest" terminology) from Leo Breiman considered all features as you suggest [Breiman 1996]. Below are some relevant excerpts from this article. First
45,411
Difference estimate & confidence intervals for $\chi^2$ test between 2 proportions
Just for statistically intimidated people (wait, it should be 'intimidated by statistics') that can identify themselves with this joke: A patient asks his surgeon what the odds are of him surviving an impending operation. The doctor replies that the odds are usually 50-50. "But there is no need to worry," the doctor explains. "The first fifty have already died. It is meant to be a quick reference for those confused with the terminology and overlapping tests - I am not addressing confidence intervals. COMPARING PROPORTIONS BETWEEN SAMPLES: I will use the following toy tabulated data: Antacid <- matrix(c(64, 178 - 64, 92, 190 - 92), nrow = 2) Antacid_marginals <- matrix(c(64, 178 - 64, 92, 190 - 92), nrow = 2) Antacid_marginals <- rbind(Antacid_marginals, margin.table(Antacid_marginals,2)) Antacid_marginals <- cbind(Antacid_marginals, margin.table(Antacid_marginals,1)) dimnames(Antacid_marginals) = list(Symptoms = c("Heartburn", "Normal","Totals"), Medication = c("Drug A", "Drug B", "Totals")) This is what it looks like (with marginals): Medication Symptoms Drug A Drug B Totals Heartburn 64 92 156 Normal 114 98 212 Totals 178 190 368 So we have 368patients: 178 on Drug A, and 190 on Drug B and we try to see if there are differences in the proportion of heartburn symptoms between drug A and B, i.e. $p1 = 64/178$ vs $p2 = 92/190$. 1. FISHER EXACT TEST: There is a discussion on Wikipedia about "Controversies". Based on the hypergeometric distribution, it is probably most adequate when the expected values in any of the cells of a contingency table are below 5 - 10. The story of the RA Fisher and the tea lady is great, and can be reproduced in [R] by simply grabbing the code here. [R] seems to tolerate without a pause the large numbers in our data (no problem with factorials): Antacid <- matrix(c(64, 178 - 64, 92, 190 - 92), nrow = 2) fisher.test(Antacid, alternative = "two.sided") Fisher's Exact Test for Count Data data: Antacid p-value = 0.02011 alternative hypothesis: true odds ratio is not equal to 1 95 percent confidence interval: 0.3850709 0.9277156 sample estimates: odds ratio 0.5988478 2. CHI-SQUARE TEST OF HOMOGENEITY: Otherwise known as the goodness of fit Pearson's chi squared test. For larger samples (> 5 expected frequency count in each cell) the $\chi^2$ provides an approximation of the significance value. The test is based on calculating the expected frequency counts obtained by cross-multiplying the marginals (assuming normal distribution of the marginals, it makes sense that we end up with a $\chi^2$ distributed test statistic, since if $X\sim N(\mu,\sigma^)$, then $X^2\sim \chi^2(1))$: Medication Symptoms Drug A Drug B Heartburn 156 * 178 / 368 = 75 156 * 190 / 368 = 81 Normal 212 * 178 / 368 = 103 212 * 190 / 368 = 109 The degrees of freedom will be calculated as the {number of populations (Heartburn sufferers and Normals, i.e. 2) minus 1 } * {number of levels in the categorical variable (Drug A and Drug B, i.e. 2) minus 1}. Therefore, in a 2x2 table we are dealing with 1 d.f. And crucially, a $\chi^2$ of $1\,df$ is exactly a squared $N \sim (0,1)$ (proof here), which explains the sentence "a chi-square test for equality of two proportions is exactly the same thing as a z-test. The chi-squared distribution with one degree of freedom is just that of a normal deviate, squared. You're basically just repeating the chi-squared test on a subset of the contingency table" in this post. The Test Statistic is calculated as: $\chi^2=\frac{(64-75)^2}{75} + \frac{(92-81)^2}{81} +\frac{(114-103)^2}{103} + \frac{(98-109)^2}{109} = 5.39$ This is calculated in R with the function prop.test() or chisq.test(), which should yield the same result, as indicated here: prop.test(Antacid, correct = F) 2-sample test for equality of proportions without continuity correction data: Antacid X-squared = 5.8481, df = 1, p-value = 0.01559 alternative hypothesis: two.sided 95 percent confidence interval: -0.22976374 -0.02519514 sample estimates: prop 1 prop 2 0.4102564 0.5377358 or.. chisq.test(Antacid, correct = F) Pearson's Chi-squared test data: Antacid X-squared = 5.8481, df = 1, p-value = 0.01559 3. G-TEST: The Pearson's chi-test statistic is the second order Taylor expansion around 1 of the G test; hence they tend to converge. In R: library(DescTools) GTest(Antacid, correct = 'none') Log likelihood ratio (G-test) test of independence without correction data: Antacid G = 5.8703, X-squared df = 1, p-value = 0.0154 4. Z-TEST OF PROPORTIONS: The normal distribution is a good approximation for a binomial when $np>5$ and $n(1-p)>5$. When the occurrences of successes are small in comparison with the total amount of observations, it is the actual number of expected observations that will determine if a normal approximation of a poisson process can be considered ($\lambda \geq 5$). Although the post hyperlinked is old, I haven't found in CV an R function for it. This may be due to the fact explained above re: $\chi^2_{(df=1)}\sim \, N_{(0,1)}^2$. The Test Statistic is: $ \displaystyle Z = \frac{\frac{x_1}{n_1}-\frac{x_2}{n_2}}{\sqrt{p\,(1-p)(1/n_1+1/n_2)}}$ with $\displaystyle p = \frac{x_1\,+\,x_2}{n_1\,+\,n_2}$, where $x_1$ and $x_2$ are the number of "successes" (in our case, sadly, heartburn), over the number of subjects in that each one of the levels of the categorical variable (Drug A and Drug B), i.e. $n_1$ and $n_2$. In the linked page there is an ad hoc formula. I have been toying with a spin-off with a lot of loose ends. It defaults to a two-tailed alpha value of 0.05, but can be changed, as much as it can be turned into a one tailed t = 1: zprop = function(x1, x2, n1, n2, alpha=0.05, t = 2){ nume = (x1/n1) - (x2/n2) p = (x1 + x2) / (n1 + n2) deno = sqrt(p * (1 - p) * (1/n1 + 1/n2)) z = nume / deno print(c("Z value:",abs(round(z,4)))) print(c("Cut-off quantile:", abs(round(qnorm(alpha/t),2)))) print(c("pvalue:", pnorm(-abs(z)))) } In our case: zprop(64, 92 , 178, 190) [1] Z value: 2.4183 [1] Cut-off quantile: 1.96 [1] pvalue: 0.0077 Giving the same z value as the function in the R-Bloggers: z.prop(64, 178 , 92, 190) [1] -5.44273 OK... Hope it helps somebody out there, and I'm sure mistakes will be pointed out...
Difference estimate & confidence intervals for $\chi^2$ test between 2 proportions
Just for statistically intimidated people (wait, it should be 'intimidated by statistics') that can identify themselves with this joke: A patient asks his surgeon what the odds are of him surviving a
Difference estimate & confidence intervals for $\chi^2$ test between 2 proportions Just for statistically intimidated people (wait, it should be 'intimidated by statistics') that can identify themselves with this joke: A patient asks his surgeon what the odds are of him surviving an impending operation. The doctor replies that the odds are usually 50-50. "But there is no need to worry," the doctor explains. "The first fifty have already died. It is meant to be a quick reference for those confused with the terminology and overlapping tests - I am not addressing confidence intervals. COMPARING PROPORTIONS BETWEEN SAMPLES: I will use the following toy tabulated data: Antacid <- matrix(c(64, 178 - 64, 92, 190 - 92), nrow = 2) Antacid_marginals <- matrix(c(64, 178 - 64, 92, 190 - 92), nrow = 2) Antacid_marginals <- rbind(Antacid_marginals, margin.table(Antacid_marginals,2)) Antacid_marginals <- cbind(Antacid_marginals, margin.table(Antacid_marginals,1)) dimnames(Antacid_marginals) = list(Symptoms = c("Heartburn", "Normal","Totals"), Medication = c("Drug A", "Drug B", "Totals")) This is what it looks like (with marginals): Medication Symptoms Drug A Drug B Totals Heartburn 64 92 156 Normal 114 98 212 Totals 178 190 368 So we have 368patients: 178 on Drug A, and 190 on Drug B and we try to see if there are differences in the proportion of heartburn symptoms between drug A and B, i.e. $p1 = 64/178$ vs $p2 = 92/190$. 1. FISHER EXACT TEST: There is a discussion on Wikipedia about "Controversies". Based on the hypergeometric distribution, it is probably most adequate when the expected values in any of the cells of a contingency table are below 5 - 10. The story of the RA Fisher and the tea lady is great, and can be reproduced in [R] by simply grabbing the code here. [R] seems to tolerate without a pause the large numbers in our data (no problem with factorials): Antacid <- matrix(c(64, 178 - 64, 92, 190 - 92), nrow = 2) fisher.test(Antacid, alternative = "two.sided") Fisher's Exact Test for Count Data data: Antacid p-value = 0.02011 alternative hypothesis: true odds ratio is not equal to 1 95 percent confidence interval: 0.3850709 0.9277156 sample estimates: odds ratio 0.5988478 2. CHI-SQUARE TEST OF HOMOGENEITY: Otherwise known as the goodness of fit Pearson's chi squared test. For larger samples (> 5 expected frequency count in each cell) the $\chi^2$ provides an approximation of the significance value. The test is based on calculating the expected frequency counts obtained by cross-multiplying the marginals (assuming normal distribution of the marginals, it makes sense that we end up with a $\chi^2$ distributed test statistic, since if $X\sim N(\mu,\sigma^)$, then $X^2\sim \chi^2(1))$: Medication Symptoms Drug A Drug B Heartburn 156 * 178 / 368 = 75 156 * 190 / 368 = 81 Normal 212 * 178 / 368 = 103 212 * 190 / 368 = 109 The degrees of freedom will be calculated as the {number of populations (Heartburn sufferers and Normals, i.e. 2) minus 1 } * {number of levels in the categorical variable (Drug A and Drug B, i.e. 2) minus 1}. Therefore, in a 2x2 table we are dealing with 1 d.f. And crucially, a $\chi^2$ of $1\,df$ is exactly a squared $N \sim (0,1)$ (proof here), which explains the sentence "a chi-square test for equality of two proportions is exactly the same thing as a z-test. The chi-squared distribution with one degree of freedom is just that of a normal deviate, squared. You're basically just repeating the chi-squared test on a subset of the contingency table" in this post. The Test Statistic is calculated as: $\chi^2=\frac{(64-75)^2}{75} + \frac{(92-81)^2}{81} +\frac{(114-103)^2}{103} + \frac{(98-109)^2}{109} = 5.39$ This is calculated in R with the function prop.test() or chisq.test(), which should yield the same result, as indicated here: prop.test(Antacid, correct = F) 2-sample test for equality of proportions without continuity correction data: Antacid X-squared = 5.8481, df = 1, p-value = 0.01559 alternative hypothesis: two.sided 95 percent confidence interval: -0.22976374 -0.02519514 sample estimates: prop 1 prop 2 0.4102564 0.5377358 or.. chisq.test(Antacid, correct = F) Pearson's Chi-squared test data: Antacid X-squared = 5.8481, df = 1, p-value = 0.01559 3. G-TEST: The Pearson's chi-test statistic is the second order Taylor expansion around 1 of the G test; hence they tend to converge. In R: library(DescTools) GTest(Antacid, correct = 'none') Log likelihood ratio (G-test) test of independence without correction data: Antacid G = 5.8703, X-squared df = 1, p-value = 0.0154 4. Z-TEST OF PROPORTIONS: The normal distribution is a good approximation for a binomial when $np>5$ and $n(1-p)>5$. When the occurrences of successes are small in comparison with the total amount of observations, it is the actual number of expected observations that will determine if a normal approximation of a poisson process can be considered ($\lambda \geq 5$). Although the post hyperlinked is old, I haven't found in CV an R function for it. This may be due to the fact explained above re: $\chi^2_{(df=1)}\sim \, N_{(0,1)}^2$. The Test Statistic is: $ \displaystyle Z = \frac{\frac{x_1}{n_1}-\frac{x_2}{n_2}}{\sqrt{p\,(1-p)(1/n_1+1/n_2)}}$ with $\displaystyle p = \frac{x_1\,+\,x_2}{n_1\,+\,n_2}$, where $x_1$ and $x_2$ are the number of "successes" (in our case, sadly, heartburn), over the number of subjects in that each one of the levels of the categorical variable (Drug A and Drug B), i.e. $n_1$ and $n_2$. In the linked page there is an ad hoc formula. I have been toying with a spin-off with a lot of loose ends. It defaults to a two-tailed alpha value of 0.05, but can be changed, as much as it can be turned into a one tailed t = 1: zprop = function(x1, x2, n1, n2, alpha=0.05, t = 2){ nume = (x1/n1) - (x2/n2) p = (x1 + x2) / (n1 + n2) deno = sqrt(p * (1 - p) * (1/n1 + 1/n2)) z = nume / deno print(c("Z value:",abs(round(z,4)))) print(c("Cut-off quantile:", abs(round(qnorm(alpha/t),2)))) print(c("pvalue:", pnorm(-abs(z)))) } In our case: zprop(64, 92 , 178, 190) [1] Z value: 2.4183 [1] Cut-off quantile: 1.96 [1] pvalue: 0.0077 Giving the same z value as the function in the R-Bloggers: z.prop(64, 178 , 92, 190) [1] -5.44273 OK... Hope it helps somebody out there, and I'm sure mistakes will be pointed out...
Difference estimate & confidence intervals for $\chi^2$ test between 2 proportions Just for statistically intimidated people (wait, it should be 'intimidated by statistics') that can identify themselves with this joke: A patient asks his surgeon what the odds are of him surviving a
45,412
Why do we use conditional expectation vs regular expectation in regression?
$E(Y)$ is just the mean of your responses: it's the same thing as a regression where all you have is an intercept. For all values of $X$, you are predicting the same value for the response. We use conditional expectation because we expect there to be a relationship between a predictor variable and the response variable, such that we want our predictions to be made in the context of a specific value of the predictor(s). Consider the following prediction task: you have logged the distance your car has traveled between fillups and the amount of gas you put in the tank each time, so you have data for the MPG of your car. Sometimes you fill up the tank when it's nearly empty, sometimes you just top it off. Let's say you want to use your data to predict how much gasoline you will expend on a particular trip. You regress your response variable of gasoline volume against the predictor variable of distance and get a model of the form $gas = b_0 + b_1 distance$. If you were to use $E[y]$ for your predictions here, you would calculate the mean gas volume for all trips and say "regardless of the distance we're going to travel, I anticipate that we will use $E[gas]$ gallons of fuel." But, because we have the regression model, we can say "given that we will travel $d$ miles, we expect to use $E[gas|distance=d] = b_0 + b_1 d$ gallons of fuel." If most of your trips are about the same distance, just using $E[gas]$ might actually give you decent results. But given that we know there is a relationship between distance traveled and gas used, we anticipate that the conditional expectation will give us much better predictions than the blanket prediction of the unconditioned expectation.
Why do we use conditional expectation vs regular expectation in regression?
$E(Y)$ is just the mean of your responses: it's the same thing as a regression where all you have is an intercept. For all values of $X$, you are predicting the same value for the response. We use con
Why do we use conditional expectation vs regular expectation in regression? $E(Y)$ is just the mean of your responses: it's the same thing as a regression where all you have is an intercept. For all values of $X$, you are predicting the same value for the response. We use conditional expectation because we expect there to be a relationship between a predictor variable and the response variable, such that we want our predictions to be made in the context of a specific value of the predictor(s). Consider the following prediction task: you have logged the distance your car has traveled between fillups and the amount of gas you put in the tank each time, so you have data for the MPG of your car. Sometimes you fill up the tank when it's nearly empty, sometimes you just top it off. Let's say you want to use your data to predict how much gasoline you will expend on a particular trip. You regress your response variable of gasoline volume against the predictor variable of distance and get a model of the form $gas = b_0 + b_1 distance$. If you were to use $E[y]$ for your predictions here, you would calculate the mean gas volume for all trips and say "regardless of the distance we're going to travel, I anticipate that we will use $E[gas]$ gallons of fuel." But, because we have the regression model, we can say "given that we will travel $d$ miles, we expect to use $E[gas|distance=d] = b_0 + b_1 d$ gallons of fuel." If most of your trips are about the same distance, just using $E[gas]$ might actually give you decent results. But given that we know there is a relationship between distance traveled and gas used, we anticipate that the conditional expectation will give us much better predictions than the blanket prediction of the unconditioned expectation.
Why do we use conditional expectation vs regular expectation in regression? $E(Y)$ is just the mean of your responses: it's the same thing as a regression where all you have is an intercept. For all values of $X$, you are predicting the same value for the response. We use con
45,413
Why do we use conditional expectation vs regular expectation in regression?
There are two basic versions of a regression specification, regarding the assumptions about the nature of the variables involved: In the first, the regressors are assumed deterministic , and so the actual matrix contains elements that are not realizations of random variables. This comes from an "experimental design" tradition (and hence sometimes the regressor matrix is called the "design matrix"). In such a set up the regressors are not random variables and so it is not meaningful to "condition" on them. So we have to formulate the model in terms of unconditional expected values, like the ones OP wrote. The second version mainly relates to a non-experimental setting, like economics for example, we treat the regressors as random variables, while the specific sample/regressor matrix as being comprised of realizations of random variables. Here, we condition on $X$ to be humble: we do not claim that we know the unconditional behavior of $Y$ or of the error, but we make "narrower" assumptions, conditional assumptions. Hence $E(u\mid X) =0$ etc. Intuitively we restrict ourselves to "what can I say about the relation between $Y$ and $X$ , given the specific data that I have in hand?" Apart for humbleness, it also cleverly permits us to derive all sorts of useful results (which we could not if we assumed stochastic regressors and considered at the same time assumptions on unconditional expectations). For example, to stick to basics, in proving unbiasedness of the OLS estimator we write $$\hat \beta = (\mathbf X'\mathbf X)^{-1}\mathbf X' \mathbf y =(\mathbf X'\mathbf X)^{-1}\mathbf X' (\mathbf X'\beta+\mathbf u) = \beta + (\mathbf X'\mathbf X)^{-1}\mathbf X'\mathbf u$$ Assume that we treat the regressors as stochastic. If you want to check unbiasedness, you will examine $$E(\hat \beta) = \beta + E\left((\mathbf X'\mathbf X)^{-1}\mathbf X'\mathbf u\right)$$ Where does that leave you? Nowhere - it is difficult to justify an a priori assumption like $E\left((\mathbf X'\mathbf X)^{-1}\mathbf X'\mathbf u\right)=0$. But note that, by the properties of expected values $$E\left((\mathbf X'\mathbf X)^{-1}\mathbf X'\mathbf u\right) = E\left[E\left((\mathbf X'\mathbf X)^{-1}\mathbf X'\mathbf u\right)\mid X\right]$$ $$=E\left[(\mathbf X'\mathbf X)^{-1}\mathbf X'E\left(\mathbf u\mid X\right)\right]$$ Now, to have unbiasedness, we only need to a priori assume that $E\left(\mathbf u\mid X\right)=0$, which can at least be logically argued upon. Finally, note that there is a drawback in assuming deterministic, non-stochastic regressors, which is sometimes overlooked: If our model is $$y_i = a +bx_i + u_i,\;\; i=1,..,n$$ then under non-stochastic regressors we have $$E(y_i) = a+bx_i$$ But this means that each $y_i$ has in principle a different expected value : so the $y_i$'s here do not come from an identically distributed population. If they don't, then our sample $\{Y,X\}$, that contains as a random variable only the $Y$ is not "random" (i.e. it is not i.i.d), due to the assumption that the $X$'s are deterministic.
Why do we use conditional expectation vs regular expectation in regression?
There are two basic versions of a regression specification, regarding the assumptions about the nature of the variables involved: In the first, the regressors are assumed deterministic , and so the
Why do we use conditional expectation vs regular expectation in regression? There are two basic versions of a regression specification, regarding the assumptions about the nature of the variables involved: In the first, the regressors are assumed deterministic , and so the actual matrix contains elements that are not realizations of random variables. This comes from an "experimental design" tradition (and hence sometimes the regressor matrix is called the "design matrix"). In such a set up the regressors are not random variables and so it is not meaningful to "condition" on them. So we have to formulate the model in terms of unconditional expected values, like the ones OP wrote. The second version mainly relates to a non-experimental setting, like economics for example, we treat the regressors as random variables, while the specific sample/regressor matrix as being comprised of realizations of random variables. Here, we condition on $X$ to be humble: we do not claim that we know the unconditional behavior of $Y$ or of the error, but we make "narrower" assumptions, conditional assumptions. Hence $E(u\mid X) =0$ etc. Intuitively we restrict ourselves to "what can I say about the relation between $Y$ and $X$ , given the specific data that I have in hand?" Apart for humbleness, it also cleverly permits us to derive all sorts of useful results (which we could not if we assumed stochastic regressors and considered at the same time assumptions on unconditional expectations). For example, to stick to basics, in proving unbiasedness of the OLS estimator we write $$\hat \beta = (\mathbf X'\mathbf X)^{-1}\mathbf X' \mathbf y =(\mathbf X'\mathbf X)^{-1}\mathbf X' (\mathbf X'\beta+\mathbf u) = \beta + (\mathbf X'\mathbf X)^{-1}\mathbf X'\mathbf u$$ Assume that we treat the regressors as stochastic. If you want to check unbiasedness, you will examine $$E(\hat \beta) = \beta + E\left((\mathbf X'\mathbf X)^{-1}\mathbf X'\mathbf u\right)$$ Where does that leave you? Nowhere - it is difficult to justify an a priori assumption like $E\left((\mathbf X'\mathbf X)^{-1}\mathbf X'\mathbf u\right)=0$. But note that, by the properties of expected values $$E\left((\mathbf X'\mathbf X)^{-1}\mathbf X'\mathbf u\right) = E\left[E\left((\mathbf X'\mathbf X)^{-1}\mathbf X'\mathbf u\right)\mid X\right]$$ $$=E\left[(\mathbf X'\mathbf X)^{-1}\mathbf X'E\left(\mathbf u\mid X\right)\right]$$ Now, to have unbiasedness, we only need to a priori assume that $E\left(\mathbf u\mid X\right)=0$, which can at least be logically argued upon. Finally, note that there is a drawback in assuming deterministic, non-stochastic regressors, which is sometimes overlooked: If our model is $$y_i = a +bx_i + u_i,\;\; i=1,..,n$$ then under non-stochastic regressors we have $$E(y_i) = a+bx_i$$ But this means that each $y_i$ has in principle a different expected value : so the $y_i$'s here do not come from an identically distributed population. If they don't, then our sample $\{Y,X\}$, that contains as a random variable only the $Y$ is not "random" (i.e. it is not i.i.d), due to the assumption that the $X$'s are deterministic.
Why do we use conditional expectation vs regular expectation in regression? There are two basic versions of a regression specification, regarding the assumptions about the nature of the variables involved: In the first, the regressors are assumed deterministic , and so the
45,414
Why do we use conditional expectation vs regular expectation in regression?
Let's say you observe a RV $X$ and you want to predict a second RV $Y$ where your predictor of $Y$ is $g(X)$. Then you can prove that the "best" predictor of $Y$ is $g(X) = E[Y \mid X]$, where "best" is the function $g$ that minimizes $E[(Y-g(X))^2]$. So $E[Y \mid X]$ will always be at least as good as, if not better than $E[Y]$. To prove that $E[Y|X]$ is the "best" predictor possible we just need to show that $$E[(Y-g(X))^2] \ge E[(Y-E[Y \mid X])^2]$$ Let's start off by looking at $E[(Y-g(X))^2 \mid X]$ which is not quite the same as the LHS above but not to worry, at the end we can leverage the property that $E[E[X|Y]] = E[X]$. So, $$E[(Y-g(X))^2 \mid X] = E[(Y - E[Y \mid X] + E[Y \mid X] - g(X))^2 \mid X]$$ $$=E[(Y- E[Y \mid X]))^2 \mid X]$$ $$ + \, E[(E[Y \mid X] - g(X))^2 \mid X]$$ $$ + \, 2E[(Y- E[Y \mid X])(E[Y \mid X] - g(X)) \mid X]$$ Where the above is basically doing $$(x+y)^2 = (x-c+c+y)^2 = (x-c)^2 + (x+c)^2+2(x-c)(x+c)$$ and using the linearity of expectations. Focusing on the third term of the expansion only, we can show that it equals zero. $$2E[(Y- E[Y \mid X])(E[Y \mid X] - g(X)) \mid X]=0$$ This is because given $X$, the term $E[Y \mid X] - g(X)$ is like a constant and can be pulled out of the expectation using the property that $E[aX]=aE[X]$. Letting the constant we pulled out equal $c$ we have $$c \cdot E[Y- E[Y \mid X] \mid X] = c \cdot (E[Y \mid X]- E[E[Y \mid X] \mid X] )$$ $$= c \cdot (E[Y \mid X] - E[Y \mid X]) = 0$$ From the property $E[g(X) \mid X] = g(X)$ we know that $E[E[Y \mid X] \mid X] = E[Y \mid X]$ since $E[Y \mid X]$ is a function of $X$. Therefore going back to the expansion, we have $$E[(Y-g(X))^2 \mid X] = E[(Y- E[Y \mid X]))^2 \mid X] + E[(E[Y \mid X] - g(X))^2 \mid X]$$ Noting that the second term on the RHS must always be positive, we can say $$E[(Y-g(X))^2 \mid X] \ge E[(Y- E[Y \mid X]))^2 \mid X]$$ and then taking the expected value of both sides, leveraging the property that $E[X] = E[E[X \mid Y]]$, we get $$E[(Y-g(X))^2] \ge E[(Y-E[Y \mid X])^2]$$ Which shows that the "best" predictor is $E[Y \mid X]$. Note that it will be as good as $E[Y]$ if $Y$ and $X$ are independent.
Why do we use conditional expectation vs regular expectation in regression?
Let's say you observe a RV $X$ and you want to predict a second RV $Y$ where your predictor of $Y$ is $g(X)$. Then you can prove that the "best" predictor of $Y$ is $g(X) = E[Y \mid X]$, where "best"
Why do we use conditional expectation vs regular expectation in regression? Let's say you observe a RV $X$ and you want to predict a second RV $Y$ where your predictor of $Y$ is $g(X)$. Then you can prove that the "best" predictor of $Y$ is $g(X) = E[Y \mid X]$, where "best" is the function $g$ that minimizes $E[(Y-g(X))^2]$. So $E[Y \mid X]$ will always be at least as good as, if not better than $E[Y]$. To prove that $E[Y|X]$ is the "best" predictor possible we just need to show that $$E[(Y-g(X))^2] \ge E[(Y-E[Y \mid X])^2]$$ Let's start off by looking at $E[(Y-g(X))^2 \mid X]$ which is not quite the same as the LHS above but not to worry, at the end we can leverage the property that $E[E[X|Y]] = E[X]$. So, $$E[(Y-g(X))^2 \mid X] = E[(Y - E[Y \mid X] + E[Y \mid X] - g(X))^2 \mid X]$$ $$=E[(Y- E[Y \mid X]))^2 \mid X]$$ $$ + \, E[(E[Y \mid X] - g(X))^2 \mid X]$$ $$ + \, 2E[(Y- E[Y \mid X])(E[Y \mid X] - g(X)) \mid X]$$ Where the above is basically doing $$(x+y)^2 = (x-c+c+y)^2 = (x-c)^2 + (x+c)^2+2(x-c)(x+c)$$ and using the linearity of expectations. Focusing on the third term of the expansion only, we can show that it equals zero. $$2E[(Y- E[Y \mid X])(E[Y \mid X] - g(X)) \mid X]=0$$ This is because given $X$, the term $E[Y \mid X] - g(X)$ is like a constant and can be pulled out of the expectation using the property that $E[aX]=aE[X]$. Letting the constant we pulled out equal $c$ we have $$c \cdot E[Y- E[Y \mid X] \mid X] = c \cdot (E[Y \mid X]- E[E[Y \mid X] \mid X] )$$ $$= c \cdot (E[Y \mid X] - E[Y \mid X]) = 0$$ From the property $E[g(X) \mid X] = g(X)$ we know that $E[E[Y \mid X] \mid X] = E[Y \mid X]$ since $E[Y \mid X]$ is a function of $X$. Therefore going back to the expansion, we have $$E[(Y-g(X))^2 \mid X] = E[(Y- E[Y \mid X]))^2 \mid X] + E[(E[Y \mid X] - g(X))^2 \mid X]$$ Noting that the second term on the RHS must always be positive, we can say $$E[(Y-g(X))^2 \mid X] \ge E[(Y- E[Y \mid X]))^2 \mid X]$$ and then taking the expected value of both sides, leveraging the property that $E[X] = E[E[X \mid Y]]$, we get $$E[(Y-g(X))^2] \ge E[(Y-E[Y \mid X])^2]$$ Which shows that the "best" predictor is $E[Y \mid X]$. Note that it will be as good as $E[Y]$ if $Y$ and $X$ are independent.
Why do we use conditional expectation vs regular expectation in regression? Let's say you observe a RV $X$ and you want to predict a second RV $Y$ where your predictor of $Y$ is $g(X)$. Then you can prove that the "best" predictor of $Y$ is $g(X) = E[Y \mid X]$, where "best"
45,415
Is it ok to correlate before-and-after data?
None of those correlations you think aren't OK really aren't OK. The correlation is just a measure of linear relationship. Sometimes you need to know the extent of a relationship that you know exists, such as this one, or any of the others you listed. In this case they may want to know the amount of correlation for a variety of reasons ranging from needing it for a repeated measures t-test report to checking to see that the data are sound. Perhaps what you mean by not OK is that it's not OK to examine such a correlation with a hypothesis test where the null is a 0 correlation. That wouldn't be OK because you know that there has to be some. But that's not what you're asked to do.
Is it ok to correlate before-and-after data?
None of those correlations you think aren't OK really aren't OK. The correlation is just a measure of linear relationship. Sometimes you need to know the extent of a relationship that you know exists,
Is it ok to correlate before-and-after data? None of those correlations you think aren't OK really aren't OK. The correlation is just a measure of linear relationship. Sometimes you need to know the extent of a relationship that you know exists, such as this one, or any of the others you listed. In this case they may want to know the amount of correlation for a variety of reasons ranging from needing it for a repeated measures t-test report to checking to see that the data are sound. Perhaps what you mean by not OK is that it's not OK to examine such a correlation with a hypothesis test where the null is a 0 correlation. That wouldn't be OK because you know that there has to be some. But that's not what you're asked to do.
Is it ok to correlate before-and-after data? None of those correlations you think aren't OK really aren't OK. The correlation is just a measure of linear relationship. Sometimes you need to know the extent of a relationship that you know exists,
45,416
Is it ok to correlate before-and-after data?
This is perfectly fine. You are considering two different variables each measured once per subject. One contains the 'pre' values, the other the 'post' values. I think you are mixing up independence between observations (subjects) and independence of variables. Please note that in your situation, you might want to analyze differences between pre and post, not just looking at correlations, depending on the scientific question.
Is it ok to correlate before-and-after data?
This is perfectly fine. You are considering two different variables each measured once per subject. One contains the 'pre' values, the other the 'post' values. I think you are mixing up independence b
Is it ok to correlate before-and-after data? This is perfectly fine. You are considering two different variables each measured once per subject. One contains the 'pre' values, the other the 'post' values. I think you are mixing up independence between observations (subjects) and independence of variables. Please note that in your situation, you might want to analyze differences between pre and post, not just looking at correlations, depending on the scientific question.
Is it ok to correlate before-and-after data? This is perfectly fine. You are considering two different variables each measured once per subject. One contains the 'pre' values, the other the 'post' values. I think you are mixing up independence b
45,417
Is it ok to correlate before-and-after data?
I think it depends on what you are trying to do with your data. Technically, it is okay to correlate repeated measures from the same subject in the sense that it is mathematically possible. But if you trying to draw some kind of inference (for example, causality) from your data, simply correlated two observations that are from the same subject is not going to tell you anything useful. Here's a nice little thread talking about correlations of repeated measures within subjects.
Is it ok to correlate before-and-after data?
I think it depends on what you are trying to do with your data. Technically, it is okay to correlate repeated measures from the same subject in the sense that it is mathematically possible. But if you
Is it ok to correlate before-and-after data? I think it depends on what you are trying to do with your data. Technically, it is okay to correlate repeated measures from the same subject in the sense that it is mathematically possible. But if you trying to draw some kind of inference (for example, causality) from your data, simply correlated two observations that are from the same subject is not going to tell you anything useful. Here's a nice little thread talking about correlations of repeated measures within subjects.
Is it ok to correlate before-and-after data? I think it depends on what you are trying to do with your data. Technically, it is okay to correlate repeated measures from the same subject in the sense that it is mathematically possible. But if you
45,418
Correlation between vegetation and erosion
I agree with @John's answer but would also suggest simply plotting boxplots of erosion for each vegetation category. If the vegetation variable actually has a ordinal interpretation then we could draw some exploratory conclusions about correlations between vegetation and erosion. For example, consider the following fictional data and corresponding box plot. So as you can see from the box plots, there would appear to be a positive correlation (or association if you prefer that jargon) between erosion and vegetation level. (Of course this argument requires vegetation categories have an ordinal meaning) Here is the code to generate this in R although I know you didn't ask for it and clearly one of your tags is for SPSS. #Pseudo Data N = 10000 erosion = runif(N,0,10) vegetation = rep(1,N) vegetation[erosion > 2.5 & erosion <= 5] = 2 vegetation[erosion > 5 & erosion <= 7.5] = 3 vegetation[erosion > 7.5 & erosion <= 10] = 4 boxplot(erosion~vegetation,col=c("blue","red","green","orange"), xlab="Vegetation",ylab="Erosion")
Correlation between vegetation and erosion
I agree with @John's answer but would also suggest simply plotting boxplots of erosion for each vegetation category. If the vegetation variable actually has a ordinal interpretation then we could dra
Correlation between vegetation and erosion I agree with @John's answer but would also suggest simply plotting boxplots of erosion for each vegetation category. If the vegetation variable actually has a ordinal interpretation then we could draw some exploratory conclusions about correlations between vegetation and erosion. For example, consider the following fictional data and corresponding box plot. So as you can see from the box plots, there would appear to be a positive correlation (or association if you prefer that jargon) between erosion and vegetation level. (Of course this argument requires vegetation categories have an ordinal meaning) Here is the code to generate this in R although I know you didn't ask for it and clearly one of your tags is for SPSS. #Pseudo Data N = 10000 erosion = runif(N,0,10) vegetation = rep(1,N) vegetation[erosion > 2.5 & erosion <= 5] = 2 vegetation[erosion > 5 & erosion <= 7.5] = 3 vegetation[erosion > 7.5 & erosion <= 10] = 4 boxplot(erosion~vegetation,col=c("blue","red","green","orange"), xlab="Vegetation",ylab="Erosion")
Correlation between vegetation and erosion I agree with @John's answer but would also suggest simply plotting boxplots of erosion for each vegetation category. If the vegetation variable actually has a ordinal interpretation then we could dra
45,419
Correlation between vegetation and erosion
You could calculate a $\chi^2$ and the $\Phi$ coefficient measure as a substitute for correlation. $\Phi$ would have a similar interpretation to a Pearson correlation coefficient but should really only be used in 2x2 designs. In your case you should probably go with a Cramer's V which is standardized but doesn't quite have the correlation style interpretation. There is no nonparametric comparable linear correlation because one of your variables is purely categorical. Those numbers 1-4 labelling your categories could be arbitrarily reassigned to different categories and it wouldn't affect the true relationship but it would affect something like a Spearman correlation coefficient. Unfortunately, the above tactic wouldn't really treat your continuous variable fairly. Another way to get a correlation(ish) value is to perform an ANOVA with your continuous variable as response and categorical as predictor and then calculate $\eta^2$ (eta-squared) effect size measure. That effect size has an interpretation that's similar to $R^2$. Your second query about sample size has a fixed answer for all tests and estimates. The larger the sample, the more likely the test is to be significant. Increasing sample size increases the accuracy of your effect estimates ($\Phi$ or $\eta^2$, or any parameter estimates you're making).
Correlation between vegetation and erosion
You could calculate a $\chi^2$ and the $\Phi$ coefficient measure as a substitute for correlation. $\Phi$ would have a similar interpretation to a Pearson correlation coefficient but should really onl
Correlation between vegetation and erosion You could calculate a $\chi^2$ and the $\Phi$ coefficient measure as a substitute for correlation. $\Phi$ would have a similar interpretation to a Pearson correlation coefficient but should really only be used in 2x2 designs. In your case you should probably go with a Cramer's V which is standardized but doesn't quite have the correlation style interpretation. There is no nonparametric comparable linear correlation because one of your variables is purely categorical. Those numbers 1-4 labelling your categories could be arbitrarily reassigned to different categories and it wouldn't affect the true relationship but it would affect something like a Spearman correlation coefficient. Unfortunately, the above tactic wouldn't really treat your continuous variable fairly. Another way to get a correlation(ish) value is to perform an ANOVA with your continuous variable as response and categorical as predictor and then calculate $\eta^2$ (eta-squared) effect size measure. That effect size has an interpretation that's similar to $R^2$. Your second query about sample size has a fixed answer for all tests and estimates. The larger the sample, the more likely the test is to be significant. Increasing sample size increases the accuracy of your effect estimates ($\Phi$ or $\eta^2$, or any parameter estimates you're making).
Correlation between vegetation and erosion You could calculate a $\chi^2$ and the $\Phi$ coefficient measure as a substitute for correlation. $\Phi$ would have a similar interpretation to a Pearson correlation coefficient but should really onl
45,420
Maximum Likelihood Curve/Model Fitting in Python
Here's some pseudocode to do it. Of course, it depends on the error structure you choose. You don't need the stats models to do it, because Scipy has an minimizer built-in. The minimizer probably doesn't give you CIs though, like mle2 will. There may be another minimizer that will profile your parameters, but I don't know of one on the top of my head. Anyway, here you go from scipy import stats import numpy as np from scipy.optimize import minimize import pylab as py ydata = np.array([0.1,0.15,0.2,0.3,0.7,0.8,0.9, 0.9, 0.95]) xdata = np.array(range(0,len(ydata),1)) def sigmoid(params): k = params[0] x0 = params[1] sd = params[2] yPred = 1 / (1+ np.exp(-k*(xdata-x0))) # Calculate negative log likelihood LL = -np.sum( stats.norm.logpdf(ydata, loc=yPred, scale=sd ) ) return(LL) initParams = [1, 1, 1] results = minimize(sigmoid, initParams, method='Nelder-Mead') print results.x estParms = results.x yOut = yPred = 1 / (1+ np.exp(-estParms[0]*(xdata-estParms[1]))) py.clf() py.plot(xdata,ydata, 'go') py.plot(xdata, yOut) py.show() This gives me the following:
Maximum Likelihood Curve/Model Fitting in Python
Here's some pseudocode to do it. Of course, it depends on the error structure you choose. You don't need the stats models to do it, because Scipy has an minimizer built-in. The minimizer probably does
Maximum Likelihood Curve/Model Fitting in Python Here's some pseudocode to do it. Of course, it depends on the error structure you choose. You don't need the stats models to do it, because Scipy has an minimizer built-in. The minimizer probably doesn't give you CIs though, like mle2 will. There may be another minimizer that will profile your parameters, but I don't know of one on the top of my head. Anyway, here you go from scipy import stats import numpy as np from scipy.optimize import minimize import pylab as py ydata = np.array([0.1,0.15,0.2,0.3,0.7,0.8,0.9, 0.9, 0.95]) xdata = np.array(range(0,len(ydata),1)) def sigmoid(params): k = params[0] x0 = params[1] sd = params[2] yPred = 1 / (1+ np.exp(-k*(xdata-x0))) # Calculate negative log likelihood LL = -np.sum( stats.norm.logpdf(ydata, loc=yPred, scale=sd ) ) return(LL) initParams = [1, 1, 1] results = minimize(sigmoid, initParams, method='Nelder-Mead') print results.x estParms = results.x yOut = yPred = 1 / (1+ np.exp(-estParms[0]*(xdata-estParms[1]))) py.clf() py.plot(xdata,ydata, 'go') py.plot(xdata, yOut) py.show() This gives me the following:
Maximum Likelihood Curve/Model Fitting in Python Here's some pseudocode to do it. Of course, it depends on the error structure you choose. You don't need the stats models to do it, because Scipy has an minimizer built-in. The minimizer probably does
45,421
How do you report percentage accuracy for glmnet logistic regression?
glmnet is designed around a proper accuracy score, the (penalized) deviance. Summaries of predictive discrimination should use proper scores, not arbitrary classifications that are at odds with costs of false positives and false negatives. Consider a couple of accepted proper scoring rules: Brier (quadratic) score and logarithmic (deviance-like) score. You can manipulate the proportion classified correctly in a number of silly ways. The easiest way to see this is if the prevalence of $Y=1$ is 0.98 you will be 0.98 accurate by ignoring all the data and predicting everyone to have $Y=1$. Another way to saying all this is that by changing from an arbitrary cutoff of 0.5 to another arbitrary cutoff, different features will be selected. An improper scoring rule is optimized by a bogus model.
How do you report percentage accuracy for glmnet logistic regression?
glmnet is designed around a proper accuracy score, the (penalized) deviance. Summaries of predictive discrimination should use proper scores, not arbitrary classifications that are at odds with costs
How do you report percentage accuracy for glmnet logistic regression? glmnet is designed around a proper accuracy score, the (penalized) deviance. Summaries of predictive discrimination should use proper scores, not arbitrary classifications that are at odds with costs of false positives and false negatives. Consider a couple of accepted proper scoring rules: Brier (quadratic) score and logarithmic (deviance-like) score. You can manipulate the proportion classified correctly in a number of silly ways. The easiest way to see this is if the prevalence of $Y=1$ is 0.98 you will be 0.98 accurate by ignoring all the data and predicting everyone to have $Y=1$. Another way to saying all this is that by changing from an arbitrary cutoff of 0.5 to another arbitrary cutoff, different features will be selected. An improper scoring rule is optimized by a bogus model.
How do you report percentage accuracy for glmnet logistic regression? glmnet is designed around a proper accuracy score, the (penalized) deviance. Summaries of predictive discrimination should use proper scores, not arbitrary classifications that are at odds with costs
45,422
How do you report percentage accuracy for glmnet logistic regression?
The predict function for glmnet offers a "class" type that will predict the class rather than the response for binomial logistic regression, eliminating the need for your conditionals. You could also do the cv.glmnet using the type.measure parameter value "auc" or "class" to produce some validation accuracy measures prior to prediction.
How do you report percentage accuracy for glmnet logistic regression?
The predict function for glmnet offers a "class" type that will predict the class rather than the response for binomial logistic regression, eliminating the need for your conditionals. You could also
How do you report percentage accuracy for glmnet logistic regression? The predict function for glmnet offers a "class" type that will predict the class rather than the response for binomial logistic regression, eliminating the need for your conditionals. You could also do the cv.glmnet using the type.measure parameter value "auc" or "class" to produce some validation accuracy measures prior to prediction.
How do you report percentage accuracy for glmnet logistic regression? The predict function for glmnet offers a "class" type that will predict the class rather than the response for binomial logistic regression, eliminating the need for your conditionals. You could also
45,423
How do you report percentage accuracy for glmnet logistic regression?
A much simpler way of doing this is by using the predict function and finding the mean error: mean(predicted_y!=Yactual)
How do you report percentage accuracy for glmnet logistic regression?
A much simpler way of doing this is by using the predict function and finding the mean error: mean(predicted_y!=Yactual)
How do you report percentage accuracy for glmnet logistic regression? A much simpler way of doing this is by using the predict function and finding the mean error: mean(predicted_y!=Yactual)
How do you report percentage accuracy for glmnet logistic regression? A much simpler way of doing this is by using the predict function and finding the mean error: mean(predicted_y!=Yactual)
45,424
Order of variables in R lm model
Updated: There is only one intercept in the equation. The intercept consists of the observations related to factor A and year 1985 (which is the case for model 3). However, in your first case, you are omitting factor A (and thus it acts as base), where as in the model 2 you are using year 1985 as the base. So the coefficients must be different because you are comparing with the different bases. If you want to run the fixed effect, then there should be only 7 dummies (4 for years, and 3 for fm as in out_3). summary(out_1) Call: lm(formula = y ~ x + factor(yr) + factor(fm) - 1, data = d) Residuals: Min 1Q Median 3Q Max -1.5538 -0.5543 -0.1142 0.3762 2.1349 Coefficients: Estimate Std. Error t value Pr(>|t|) x 0.1723 0.4289 0.402 0.696 factor(yr)1985 0.7434 0.7129 1.043 0.319 factor(yr)1986 0.2433 0.7349 0.331 0.747 factor(yr)1987 0.5862 0.7015 0.836 0.421 factor(yr)1988 1.1247 0.6945 1.619 0.134 factor(yr)1989 1.0779 0.6981 1.544 0.151 factor(fm)B -0.8163 0.7025 -1.162 0.270 factor(fm)C -1.0703 0.7171 -1.493 0.164 factor(fm)D -1.2179 0.7067 -1.723 0.113 Residual standard error: 1.095 on 11 degrees of freedom Multiple R-squared: 0.3347, Adjusted R-squared: -0.2096 F-statistic: 0.615 on 9 and 11 DF, p-value: 0.7628 > summary(out_2) Call: lm(formula = y ~ x + factor(fm) + factor(yr) - 1, data = d) Residuals: Min 1Q Median 3Q Max -1.5538 -0.5543 -0.1142 0.3762 2.1349 Coefficients: Estimate Std. Error t value Pr(>|t|) x 0.17232 0.42894 0.402 0.696 factor(fm)A 0.74338 0.71286 1.043 0.319 factor(fm)B -0.07289 0.69443 -0.105 0.918 factor(fm)C -0.32696 0.69275 -0.472 0.646 factor(fm)D -0.47447 0.75862 -0.625 0.544 factor(yr)1986 -0.50005 0.77809 -0.643 0.534 factor(yr)1987 -0.15720 0.82354 -0.191 0.852 factor(yr)1988 0.38128 0.78301 0.487 0.636 factor(yr)1989 0.33454 0.77855 0.430 0.676 Residual standard error: 1.095 on 11 degrees of freedom Multiple R-squared: 0.3347, Adjusted R-squared: -0.2096 F-statistic: 0.615 on 9 and 11 DF, p-value: 0.7628 out_3 = lm(y~x+factor(fm)+factor(yr), data=d) > summary(out_3) Call: lm(formula = y ~ x + factor(fm) + factor(yr), data = d) Residuals: Min 1Q Median 3Q Max -1.2632 -0.2938 -0.1132 0.2488 1.2838 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -1.04018 0.49474 -2.102 0.05935 . x 0.03699 0.22976 0.161 0.87501 factor(fm)B 0.06037 0.48535 0.124 0.90325 factor(fm)C -0.27198 0.49027 -0.555 0.59017 factor(fm)D 0.34259 0.50111 0.684 0.50833 factor(yr)1986 1.14448 0.62217 1.839 0.09296 . factor(yr)1987 1.39348 0.54603 2.552 0.02690 * factor(yr)1988 1.95007 0.54562 3.574 0.00436 ** factor(yr)1989 1.34118 0.57869 2.318 0.04075 * --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.7643 on 11 degrees of freedom Multiple R-squared: 0.5898, Adjusted R-squared: 0.2915 F-statistic: 1.977 on 8 and 11 DF, p-value: 0.146
Order of variables in R lm model
Updated: There is only one intercept in the equation. The intercept consists of the observations related to factor A and year 1985 (which is the case for model 3). However, in your first case, you ar
Order of variables in R lm model Updated: There is only one intercept in the equation. The intercept consists of the observations related to factor A and year 1985 (which is the case for model 3). However, in your first case, you are omitting factor A (and thus it acts as base), where as in the model 2 you are using year 1985 as the base. So the coefficients must be different because you are comparing with the different bases. If you want to run the fixed effect, then there should be only 7 dummies (4 for years, and 3 for fm as in out_3). summary(out_1) Call: lm(formula = y ~ x + factor(yr) + factor(fm) - 1, data = d) Residuals: Min 1Q Median 3Q Max -1.5538 -0.5543 -0.1142 0.3762 2.1349 Coefficients: Estimate Std. Error t value Pr(>|t|) x 0.1723 0.4289 0.402 0.696 factor(yr)1985 0.7434 0.7129 1.043 0.319 factor(yr)1986 0.2433 0.7349 0.331 0.747 factor(yr)1987 0.5862 0.7015 0.836 0.421 factor(yr)1988 1.1247 0.6945 1.619 0.134 factor(yr)1989 1.0779 0.6981 1.544 0.151 factor(fm)B -0.8163 0.7025 -1.162 0.270 factor(fm)C -1.0703 0.7171 -1.493 0.164 factor(fm)D -1.2179 0.7067 -1.723 0.113 Residual standard error: 1.095 on 11 degrees of freedom Multiple R-squared: 0.3347, Adjusted R-squared: -0.2096 F-statistic: 0.615 on 9 and 11 DF, p-value: 0.7628 > summary(out_2) Call: lm(formula = y ~ x + factor(fm) + factor(yr) - 1, data = d) Residuals: Min 1Q Median 3Q Max -1.5538 -0.5543 -0.1142 0.3762 2.1349 Coefficients: Estimate Std. Error t value Pr(>|t|) x 0.17232 0.42894 0.402 0.696 factor(fm)A 0.74338 0.71286 1.043 0.319 factor(fm)B -0.07289 0.69443 -0.105 0.918 factor(fm)C -0.32696 0.69275 -0.472 0.646 factor(fm)D -0.47447 0.75862 -0.625 0.544 factor(yr)1986 -0.50005 0.77809 -0.643 0.534 factor(yr)1987 -0.15720 0.82354 -0.191 0.852 factor(yr)1988 0.38128 0.78301 0.487 0.636 factor(yr)1989 0.33454 0.77855 0.430 0.676 Residual standard error: 1.095 on 11 degrees of freedom Multiple R-squared: 0.3347, Adjusted R-squared: -0.2096 F-statistic: 0.615 on 9 and 11 DF, p-value: 0.7628 out_3 = lm(y~x+factor(fm)+factor(yr), data=d) > summary(out_3) Call: lm(formula = y ~ x + factor(fm) + factor(yr), data = d) Residuals: Min 1Q Median 3Q Max -1.2632 -0.2938 -0.1132 0.2488 1.2838 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -1.04018 0.49474 -2.102 0.05935 . x 0.03699 0.22976 0.161 0.87501 factor(fm)B 0.06037 0.48535 0.124 0.90325 factor(fm)C -0.27198 0.49027 -0.555 0.59017 factor(fm)D 0.34259 0.50111 0.684 0.50833 factor(yr)1986 1.14448 0.62217 1.839 0.09296 . factor(yr)1987 1.39348 0.54603 2.552 0.02690 * factor(yr)1988 1.95007 0.54562 3.574 0.00436 ** factor(yr)1989 1.34118 0.57869 2.318 0.04075 * --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.7643 on 11 degrees of freedom Multiple R-squared: 0.5898, Adjusted R-squared: 0.2915 F-statistic: 1.977 on 8 and 11 DF, p-value: 0.146
Order of variables in R lm model Updated: There is only one intercept in the equation. The intercept consists of the observations related to factor A and year 1985 (which is the case for model 3). However, in your first case, you ar
45,425
Order of variables in R lm model
# install.packages("tidyverse") library(dplyr) library(tibble) set.seed(0) d <- tibble( fm = c(rep("A", 5), rep("B", 5), rep("C", 5), rep("D", 5)), yr = rep(c(1985, 1986, 1987, 1988, 1989), 4), y = rnorm(length(yr)), x = rnorm(length(yr)) ) %>% mutate(shock = ifelse(yr == 1988, 1, 0)) In light of more recent posts on this topic, I thought I would highlight that R uses variable ordering to break collinearity. For example, factor(fm) - 1 in the first run and factor(yr) - 1 in the second run may give the impression that we are explicitly deciding which factor level to drop; this is not the case. Software makes compromises based upon variable ordering. Here is your first model: summary(lm(y ~ -1 + x + factor(fm) + factor(yr), data = d)) where I moved the -1 to the right of the tilde to avoid any confusion. Here, the -1 removes the intercept (i.e., column of 1's). The next variable, proceeding from left to right, is the firm fixed effects denoted by factor(fm); all levels will now be estimated. The third variable is the year fixed effects denoted by factor(yr). One level (i.e., 1985) must be dropped. Remember that all columns representing your firm dummies sum to unity, so R is going to drop a year effect to break the collinearity. See the abridged output below: Call: lm(formula = y ~ -1 + x + factor(fm) + factor(yr), data = d) Coefficients: Estimate Std. Error t value Pr(>|t|) x 0.17232 0.42894 0.402 0.696 factor(fm)A 0.74338 0.71286 1.043 0.319 factor(fm)B -0.07289 0.69443 -0.105 0.918 factor(fm)C -0.32696 0.69275 -0.472 0.646 factor(fm)D -0.47447 0.75862 -0.625 0.544 factor(yr)1986 -0.50005 0.77809 -0.643 0.534 factor(yr)1987 -0.15720 0.82354 -0.191 0.852 factor(yr)1988 0.38128 0.78301 0.487 0.636 factor(yr)1989 0.33454 0.77855 0.430 0.676 Now suppose we swap the firm and year effects. The model has the same structure as before: summary(lm(y ~ -1 + x + factor(yr) + factor(fm), data = d)) where we still introduce -1 inside of the lm() function but now the firm fixed effects are third in precedence. As a consequence, software will exclude a firm. As before, your series of year dummies sum to unity, so now a firm effect is dropped from estimation. See the abridged output below: Call: lm(formula = y ~ -1 + x + factor(yr) + factor(fm), data = d) Coefficients: Estimate Std. Error t value Pr(>|t|) x 0.1723 0.4289 0.402 0.696 factor(yr)1985 0.7434 0.7129 1.043 0.319 factor(yr)1986 0.2433 0.7349 0.331 0.747 factor(yr)1987 0.5862 0.7015 0.836 0.421 factor(yr)1988 1.1247 0.6945 1.619 0.134 factor(yr)1989 1.0779 0.6981 1.544 0.151 factor(fm)B -0.8163 0.7025 -1.162 0.270 factor(fm)C -1.0703 0.7171 -1.493 0.164 factor(fm)D -1.2179 0.7067 -1.723 0.113 Ordering wouldn't matter in this context if the intercept was included. It should be clear that one of the firm dummies and one of the year dummies will be collinear with the column of 1's appended to the model matrix. Run a third model but on this trial do not drop the intercept. It should result in 3 separate firm effects and 4 separate year effects. I am not sure why all estimates of x in the previous answer aren't equivalent (well noted by @SextusEmpiricus); they should be similar. A even better demonstration of how R breaks collinearity is when your model incorporates a redundant predictor at the level of $i$ or $t$. Suppose you suspect a macro level shock hit firms in 1988. You model the shock by including a time dummy specific to all entities in your panel. I will run one model with the shock preceding the time effects, then I will follow with a second run including the shock after the time effects. Here is the first run: Call: lm(formula = y ~ x + factor(fm) + shock + factor(yr), data = d) Coefficients: (1 not defined because of singularities) Estimate Std. Error t value Pr(>|t|) (Intercept) 0.7434 0.7129 1.043 0.319 x 0.1723 0.4289 0.402 0.696 factor(fm)B -0.8163 0.7025 -1.162 0.270 factor(fm)C -1.0703 0.7171 -1.493 0.164 factor(fm)D -1.2179 0.7067 -1.723 0.113 shock 0.3813 0.7830 0.487 0.636 factor(yr)1986 -0.5001 0.7781 -0.643 0.534 factor(yr)1987 -0.1572 0.8235 -0.191 0.852 factor(yr)1988 NA NA NA NA factor(yr)1989 0.3345 0.7785 0.430 0.676 Note the 1988 time shock precedes the year fixed effects in variable ordering. One year effect must be dropped to break the collinearity; R goes to the time effects. Now I will swap the ordering and re-estimate the model: Call: lm(formula = y ~ x + factor(fm) + factor(yr) + shock, data = d) Coefficients: (1 not defined because of singularities) Estimate Std. Error t value Pr(>|t|) (Intercept) 0.7434 0.7129 1.043 0.319 x 0.1723 0.4289 0.402 0.696 factor(fm)B -0.8163 0.7025 -1.162 0.270 factor(fm)C -1.0703 0.7171 -1.493 0.164 factor(fm)D -1.2179 0.7067 -1.723 0.113 factor(yr)1986 -0.5001 0.7781 -0.643 0.534 factor(yr)1987 -0.1572 0.8235 -0.191 0.852 factor(yr)1988 0.3813 0.7830 0.487 0.636 factor(yr)1989 0.3345 0.7785 0.430 0.676 shock NA NA NA NA Here, R drops shock as it is specified after the time effects. Remember, the year fixed effects represent the common shocks in each year affecting all firms, and so the time dummy modeling the shock in 1988 is redundant with the year fixed effects. This is yet another example of when ordering matters.
Order of variables in R lm model
# install.packages("tidyverse") library(dplyr) library(tibble) set.seed(0) d <- tibble( fm = c(rep("A", 5), rep("B", 5), rep("C", 5), rep("D", 5)), yr = rep(c(1985, 1986, 1987, 1988, 1989), 4),
Order of variables in R lm model # install.packages("tidyverse") library(dplyr) library(tibble) set.seed(0) d <- tibble( fm = c(rep("A", 5), rep("B", 5), rep("C", 5), rep("D", 5)), yr = rep(c(1985, 1986, 1987, 1988, 1989), 4), y = rnorm(length(yr)), x = rnorm(length(yr)) ) %>% mutate(shock = ifelse(yr == 1988, 1, 0)) In light of more recent posts on this topic, I thought I would highlight that R uses variable ordering to break collinearity. For example, factor(fm) - 1 in the first run and factor(yr) - 1 in the second run may give the impression that we are explicitly deciding which factor level to drop; this is not the case. Software makes compromises based upon variable ordering. Here is your first model: summary(lm(y ~ -1 + x + factor(fm) + factor(yr), data = d)) where I moved the -1 to the right of the tilde to avoid any confusion. Here, the -1 removes the intercept (i.e., column of 1's). The next variable, proceeding from left to right, is the firm fixed effects denoted by factor(fm); all levels will now be estimated. The third variable is the year fixed effects denoted by factor(yr). One level (i.e., 1985) must be dropped. Remember that all columns representing your firm dummies sum to unity, so R is going to drop a year effect to break the collinearity. See the abridged output below: Call: lm(formula = y ~ -1 + x + factor(fm) + factor(yr), data = d) Coefficients: Estimate Std. Error t value Pr(>|t|) x 0.17232 0.42894 0.402 0.696 factor(fm)A 0.74338 0.71286 1.043 0.319 factor(fm)B -0.07289 0.69443 -0.105 0.918 factor(fm)C -0.32696 0.69275 -0.472 0.646 factor(fm)D -0.47447 0.75862 -0.625 0.544 factor(yr)1986 -0.50005 0.77809 -0.643 0.534 factor(yr)1987 -0.15720 0.82354 -0.191 0.852 factor(yr)1988 0.38128 0.78301 0.487 0.636 factor(yr)1989 0.33454 0.77855 0.430 0.676 Now suppose we swap the firm and year effects. The model has the same structure as before: summary(lm(y ~ -1 + x + factor(yr) + factor(fm), data = d)) where we still introduce -1 inside of the lm() function but now the firm fixed effects are third in precedence. As a consequence, software will exclude a firm. As before, your series of year dummies sum to unity, so now a firm effect is dropped from estimation. See the abridged output below: Call: lm(formula = y ~ -1 + x + factor(yr) + factor(fm), data = d) Coefficients: Estimate Std. Error t value Pr(>|t|) x 0.1723 0.4289 0.402 0.696 factor(yr)1985 0.7434 0.7129 1.043 0.319 factor(yr)1986 0.2433 0.7349 0.331 0.747 factor(yr)1987 0.5862 0.7015 0.836 0.421 factor(yr)1988 1.1247 0.6945 1.619 0.134 factor(yr)1989 1.0779 0.6981 1.544 0.151 factor(fm)B -0.8163 0.7025 -1.162 0.270 factor(fm)C -1.0703 0.7171 -1.493 0.164 factor(fm)D -1.2179 0.7067 -1.723 0.113 Ordering wouldn't matter in this context if the intercept was included. It should be clear that one of the firm dummies and one of the year dummies will be collinear with the column of 1's appended to the model matrix. Run a third model but on this trial do not drop the intercept. It should result in 3 separate firm effects and 4 separate year effects. I am not sure why all estimates of x in the previous answer aren't equivalent (well noted by @SextusEmpiricus); they should be similar. A even better demonstration of how R breaks collinearity is when your model incorporates a redundant predictor at the level of $i$ or $t$. Suppose you suspect a macro level shock hit firms in 1988. You model the shock by including a time dummy specific to all entities in your panel. I will run one model with the shock preceding the time effects, then I will follow with a second run including the shock after the time effects. Here is the first run: Call: lm(formula = y ~ x + factor(fm) + shock + factor(yr), data = d) Coefficients: (1 not defined because of singularities) Estimate Std. Error t value Pr(>|t|) (Intercept) 0.7434 0.7129 1.043 0.319 x 0.1723 0.4289 0.402 0.696 factor(fm)B -0.8163 0.7025 -1.162 0.270 factor(fm)C -1.0703 0.7171 -1.493 0.164 factor(fm)D -1.2179 0.7067 -1.723 0.113 shock 0.3813 0.7830 0.487 0.636 factor(yr)1986 -0.5001 0.7781 -0.643 0.534 factor(yr)1987 -0.1572 0.8235 -0.191 0.852 factor(yr)1988 NA NA NA NA factor(yr)1989 0.3345 0.7785 0.430 0.676 Note the 1988 time shock precedes the year fixed effects in variable ordering. One year effect must be dropped to break the collinearity; R goes to the time effects. Now I will swap the ordering and re-estimate the model: Call: lm(formula = y ~ x + factor(fm) + factor(yr) + shock, data = d) Coefficients: (1 not defined because of singularities) Estimate Std. Error t value Pr(>|t|) (Intercept) 0.7434 0.7129 1.043 0.319 x 0.1723 0.4289 0.402 0.696 factor(fm)B -0.8163 0.7025 -1.162 0.270 factor(fm)C -1.0703 0.7171 -1.493 0.164 factor(fm)D -1.2179 0.7067 -1.723 0.113 factor(yr)1986 -0.5001 0.7781 -0.643 0.534 factor(yr)1987 -0.1572 0.8235 -0.191 0.852 factor(yr)1988 0.3813 0.7830 0.487 0.636 factor(yr)1989 0.3345 0.7785 0.430 0.676 shock NA NA NA NA Here, R drops shock as it is specified after the time effects. Remember, the year fixed effects represent the common shocks in each year affecting all firms, and so the time dummy modeling the shock in 1988 is redundant with the year fixed effects. This is yet another example of when ordering matters.
Order of variables in R lm model # install.packages("tidyverse") library(dplyr) library(tibble) set.seed(0) d <- tibble( fm = c(rep("A", 5), rep("B", 5), rep("C", 5), rep("D", 5)), yr = rep(c(1985, 1986, 1987, 1988, 1989), 4),
45,426
Validity of normality assumption in the case of multiple independent data sets with small sample size
This may help: DR Cox, PJ Solomon. 1986. Analysis of variability with large numbers of small samples. Biometrika 73: 543-554. Abstract: Procedures are discussed for the detailed analysis of distributional form, based on many samples of size r, where especially r= 2, 3, 4. The possibility of discriminating between different kinds of departure from the standard normal assumptions is discussed. Both graphical and more formal procedures are developed and illustrated by some data on pulse rates.
Validity of normality assumption in the case of multiple independent data sets with small sample siz
This may help: DR Cox, PJ Solomon. 1986. Analysis of variability with large numbers of small samples. Biometrika 73: 543-554. Abstract: Procedures are discussed for the detailed analysis of distri
Validity of normality assumption in the case of multiple independent data sets with small sample size This may help: DR Cox, PJ Solomon. 1986. Analysis of variability with large numbers of small samples. Biometrika 73: 543-554. Abstract: Procedures are discussed for the detailed analysis of distributional form, based on many samples of size r, where especially r= 2, 3, 4. The possibility of discriminating between different kinds of departure from the standard normal assumptions is discussed. Both graphical and more formal procedures are developed and illustrated by some data on pulse rates.
Validity of normality assumption in the case of multiple independent data sets with small sample siz This may help: DR Cox, PJ Solomon. 1986. Analysis of variability with large numbers of small samples. Biometrika 73: 543-554. Abstract: Procedures are discussed for the detailed analysis of distri
45,427
Validity of normality assumption in the case of multiple independent data sets with small sample size
Due to limitations in experimental setup, I only have small data sets with n=3. Despite the low df the difference between treated and control is large enough to generate a significant p-value. The problem is that with small sample sizes doing a t-test becomes more sensitive to the assumption that the data are drawn from a population of a normal distribution. In my case however, multiple independent experiments consistently yield a similar result. I cannot group the data of the experiments because of small differences in the data. If you treat the experiments as blocks, that can be used to account for this. (Alternatively, you may want to use random effects term on intercepts, especially if this is not under control.) So my question is whether it is defensible to make the normality assumption based on the data of multiple independent experiments with a small sample size? You can attempt to assess it if you assume a common error distribution and combine residuals across all experiments in order to do say a normal Q-Q plot (normal scores plot). If not am I right that it would not be appropriate to use any statistics in this case? You can still test your hypothesis without normality, but beware, you won't get very significant results with nonparametric tests and such tiny sample sizes. However, the combining experiments strategy (of using blocks) can work there too.
Validity of normality assumption in the case of multiple independent data sets with small sample siz
Due to limitations in experimental setup, I only have small data sets with n=3. Despite the low df the difference between treated and control is large enough to generate a significant p-value. The pro
Validity of normality assumption in the case of multiple independent data sets with small sample size Due to limitations in experimental setup, I only have small data sets with n=3. Despite the low df the difference between treated and control is large enough to generate a significant p-value. The problem is that with small sample sizes doing a t-test becomes more sensitive to the assumption that the data are drawn from a population of a normal distribution. In my case however, multiple independent experiments consistently yield a similar result. I cannot group the data of the experiments because of small differences in the data. If you treat the experiments as blocks, that can be used to account for this. (Alternatively, you may want to use random effects term on intercepts, especially if this is not under control.) So my question is whether it is defensible to make the normality assumption based on the data of multiple independent experiments with a small sample size? You can attempt to assess it if you assume a common error distribution and combine residuals across all experiments in order to do say a normal Q-Q plot (normal scores plot). If not am I right that it would not be appropriate to use any statistics in this case? You can still test your hypothesis without normality, but beware, you won't get very significant results with nonparametric tests and such tiny sample sizes. However, the combining experiments strategy (of using blocks) can work there too.
Validity of normality assumption in the case of multiple independent data sets with small sample siz Due to limitations in experimental setup, I only have small data sets with n=3. Despite the low df the difference between treated and control is large enough to generate a significant p-value. The pro
45,428
Validity of normality assumption in the case of multiple independent data sets with small sample size
There are certainly alternative statistics. You could do permutation tests, for example. You could also do nonparametric tests, such as Wilcoxon.
Validity of normality assumption in the case of multiple independent data sets with small sample siz
There are certainly alternative statistics. You could do permutation tests, for example. You could also do nonparametric tests, such as Wilcoxon.
Validity of normality assumption in the case of multiple independent data sets with small sample size There are certainly alternative statistics. You could do permutation tests, for example. You could also do nonparametric tests, such as Wilcoxon.
Validity of normality assumption in the case of multiple independent data sets with small sample siz There are certainly alternative statistics. You could do permutation tests, for example. You could also do nonparametric tests, such as Wilcoxon.
45,429
Gauss-Markov assumptions
The LS-Estimator is:$$b=\beta + (X'X)^{-1}X'e$$ The estimator is unbiased if $(X'X)^{-1}X'e$ converges to zero, and this is the case, if the designmatrix $X$ is not correlated with the error $e$. So, the necessary assumption is: $$E[X_{t,k}*e_t]=0$$
Gauss-Markov assumptions
The LS-Estimator is:$$b=\beta + (X'X)^{-1}X'e$$ The estimator is unbiased if $(X'X)^{-1}X'e$ converges to zero, and this is the case, if the designmatrix $X$ is not correlated with the error $e$. So,
Gauss-Markov assumptions The LS-Estimator is:$$b=\beta + (X'X)^{-1}X'e$$ The estimator is unbiased if $(X'X)^{-1}X'e$ converges to zero, and this is the case, if the designmatrix $X$ is not correlated with the error $e$. So, the necessary assumption is: $$E[X_{t,k}*e_t]=0$$
Gauss-Markov assumptions The LS-Estimator is:$$b=\beta + (X'X)^{-1}X'e$$ The estimator is unbiased if $(X'X)^{-1}X'e$ converges to zero, and this is the case, if the designmatrix $X$ is not correlated with the error $e$. So,
45,430
Gauss-Markov assumptions
The Gauss-Markov Theorem is actually telling us that in a regression model, where the expected value of our error terms is zero, $E(\epsilon_{i}) = 0$ and variance of the error terms is constant and finite $\sigma^{2}(\epsilon_{i}) = \sigma^{2} < \infty$ and $\epsilon_{i}$ and $\epsilon_{j}$ are uncorrelated for all i and j the least squares estimator $b_{0}$ and $b_{1}$ are unbiased and have minimum variance among all unbiased linear estimators. Note that there might be biased estimator which have a even lower variance. Extensive information about the Gauss-Markov Theorem, such as the mathematical proof of the Gauss-Markov Theorem can be found here http://economictheoryblog.com/2015/02/26/markov_theorem/ However, if you want to know which assumption is necessary for $b1$ to be an unbiased estimator for $\beta1$, I guess that assumption 1 to 4 of the following post (http://economictheoryblog.com/2015/04/01/ols_assumptions/) must be fulfilled to have an unbiased estimator.
Gauss-Markov assumptions
The Gauss-Markov Theorem is actually telling us that in a regression model, where the expected value of our error terms is zero, $E(\epsilon_{i}) = 0$ and variance of the error terms is constant and f
Gauss-Markov assumptions The Gauss-Markov Theorem is actually telling us that in a regression model, where the expected value of our error terms is zero, $E(\epsilon_{i}) = 0$ and variance of the error terms is constant and finite $\sigma^{2}(\epsilon_{i}) = \sigma^{2} < \infty$ and $\epsilon_{i}$ and $\epsilon_{j}$ are uncorrelated for all i and j the least squares estimator $b_{0}$ and $b_{1}$ are unbiased and have minimum variance among all unbiased linear estimators. Note that there might be biased estimator which have a even lower variance. Extensive information about the Gauss-Markov Theorem, such as the mathematical proof of the Gauss-Markov Theorem can be found here http://economictheoryblog.com/2015/02/26/markov_theorem/ However, if you want to know which assumption is necessary for $b1$ to be an unbiased estimator for $\beta1$, I guess that assumption 1 to 4 of the following post (http://economictheoryblog.com/2015/04/01/ols_assumptions/) must be fulfilled to have an unbiased estimator.
Gauss-Markov assumptions The Gauss-Markov Theorem is actually telling us that in a regression model, where the expected value of our error terms is zero, $E(\epsilon_{i}) = 0$ and variance of the error terms is constant and f
45,431
Gauss-Markov assumptions
$$\hat{\beta} = ([inv(X'X)]X')(X\beta + \epsilon)$$ $$\hat{\beta} = \beta + ([inv(X'X)]X')\epsilon$$ $\hat{\beta}$ is an unbiased estimator of $\beta$ under two conditions: $X$ is non-stochastic $$E(\hat{\beta}) = \beta + E[([inv(X'X)]X')\epsilon]$$ if $X$ is deterministic, this would reduce to: $$E(\hat{\beta}) = \beta + ([inv(X'X)]X') E[\epsilon]$$ The second term on right hand side, $E[\epsilon]$ is zero under one of the Gauss markov assumption. $X$ is stochastic but independent of error ($\epsilon$) Using this, we can reduce the equation to: $$E(\hat{\beta}) = \beta + inv(X'X)] E[(X')\epsilon]$$ where $E[(X')\epsilon] = 0$ from an assumption that comes from one of the OLS's properties, $E[X'e] = 0$. Reference: https://web.stanford.edu/~mrosenfe/soc_meth_proj3/matrix_OLS_NYU_notes.pdf Thanks Anurag
Gauss-Markov assumptions
$$\hat{\beta} = ([inv(X'X)]X')(X\beta + \epsilon)$$ $$\hat{\beta} = \beta + ([inv(X'X)]X')\epsilon$$ $\hat{\beta}$ is an unbiased estimator of $\beta$ under two conditions: $X$ is non-stochastic $$E(
Gauss-Markov assumptions $$\hat{\beta} = ([inv(X'X)]X')(X\beta + \epsilon)$$ $$\hat{\beta} = \beta + ([inv(X'X)]X')\epsilon$$ $\hat{\beta}$ is an unbiased estimator of $\beta$ under two conditions: $X$ is non-stochastic $$E(\hat{\beta}) = \beta + E[([inv(X'X)]X')\epsilon]$$ if $X$ is deterministic, this would reduce to: $$E(\hat{\beta}) = \beta + ([inv(X'X)]X') E[\epsilon]$$ The second term on right hand side, $E[\epsilon]$ is zero under one of the Gauss markov assumption. $X$ is stochastic but independent of error ($\epsilon$) Using this, we can reduce the equation to: $$E(\hat{\beta}) = \beta + inv(X'X)] E[(X')\epsilon]$$ where $E[(X')\epsilon] = 0$ from an assumption that comes from one of the OLS's properties, $E[X'e] = 0$. Reference: https://web.stanford.edu/~mrosenfe/soc_meth_proj3/matrix_OLS_NYU_notes.pdf Thanks Anurag
Gauss-Markov assumptions $$\hat{\beta} = ([inv(X'X)]X')(X\beta + \epsilon)$$ $$\hat{\beta} = \beta + ([inv(X'X)]X')\epsilon$$ $\hat{\beta}$ is an unbiased estimator of $\beta$ under two conditions: $X$ is non-stochastic $$E(
45,432
Distribution of function of variable having a Gaussian distribution
I think you are talking about change of variables. If X is a continuous r.v. with pdf $f_X(x)$ and sample space S, if $g: S \rightarrow T$ is an invertible transformation with differentiable inverse $h = g^{-1}$, and $Y = g(X)$, then Y is a continuous r.v. with pdf $f_Y(y)$ defined by $f_Y(y) = f_X(h(y)) \cdot |h'(y)|$. For example, suppose $X \sim exp(\lambda)$, what is the distribution of $X^2$? Well, here we have $g: (0,\infty) \rightarrow (0,\infty)$ defined by $g(x) = x^2$. The inverse if $h(y) = g^{-1}(y) = \sqrt y$ Then $h'(y) = 0.5 y^{-1/2}$. The density of X is $f_X(x) = \lambda e^{-\lambda x}$ so $f_X(h(y)) = \lambda e^{-\lambda \sqrt y}$. And finally multiplying by the derivative gives $$ f_Y(y) = f_X(h(y)) \cdot |h'(y)| = \lambda e^{-\lambda \sqrt y} \cdot 0.5 y^{-1/2} $$ This simplifies to $$f_Y(y) = \frac{\lambda e^{-\lambda \sqrt y}}{2\sqrt y}$$ There is your density for a function of a random variable.
Distribution of function of variable having a Gaussian distribution
I think you are talking about change of variables. If X is a continuous r.v. with pdf $f_X(x)$ and sample space S, if $g: S \rightarrow T$ is an invertible transformation with differentiable inverse $
Distribution of function of variable having a Gaussian distribution I think you are talking about change of variables. If X is a continuous r.v. with pdf $f_X(x)$ and sample space S, if $g: S \rightarrow T$ is an invertible transformation with differentiable inverse $h = g^{-1}$, and $Y = g(X)$, then Y is a continuous r.v. with pdf $f_Y(y)$ defined by $f_Y(y) = f_X(h(y)) \cdot |h'(y)|$. For example, suppose $X \sim exp(\lambda)$, what is the distribution of $X^2$? Well, here we have $g: (0,\infty) \rightarrow (0,\infty)$ defined by $g(x) = x^2$. The inverse if $h(y) = g^{-1}(y) = \sqrt y$ Then $h'(y) = 0.5 y^{-1/2}$. The density of X is $f_X(x) = \lambda e^{-\lambda x}$ so $f_X(h(y)) = \lambda e^{-\lambda \sqrt y}$. And finally multiplying by the derivative gives $$ f_Y(y) = f_X(h(y)) \cdot |h'(y)| = \lambda e^{-\lambda \sqrt y} \cdot 0.5 y^{-1/2} $$ This simplifies to $$f_Y(y) = \frac{\lambda e^{-\lambda \sqrt y}}{2\sqrt y}$$ There is your density for a function of a random variable.
Distribution of function of variable having a Gaussian distribution I think you are talking about change of variables. If X is a continuous r.v. with pdf $f_X(x)$ and sample space S, if $g: S \rightarrow T$ is an invertible transformation with differentiable inverse $
45,433
Distribution of function of variable having a Gaussian distribution
Addressing the last question in particular -- 1) Consider $X$ being standard Gaussian (mean 0, variance 1), and $U = \Phi(X)$ where $\Phi()$ is the standard normal cdf. Does $U$ have a Gaussian distribution? Let's simulate (in R in this case): u <- pnorm(rnorm(100000L)) hist(u,n=300) ... nope. In fact you can work out that it must be standard uniform. 2) Consider $X$ being standard Gaussian (mean 0, variance 1), and $Y = f(X) = X^2$. Does $Y$ have a Gaussian distribution? Let's simulate (in R): y <- rnorm(100000L)^2 hist(y,n=300) and what do we see? ... nope. In fact you can work out that it's chi-squared(1). In particular circumstances, certain results imply you can obtain an approximately Gaussian distribution... but it's not the general case. For example, if the mean is many standard deviations from 0, (e.g. $X\sim N(5,0.1^2)$), then $Y=X^2$ is at least approximately normal: y <- rnorm(100000L,5,.1)^2 hist(y,n=300) ... and similarly $\exp(X)$, and $X^{1/3}$ and $log(X^2+\sqrt\pi)$, and a whole menagerie of other transformations will also give approximately Gaussian distributions in this case. Edit: You do get exact normality if you transform a Gaussian random variable with a linear transformation, so, as @DilipSarwate points out, if $X$ is Gaussian, $Y = a+bX$ is Gaussian (the case $b=0$ which was discussed by @gung and @whuber in comments is 'degenerate', but usually still counted as Gaussian when considering the whole location-scale family of Gaussians). It's not quite the case that you can get to a normal only by linear transformation, though if you are restricted to monotonic transformations, I think this will be the case. A nonlinear transformation of a normal that yields a normal: Let $X$ be standard Gaussian. Let $F_1$ be the cdf of a $\chi^2_1$ random variable and $\Phi$ be the cdf of a standard normal. Then $\Phi^{-1}(F_1(X^2))$ is a nonlinear (and non-monotonic) transformation of $X$ where the resulting random variable is Gaussian. y <- qnorm(pchisq(rnorm(100000L)^2,1)) hist(y,n=200) In respect of the first question, if $Y=h(X)$ you can in principle work out the distribution of $Y$. If $X$ is continuous and $h$ is invertible, it goes like this: If $F_X$ is the cdf of $X$ then $P(Y\leq y) = P(h(X)\leq y) = P(X\leq h^{-1}(y)) = F_X(h^{-1}(y)))$. From there one can work out the density by differentiation, leading to the standard result: $$f_Y(y)= f_X(h^{-1}(y)) \left|\frac{d h^{-1}(y)}{dy}\right|$$ In other cases things are more complicated, but in some cases may still be doable.
Distribution of function of variable having a Gaussian distribution
Addressing the last question in particular -- 1) Consider $X$ being standard Gaussian (mean 0, variance 1), and $U = \Phi(X)$ where $\Phi()$ is the standard normal cdf. Does $U$ have a Gaussian distr
Distribution of function of variable having a Gaussian distribution Addressing the last question in particular -- 1) Consider $X$ being standard Gaussian (mean 0, variance 1), and $U = \Phi(X)$ where $\Phi()$ is the standard normal cdf. Does $U$ have a Gaussian distribution? Let's simulate (in R in this case): u <- pnorm(rnorm(100000L)) hist(u,n=300) ... nope. In fact you can work out that it must be standard uniform. 2) Consider $X$ being standard Gaussian (mean 0, variance 1), and $Y = f(X) = X^2$. Does $Y$ have a Gaussian distribution? Let's simulate (in R): y <- rnorm(100000L)^2 hist(y,n=300) and what do we see? ... nope. In fact you can work out that it's chi-squared(1). In particular circumstances, certain results imply you can obtain an approximately Gaussian distribution... but it's not the general case. For example, if the mean is many standard deviations from 0, (e.g. $X\sim N(5,0.1^2)$), then $Y=X^2$ is at least approximately normal: y <- rnorm(100000L,5,.1)^2 hist(y,n=300) ... and similarly $\exp(X)$, and $X^{1/3}$ and $log(X^2+\sqrt\pi)$, and a whole menagerie of other transformations will also give approximately Gaussian distributions in this case. Edit: You do get exact normality if you transform a Gaussian random variable with a linear transformation, so, as @DilipSarwate points out, if $X$ is Gaussian, $Y = a+bX$ is Gaussian (the case $b=0$ which was discussed by @gung and @whuber in comments is 'degenerate', but usually still counted as Gaussian when considering the whole location-scale family of Gaussians). It's not quite the case that you can get to a normal only by linear transformation, though if you are restricted to monotonic transformations, I think this will be the case. A nonlinear transformation of a normal that yields a normal: Let $X$ be standard Gaussian. Let $F_1$ be the cdf of a $\chi^2_1$ random variable and $\Phi$ be the cdf of a standard normal. Then $\Phi^{-1}(F_1(X^2))$ is a nonlinear (and non-monotonic) transformation of $X$ where the resulting random variable is Gaussian. y <- qnorm(pchisq(rnorm(100000L)^2,1)) hist(y,n=200) In respect of the first question, if $Y=h(X)$ you can in principle work out the distribution of $Y$. If $X$ is continuous and $h$ is invertible, it goes like this: If $F_X$ is the cdf of $X$ then $P(Y\leq y) = P(h(X)\leq y) = P(X\leq h^{-1}(y)) = F_X(h^{-1}(y)))$. From there one can work out the density by differentiation, leading to the standard result: $$f_Y(y)= f_X(h^{-1}(y)) \left|\frac{d h^{-1}(y)}{dy}\right|$$ In other cases things are more complicated, but in some cases may still be doable.
Distribution of function of variable having a Gaussian distribution Addressing the last question in particular -- 1) Consider $X$ being standard Gaussian (mean 0, variance 1), and $U = \Phi(X)$ where $\Phi()$ is the standard normal cdf. Does $U$ have a Gaussian distr
45,434
Minimum no. of observations required for statistical distribution fitting!
Well, in the special case of loss data I think most appropriate is the second source, but I give you some others too: http://imash.leeds.ac.uk/dicode/wp4/Stats2-Forum/view_topic.php?id=10079 http://www.mathwave.com/articles/distribution-fitting-preliminary.html a pdf: http://www.vanbelle.org/chapters/webchapter2.pdf and see this related question: How many data points to fit an ex-Gaussian distribution? I can tell you from my research, that in case of loss returns from stocks you need quite a lot of values to estimate an appropriate distribution correctly. Loss distributions are often leptokurtic and skewed, therefore the assumption of normality can be rejected. Especially if you are interested in Risk Management you focus on the tails. Therefore you will need at least 200 observations from my knowledge to get a basic idea of the distributions of extreme values. If you really want to do extreme value theory for risk management you will have to consider way more observations, since these are values which occur mostly with a small probability, so in case of, let's say 5% you have just 0,05*200=10 extreme values. Please note, you say "stable distribution". This is not really convenient in this context, since stable distributions are a different topic, e.g. the Cauchy distribution is stable. I think it is more appropriate to say, that the estimators should have a small variance, so they do not vary to much, if you do a reestimation with another sample. This will lead to another statistical topic.
Minimum no. of observations required for statistical distribution fitting!
Well, in the special case of loss data I think most appropriate is the second source, but I give you some others too: http://imash.leeds.ac.uk/dicode/wp4/Stats2-Forum/view_topic.php?id=10079 http://
Minimum no. of observations required for statistical distribution fitting! Well, in the special case of loss data I think most appropriate is the second source, but I give you some others too: http://imash.leeds.ac.uk/dicode/wp4/Stats2-Forum/view_topic.php?id=10079 http://www.mathwave.com/articles/distribution-fitting-preliminary.html a pdf: http://www.vanbelle.org/chapters/webchapter2.pdf and see this related question: How many data points to fit an ex-Gaussian distribution? I can tell you from my research, that in case of loss returns from stocks you need quite a lot of values to estimate an appropriate distribution correctly. Loss distributions are often leptokurtic and skewed, therefore the assumption of normality can be rejected. Especially if you are interested in Risk Management you focus on the tails. Therefore you will need at least 200 observations from my knowledge to get a basic idea of the distributions of extreme values. If you really want to do extreme value theory for risk management you will have to consider way more observations, since these are values which occur mostly with a small probability, so in case of, let's say 5% you have just 0,05*200=10 extreme values. Please note, you say "stable distribution". This is not really convenient in this context, since stable distributions are a different topic, e.g. the Cauchy distribution is stable. I think it is more appropriate to say, that the estimators should have a small variance, so they do not vary to much, if you do a reestimation with another sample. This will lead to another statistical topic.
Minimum no. of observations required for statistical distribution fitting! Well, in the special case of loss data I think most appropriate is the second source, but I give you some others too: http://imash.leeds.ac.uk/dicode/wp4/Stats2-Forum/view_topic.php?id=10079 http://
45,435
What is behind JAGS (Just Another Gibbs Sampler)?
There are several tools used by JAGS and/or BUGS. Where conjugate distributions are used, straight Gibbs sampling is done. When that's not the case, adaptive rejection, slice sampling, or Metropolis-Hastings might be used (this is the case with BUGS at least; I believe it would be the case for JAGS as well). You can examine the source code yourself and see exactly what it's doing in various circumstances. Also check out the discussion and the wiki. Martyn Plummer's jags blog also has useful information: http://martynplummer.wordpress.com/
What is behind JAGS (Just Another Gibbs Sampler)?
There are several tools used by JAGS and/or BUGS. Where conjugate distributions are used, straight Gibbs sampling is done. When that's not the case, adaptive rejection, slice sampling, or Metropolis-H
What is behind JAGS (Just Another Gibbs Sampler)? There are several tools used by JAGS and/or BUGS. Where conjugate distributions are used, straight Gibbs sampling is done. When that's not the case, adaptive rejection, slice sampling, or Metropolis-Hastings might be used (this is the case with BUGS at least; I believe it would be the case for JAGS as well). You can examine the source code yourself and see exactly what it's doing in various circumstances. Also check out the discussion and the wiki. Martyn Plummer's jags blog also has useful information: http://martynplummer.wordpress.com/
What is behind JAGS (Just Another Gibbs Sampler)? There are several tools used by JAGS and/or BUGS. Where conjugate distributions are used, straight Gibbs sampling is done. When that's not the case, adaptive rejection, slice sampling, or Metropolis-H
45,436
What is behind JAGS (Just Another Gibbs Sampler)?
According to the JAGS documentation, A report on the samplers chosen by the model, and the stochastic nodes they act on, can be generated using the “SAMPLERS TO” command. It seems that the user can't control the choice of sampler, which is automatically chosen by JAGS, as described in the manual. I'd say that typically, it will choose a slice sampler. Again, to quote the documentation, Slice sampling [Neal, 2003] is the “work horse” sampling method in JAGS.
What is behind JAGS (Just Another Gibbs Sampler)?
According to the JAGS documentation, A report on the samplers chosen by the model, and the stochastic nodes they act on, can be generated using the “SAMPLERS TO” command. It seems that the user can
What is behind JAGS (Just Another Gibbs Sampler)? According to the JAGS documentation, A report on the samplers chosen by the model, and the stochastic nodes they act on, can be generated using the “SAMPLERS TO” command. It seems that the user can't control the choice of sampler, which is automatically chosen by JAGS, as described in the manual. I'd say that typically, it will choose a slice sampler. Again, to quote the documentation, Slice sampling [Neal, 2003] is the “work horse” sampling method in JAGS.
What is behind JAGS (Just Another Gibbs Sampler)? According to the JAGS documentation, A report on the samplers chosen by the model, and the stochastic nodes they act on, can be generated using the “SAMPLERS TO” command. It seems that the user can
45,437
Acceptance Rate of Statistical Journals
Well, you can usually obtain these statistics in the annual reports, which are available if you have a subscription to elsevier or otherwise. For statistics per se, it is difficult to find a comprised table, as it is usually applied in a interdisciplinary/multidisciplinary context. However, you fill easily find lists (google) on other disciplines that will encompass statistical journals. For example, in economic journal reviews, you will always find a sub section on econometrics and statistics journals. I found, however, a summary of annual reports where you can obtain a lot of data on actual rejection rates for most statistical journals (2010) [here], yet not "exactly" neatly organized in a table. However, a word of (kindly advised) warning. Rejection rates are essentially meaningless imho. You will find 4 star journals with 5% acceptance rate, but also as high as 30%. Note, that some high impact journals ask for more than 200 dollars submission fee + revision fee extra (if it gets to that stage), so that only "confident" researchers consider to submit in the first place. Other journals in the same league are essentially for free which attracts a lot of first timers and thus increases the rejection rate. This totally skews the sample. Moreover, some authors are in high impact journals were accepted by invitation, which biases further the results. Good luck!
Acceptance Rate of Statistical Journals
Well, you can usually obtain these statistics in the annual reports, which are available if you have a subscription to elsevier or otherwise. For statistics per se, it is difficult to find a comprised
Acceptance Rate of Statistical Journals Well, you can usually obtain these statistics in the annual reports, which are available if you have a subscription to elsevier or otherwise. For statistics per se, it is difficult to find a comprised table, as it is usually applied in a interdisciplinary/multidisciplinary context. However, you fill easily find lists (google) on other disciplines that will encompass statistical journals. For example, in economic journal reviews, you will always find a sub section on econometrics and statistics journals. I found, however, a summary of annual reports where you can obtain a lot of data on actual rejection rates for most statistical journals (2010) [here], yet not "exactly" neatly organized in a table. However, a word of (kindly advised) warning. Rejection rates are essentially meaningless imho. You will find 4 star journals with 5% acceptance rate, but also as high as 30%. Note, that some high impact journals ask for more than 200 dollars submission fee + revision fee extra (if it gets to that stage), so that only "confident" researchers consider to submit in the first place. Other journals in the same league are essentially for free which attracts a lot of first timers and thus increases the rejection rate. This totally skews the sample. Moreover, some authors are in high impact journals were accepted by invitation, which biases further the results. Good luck!
Acceptance Rate of Statistical Journals Well, you can usually obtain these statistics in the annual reports, which are available if you have a subscription to elsevier or otherwise. For statistics per se, it is difficult to find a comprised
45,438
contrapositive of probability
No, $P(A\mid B) = 0.95$ does not tell you very much about $P(B^c\mid A^c)$. For example, suppose that $P(B) = 0.5$ and $P(A\cap B) = 0.475$ so that $$P(A\mid B) = \frac{P(A\cap B)}{P(B)} = \frac{0.475}{0.5} = 0.95.$$ We also have that $P(A^c\cap B) = P(B) - P(A\cap B) = 0.5-0.475 = 0.025$. Now consider two possibilities for $P(A^c\cap B^c)$ and $P(A\cap B^c)$. Suppose $P(A^c\cap B^c) = 0$ and $P(A\cap B^c) = 0.5$. This means that $P(A) = P(A\cap B) + P(A\cap B^c) = 0.475 + 0.5 = 0.975$ and so $P(A^c) = 1-P(A) = 0.025$. Hence, $$P(B^c\mid A^c) = \frac{P(A^c \cap B^c)}{P(A^c)} = 0.$$ Suppose $P(A^c\cap B^c) = 0.5$ and $P(A\cap B^c) = 0$. This means that $P(A^c) = P(A^c\cap B) + P(A^c\cap B^c) = 0.025+0.5 = 0.525$. Hence, $$P(B^c\mid A^c) = \frac{P(A^c \cap B^c)}{P(A^c)} = \frac{0.5}{0.525} = 0.95238\ldots.$$ For intermediate choices of $P(A^c\cap B^c)$ and $P(A\cap B^c)$, we can come up with other values, including your desired $0.95$, for $P(B^c\mid A^c)$.
contrapositive of probability
No, $P(A\mid B) = 0.95$ does not tell you very much about $P(B^c\mid A^c)$. For example, suppose that $P(B) = 0.5$ and $P(A\cap B) = 0.475$ so that $$P(A\mid B) = \frac{P(A\cap B)}{P(B)} = \frac{0.475
contrapositive of probability No, $P(A\mid B) = 0.95$ does not tell you very much about $P(B^c\mid A^c)$. For example, suppose that $P(B) = 0.5$ and $P(A\cap B) = 0.475$ so that $$P(A\mid B) = \frac{P(A\cap B)}{P(B)} = \frac{0.475}{0.5} = 0.95.$$ We also have that $P(A^c\cap B) = P(B) - P(A\cap B) = 0.5-0.475 = 0.025$. Now consider two possibilities for $P(A^c\cap B^c)$ and $P(A\cap B^c)$. Suppose $P(A^c\cap B^c) = 0$ and $P(A\cap B^c) = 0.5$. This means that $P(A) = P(A\cap B) + P(A\cap B^c) = 0.475 + 0.5 = 0.975$ and so $P(A^c) = 1-P(A) = 0.025$. Hence, $$P(B^c\mid A^c) = \frac{P(A^c \cap B^c)}{P(A^c)} = 0.$$ Suppose $P(A^c\cap B^c) = 0.5$ and $P(A\cap B^c) = 0$. This means that $P(A^c) = P(A^c\cap B) + P(A^c\cap B^c) = 0.025+0.5 = 0.525$. Hence, $$P(B^c\mid A^c) = \frac{P(A^c \cap B^c)}{P(A^c)} = \frac{0.5}{0.525} = 0.95238\ldots.$$ For intermediate choices of $P(A^c\cap B^c)$ and $P(A\cap B^c)$, we can come up with other values, including your desired $0.95$, for $P(B^c\mid A^c)$.
contrapositive of probability No, $P(A\mid B) = 0.95$ does not tell you very much about $P(B^c\mid A^c)$. For example, suppose that $P(B) = 0.5$ and $P(A\cap B) = 0.475$ so that $$P(A\mid B) = \frac{P(A\cap B)}{P(B)} = \frac{0.475
45,439
contrapositive of probability
To approach it conceptually, I'd say that the contrapositive is only implied in the case of absolute conditionals. A->B means "A always implies B (i.e., P(B|A) = 1). It does not mean "this conditional is considered correct for any case in which A and B are true." If P(B|A) = .95 then there are cases that contradict the statement A->B and therefore the contrapositive of that rule is not implied in any fashion.
contrapositive of probability
To approach it conceptually, I'd say that the contrapositive is only implied in the case of absolute conditionals. A->B means "A always implies B (i.e., P(B|A) = 1). It does not mean "this conditional
contrapositive of probability To approach it conceptually, I'd say that the contrapositive is only implied in the case of absolute conditionals. A->B means "A always implies B (i.e., P(B|A) = 1). It does not mean "this conditional is considered correct for any case in which A and B are true." If P(B|A) = .95 then there are cases that contradict the statement A->B and therefore the contrapositive of that rule is not implied in any fashion.
contrapositive of probability To approach it conceptually, I'd say that the contrapositive is only implied in the case of absolute conditionals. A->B means "A always implies B (i.e., P(B|A) = 1). It does not mean "this conditional
45,440
contrapositive of probability
A couple of points in addition to the good answers you see already. You use the phrase "null hypothesis" which is generally used in frequentist statistics. In frequentist statistics the null hypothesis is a fixed fact not subject to probability so saying something like the "null hypothesis is wrong with 95% chance" is meaningless. Bayesians define probability in terms of our knowledge about something and can therefore talk about the probability of a null hypothesis being true, but most Bayesians don't like to use the phrase "null hypothesis". But if we mix the 2 and talk about a Bayesian probability of the null hypothesis being true, then we also need a prior distribution and the posterior probability will depend on that prior along with the data. Consider the null hypothesis that a coin is 2-headed (prob of heads is 1) and the observed data of 1 flip of the coin which came up heads. In frequentist statistics this would result in a p-value of 1 (or 100%) which means that the observed data is consistent with the null hypothesis. It does not mean that there is a 100% chance that the coin is 2 headed. In fact the data we have is consistent with a null of a fair coin (p=0.5) and other possibilities as well. If we only do this once then the coin is either 2-headed or it is not, there is no probability involved with regaurd to the coin itself.
contrapositive of probability
A couple of points in addition to the good answers you see already. You use the phrase "null hypothesis" which is generally used in frequentist statistics. In frequentist statistics the null hypothes
contrapositive of probability A couple of points in addition to the good answers you see already. You use the phrase "null hypothesis" which is generally used in frequentist statistics. In frequentist statistics the null hypothesis is a fixed fact not subject to probability so saying something like the "null hypothesis is wrong with 95% chance" is meaningless. Bayesians define probability in terms of our knowledge about something and can therefore talk about the probability of a null hypothesis being true, but most Bayesians don't like to use the phrase "null hypothesis". But if we mix the 2 and talk about a Bayesian probability of the null hypothesis being true, then we also need a prior distribution and the posterior probability will depend on that prior along with the data. Consider the null hypothesis that a coin is 2-headed (prob of heads is 1) and the observed data of 1 flip of the coin which came up heads. In frequentist statistics this would result in a p-value of 1 (or 100%) which means that the observed data is consistent with the null hypothesis. It does not mean that there is a 100% chance that the coin is 2 headed. In fact the data we have is consistent with a null of a fair coin (p=0.5) and other possibilities as well. If we only do this once then the coin is either 2-headed or it is not, there is no probability involved with regaurd to the coin itself.
contrapositive of probability A couple of points in addition to the good answers you see already. You use the phrase "null hypothesis" which is generally used in frequentist statistics. In frequentist statistics the null hypothes
45,441
Interpreting p-value significance from Pearson correlation
You have interpreted these results correctly according to the conventional textbook scheme. Personally, I am often not a fan of the standard way of thinking about p-values. (Mounting soapbox...) Firstly, it's worth considering that there are several valid ways to look at p-values. Fisher thought of them as a continuous measure of evidence against the null hypothesis, and Neyman & Pearson used them as the hub around which the decision making process turned. The most common way p-values seem to be used is not valid under either approach. The Neyman-Pearson framework has much to speak for it, in my opinion, but is primarily applicable in situations where there are theories that clearly posit two possible values, a null value (which could be $r_{null}=0$, but could be another number), and an alternative value ($r_{alt}$). In such a case, you could design your whole investigation around differentiating between those two values. This would entail specifying, among other things, $\alpha$ (the long-run type I error rate you're willing to live with), $\beta$ (the long-run type II error rate you're willing to live with), $N$ (the sample size), etc. In that context, it makes sense to me to say that something is 'significant' or 'not-significant'. However, I believe those situations are the minority of the cases. For example, for your second sample, I would say that you cannot conclude with more than 70% confidence that the correlation is positive. You will also want to examine your data and think about possible non-linearities and range restriction. (Stepping down from soapbox...)
Interpreting p-value significance from Pearson correlation
You have interpreted these results correctly according to the conventional textbook scheme. Personally, I am often not a fan of the standard way of thinking about p-values. (Mounting soapbox...) F
Interpreting p-value significance from Pearson correlation You have interpreted these results correctly according to the conventional textbook scheme. Personally, I am often not a fan of the standard way of thinking about p-values. (Mounting soapbox...) Firstly, it's worth considering that there are several valid ways to look at p-values. Fisher thought of them as a continuous measure of evidence against the null hypothesis, and Neyman & Pearson used them as the hub around which the decision making process turned. The most common way p-values seem to be used is not valid under either approach. The Neyman-Pearson framework has much to speak for it, in my opinion, but is primarily applicable in situations where there are theories that clearly posit two possible values, a null value (which could be $r_{null}=0$, but could be another number), and an alternative value ($r_{alt}$). In such a case, you could design your whole investigation around differentiating between those two values. This would entail specifying, among other things, $\alpha$ (the long-run type I error rate you're willing to live with), $\beta$ (the long-run type II error rate you're willing to live with), $N$ (the sample size), etc. In that context, it makes sense to me to say that something is 'significant' or 'not-significant'. However, I believe those situations are the minority of the cases. For example, for your second sample, I would say that you cannot conclude with more than 70% confidence that the correlation is positive. You will also want to examine your data and think about possible non-linearities and range restriction. (Stepping down from soapbox...)
Interpreting p-value significance from Pearson correlation You have interpreted these results correctly according to the conventional textbook scheme. Personally, I am often not a fan of the standard way of thinking about p-values. (Mounting soapbox...) F
45,442
Interpreting p-value significance from Pearson correlation
Consistent with @gung, I believe that hypothesis testing is very problematic, especially in this particular correlation assessment setting. It is far more useful, and will get us into less trouble, to think of this as an estimation problem: we are estimating the unitness strength of association of two variables. We can compute an uncertainty interval for the estimate, e.g. a 0.95 confidence interval. If this interval is $[a,b]$ we can roughly say that our data are consistent with an underlying true correlation between $a$ and $b$ with 0.95 "confidence", if model and random sampling assumptions are true. You can also compute a worst-case (which happens with the true correlation is zero) margin of error for the estimating the correlation. This is described in BBR Section 8.5.2.
Interpreting p-value significance from Pearson correlation
Consistent with @gung, I believe that hypothesis testing is very problematic, especially in this particular correlation assessment setting. It is far more useful, and will get us into less trouble, t
Interpreting p-value significance from Pearson correlation Consistent with @gung, I believe that hypothesis testing is very problematic, especially in this particular correlation assessment setting. It is far more useful, and will get us into less trouble, to think of this as an estimation problem: we are estimating the unitness strength of association of two variables. We can compute an uncertainty interval for the estimate, e.g. a 0.95 confidence interval. If this interval is $[a,b]$ we can roughly say that our data are consistent with an underlying true correlation between $a$ and $b$ with 0.95 "confidence", if model and random sampling assumptions are true. You can also compute a worst-case (which happens with the true correlation is zero) margin of error for the estimating the correlation. This is described in BBR Section 8.5.2.
Interpreting p-value significance from Pearson correlation Consistent with @gung, I believe that hypothesis testing is very problematic, especially in this particular correlation assessment setting. It is far more useful, and will get us into less trouble, t
45,443
Calculating the probability of a rare event
Well, 60 pedestrians in a year would be a lot, that's right. But you only have a sample of one month, so it would be more appropriate to scale the yearly average number of deaths down, not the observation up: ppois(5,3/12,lower.tail=FALSE) [1] 2.738136e-07 Still unusual, but far less so than 60 over an entire year. And don't forget selection bias. Newspapers by definition report unusual things, because usual things are not news. So if you read something in the newspaper, it would be very unusual for it to be usual.
Calculating the probability of a rare event
Well, 60 pedestrians in a year would be a lot, that's right. But you only have a sample of one month, so it would be more appropriate to scale the yearly average number of deaths down, not the observa
Calculating the probability of a rare event Well, 60 pedestrians in a year would be a lot, that's right. But you only have a sample of one month, so it would be more appropriate to scale the yearly average number of deaths down, not the observation up: ppois(5,3/12,lower.tail=FALSE) [1] 2.738136e-07 Still unusual, but far less so than 60 over an entire year. And don't forget selection bias. Newspapers by definition report unusual things, because usual things are not news. So if you read something in the newspaper, it would be very unusual for it to be usual.
Calculating the probability of a rare event Well, 60 pedestrians in a year would be a lot, that's right. But you only have a sample of one month, so it would be more appropriate to scale the yearly average number of deaths down, not the observa
45,444
Breusch–Pagan test for heteroscedasticity contradicts White's test?
The Breusch-Pagan test only checks for the linear form of heteroskedasticity i.e. it models the error variance as $\sigma_i^2 = \sigma^2h(z_i'\alpha)$ where $z_i$ is a vector of your independent variables. It tests $H_0: \alpha = 0$ versus $H_a: \alpha \neq 0$. The White test on the other hand is more generic. It relies on the intuition that if there is no heteroskedasticity the classical error variance esitmator should gives you standard error estimates close enough to those estimated by the robust estimator. Therefore, it is able to detect more general form of heteroskedasticity than the Breusch-Pagan test. A shortcoming of the White test is that it can lose its power very quickly particularly if the model has many regressors. This could be the reason for the results such as yours.
Breusch–Pagan test for heteroscedasticity contradicts White's test?
The Breusch-Pagan test only checks for the linear form of heteroskedasticity i.e. it models the error variance as $\sigma_i^2 = \sigma^2h(z_i'\alpha)$ where $z_i$ is a vector of your independent varia
Breusch–Pagan test for heteroscedasticity contradicts White's test? The Breusch-Pagan test only checks for the linear form of heteroskedasticity i.e. it models the error variance as $\sigma_i^2 = \sigma^2h(z_i'\alpha)$ where $z_i$ is a vector of your independent variables. It tests $H_0: \alpha = 0$ versus $H_a: \alpha \neq 0$. The White test on the other hand is more generic. It relies on the intuition that if there is no heteroskedasticity the classical error variance esitmator should gives you standard error estimates close enough to those estimated by the robust estimator. Therefore, it is able to detect more general form of heteroskedasticity than the Breusch-Pagan test. A shortcoming of the White test is that it can lose its power very quickly particularly if the model has many regressors. This could be the reason for the results such as yours.
Breusch–Pagan test for heteroscedasticity contradicts White's test? The Breusch-Pagan test only checks for the linear form of heteroskedasticity i.e. it models the error variance as $\sigma_i^2 = \sigma^2h(z_i'\alpha)$ where $z_i$ is a vector of your independent varia
45,445
Breusch–Pagan test for heteroscedasticity contradicts White's test?
Breusch-Pagan / Cook-Weisberg tests the null hypothesis that the error variances are all equal versus the alternative that the error variances are a multiplicative function of one or more variables. For example, in the default form of the hettest command shown above, the alternative hypothesis states that the error variances increase (or decrease) as the predicted values of Y increase, e.g. the bigger the predicted value of Y, the bigger the error variance is. A large chi-square would indicate that heteroscedasticity was present. In your example, the chi-square value was large and the p-value is small, indicating heteroskedasticity was present.
Breusch–Pagan test for heteroscedasticity contradicts White's test?
Breusch-Pagan / Cook-Weisberg tests the null hypothesis that the error variances are all equal versus the alternative that the error variances are a multiplicative function of one or more variables.
Breusch–Pagan test for heteroscedasticity contradicts White's test? Breusch-Pagan / Cook-Weisberg tests the null hypothesis that the error variances are all equal versus the alternative that the error variances are a multiplicative function of one or more variables. For example, in the default form of the hettest command shown above, the alternative hypothesis states that the error variances increase (or decrease) as the predicted values of Y increase, e.g. the bigger the predicted value of Y, the bigger the error variance is. A large chi-square would indicate that heteroscedasticity was present. In your example, the chi-square value was large and the p-value is small, indicating heteroskedasticity was present.
Breusch–Pagan test for heteroscedasticity contradicts White's test? Breusch-Pagan / Cook-Weisberg tests the null hypothesis that the error variances are all equal versus the alternative that the error variances are a multiplicative function of one or more variables.
45,446
LibSVM cost weights for unbalanced data doesn't work
I just know of two methods to deal with unbalanced sets with SVMs: Use bagging: you create bootstrap samples of your data, so that you a a big number of well-balanced problems. You train a SVM on each of them, and then use majority voting on the resulting ensemble of classifiers. If you are using C-SVM, then you can reweight the missclassification cost, $$C\sum_{i}\psi_{i}$$ into $$ C_{+}\sum_{i \epsilon I_{+}}\psi_{i} + C_{-}\sum_{i \epsilon I_{-}}\psi_{i}$$ where $I_{+}$, resp. $I_{-}$, is the set of indices for the positive examples, resp. for the negative examples. You choose the new soft-marging constants so that $\frac{C_{+}}{C_{-}} = \frac{n_{-}}{n_{+}}$, where $n_{+}$ and $n_{-}$ are the number of positive and negative samples resp.
LibSVM cost weights for unbalanced data doesn't work
I just know of two methods to deal with unbalanced sets with SVMs: Use bagging: you create bootstrap samples of your data, so that you a a big number of well-balanced problems. You train a SVM on eac
LibSVM cost weights for unbalanced data doesn't work I just know of two methods to deal with unbalanced sets with SVMs: Use bagging: you create bootstrap samples of your data, so that you a a big number of well-balanced problems. You train a SVM on each of them, and then use majority voting on the resulting ensemble of classifiers. If you are using C-SVM, then you can reweight the missclassification cost, $$C\sum_{i}\psi_{i}$$ into $$ C_{+}\sum_{i \epsilon I_{+}}\psi_{i} + C_{-}\sum_{i \epsilon I_{-}}\psi_{i}$$ where $I_{+}$, resp. $I_{-}$, is the set of indices for the positive examples, resp. for the negative examples. You choose the new soft-marging constants so that $\frac{C_{+}}{C_{-}} = \frac{n_{-}}{n_{+}}$, where $n_{+}$ and $n_{-}$ are the number of positive and negative samples resp.
LibSVM cost weights for unbalanced data doesn't work I just know of two methods to deal with unbalanced sets with SVMs: Use bagging: you create bootstrap samples of your data, so that you a a big number of well-balanced problems. You train a SVM on eac
45,447
LibSVM cost weights for unbalanced data doesn't work
ANSWER: remove -b 1 or make it -b 0 -b probability_estimates: whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0) I encountered the same problem and came across this post from googling. Apparently it doesn't work with probability estimates on.
LibSVM cost weights for unbalanced data doesn't work
ANSWER: remove -b 1 or make it -b 0 -b probability_estimates: whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0) I encountered the same problem and came across this post
LibSVM cost weights for unbalanced data doesn't work ANSWER: remove -b 1 or make it -b 0 -b probability_estimates: whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0) I encountered the same problem and came across this post from googling. Apparently it doesn't work with probability estimates on.
LibSVM cost weights for unbalanced data doesn't work ANSWER: remove -b 1 or make it -b 0 -b probability_estimates: whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0) I encountered the same problem and came across this post
45,448
LibSVM cost weights for unbalanced data doesn't work
If you're performing a ranking task, it might make more sense to evaluate your system in terms of area under the ROC curve! Accuracy, for ranking tasks, isn't necessarily what you want to optimize your system for, in my view. More to your question, how skewed is your data? There's been quite a bit of work on dealing with skewed data in biomedical classification (because this comes up a lot, in biomedicine). My PhD advisor wrote an algorithm called cost-proportionate rejection sampling that I think will address your needs--I'm fairly certain we ended up using it with LibSVM because of the same problem! Briefly, the algorithm addresses the issue of disproportionate costs of misclassification (e.g., if one document out of 100 describes a disease of interest, you don't want to miss that document). It resamples the data according to the cost function $$P(c)=\frac{{\rm Cost}(c)}{\max[\text{Cost}(c),\ \forall_{c}\in C]}$$ In words, each sample is included according to the probability $P$ of including a sample of class $c$ is determined by the misclassification cost ${\rm Cost}(c)$ for that sample, divided by the sample misclassification cost.
LibSVM cost weights for unbalanced data doesn't work
If you're performing a ranking task, it might make more sense to evaluate your system in terms of area under the ROC curve! Accuracy, for ranking tasks, isn't necessarily what you want to optimize you
LibSVM cost weights for unbalanced data doesn't work If you're performing a ranking task, it might make more sense to evaluate your system in terms of area under the ROC curve! Accuracy, for ranking tasks, isn't necessarily what you want to optimize your system for, in my view. More to your question, how skewed is your data? There's been quite a bit of work on dealing with skewed data in biomedical classification (because this comes up a lot, in biomedicine). My PhD advisor wrote an algorithm called cost-proportionate rejection sampling that I think will address your needs--I'm fairly certain we ended up using it with LibSVM because of the same problem! Briefly, the algorithm addresses the issue of disproportionate costs of misclassification (e.g., if one document out of 100 describes a disease of interest, you don't want to miss that document). It resamples the data according to the cost function $$P(c)=\frac{{\rm Cost}(c)}{\max[\text{Cost}(c),\ \forall_{c}\in C]}$$ In words, each sample is included according to the probability $P$ of including a sample of class $c$ is determined by the misclassification cost ${\rm Cost}(c)$ for that sample, divided by the sample misclassification cost.
LibSVM cost weights for unbalanced data doesn't work If you're performing a ranking task, it might make more sense to evaluate your system in terms of area under the ROC curve! Accuracy, for ranking tasks, isn't necessarily what you want to optimize you
45,449
What is the preferred way to give asymmetric uncertainties?
Assuming your paper only reports one or a few such values, there is nothing wrong with being wordy so no one can get confused: "The mean is 4.1 and the 95% confidence interval ranges from 2.6 to 6.2." (Of course, replace "mean" with "slope" or whatever parameter you are actually reporting.)
What is the preferred way to give asymmetric uncertainties?
Assuming your paper only reports one or a few such values, there is nothing wrong with being wordy so no one can get confused: "The mean is 4.1 and the 95% confidence interval ranges from 2.6 to 6.2
What is the preferred way to give asymmetric uncertainties? Assuming your paper only reports one or a few such values, there is nothing wrong with being wordy so no one can get confused: "The mean is 4.1 and the 95% confidence interval ranges from 2.6 to 6.2." (Of course, replace "mean" with "slope" or whatever parameter you are actually reporting.)
What is the preferred way to give asymmetric uncertainties? Assuming your paper only reports one or a few such values, there is nothing wrong with being wordy so no one can get confused: "The mean is 4.1 and the 95% confidence interval ranges from 2.6 to 6.2
45,450
What is the preferred way to give asymmetric uncertainties?
It would depend on the field and the journal. In the social sciences, it would be mean = 4.1, 95% CI = ??? I like specifying that it's a CI, because the +- notation could be standard deviation, standard errors, or who knows what.
What is the preferred way to give asymmetric uncertainties?
It would depend on the field and the journal. In the social sciences, it would be mean = 4.1, 95% CI = ??? I like specifying that it's a CI, because the +- notation could be standard deviation, stan
What is the preferred way to give asymmetric uncertainties? It would depend on the field and the journal. In the social sciences, it would be mean = 4.1, 95% CI = ??? I like specifying that it's a CI, because the +- notation could be standard deviation, standard errors, or who knows what.
What is the preferred way to give asymmetric uncertainties? It would depend on the field and the journal. In the social sciences, it would be mean = 4.1, 95% CI = ??? I like specifying that it's a CI, because the +- notation could be standard deviation, stan
45,451
What is the preferred way to give asymmetric uncertainties?
Astrophysics commonly use $4.1^{+2.1}_{-1.5}$ style, for example : http://iopscience.iop.org/0004-637X/765/1/47 Also see wikipedia using the same style: http://en.wikipedia.org/wiki/R136a1
What is the preferred way to give asymmetric uncertainties?
Astrophysics commonly use $4.1^{+2.1}_{-1.5}$ style, for example : http://iopscience.iop.org/0004-637X/765/1/47 Also see wikipedia using the same style: http://en.wikipedia.org/wiki/R136a1
What is the preferred way to give asymmetric uncertainties? Astrophysics commonly use $4.1^{+2.1}_{-1.5}$ style, for example : http://iopscience.iop.org/0004-637X/765/1/47 Also see wikipedia using the same style: http://en.wikipedia.org/wiki/R136a1
What is the preferred way to give asymmetric uncertainties? Astrophysics commonly use $4.1^{+2.1}_{-1.5}$ style, for example : http://iopscience.iop.org/0004-637X/765/1/47 Also see wikipedia using the same style: http://en.wikipedia.org/wiki/R136a1
45,452
Spectral clustering of graph
The problem of finding the correct number of classes is unsolved and there are many approaches that deal with this problem. For general approaches, you can have a look at the problem of finding k in a k-means. When performing spectral analysis, you can use the eigengap method to find a good approximation of the number of classes. It consists in computing the differences between the consecutive ordered eigenvalues of the graph Laplacian. If the difference between say, the 4th and the 5th eigenvalues is large compared to the other differences, then it is likely that there will be 4 classes in the graph. Note however that there is no perfect method to say whether a difference is large enough or not. In particular, just considering the largest difference might not lead to the best partition. A common technique is to consider several numbers of classes and perform several k-means (or any other clustering). Then, keep the partition having the highest quality according to some external measure.
Spectral clustering of graph
The problem of finding the correct number of classes is unsolved and there are many approaches that deal with this problem. For general approaches, you can have a look at the problem of finding k in a
Spectral clustering of graph The problem of finding the correct number of classes is unsolved and there are many approaches that deal with this problem. For general approaches, you can have a look at the problem of finding k in a k-means. When performing spectral analysis, you can use the eigengap method to find a good approximation of the number of classes. It consists in computing the differences between the consecutive ordered eigenvalues of the graph Laplacian. If the difference between say, the 4th and the 5th eigenvalues is large compared to the other differences, then it is likely that there will be 4 classes in the graph. Note however that there is no perfect method to say whether a difference is large enough or not. In particular, just considering the largest difference might not lead to the best partition. A common technique is to consider several numbers of classes and perform several k-means (or any other clustering). Then, keep the partition having the highest quality according to some external measure.
Spectral clustering of graph The problem of finding the correct number of classes is unsolved and there are many approaches that deal with this problem. For general approaches, you can have a look at the problem of finding k in a
45,453
Spectral clustering of graph
If you're using R or Python (or even C), you can have a look at the excellent igraph package. Especially, look at the various community detection algorithms that this package implements. What you discuss is closely related to the leading eigenvector algorithm of Newman (2006). Here is the paper introducing this algorithm, it is a very interesting read. A good strategy is to implement several community detection algorithms and aggregate the results. This leads to algorithm-independent, more stable and significant results. Here is a link to a function that I wrote for that purpose. One "external measure" (as mentioned by P.-N. Mougel above) that you can use is the modularity.
Spectral clustering of graph
If you're using R or Python (or even C), you can have a look at the excellent igraph package. Especially, look at the various community detection algorithms that this package implements. What you disc
Spectral clustering of graph If you're using R or Python (or even C), you can have a look at the excellent igraph package. Especially, look at the various community detection algorithms that this package implements. What you discuss is closely related to the leading eigenvector algorithm of Newman (2006). Here is the paper introducing this algorithm, it is a very interesting read. A good strategy is to implement several community detection algorithms and aggregate the results. This leads to algorithm-independent, more stable and significant results. Here is a link to a function that I wrote for that purpose. One "external measure" (as mentioned by P.-N. Mougel above) that you can use is the modularity.
Spectral clustering of graph If you're using R or Python (or even C), you can have a look at the excellent igraph package. Especially, look at the various community detection algorithms that this package implements. What you disc
45,454
What is crisp logic (in the area of classification)?
Crisp vs Fuzzy Logic As far as I remember, crisp logic is the same as boolean logic. Either a statement is true or it is not, meanwhile fuzzy logic captures the degree to which something is true. Consider the statement: "The agreed to met at 12 o'clock but Ben was not punctual." Crisp logic: If Ben showed up precisley at 12, he is punctual, otherwise he is too early or too late. Fuzzy logic: The degree, to which Ben was punctual, depends on how much earlier or later he showed up (e.g. 0, if he showed up 11:45 or 12:15, 1 at 12:00 and a linear increase / decrease in between). I do not exactly know who first used the term "crisp", but I have seen it multiple times in the closely related Fuzzy Set Theory, where it has been used to distinguish Cantor's set theory from Zadeh's. So if you are looking for a reference, the original work of Zadeh or one the textbooks in the area might be a way to go. ... in Machine Learning In Machine Learning most of the classifiers produce so called scores, which are in general more or less rough estimates of the probability that the scored instance belongs to a particular class. To the best of my knowledge, these scores have no explicit link to Fuzzy Logic. Both Fuzzy Logic and Probability Theory are close to each other, but technically they are not the same (Fuzzy_logic#Comparison_to_probability (english wikipedia)). So it is not correct to label the output of Logistic Regression as fuzzy. Aside, the mentioned decision tree also calculates scores (the subjective probability that an instance in the leaf belongs to the particular class), which often results in a majority-decision for the leaf. Summary But if you are willing to drop the difference between Fuzzy Logic and Probability for the sake of simplicity, you may say that the scores produced by a suitable classifier are fuzzy, meanwhile the decision for a class based on the score is crisp. For example in a direct mail campaign, you can calculate a score how likely it is that a customer will respond, but in the end you have to perform a crisp decision which customers you will send an actual letter. This paper might be interesting (Eyke Hüllermeier- Fuzzy Sets in Machine Learning and Data Mining). From the abstract: Over the past years, methods for the automated induction of models and the extraction of interesting patterns from empirical data have attracted considerable attention in the fuzzy set community. This paper briefly reviews some typical applications and highlights potential contributions that fuzzy set theory can make to machine learning, data mining, and related fields. The paper concludes with a critical consideration of recent developments and some suggestions for future research directions.
What is crisp logic (in the area of classification)?
Crisp vs Fuzzy Logic As far as I remember, crisp logic is the same as boolean logic. Either a statement is true or it is not, meanwhile fuzzy logic captures the degree to which something is true. Cons
What is crisp logic (in the area of classification)? Crisp vs Fuzzy Logic As far as I remember, crisp logic is the same as boolean logic. Either a statement is true or it is not, meanwhile fuzzy logic captures the degree to which something is true. Consider the statement: "The agreed to met at 12 o'clock but Ben was not punctual." Crisp logic: If Ben showed up precisley at 12, he is punctual, otherwise he is too early or too late. Fuzzy logic: The degree, to which Ben was punctual, depends on how much earlier or later he showed up (e.g. 0, if he showed up 11:45 or 12:15, 1 at 12:00 and a linear increase / decrease in between). I do not exactly know who first used the term "crisp", but I have seen it multiple times in the closely related Fuzzy Set Theory, where it has been used to distinguish Cantor's set theory from Zadeh's. So if you are looking for a reference, the original work of Zadeh or one the textbooks in the area might be a way to go. ... in Machine Learning In Machine Learning most of the classifiers produce so called scores, which are in general more or less rough estimates of the probability that the scored instance belongs to a particular class. To the best of my knowledge, these scores have no explicit link to Fuzzy Logic. Both Fuzzy Logic and Probability Theory are close to each other, but technically they are not the same (Fuzzy_logic#Comparison_to_probability (english wikipedia)). So it is not correct to label the output of Logistic Regression as fuzzy. Aside, the mentioned decision tree also calculates scores (the subjective probability that an instance in the leaf belongs to the particular class), which often results in a majority-decision for the leaf. Summary But if you are willing to drop the difference between Fuzzy Logic and Probability for the sake of simplicity, you may say that the scores produced by a suitable classifier are fuzzy, meanwhile the decision for a class based on the score is crisp. For example in a direct mail campaign, you can calculate a score how likely it is that a customer will respond, but in the end you have to perform a crisp decision which customers you will send an actual letter. This paper might be interesting (Eyke Hüllermeier- Fuzzy Sets in Machine Learning and Data Mining). From the abstract: Over the past years, methods for the automated induction of models and the extraction of interesting patterns from empirical data have attracted considerable attention in the fuzzy set community. This paper briefly reviews some typical applications and highlights potential contributions that fuzzy set theory can make to machine learning, data mining, and related fields. The paper concludes with a critical consideration of recent developments and some suggestions for future research directions.
What is crisp logic (in the area of classification)? Crisp vs Fuzzy Logic As far as I remember, crisp logic is the same as boolean logic. Either a statement is true or it is not, meanwhile fuzzy logic captures the degree to which something is true. Cons
45,455
What is crisp logic (in the area of classification)?
crisp / fuzzy is used in fuzzy logic hard / soft is sometimes used for continuous classifier scores in [0, 1] as well, e.g. in the remote sensing community. Interpretation of continuous [0, 1] scores varies: mixtures of pure, hard/crisp classes that are not resolved by the measurement cases that are truly in between classes probability, that a case belons (completely) to the class. Note that fuzzy logics usually is not about probabilities but about genuinely belonging to more than one class (partially), i.e. the first two bullet points. Reichenbach developed a probability logic (in the 1930s). You may want to check out the manyvalued and fuzzy logic articles at the Stanford Encyclopedia of Philosophy. I have a paper upcoming (about using samples with soft/fuzzy reference for classifier validation), but it is not yet through the review process so I cannot yet make it publicly available here. If you're intrested in the manuscript, send me an email (Claudia dot Beleites at ipht minus jena dot de) The paper will be available at arxiv once it is accepted.
What is crisp logic (in the area of classification)?
crisp / fuzzy is used in fuzzy logic hard / soft is sometimes used for continuous classifier scores in [0, 1] as well, e.g. in the remote sensing community. Interpretation of continuous [0, 1] score
What is crisp logic (in the area of classification)? crisp / fuzzy is used in fuzzy logic hard / soft is sometimes used for continuous classifier scores in [0, 1] as well, e.g. in the remote sensing community. Interpretation of continuous [0, 1] scores varies: mixtures of pure, hard/crisp classes that are not resolved by the measurement cases that are truly in between classes probability, that a case belons (completely) to the class. Note that fuzzy logics usually is not about probabilities but about genuinely belonging to more than one class (partially), i.e. the first two bullet points. Reichenbach developed a probability logic (in the 1930s). You may want to check out the manyvalued and fuzzy logic articles at the Stanford Encyclopedia of Philosophy. I have a paper upcoming (about using samples with soft/fuzzy reference for classifier validation), but it is not yet through the review process so I cannot yet make it publicly available here. If you're intrested in the manuscript, send me an email (Claudia dot Beleites at ipht minus jena dot de) The paper will be available at arxiv once it is accepted.
What is crisp logic (in the area of classification)? crisp / fuzzy is used in fuzzy logic hard / soft is sometimes used for continuous classifier scores in [0, 1] as well, e.g. in the remote sensing community. Interpretation of continuous [0, 1] score
45,456
What is crisp logic (in the area of classification)?
The statement which is either true or false but not both is called a proportion is denoted by an upper case letter of alphabets , a simple proportion is also known as an atom, in order to represent complex information one has to build a sequence of proportion link using connectives or operators There are five major operators are as follows .... 1. AND (^) 2. OR (/) 3. NOT ~ 4. IMPLICATION => 5. EQUALITY = Please ignore my spell mistake as i am a student so please dont mind if you find any spell mistakes in my answer
What is crisp logic (in the area of classification)?
The statement which is either true or false but not both is called a proportion is denoted by an upper case letter of alphabets , a simple proportion is also known as an atom, in order to represent co
What is crisp logic (in the area of classification)? The statement which is either true or false but not both is called a proportion is denoted by an upper case letter of alphabets , a simple proportion is also known as an atom, in order to represent complex information one has to build a sequence of proportion link using connectives or operators There are five major operators are as follows .... 1. AND (^) 2. OR (/) 3. NOT ~ 4. IMPLICATION => 5. EQUALITY = Please ignore my spell mistake as i am a student so please dont mind if you find any spell mistakes in my answer
What is crisp logic (in the area of classification)? The statement which is either true or false but not both is called a proportion is denoted by an upper case letter of alphabets , a simple proportion is also known as an atom, in order to represent co
45,457
Summarizing k-fold cross validation results
box and whisker plots are commonly used to visually compare and summarize cross validation results. Here is an example, taken from the cvTools package in R. library(cvTools) ## set up folds for cross-validation folds <- cvFolds(nrow(coleman), K = 5, R = 50) ## compare LS, MM and LTS regression # perform cross-validation for an LS regression model fitLm <- lm(Y ~ ., data = coleman) cvFitLm <- cvLm(fitLm, cost = rtmspe, folds = folds, trim = 0.1) ... # plot results for the MM regression model bwplot(cvFitLmrob) # plot combined results bwplot(cvFits)
Summarizing k-fold cross validation results
box and whisker plots are commonly used to visually compare and summarize cross validation results. Here is an example, taken from the cvTools package in R. library(cvTools) ## set up folds for cros
Summarizing k-fold cross validation results box and whisker plots are commonly used to visually compare and summarize cross validation results. Here is an example, taken from the cvTools package in R. library(cvTools) ## set up folds for cross-validation folds <- cvFolds(nrow(coleman), K = 5, R = 50) ## compare LS, MM and LTS regression # perform cross-validation for an LS regression model fitLm <- lm(Y ~ ., data = coleman) cvFitLm <- cvLm(fitLm, cost = rtmspe, folds = folds, trim = 0.1) ... # plot results for the MM regression model bwplot(cvFitLmrob) # plot combined results bwplot(cvFits)
Summarizing k-fold cross validation results box and whisker plots are commonly used to visually compare and summarize cross validation results. Here is an example, taken from the cvTools package in R. library(cvTools) ## set up folds for cros
45,458
Initialize ARIMA simulations with different time-series
You can "fit" the model to different data and then simulate: m2 <- Arima(z,model=m1) simulate.Arima(m2,future=TRUE,bootstrap=TRUE) m2 will have the same parameters as m1 (they are not re-estimated), but the residuals, etc., are computed on the new data. However, I am concerned with your model. Seasonal models are for when the seasonality is fixed and known. With animal population data, you almost certainly have aperiodic population cycling. This is a well-known phenomenon and can easily be handled with non-seasonal ARIMA models. Look at the literature on the Canadian lynx data for discussion. By all means, use the square root, but then I would use a non-seasonal ARIMA model. Provided the AR order is greater than 1, it is possible to have cycles. See You can do all this in one step: m1 <- auto.arima(y, lambda=0.5) Then proceed with your simulations as above.
Initialize ARIMA simulations with different time-series
You can "fit" the model to different data and then simulate: m2 <- Arima(z,model=m1) simulate.Arima(m2,future=TRUE,bootstrap=TRUE) m2 will have the same parameters as m1 (they are not re-estimated),
Initialize ARIMA simulations with different time-series You can "fit" the model to different data and then simulate: m2 <- Arima(z,model=m1) simulate.Arima(m2,future=TRUE,bootstrap=TRUE) m2 will have the same parameters as m1 (they are not re-estimated), but the residuals, etc., are computed on the new data. However, I am concerned with your model. Seasonal models are for when the seasonality is fixed and known. With animal population data, you almost certainly have aperiodic population cycling. This is a well-known phenomenon and can easily be handled with non-seasonal ARIMA models. Look at the literature on the Canadian lynx data for discussion. By all means, use the square root, but then I would use a non-seasonal ARIMA model. Provided the AR order is greater than 1, it is possible to have cycles. See You can do all this in one step: m1 <- auto.arima(y, lambda=0.5) Then proceed with your simulations as above.
Initialize ARIMA simulations with different time-series You can "fit" the model to different data and then simulate: m2 <- Arima(z,model=m1) simulate.Arima(m2,future=TRUE,bootstrap=TRUE) m2 will have the same parameters as m1 (they are not re-estimated),
45,459
Initialize ARIMA simulations with different time-series
On a related note, you can accomplish the same objective if your ARIMA model has external regressors. This has been helpful for me on occasion. For instance, say your first model was created as follows: fit.arimax <- Arima(response, order=c(1, 0, 1), xreg=xreg) Then suppose that after creating your model, you observe additional values in your response and external regression variables, and would like to forecast or simulate future outcomes given these new observations. E.g., say you are predicting electricity demand, and you observe another hour of demand (i.e. response) and temperature (i.e. external regression) data. Then, you may fit the original model to the updated time series as follows, where response.new and xreg.new are your updated response and regression variables. fit.arimax.new <- Arima(response.new, model=fit.arimax, xreg=xreg.new) You can use this new model to forecast or simulate future outcomes, conditional on all observed data. Note that you must provide forecast external regressors for each. E.g., forecast.Arima(fit.arimax.new, h=length(xreg.forecast), xreg=xreg.forecast) simulate.Arima(fit.arimax.new, n=length(xreg.forecast), xreg=xreg.forecast) Another way to accomplish all of this is to make an entirely new model using the updated data. But the method described above is appropriate in real-time applications, in which case fitting a new ARIMA model would take too long.
Initialize ARIMA simulations with different time-series
On a related note, you can accomplish the same objective if your ARIMA model has external regressors. This has been helpful for me on occasion. For instance, say your first model was created as follow
Initialize ARIMA simulations with different time-series On a related note, you can accomplish the same objective if your ARIMA model has external regressors. This has been helpful for me on occasion. For instance, say your first model was created as follows: fit.arimax <- Arima(response, order=c(1, 0, 1), xreg=xreg) Then suppose that after creating your model, you observe additional values in your response and external regression variables, and would like to forecast or simulate future outcomes given these new observations. E.g., say you are predicting electricity demand, and you observe another hour of demand (i.e. response) and temperature (i.e. external regression) data. Then, you may fit the original model to the updated time series as follows, where response.new and xreg.new are your updated response and regression variables. fit.arimax.new <- Arima(response.new, model=fit.arimax, xreg=xreg.new) You can use this new model to forecast or simulate future outcomes, conditional on all observed data. Note that you must provide forecast external regressors for each. E.g., forecast.Arima(fit.arimax.new, h=length(xreg.forecast), xreg=xreg.forecast) simulate.Arima(fit.arimax.new, n=length(xreg.forecast), xreg=xreg.forecast) Another way to accomplish all of this is to make an entirely new model using the updated data. But the method described above is appropriate in real-time applications, in which case fitting a new ARIMA model would take too long.
Initialize ARIMA simulations with different time-series On a related note, you can accomplish the same objective if your ARIMA model has external regressors. This has been helpful for me on occasion. For instance, say your first model was created as follow
45,460
Is it true that in high dimensions, data is easier to separate linearly?
Trivially, if you have $N$ data points, they will be linearly separable in $N-1$ dimensions. Any structure in the data may reduce the required dimensionality for linear separation further. You might say that (a projection of) a data set either is or is not completely linearly separable, in which using any (projection into) dimensionality lower than $N-1$ requires either additional properties of the data, of the projection into this higher dimensionality, or can be viewed as a heuristic (for instance in the case of random projections). In general we usually do not care to much about precise separability, in which case it is sufficient that we can meaningfully separate more data points correctly in higher dimensions.
Is it true that in high dimensions, data is easier to separate linearly?
Trivially, if you have $N$ data points, they will be linearly separable in $N-1$ dimensions. Any structure in the data may reduce the required dimensionality for linear separation further. You might s
Is it true that in high dimensions, data is easier to separate linearly? Trivially, if you have $N$ data points, they will be linearly separable in $N-1$ dimensions. Any structure in the data may reduce the required dimensionality for linear separation further. You might say that (a projection of) a data set either is or is not completely linearly separable, in which using any (projection into) dimensionality lower than $N-1$ requires either additional properties of the data, of the projection into this higher dimensionality, or can be viewed as a heuristic (for instance in the case of random projections). In general we usually do not care to much about precise separability, in which case it is sufficient that we can meaningfully separate more data points correctly in higher dimensions.
Is it true that in high dimensions, data is easier to separate linearly? Trivially, if you have $N$ data points, they will be linearly separable in $N-1$ dimensions. Any structure in the data may reduce the required dimensionality for linear separation further. You might s
45,461
Is it true that in high dimensions, data is easier to separate linearly?
I'm not sure if it matters whether the data actually has a high dimensionality or whether data is projected into a higher dimension. In the latter case, it is true that it's easier to linearly separate something projected into a higher dimension, hence the whole idea of kernel methods. (See Cover's Theorem, etc.) My typical example is a bullseye-shaped data set, where you have two-dimensional data with one class totally surrounded by another. Not linearly separable in 2 dimensions, but project it into 3 dimensions, with the third dimension being the point's distance from the center, and it's linearly separable.
Is it true that in high dimensions, data is easier to separate linearly?
I'm not sure if it matters whether the data actually has a high dimensionality or whether data is projected into a higher dimension. In the latter case, it is true that it's easier to linearly separat
Is it true that in high dimensions, data is easier to separate linearly? I'm not sure if it matters whether the data actually has a high dimensionality or whether data is projected into a higher dimension. In the latter case, it is true that it's easier to linearly separate something projected into a higher dimension, hence the whole idea of kernel methods. (See Cover's Theorem, etc.) My typical example is a bullseye-shaped data set, where you have two-dimensional data with one class totally surrounded by another. Not linearly separable in 2 dimensions, but project it into 3 dimensions, with the third dimension being the point's distance from the center, and it's linearly separable.
Is it true that in high dimensions, data is easier to separate linearly? I'm not sure if it matters whether the data actually has a high dimensionality or whether data is projected into a higher dimension. In the latter case, it is true that it's easier to linearly separat
45,462
Is it true that in high dimensions, data is easier to separate linearly?
I think what you might be asking about is the use of kernels to make a data set more compatible with linear techniques. A short piece about this is available here: http://ldtopology.wordpress.com/2012/05/27/making-linear-data-algorithms-less-linear-kernels/.
Is it true that in high dimensions, data is easier to separate linearly?
I think what you might be asking about is the use of kernels to make a data set more compatible with linear techniques. A short piece about this is available here: http://ldtopology.wordpress.com/2012
Is it true that in high dimensions, data is easier to separate linearly? I think what you might be asking about is the use of kernels to make a data set more compatible with linear techniques. A short piece about this is available here: http://ldtopology.wordpress.com/2012/05/27/making-linear-data-algorithms-less-linear-kernels/.
Is it true that in high dimensions, data is easier to separate linearly? I think what you might be asking about is the use of kernels to make a data set more compatible with linear techniques. A short piece about this is available here: http://ldtopology.wordpress.com/2012
45,463
Are support vector regression and kernel ridge regression used for the same type of problems?
Yes, they refer to the same class of problems, aka. fitting a linear function to data in possibly transformed space, but they don't solve the same optimization problem (they have different loss functions), and will give different results. To see the exact difference you may want to see chapters $3.4.1$ and $12.3.6$ of Elements of Statistical learning II, the e-book can be found for free here.
Are support vector regression and kernel ridge regression used for the same type of problems?
Yes, they refer to the same class of problems, aka. fitting a linear function to data in possibly transformed space, but they don't solve the same optimization problem (they have different loss functi
Are support vector regression and kernel ridge regression used for the same type of problems? Yes, they refer to the same class of problems, aka. fitting a linear function to data in possibly transformed space, but they don't solve the same optimization problem (they have different loss functions), and will give different results. To see the exact difference you may want to see chapters $3.4.1$ and $12.3.6$ of Elements of Statistical learning II, the e-book can be found for free here.
Are support vector regression and kernel ridge regression used for the same type of problems? Yes, they refer to the same class of problems, aka. fitting a linear function to data in possibly transformed space, but they don't solve the same optimization problem (they have different loss functi
45,464
How does a generalized linear mixed model estimate means and how does this differ from calculating means by hand?
Here are the short answers to your questions: The regression model allows you use the structure of the model to estimate the mean at predictor values by plugging the value into the fitted model equation. You can even do this for predictor values you didn't directly observe in the data set (more about this below). The difference is that you're calculating the expected value (mean) conditional on the predictor values and random effects, which can be quite different from the mean unconditional on the predictor values (which I assume is what you mean by the means calculated by hand), if the predictors truly are important in predicting the response. Here are the long answers to your questions: Specifically, in the generalized linear mixed model you must be dealing with data that has some clustering in it, so let $Y_{ij}$ be the outcome variable for individual $i$ in cluster $j$ with corresponding predictor values ${\bf X}_{ij}$. The basic generalized linear mixed model with a random intercept is $$ \varphi \left( E(Y_{ij}|{\bf X}_{ij}, \eta_j) \right) = \alpha + {\bf X}_{ij}{\boldsymbol \beta} + \eta_j $$ where $\eta_j \sim N(0,\sigma^{2}_{\eta})$ is the cluster $j$ random effect and $\varepsilon \sim N(0,\sigma^{2}_{\varepsilon})$ is the leftover error term and $\varphi(\cdot)$ is the link function. The link function is used to express the mean of the outcome variable as something that is linear in the predictors/random effects and is often used to change a bounded value (e.g. in (0,1)) to an unbounded range. The link function depends on the type of GLM. Some examples: $\varphi(x) = x$ is the identity link, in which case you have a linear model (this appears to be the case in the example you've mentioned) $\varphi(x) = \log \left( \frac{x}{1-x} \right)$ is the logistic link, used for logistic GLMMs. $\varphi(x) = \log(x)$ is the log link, used for Poisson GLMMs. $\varphi(x) = \Phi^{-1}(x)$ is the probit link, used for Probit GLMMS. To answer question (1): Now, if we have estimates of $\alpha$ and $\boldsymbol \beta$, then we can estimate the conditional mean of $Y_{ij}$, given the random effects and the predictor values: $$ \widehat{E}(Y_{ij} | {\boldsymbol X}_{ij},\eta_j) = \varphi^{-1}(\hat \alpha + {\bf X}_{ij}\hat {\boldsymbol \beta} + \eta_j)$$ In your example, the times are covariates (i.e. ${\bf X}_{ij}$s) in the model which are plugged into the regression equation to estimate the monthly means. One useful thing this allows you to do is to estimate the mean for a predictor value you didn't directly observe. That is, the (linear) structure imposed by the model allows you to estimate $E(Y|X)$ for values of $X$ you didn't observe, by linear interpolation - when the linear model is a good fit this is a very nice bonus, since you wouldn't be able to calculate this quantity by hand without the model. Note: One should exercise extreme caution when plugging in predictor values that go outside of the range of the data used to fit the model. This is called extrapolation and can perform arbitrarily poorly if the model does not apply outside of the range of the observed data. The equation above can also be used to estimate relative changes in an individual's average outcome for different predictor values. Often times this relative change doesn't even depend on the unobserved random effect. For example, when you use the log link: $$\frac{ \widehat{E}(Y_{ij} | {\boldsymbol X}_{ij},\eta_j) } { \widehat{E}(Y_{ij} | {\boldsymbol X}'_{ij},\eta_j) } = \frac{ \exp (\hat \alpha + {\bf X}_{ij}\hat {\boldsymbol \beta} + \eta_j)}{ \exp (\hat \alpha + {\bf X}'_{ij}\hat {\boldsymbol \beta} + \eta_j)} = \exp \left( ({\bf X}_{ij}-{\bf X}'_{ij})\hat {\boldsymbol \beta} \right) $$ Note: The mean unconditional on the random effect is the average over the random effects: $$ E(Y_{ij} | {\boldsymbol X}_{ij}) = E_{\eta} \left( E(Y_{ij} | {\boldsymbol X}_{ij},\eta_j) \right) $$ which is not trivially related to the conditional expectation (since it is an intergral of the conditional expectation) except the identity link is used (i.e. you have a linear model). Some remarks about the mean unconditional on the random effects: In a linear mixed effects model, the mean unconditional on the random effects is the same as the conditional mean - this is fairly clear when you plug in the identity link and use the fact that the random effects have mean 0. This fact does not always hold in the case with non-linear models (see here for more discussion). The change in the conditional mean as a function of the predictors (but unconditional on the random effects) is related to the average change in the population for a change in the predictor value. The change in the condition mean when the random effects are conditioned on is related to the change in the expected value for a particular individual for a change in the predictor value. More on this can be read about in the link above. To answer question (2): When you calculate the sample mean you're effectively marginalizing over the predictor values and throwing out the information they provide. That is, assuming your ${\bf X}$s are a random sample (that is, your data are not from a retrospective study or something else like that), then the sample mean estimates $$ E(Y_{ij}) = E_{\bf X} \left( E(Y_{ij} | {\bf X}_{ij} ) \right) $$ If ${\bf X}_{ij}$ truly does have an effect, then $E(Y_{ij} | {\bf X}_{ij} )$ can be very different from $E(Y_{ij})$ and that's the explanation for what you're seeing. Note that if you have categorical predictors, then you can estimate the conditional means by stratifying the data set and calculating the mean within each strata, but this is exactly what the regression model does. So, in any case, you're no worse off using the regression estimates of the mean, as long as the model fits reasonably well.
How does a generalized linear mixed model estimate means and how does this differ from calculating m
Here are the short answers to your questions: The regression model allows you use the structure of the model to estimate the mean at predictor values by plugging the value into the fitted model equa
How does a generalized linear mixed model estimate means and how does this differ from calculating means by hand? Here are the short answers to your questions: The regression model allows you use the structure of the model to estimate the mean at predictor values by plugging the value into the fitted model equation. You can even do this for predictor values you didn't directly observe in the data set (more about this below). The difference is that you're calculating the expected value (mean) conditional on the predictor values and random effects, which can be quite different from the mean unconditional on the predictor values (which I assume is what you mean by the means calculated by hand), if the predictors truly are important in predicting the response. Here are the long answers to your questions: Specifically, in the generalized linear mixed model you must be dealing with data that has some clustering in it, so let $Y_{ij}$ be the outcome variable for individual $i$ in cluster $j$ with corresponding predictor values ${\bf X}_{ij}$. The basic generalized linear mixed model with a random intercept is $$ \varphi \left( E(Y_{ij}|{\bf X}_{ij}, \eta_j) \right) = \alpha + {\bf X}_{ij}{\boldsymbol \beta} + \eta_j $$ where $\eta_j \sim N(0,\sigma^{2}_{\eta})$ is the cluster $j$ random effect and $\varepsilon \sim N(0,\sigma^{2}_{\varepsilon})$ is the leftover error term and $\varphi(\cdot)$ is the link function. The link function is used to express the mean of the outcome variable as something that is linear in the predictors/random effects and is often used to change a bounded value (e.g. in (0,1)) to an unbounded range. The link function depends on the type of GLM. Some examples: $\varphi(x) = x$ is the identity link, in which case you have a linear model (this appears to be the case in the example you've mentioned) $\varphi(x) = \log \left( \frac{x}{1-x} \right)$ is the logistic link, used for logistic GLMMs. $\varphi(x) = \log(x)$ is the log link, used for Poisson GLMMs. $\varphi(x) = \Phi^{-1}(x)$ is the probit link, used for Probit GLMMS. To answer question (1): Now, if we have estimates of $\alpha$ and $\boldsymbol \beta$, then we can estimate the conditional mean of $Y_{ij}$, given the random effects and the predictor values: $$ \widehat{E}(Y_{ij} | {\boldsymbol X}_{ij},\eta_j) = \varphi^{-1}(\hat \alpha + {\bf X}_{ij}\hat {\boldsymbol \beta} + \eta_j)$$ In your example, the times are covariates (i.e. ${\bf X}_{ij}$s) in the model which are plugged into the regression equation to estimate the monthly means. One useful thing this allows you to do is to estimate the mean for a predictor value you didn't directly observe. That is, the (linear) structure imposed by the model allows you to estimate $E(Y|X)$ for values of $X$ you didn't observe, by linear interpolation - when the linear model is a good fit this is a very nice bonus, since you wouldn't be able to calculate this quantity by hand without the model. Note: One should exercise extreme caution when plugging in predictor values that go outside of the range of the data used to fit the model. This is called extrapolation and can perform arbitrarily poorly if the model does not apply outside of the range of the observed data. The equation above can also be used to estimate relative changes in an individual's average outcome for different predictor values. Often times this relative change doesn't even depend on the unobserved random effect. For example, when you use the log link: $$\frac{ \widehat{E}(Y_{ij} | {\boldsymbol X}_{ij},\eta_j) } { \widehat{E}(Y_{ij} | {\boldsymbol X}'_{ij},\eta_j) } = \frac{ \exp (\hat \alpha + {\bf X}_{ij}\hat {\boldsymbol \beta} + \eta_j)}{ \exp (\hat \alpha + {\bf X}'_{ij}\hat {\boldsymbol \beta} + \eta_j)} = \exp \left( ({\bf X}_{ij}-{\bf X}'_{ij})\hat {\boldsymbol \beta} \right) $$ Note: The mean unconditional on the random effect is the average over the random effects: $$ E(Y_{ij} | {\boldsymbol X}_{ij}) = E_{\eta} \left( E(Y_{ij} | {\boldsymbol X}_{ij},\eta_j) \right) $$ which is not trivially related to the conditional expectation (since it is an intergral of the conditional expectation) except the identity link is used (i.e. you have a linear model). Some remarks about the mean unconditional on the random effects: In a linear mixed effects model, the mean unconditional on the random effects is the same as the conditional mean - this is fairly clear when you plug in the identity link and use the fact that the random effects have mean 0. This fact does not always hold in the case with non-linear models (see here for more discussion). The change in the conditional mean as a function of the predictors (but unconditional on the random effects) is related to the average change in the population for a change in the predictor value. The change in the condition mean when the random effects are conditioned on is related to the change in the expected value for a particular individual for a change in the predictor value. More on this can be read about in the link above. To answer question (2): When you calculate the sample mean you're effectively marginalizing over the predictor values and throwing out the information they provide. That is, assuming your ${\bf X}$s are a random sample (that is, your data are not from a retrospective study or something else like that), then the sample mean estimates $$ E(Y_{ij}) = E_{\bf X} \left( E(Y_{ij} | {\bf X}_{ij} ) \right) $$ If ${\bf X}_{ij}$ truly does have an effect, then $E(Y_{ij} | {\bf X}_{ij} )$ can be very different from $E(Y_{ij})$ and that's the explanation for what you're seeing. Note that if you have categorical predictors, then you can estimate the conditional means by stratifying the data set and calculating the mean within each strata, but this is exactly what the regression model does. So, in any case, you're no worse off using the regression estimates of the mean, as long as the model fits reasonably well.
How does a generalized linear mixed model estimate means and how does this differ from calculating m Here are the short answers to your questions: The regression model allows you use the structure of the model to estimate the mean at predictor values by plugging the value into the fitted model equa
45,465
Fuzzy K-means - Cluster Sizes
K-means and also fuzzy k-means (emphasized by your "the winner takes it all" strategy) assume that clusters have the same spatial extend. This is best explained by looking at an object $o$ almost half-way between cluster centers $c_i$ and $c_j$. If it is slightly closer to $c_i$, it will go into cluster $i$, if it is slightly closer to $c_j$ it will go into $j$. I.e. k-means assumes that splitting the dataset at the hyperplane orthogonal on the mean between the two points (i.e. the Voronoi cell boundary) is the proper split and does not at all take into account that clusters may have different spatial extend. EM clustering (Wikipedia) with Gaussian mixtures is essentially an extension of Fuzzy k-means that does a) not assume all dimensions are equally important and b) the clusters may have a different spatial extend. You could simplify it by removing the Gaussian Mixture (or at least the covariances), and just keep a cluster weight. This weight would essentially give the relative cluster size. Or you might want to look into more advanced methods for arbitrary shaped clusters such as DBSCAN (Wikipedia) and OPTICS (Wikipedia).
Fuzzy K-means - Cluster Sizes
K-means and also fuzzy k-means (emphasized by your "the winner takes it all" strategy) assume that clusters have the same spatial extend. This is best explained by looking at an object $o$ almost half
Fuzzy K-means - Cluster Sizes K-means and also fuzzy k-means (emphasized by your "the winner takes it all" strategy) assume that clusters have the same spatial extend. This is best explained by looking at an object $o$ almost half-way between cluster centers $c_i$ and $c_j$. If it is slightly closer to $c_i$, it will go into cluster $i$, if it is slightly closer to $c_j$ it will go into $j$. I.e. k-means assumes that splitting the dataset at the hyperplane orthogonal on the mean between the two points (i.e. the Voronoi cell boundary) is the proper split and does not at all take into account that clusters may have different spatial extend. EM clustering (Wikipedia) with Gaussian mixtures is essentially an extension of Fuzzy k-means that does a) not assume all dimensions are equally important and b) the clusters may have a different spatial extend. You could simplify it by removing the Gaussian Mixture (or at least the covariances), and just keep a cluster weight. This weight would essentially give the relative cluster size. Or you might want to look into more advanced methods for arbitrary shaped clusters such as DBSCAN (Wikipedia) and OPTICS (Wikipedia).
Fuzzy K-means - Cluster Sizes K-means and also fuzzy k-means (emphasized by your "the winner takes it all" strategy) assume that clusters have the same spatial extend. This is best explained by looking at an object $o$ almost half
45,466
Fuzzy K-means - Cluster Sizes
Why not using fanny() from the cluster package? You can find the details of the algorithm in the details section of the help. Here is the example code from ?fanny ## generate 10+15 objects in two clusters, plus 3 objects lying ## between those clusters. x <- rbind(cbind(rnorm(10, 0, 0.5), rnorm(10, 0, 0.5)), cbind(rnorm(15, 5, 0.5), rnorm(15, 5, 0.5)), cbind(rnorm( 3,3.2,0.5), rnorm( 3,3.2,0.5))) fannyx <- fanny(x, 2) ## Note that observations 26:28 are "fuzzy" (closer to # 2): fannyx summary(fannyx) plot(fannyx) (fan.x.15 <- fanny(x, 2, memb.exp = 1.5)) # 'crispier' for obs. 26:28 (fanny(x, 2, memb.exp = 3)) # more fuzzy in general data(ruspini) f4 <- fanny(ruspini, 4) stopifnot(rle(f4$clustering)$lengths == c(20,23,17,15)) plot(f4, which = 1) ## Plot similar to Figure 6 in Stryuf et al (1996) plot(fanny(ruspini, 5))
Fuzzy K-means - Cluster Sizes
Why not using fanny() from the cluster package? You can find the details of the algorithm in the details section of the help. Here is the example code from ?fanny ## generate 10+15 objects in two clu
Fuzzy K-means - Cluster Sizes Why not using fanny() from the cluster package? You can find the details of the algorithm in the details section of the help. Here is the example code from ?fanny ## generate 10+15 objects in two clusters, plus 3 objects lying ## between those clusters. x <- rbind(cbind(rnorm(10, 0, 0.5), rnorm(10, 0, 0.5)), cbind(rnorm(15, 5, 0.5), rnorm(15, 5, 0.5)), cbind(rnorm( 3,3.2,0.5), rnorm( 3,3.2,0.5))) fannyx <- fanny(x, 2) ## Note that observations 26:28 are "fuzzy" (closer to # 2): fannyx summary(fannyx) plot(fannyx) (fan.x.15 <- fanny(x, 2, memb.exp = 1.5)) # 'crispier' for obs. 26:28 (fanny(x, 2, memb.exp = 3)) # more fuzzy in general data(ruspini) f4 <- fanny(ruspini, 4) stopifnot(rle(f4$clustering)$lengths == c(20,23,17,15)) plot(f4, which = 1) ## Plot similar to Figure 6 in Stryuf et al (1996) plot(fanny(ruspini, 5))
Fuzzy K-means - Cluster Sizes Why not using fanny() from the cluster package? You can find the details of the algorithm in the details section of the help. Here is the example code from ?fanny ## generate 10+15 objects in two clu
45,467
How to decide if to do dimensionality reduction before clustering?
You do dimensionality reduction if it improves results. You don't do dimensionality reduction if the results become worse. There is no one size fits all in data mining. You have to do multiple iterations of preprocessing, data mining, evaluating, retry, until your results work for you. Different data sets have different requirements. Remember how the KDD process looks like: Notice the grey arrows going back. If the result does not make you happy, try going back and e.g. try to use different preprocessing such as dimensionality reduction. But 10 dimensions is not high dimensional anyway, probably no need to be afraid of the curse of dimensionality, unless you do some grid based methods. For the behaviour of high-dimensional data, I can recommend the articles by Houle et al: Can Shared-Neighbor Distances Defeat the Curse of Dimensionality? M. E. Houle, H.-P. Kriegel, P. Kröger, E. Schubert and A. Zimek SSDBM 2010 They show that there is no direct relationship of the number of dimensions and the ability to cluster the dataset. But it is more a question of the signal-to-noise ratio. A high-dimensional dataset can be very easy and good to cluster if all the dimensions contribute signal. If most of the dimensions are noise, a much smaller dataset will already break down. So in particular, there is no rule of thumb such as "10 is good, 50 is bad", sorry.
How to decide if to do dimensionality reduction before clustering?
You do dimensionality reduction if it improves results. You don't do dimensionality reduction if the results become worse. There is no one size fits all in data mining. You have to do multiple iterati
How to decide if to do dimensionality reduction before clustering? You do dimensionality reduction if it improves results. You don't do dimensionality reduction if the results become worse. There is no one size fits all in data mining. You have to do multiple iterations of preprocessing, data mining, evaluating, retry, until your results work for you. Different data sets have different requirements. Remember how the KDD process looks like: Notice the grey arrows going back. If the result does not make you happy, try going back and e.g. try to use different preprocessing such as dimensionality reduction. But 10 dimensions is not high dimensional anyway, probably no need to be afraid of the curse of dimensionality, unless you do some grid based methods. For the behaviour of high-dimensional data, I can recommend the articles by Houle et al: Can Shared-Neighbor Distances Defeat the Curse of Dimensionality? M. E. Houle, H.-P. Kriegel, P. Kröger, E. Schubert and A. Zimek SSDBM 2010 They show that there is no direct relationship of the number of dimensions and the ability to cluster the dataset. But it is more a question of the signal-to-noise ratio. A high-dimensional dataset can be very easy and good to cluster if all the dimensions contribute signal. If most of the dimensions are noise, a much smaller dataset will already break down. So in particular, there is no rule of thumb such as "10 is good, 50 is bad", sorry.
How to decide if to do dimensionality reduction before clustering? You do dimensionality reduction if it improves results. You don't do dimensionality reduction if the results become worse. There is no one size fits all in data mining. You have to do multiple iterati
45,468
Logistic regression: Is it valid to code NA as 0?
I would say "no". If you have this as a numeric variable, then 0 would be less than 1, indicating an even more frequent visitor; indeed, 0 has a sensible interpretation as "visited the site today".
Logistic regression: Is it valid to code NA as 0?
I would say "no". If you have this as a numeric variable, then 0 would be less than 1, indicating an even more frequent visitor; indeed, 0 has a sensible interpretation as "visited the site today".
Logistic regression: Is it valid to code NA as 0? I would say "no". If you have this as a numeric variable, then 0 would be less than 1, indicating an even more frequent visitor; indeed, 0 has a sensible interpretation as "visited the site today".
Logistic regression: Is it valid to code NA as 0? I would say "no". If you have this as a numeric variable, then 0 would be less than 1, indicating an even more frequent visitor; indeed, 0 has a sensible interpretation as "visited the site today".
45,469
Logistic regression: Is it valid to code NA as 0?
To answer the direct question, no. As @PeterFlom points out, 0 has the interpretation "visited today." You likely already have a lot of 0's in your data from people who did just that. I don't know that I would call this data "missing". The data is all there, it's just that the interpretation is a little difficult. To make this clear, think about what would happen if you imputed the missing data--what would you impute it to? You're stuck with the same problem. You know what the data is, but you do not know how to model it. Similarly, if you code it as NA, what does that mean for the model? You still have to make a choice as to how to model it. Row-wise deletion would work, but alter the question you are answering to, "Among previous visitors...." Some potential ways of modeling this: Make it a really high number (close to $\infty$) Create a two-part model, the first stage of which models the decision to become a "customer" of the website, the second stage is what you have now Create a dummy for first-time visitor (first), and interact it with the number of days since last visit variable (visit). E.g. include first and first*visit without including visit. Of those, the 2-part model seems the most appropriate but it's a lot more work. The others would probably get you something reasonable in a pinch. You could even compare across the three approaches and get a crude sensitivity analysis that way.
Logistic regression: Is it valid to code NA as 0?
To answer the direct question, no. As @PeterFlom points out, 0 has the interpretation "visited today." You likely already have a lot of 0's in your data from people who did just that. I don't know t
Logistic regression: Is it valid to code NA as 0? To answer the direct question, no. As @PeterFlom points out, 0 has the interpretation "visited today." You likely already have a lot of 0's in your data from people who did just that. I don't know that I would call this data "missing". The data is all there, it's just that the interpretation is a little difficult. To make this clear, think about what would happen if you imputed the missing data--what would you impute it to? You're stuck with the same problem. You know what the data is, but you do not know how to model it. Similarly, if you code it as NA, what does that mean for the model? You still have to make a choice as to how to model it. Row-wise deletion would work, but alter the question you are answering to, "Among previous visitors...." Some potential ways of modeling this: Make it a really high number (close to $\infty$) Create a two-part model, the first stage of which models the decision to become a "customer" of the website, the second stage is what you have now Create a dummy for first-time visitor (first), and interact it with the number of days since last visit variable (visit). E.g. include first and first*visit without including visit. Of those, the 2-part model seems the most appropriate but it's a lot more work. The others would probably get you something reasonable in a pinch. You could even compare across the three approaches and get a crude sensitivity analysis that way.
Logistic regression: Is it valid to code NA as 0? To answer the direct question, no. As @PeterFlom points out, 0 has the interpretation "visited today." You likely already have a lot of 0's in your data from people who did just that. I don't know t
45,470
Logistic regression: Is it valid to code NA as 0?
If the outcome of interest is number of days since last visit, then first-time users don't provide any information about that outcome, so it seems like leaving out first time visitors is the only thing to do. In any case, coding first time users as 0 reflects a belief that first time users are equivalent to a person who has visited the website before, and whose last visit was 0 days ago, which doesn't make much sense. Therefore, I'd strongly advise against coding in this way, since it would seriously damage interpretability of your results.
Logistic regression: Is it valid to code NA as 0?
If the outcome of interest is number of days since last visit, then first-time users don't provide any information about that outcome, so it seems like leaving out first time visitors is the only thin
Logistic regression: Is it valid to code NA as 0? If the outcome of interest is number of days since last visit, then first-time users don't provide any information about that outcome, so it seems like leaving out first time visitors is the only thing to do. In any case, coding first time users as 0 reflects a belief that first time users are equivalent to a person who has visited the website before, and whose last visit was 0 days ago, which doesn't make much sense. Therefore, I'd strongly advise against coding in this way, since it would seriously damage interpretability of your results.
Logistic regression: Is it valid to code NA as 0? If the outcome of interest is number of days since last visit, then first-time users don't provide any information about that outcome, so it seems like leaving out first time visitors is the only thin
45,471
Logistic regression: Is it valid to code NA as 0?
My answer is neither. You should code them as missing, a simple dot for missing numerical data if you use SAS. The use of 0 is bad because the software will treat 0 as a number when the data point is actually missing. The use of NA is no good because you have a numerical variable and you are mixing character and numerical values for the same variable. It might work in SAS though because I think SAS will convert values that it doesn't recognize into missing. But play it safe identify those cases as missing numerical data. The modeling procedure should know how to deal with that.
Logistic regression: Is it valid to code NA as 0?
My answer is neither. You should code them as missing, a simple dot for missing numerical data if you use SAS. The use of 0 is bad because the software will treat 0 as a number when the data point
Logistic regression: Is it valid to code NA as 0? My answer is neither. You should code them as missing, a simple dot for missing numerical data if you use SAS. The use of 0 is bad because the software will treat 0 as a number when the data point is actually missing. The use of NA is no good because you have a numerical variable and you are mixing character and numerical values for the same variable. It might work in SAS though because I think SAS will convert values that it doesn't recognize into missing. But play it safe identify those cases as missing numerical data. The modeling procedure should know how to deal with that.
Logistic regression: Is it valid to code NA as 0? My answer is neither. You should code them as missing, a simple dot for missing numerical data if you use SAS. The use of 0 is bad because the software will treat 0 as a number when the data point
45,472
How to verify that simulated data is normally distributed?
The issues arise with the idea of 'small' amounts of non-normality and 'some' autocorrelation. Until it's clear how to operationalise these then you're stuck with tests of normality (not near normality). There is, as you imply, quite a conceptual difference between an insensitive test of normality and a sensitive test of near normality. You can use the first as the second, but it probably won't be quite right and will behave differently in various limits. It seems to me you can proceed in two ways: General normality tests do not allow you to control which aspects of non-normality to treat as more serious than others. So can you define what aspect of normality is actually important? If you are more concerned about, e.g. fat tails or skew then you could test for these separately. Similarly, if you estimate the first order autocorrelation you can use the confidence interval on that parameter to determine how much is 'too much'. But you still have to decide what the correct order is (@Jason O. Jensen assumes it is one, but that will depend on the generation process) and whether you trust the test. If I remember correctly, the size of different normality tests (e.g. KS and Shapiro-Wilks) vary with level autocorrelation, sometimes even depending on its sign. And this in addition to the variation in their power with respect to various alternatives... Second, you say that you generate the data yourself. I'm imagining that either you are testing some kind of random number generator or you are wondering whether something has achieved an asymptotically normal distribution. For the former case, you probably have some idea about what is likely to be wrong, so can test for that, as suggested above. In the latter case, I have less intuition. It is probable that the MCMC convergence literature has something useful to say about this case.
How to verify that simulated data is normally distributed?
The issues arise with the idea of 'small' amounts of non-normality and 'some' autocorrelation. Until it's clear how to operationalise these then you're stuck with tests of normality (not near normali
How to verify that simulated data is normally distributed? The issues arise with the idea of 'small' amounts of non-normality and 'some' autocorrelation. Until it's clear how to operationalise these then you're stuck with tests of normality (not near normality). There is, as you imply, quite a conceptual difference between an insensitive test of normality and a sensitive test of near normality. You can use the first as the second, but it probably won't be quite right and will behave differently in various limits. It seems to me you can proceed in two ways: General normality tests do not allow you to control which aspects of non-normality to treat as more serious than others. So can you define what aspect of normality is actually important? If you are more concerned about, e.g. fat tails or skew then you could test for these separately. Similarly, if you estimate the first order autocorrelation you can use the confidence interval on that parameter to determine how much is 'too much'. But you still have to decide what the correct order is (@Jason O. Jensen assumes it is one, but that will depend on the generation process) and whether you trust the test. If I remember correctly, the size of different normality tests (e.g. KS and Shapiro-Wilks) vary with level autocorrelation, sometimes even depending on its sign. And this in addition to the variation in their power with respect to various alternatives... Second, you say that you generate the data yourself. I'm imagining that either you are testing some kind of random number generator or you are wondering whether something has achieved an asymptotically normal distribution. For the former case, you probably have some idea about what is likely to be wrong, so can test for that, as suggested above. In the latter case, I have less intuition. It is probable that the MCMC convergence literature has something useful to say about this case.
How to verify that simulated data is normally distributed? The issues arise with the idea of 'small' amounts of non-normality and 'some' autocorrelation. Until it's clear how to operationalise these then you're stuck with tests of normality (not near normali
45,473
How to verify that simulated data is normally distributed?
If point two is your primary concern you could 'lag' the data one observation and then regress the 'raw' data on the 'lagged' data. Do this for a lag each way and decide based on the p value whether the data is sufficiently random.
How to verify that simulated data is normally distributed?
If point two is your primary concern you could 'lag' the data one observation and then regress the 'raw' data on the 'lagged' data. Do this for a lag each way and decide based on the p value whether t
How to verify that simulated data is normally distributed? If point two is your primary concern you could 'lag' the data one observation and then regress the 'raw' data on the 'lagged' data. Do this for a lag each way and decide based on the p value whether the data is sufficiently random.
How to verify that simulated data is normally distributed? If point two is your primary concern you could 'lag' the data one observation and then regress the 'raw' data on the 'lagged' data. Do this for a lag each way and decide based on the p value whether t
45,474
How to verify that simulated data is normally distributed?
Another suggestion would be to compute the Kullback-Leiber divergence or Hellinger distance between your generated data and the normal distribution. That gives you a measure of how non-normal your data is (and hopefully you can determine what a small deviation from normality is).
How to verify that simulated data is normally distributed?
Another suggestion would be to compute the Kullback-Leiber divergence or Hellinger distance between your generated data and the normal distribution. That gives you a measure of how non-normal your dat
How to verify that simulated data is normally distributed? Another suggestion would be to compute the Kullback-Leiber divergence or Hellinger distance between your generated data and the normal distribution. That gives you a measure of how non-normal your data is (and hopefully you can determine what a small deviation from normality is).
How to verify that simulated data is normally distributed? Another suggestion would be to compute the Kullback-Leiber divergence or Hellinger distance between your generated data and the normal distribution. That gives you a measure of how non-normal your dat
45,475
How to verify that simulated data is normally distributed?
The best test that I can think of for near-normality is the visual test in: Buja, A., Cook, D. Hofmann, H., Lawrence, M. Lee, E.-K., Swayne, D.F and Wickham, H. (2009) Statistical Inference for exploratory data analysis and model diagnostics Phil. Trans. R. Soc. A 2009 367, 4361-4383 doi: 10.1098/rsta.2009.0120 The vis.test function in the TeachingDemos package for R implements variations on this test. This does assume that you either trust R's random normal generator to be good enough for comparison or that you have another source of normal enough for comparison. This test cannot be automated, but is fairly straight forward and fits the ideas above (and you could find a way to look at the autocorrelation as well if desired).
How to verify that simulated data is normally distributed?
The best test that I can think of for near-normality is the visual test in: Buja, A., Cook, D. Hofmann, H., Lawrence, M. Lee, E.-K., Swayne, D.F and Wickham, H. (2009) Statistical Inference for ex
How to verify that simulated data is normally distributed? The best test that I can think of for near-normality is the visual test in: Buja, A., Cook, D. Hofmann, H., Lawrence, M. Lee, E.-K., Swayne, D.F and Wickham, H. (2009) Statistical Inference for exploratory data analysis and model diagnostics Phil. Trans. R. Soc. A 2009 367, 4361-4383 doi: 10.1098/rsta.2009.0120 The vis.test function in the TeachingDemos package for R implements variations on this test. This does assume that you either trust R's random normal generator to be good enough for comparison or that you have another source of normal enough for comparison. This test cannot be automated, but is fairly straight forward and fits the ideas above (and you could find a way to look at the autocorrelation as well if desired).
How to verify that simulated data is normally distributed? The best test that I can think of for near-normality is the visual test in: Buja, A., Cook, D. Hofmann, H., Lawrence, M. Lee, E.-K., Swayne, D.F and Wickham, H. (2009) Statistical Inference for ex
45,476
Is there a difference between the "maximum probability" and the "mode" of a parameter?
The answer to the (now edited) question is no, there is no difference: maximum posterior probability for a given value $\hat{\theta}_{MAP}$ (the so-called maximum a-posteriori estimate of $\theta$) is equivalent to the mode of the posterior distribution of your parameter. Mathematically, you can express this in the context of parameter estimation as $$\hat{\theta}_{MAP}=\text{argmax}_{\theta}\ \ p(\theta|D,I),$$ where $p(\theta|D,I)$ is the posterior distribution of $\theta$ given the data $D$ and any information $I$ (e.g. your prior). As some people stated on the comments of the other answers this is not equivalent to the maximum likelihood estimate (MLE) in general (this is the case if you have an uniform prior, as long as this prior is defined on a suitable interval around the MLE), because $$p(\theta|D,I)=\frac{p(D|\theta,I)p(\theta|I)}{p(D|I)},$$ and you wish to maximize $p(D|\theta,I)p(\theta|I)$ in order to obtain the MAP estimate. On the other hand, the MLE maximizes $p(D|\theta,I)$ only.
Is there a difference between the "maximum probability" and the "mode" of a parameter?
The answer to the (now edited) question is no, there is no difference: maximum posterior probability for a given value $\hat{\theta}_{MAP}$ (the so-called maximum a-posteriori estimate of $\theta$) is
Is there a difference between the "maximum probability" and the "mode" of a parameter? The answer to the (now edited) question is no, there is no difference: maximum posterior probability for a given value $\hat{\theta}_{MAP}$ (the so-called maximum a-posteriori estimate of $\theta$) is equivalent to the mode of the posterior distribution of your parameter. Mathematically, you can express this in the context of parameter estimation as $$\hat{\theta}_{MAP}=\text{argmax}_{\theta}\ \ p(\theta|D,I),$$ where $p(\theta|D,I)$ is the posterior distribution of $\theta$ given the data $D$ and any information $I$ (e.g. your prior). As some people stated on the comments of the other answers this is not equivalent to the maximum likelihood estimate (MLE) in general (this is the case if you have an uniform prior, as long as this prior is defined on a suitable interval around the MLE), because $$p(\theta|D,I)=\frac{p(D|\theta,I)p(\theta|I)}{p(D|I)},$$ and you wish to maximize $p(D|\theta,I)p(\theta|I)$ in order to obtain the MAP estimate. On the other hand, the MLE maximizes $p(D|\theta,I)$ only.
Is there a difference between the "maximum probability" and the "mode" of a parameter? The answer to the (now edited) question is no, there is no difference: maximum posterior probability for a given value $\hat{\theta}_{MAP}$ (the so-called maximum a-posteriori estimate of $\theta$) is
45,477
Mean and variance of log-binomial distribution
We can use an entirely analogous technique to the one typically used to calculate the moments of a lognormal. In particular, note that if $\newcommand{\E}{\mathbb E}X \sim \mathrm{Bin}(n,p)$ and $Y = e^X$, then $Y^k = e^{k X}$. But, $\E e^{kX} = m_X(k)$ where $m_X(t)$ is the moment-generating function of $X$ evaluated at $t$. Hence, $$ \E e^{k X} = m_X(k) = (1 - p + p e^k)^n \>, $$ and so $$ \E Y = m_X(1) = (1 + (e-1)p)^n $$ and $$ \mathrm{Var}(Y) = m_X(2) - (m_X(1))^2 = (1+(e^2-1)p)^n - (1+(e-1)p)^{2n} \>. $$ Other moments of $Y$ can be computed in a similar fashion.
Mean and variance of log-binomial distribution
We can use an entirely analogous technique to the one typically used to calculate the moments of a lognormal. In particular, note that if $\newcommand{\E}{\mathbb E}X \sim \mathrm{Bin}(n,p)$ and $Y =
Mean and variance of log-binomial distribution We can use an entirely analogous technique to the one typically used to calculate the moments of a lognormal. In particular, note that if $\newcommand{\E}{\mathbb E}X \sim \mathrm{Bin}(n,p)$ and $Y = e^X$, then $Y^k = e^{k X}$. But, $\E e^{kX} = m_X(k)$ where $m_X(t)$ is the moment-generating function of $X$ evaluated at $t$. Hence, $$ \E e^{k X} = m_X(k) = (1 - p + p e^k)^n \>, $$ and so $$ \E Y = m_X(1) = (1 + (e-1)p)^n $$ and $$ \mathrm{Var}(Y) = m_X(2) - (m_X(1))^2 = (1+(e^2-1)p)^n - (1+(e-1)p)^{2n} \>. $$ Other moments of $Y$ can be computed in a similar fashion.
Mean and variance of log-binomial distribution We can use an entirely analogous technique to the one typically used to calculate the moments of a lognormal. In particular, note that if $\newcommand{\E}{\mathbb E}X \sim \mathrm{Bin}(n,p)$ and $Y =
45,478
Mean and variance of log-binomial distribution
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. See: Parameter Estimation and Goodness-of-Fit in Log Binomial Regression, L. Blizzard and D. W. Hosmer, Biometrical Journal Volume 48, Issue 1, pages 5–22, February 2006
Mean and variance of log-binomial distribution
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Mean and variance of log-binomial distribution Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. See: Parameter Estimation and Goodness-of-Fit in Log Binomial Regression, L. Blizzard and D. W. Hosmer, Biometrical Journal Volume 48, Issue 1, pages 5–22, February 2006
Mean and variance of log-binomial distribution Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
45,479
Variance explained by random effects using lme4
Such a value doesn't exists for a GLMM. The model you show that does have a Residual component is a LMM not a GLMM. In a GLMM there is a known mean-variance relationship and there isn't a parameter $\sigma$ to estimate. You can compute the residual deviance but this doesn't fit into the scheme of being a variance parameter (and hence can not be squared to give a standard deviation). That would be sufficient for it not to be shown in the output from the GLMM.
Variance explained by random effects using lme4
Such a value doesn't exists for a GLMM. The model you show that does have a Residual component is a LMM not a GLMM. In a GLMM there is a known mean-variance relationship and there isn't a parameter $\
Variance explained by random effects using lme4 Such a value doesn't exists for a GLMM. The model you show that does have a Residual component is a LMM not a GLMM. In a GLMM there is a known mean-variance relationship and there isn't a parameter $\sigma$ to estimate. You can compute the residual deviance but this doesn't fit into the scheme of being a variance parameter (and hence can not be squared to give a standard deviation). That would be sufficient for it not to be shown in the output from the GLMM.
Variance explained by random effects using lme4 Such a value doesn't exists for a GLMM. The model you show that does have a Residual component is a LMM not a GLMM. In a GLMM there is a known mean-variance relationship and there isn't a parameter $\
45,480
How to sample natural numbers, such that the sum is equal to a constant?
I believe what you are looking for is something like the Dirichlet Process [DP] which is a distribution on distributions. It is not an easy concept to understand, but the base measure you will use is the discrete distribution of cluster sizes you started with. The parameter $\alpha$ controls how 'close' to the original distribution your new one is. Since a sample from a DP is a probability distribution (in your case, a discrete one), you can multiply it by $N$ to get cluster sizes. The result won't be integers, but just rounding the numbers should not affect what you're trying to do in a meaningful way. Edit: Somehow, I am more familiar with the Dirichlet Process than the Dirichlet Distribution, which is what you are actually looking for. The DP is an infinite dimensional generalization of the DD. To be more algorithmically precise, consult the subsection talking about random number generation. Your parameters are going to be based on the cluster sizes that you want the random clusterings to look like $\{n_j\}_{j=0}^k$. In other words: $$\alpha = (\alpha_1,...,\alpha_k) = (\frac{\beta n_1}{N},...,\frac{\beta n_k}{N})$$ where $\beta$ is called a concentration parameter and it controls how close to the original distribution of cluster sizes the Dirichlet distribution will be on average. Higher values of $beta$ will mean that the resulting DD will give closer and closer values to the EXACT distribution of sample sizes you started with. So, the algorithm would be: (if you have access to a function that can generate Dirichlet Distribution samples, ignore steps 1 and 2.) Draw independent samples from $y_j = Gamma(\alpha_j,1)$ for each $j = 1..k$. Compute $x_j = y_j/\sum^k_{j=1}y_j$ for each $j$. Then you have the sample $Dirichlet(\alpha_1,...,\alpha_k) = (x_1,...,x_k)$. Multiply by the sample by $N$ to get the approximate new cluster sizes. $N(x_1,...,x_k)$. Round the result to the nearest natural number. (make sure that the new cluster sizes add to $N$ due the rounding.) Fill the new clusters of a random permutation of elements. The advantage that this has over the previously discussed option of just permuting the elements is that the cluster size distribution isn't always the same. You can allow for as much or a little variation from the original cluster sizes by controlling the concentration parameter $\beta$. In simulation this will likely result in a more robust calculation.
How to sample natural numbers, such that the sum is equal to a constant?
I believe what you are looking for is something like the Dirichlet Process [DP] which is a distribution on distributions. It is not an easy concept to understand, but the base measure you will use is
How to sample natural numbers, such that the sum is equal to a constant? I believe what you are looking for is something like the Dirichlet Process [DP] which is a distribution on distributions. It is not an easy concept to understand, but the base measure you will use is the discrete distribution of cluster sizes you started with. The parameter $\alpha$ controls how 'close' to the original distribution your new one is. Since a sample from a DP is a probability distribution (in your case, a discrete one), you can multiply it by $N$ to get cluster sizes. The result won't be integers, but just rounding the numbers should not affect what you're trying to do in a meaningful way. Edit: Somehow, I am more familiar with the Dirichlet Process than the Dirichlet Distribution, which is what you are actually looking for. The DP is an infinite dimensional generalization of the DD. To be more algorithmically precise, consult the subsection talking about random number generation. Your parameters are going to be based on the cluster sizes that you want the random clusterings to look like $\{n_j\}_{j=0}^k$. In other words: $$\alpha = (\alpha_1,...,\alpha_k) = (\frac{\beta n_1}{N},...,\frac{\beta n_k}{N})$$ where $\beta$ is called a concentration parameter and it controls how close to the original distribution of cluster sizes the Dirichlet distribution will be on average. Higher values of $beta$ will mean that the resulting DD will give closer and closer values to the EXACT distribution of sample sizes you started with. So, the algorithm would be: (if you have access to a function that can generate Dirichlet Distribution samples, ignore steps 1 and 2.) Draw independent samples from $y_j = Gamma(\alpha_j,1)$ for each $j = 1..k$. Compute $x_j = y_j/\sum^k_{j=1}y_j$ for each $j$. Then you have the sample $Dirichlet(\alpha_1,...,\alpha_k) = (x_1,...,x_k)$. Multiply by the sample by $N$ to get the approximate new cluster sizes. $N(x_1,...,x_k)$. Round the result to the nearest natural number. (make sure that the new cluster sizes add to $N$ due the rounding.) Fill the new clusters of a random permutation of elements. The advantage that this has over the previously discussed option of just permuting the elements is that the cluster size distribution isn't always the same. You can allow for as much or a little variation from the original cluster sizes by controlling the concentration parameter $\beta$. In simulation this will likely result in a more robust calculation.
How to sample natural numbers, such that the sum is equal to a constant? I believe what you are looking for is something like the Dirichlet Process [DP] which is a distribution on distributions. It is not an easy concept to understand, but the base measure you will use is
45,481
How to sample natural numbers, such that the sum is equal to a constant?
One easy way to achieve your goal is to permute the labels. Say you had 10 objects, with memberships defined as $\{1, 2, 3, 4 ,5, 6\}$, $\{7, 8\}$, $\{9\}$ and $\{10\}$. You take a random permutation $\sigma=(3, 7, 2, 5, 1, 8, 10, 9, 6, 4)$, and then your new clusters are $\{\sigma(1), \sigma(2), \sigma(3), \sigma(4), \sigma(5), \sigma(6)\} = \{1, 2, 3, 5, 7, 8\}$, $\{\sigma(7), \sigma(8)\}=\{9, 10\}$, $\{\sigma(9)\}=\{6\}$ and $\{\sigma(10)\} = \{4\}$. If you want to introduce some variability in the cluster sizes, that can probably be done, too -- e.g. by drawing clusters with sizes Poi(6), Poi(2), Poi(1) and Poi(1), rejecting the samples that do not add up to 10. (Poi($\lambda$) is a Poisson random variable with rate/expected value $\lambda$.) (I wrote this before I read @whuber's comment. Oops) Update, based on valuable @DanielJohnson's comment: For large values of the total, the procedure becomes impractical, as it will be rejecting most samples. What you would want to do, then, is to condition on the total number of objects, $N$, and then the Poisson distribution becomes a multinomial with probabilities $\lambda_1/L, \ldots, \lambda_k/L, \ldots$, where $L=\lambda_1 + \ldots + \lambda_k + \ldots$. So your samples would simply be multinomial ones. Some clusters of size 1 or 2 may get lost though, and if you don't like that, then again you could condition on all clusters being present. This would effectively introduce variability in the size of larger clusters, while the smaller ones will remain with their original sizes. Again, if you find yourself rejecting the samples too often, you can use a combination of: (1) maintaining clusters of size 1 or 2; (2) simulating the Poisson- or multinomial-distributed clusters of larger sizes.
How to sample natural numbers, such that the sum is equal to a constant?
One easy way to achieve your goal is to permute the labels. Say you had 10 objects, with memberships defined as $\{1, 2, 3, 4 ,5, 6\}$, $\{7, 8\}$, $\{9\}$ and $\{10\}$. You take a random permutation
How to sample natural numbers, such that the sum is equal to a constant? One easy way to achieve your goal is to permute the labels. Say you had 10 objects, with memberships defined as $\{1, 2, 3, 4 ,5, 6\}$, $\{7, 8\}$, $\{9\}$ and $\{10\}$. You take a random permutation $\sigma=(3, 7, 2, 5, 1, 8, 10, 9, 6, 4)$, and then your new clusters are $\{\sigma(1), \sigma(2), \sigma(3), \sigma(4), \sigma(5), \sigma(6)\} = \{1, 2, 3, 5, 7, 8\}$, $\{\sigma(7), \sigma(8)\}=\{9, 10\}$, $\{\sigma(9)\}=\{6\}$ and $\{\sigma(10)\} = \{4\}$. If you want to introduce some variability in the cluster sizes, that can probably be done, too -- e.g. by drawing clusters with sizes Poi(6), Poi(2), Poi(1) and Poi(1), rejecting the samples that do not add up to 10. (Poi($\lambda$) is a Poisson random variable with rate/expected value $\lambda$.) (I wrote this before I read @whuber's comment. Oops) Update, based on valuable @DanielJohnson's comment: For large values of the total, the procedure becomes impractical, as it will be rejecting most samples. What you would want to do, then, is to condition on the total number of objects, $N$, and then the Poisson distribution becomes a multinomial with probabilities $\lambda_1/L, \ldots, \lambda_k/L, \ldots$, where $L=\lambda_1 + \ldots + \lambda_k + \ldots$. So your samples would simply be multinomial ones. Some clusters of size 1 or 2 may get lost though, and if you don't like that, then again you could condition on all clusters being present. This would effectively introduce variability in the size of larger clusters, while the smaller ones will remain with their original sizes. Again, if you find yourself rejecting the samples too often, you can use a combination of: (1) maintaining clusters of size 1 or 2; (2) simulating the Poisson- or multinomial-distributed clusters of larger sizes.
How to sample natural numbers, such that the sum is equal to a constant? One easy way to achieve your goal is to permute the labels. Say you had 10 objects, with memberships defined as $\{1, 2, 3, 4 ,5, 6\}$, $\{7, 8\}$, $\{9\}$ and $\{10\}$. You take a random permutation
45,482
How to sample natural numbers, such that the sum is equal to a constant?
Can you think of this as $n$ balls being distributed among $k$ urns? That seems to fit your description of clusters (where you have $k$ clusters and $n$ numbers). If you need at least one ball in each urn, then first put 1 ball in each urn, then randomly select the urn for each of the remaining $n-k$ balls. Here is one possible implementation in R: > nkballs <- function(n,k) { + tmp <- sample(k, n-k, replace=TRUE) + as.numeric( table(tmp) ) + 1 + } > > nkballs(1000, 25) [1] 36 47 40 52 40 28 34 43 37 35 38 33 45 37 45 45 37 34 38 46 42 34 56 46 32 > sum(.Last.value) [1] 1000
How to sample natural numbers, such that the sum is equal to a constant?
Can you think of this as $n$ balls being distributed among $k$ urns? That seems to fit your description of clusters (where you have $k$ clusters and $n$ numbers). If you need at least one ball in ea
How to sample natural numbers, such that the sum is equal to a constant? Can you think of this as $n$ balls being distributed among $k$ urns? That seems to fit your description of clusters (where you have $k$ clusters and $n$ numbers). If you need at least one ball in each urn, then first put 1 ball in each urn, then randomly select the urn for each of the remaining $n-k$ balls. Here is one possible implementation in R: > nkballs <- function(n,k) { + tmp <- sample(k, n-k, replace=TRUE) + as.numeric( table(tmp) ) + 1 + } > > nkballs(1000, 25) [1] 36 47 40 52 40 28 34 43 37 35 38 33 45 37 45 45 37 34 38 46 42 34 56 46 32 > sum(.Last.value) [1] 1000
How to sample natural numbers, such that the sum is equal to a constant? Can you think of this as $n$ balls being distributed among $k$ urns? That seems to fit your description of clusters (where you have $k$ clusters and $n$ numbers). If you need at least one ball in ea
45,483
How to choose the most appropriate distribution for a given vector in R?
When deciding on a distribution, the science is more important than the tests. Think about what lead to the data, what values are possible, likely, and meaningful. The formal tests can find obvious differences, but often cannot rule out distributions that are similar (and note that the chi-squared distribution is a special case of the gamma distribution). Look at this quick simulation (and try it with other values): > mean(replicate(1000, ks.test( rt(5000, df=20), pnorm )$p.value)<0.05) [1] 0.111 The ks.test can only find the difference between a t-distribution with 20 df and a standard normal 11% of the time, even with a sample size of 5000. If you really want to test the distributions, then I would suggest using the vis.test function in the TeachingDemos package. Instead of rigid tests of exact fit, it presents a plot of the original data mixed in with similar plots from the candidate distribution and asks you (or another viewer) to pick out the plot of the original data. If you cannot distinguish visually between your data and the simulated data then the candidate distribution is probably a reasonable starting point (but this does not rule out other possible distributions, think about which ones make the most sense scientifically). Another approach would be to generate your new data from the density estimate of your original data. The logspline package for R has functions to estimate the density, then generate random data from that estimate. Or, generating data from a kernal density estimate means selecting a point from your data, then generating a random value from the kernal centered around that point. This can be as simple as selecting a random sample from the data with replacement, then adding small normal deviates to the values.
How to choose the most appropriate distribution for a given vector in R?
When deciding on a distribution, the science is more important than the tests. Think about what lead to the data, what values are possible, likely, and meaningful. The formal tests can find obvious
How to choose the most appropriate distribution for a given vector in R? When deciding on a distribution, the science is more important than the tests. Think about what lead to the data, what values are possible, likely, and meaningful. The formal tests can find obvious differences, but often cannot rule out distributions that are similar (and note that the chi-squared distribution is a special case of the gamma distribution). Look at this quick simulation (and try it with other values): > mean(replicate(1000, ks.test( rt(5000, df=20), pnorm )$p.value)<0.05) [1] 0.111 The ks.test can only find the difference between a t-distribution with 20 df and a standard normal 11% of the time, even with a sample size of 5000. If you really want to test the distributions, then I would suggest using the vis.test function in the TeachingDemos package. Instead of rigid tests of exact fit, it presents a plot of the original data mixed in with similar plots from the candidate distribution and asks you (or another viewer) to pick out the plot of the original data. If you cannot distinguish visually between your data and the simulated data then the candidate distribution is probably a reasonable starting point (but this does not rule out other possible distributions, think about which ones make the most sense scientifically). Another approach would be to generate your new data from the density estimate of your original data. The logspline package for R has functions to estimate the density, then generate random data from that estimate. Or, generating data from a kernal density estimate means selecting a point from your data, then generating a random value from the kernal centered around that point. This can be as simple as selecting a random sample from the data with replacement, then adding small normal deviates to the values.
How to choose the most appropriate distribution for a given vector in R? When deciding on a distribution, the science is more important than the tests. Think about what lead to the data, what values are possible, likely, and meaningful. The formal tests can find obvious
45,484
How to choose the most appropriate distribution for a given vector in R?
There is no reason one of the "official" distributions would fit your data. The most relevant statistical test for checking fit to a distribution is the Kolmogorov-Smirnov test. E.g., > x=rnorm(133) > ks.test(x,"pnorm",mean(x),sd(x)) One-sample Kolmogorov-Smirnov test data: x D = 0.0388, p-value = 0.9882 alternative hypothesis: two-sided (with the caveat that the p-value does not account for the parameter estimation). Edited: In order to find the proper p-value, one can use a Monte Carlo experiment, namely produce a sample of samples $x$ from the hypothetised distribution and for each of those, derive the ks.test distance. This sample of ks.distances can then be used to find an empirical p-value: ksdist=rep(0,10^2) for (t in 1:10^2){ x=rnorm(length(x0),mean(x0),sd(x0)) ksdist[t]=ks.test(x,"pnorm",mean(x),sd(x))$stat } empvalue=sum(ksdist>ks.test(x0,"pnorm",mean(x0),sd(x0))$stat)/10^2 For instance, > x0=rt(123,df=4) > empvalue [1] 0.02 > ks.test(x0,"pnorm",mean(x0),sd(x0))$p [1] 0.2996538 and > x0=rnorm(321) > empvalue [1] 0.1 > ks.test(x0,"pnorm",mean(x0),sd(x0))$p [1] 0.568052 shows how the simulation corrects the improper p-value. (This exercise is usually part of my final exam in exploratory statistics.)
How to choose the most appropriate distribution for a given vector in R?
There is no reason one of the "official" distributions would fit your data. The most relevant statistical test for checking fit to a distribution is the Kolmogorov-Smirnov test. E.g., > x=rnorm(133)
How to choose the most appropriate distribution for a given vector in R? There is no reason one of the "official" distributions would fit your data. The most relevant statistical test for checking fit to a distribution is the Kolmogorov-Smirnov test. E.g., > x=rnorm(133) > ks.test(x,"pnorm",mean(x),sd(x)) One-sample Kolmogorov-Smirnov test data: x D = 0.0388, p-value = 0.9882 alternative hypothesis: two-sided (with the caveat that the p-value does not account for the parameter estimation). Edited: In order to find the proper p-value, one can use a Monte Carlo experiment, namely produce a sample of samples $x$ from the hypothetised distribution and for each of those, derive the ks.test distance. This sample of ks.distances can then be used to find an empirical p-value: ksdist=rep(0,10^2) for (t in 1:10^2){ x=rnorm(length(x0),mean(x0),sd(x0)) ksdist[t]=ks.test(x,"pnorm",mean(x),sd(x))$stat } empvalue=sum(ksdist>ks.test(x0,"pnorm",mean(x0),sd(x0))$stat)/10^2 For instance, > x0=rt(123,df=4) > empvalue [1] 0.02 > ks.test(x0,"pnorm",mean(x0),sd(x0))$p [1] 0.2996538 and > x0=rnorm(321) > empvalue [1] 0.1 > ks.test(x0,"pnorm",mean(x0),sd(x0))$p [1] 0.568052 shows how the simulation corrects the improper p-value. (This exercise is usually part of my final exam in exploratory statistics.)
How to choose the most appropriate distribution for a given vector in R? There is no reason one of the "official" distributions would fit your data. The most relevant statistical test for checking fit to a distribution is the Kolmogorov-Smirnov test. E.g., > x=rnorm(133)
45,485
Identifying outlier data in high-dimensional settings
(classical) Mahalanobis distances cannot be used to find outliers in data because the Mahalanobis distance themselves are sensitive to outliers (i.e., they will always by construction sum to $(n-1)\times p$, the product of the dimensions of your dataset). The recommended solution depends on what you mean by 'high dimensional'. Denoting $p$ the number of variables and $n$ the number of observations, broadly, for $10\leq p \leq 100$, the current state of the art approach for outlier detection in high dimensional setting is the OGK algorithm of which many implementations exists. The numerical complexity of the OGK in $p$ is $\mathcal{O}(np^2+p^3)$, very close to the theoretical lower bound for this problem because methods based on convex loss functions cannot reliable detect outliers if there are more than $n/p$ of them. If your number of dimensions is much larger than the 100's, you will have to first do a (robust) dimension reduction of your data-set. Here, the current state of the art methods is the PCA-grid approach, which again, is well implemented, see also here for direct estimation of the co-variance matrix. An alternative procedure is the ROBPCA approach, which is, again, well implemented. Notice that neither of the three procedures requires $n$ to be larger than $p$. The last two methods have complexity in the order of $\mathcal{O}(nk^3)$ where $k$ is the number of components one wishes to retains (which in high dimensional data is often much smaller than $p$). Relative merits: The big advantage of ROBPCA is its computational efficiency in high dimensions. The big advantage of PCA-Grid is that it can perform both robust estimation and hard variable selection (in the sense of giving exactly 0 weight to a subset of the variables) see here for a link and the sPCAgrid() function in the pcaPP R package.
Identifying outlier data in high-dimensional settings
(classical) Mahalanobis distances cannot be used to find outliers in data because the Mahalanobis distance themselves are sensitive to outliers (i.e., they will always by construction sum to $(n-1)\t
Identifying outlier data in high-dimensional settings (classical) Mahalanobis distances cannot be used to find outliers in data because the Mahalanobis distance themselves are sensitive to outliers (i.e., they will always by construction sum to $(n-1)\times p$, the product of the dimensions of your dataset). The recommended solution depends on what you mean by 'high dimensional'. Denoting $p$ the number of variables and $n$ the number of observations, broadly, for $10\leq p \leq 100$, the current state of the art approach for outlier detection in high dimensional setting is the OGK algorithm of which many implementations exists. The numerical complexity of the OGK in $p$ is $\mathcal{O}(np^2+p^3)$, very close to the theoretical lower bound for this problem because methods based on convex loss functions cannot reliable detect outliers if there are more than $n/p$ of them. If your number of dimensions is much larger than the 100's, you will have to first do a (robust) dimension reduction of your data-set. Here, the current state of the art methods is the PCA-grid approach, which again, is well implemented, see also here for direct estimation of the co-variance matrix. An alternative procedure is the ROBPCA approach, which is, again, well implemented. Notice that neither of the three procedures requires $n$ to be larger than $p$. The last two methods have complexity in the order of $\mathcal{O}(nk^3)$ where $k$ is the number of components one wishes to retains (which in high dimensional data is often much smaller than $p$). Relative merits: The big advantage of ROBPCA is its computational efficiency in high dimensions. The big advantage of PCA-Grid is that it can perform both robust estimation and hard variable selection (in the sense of giving exactly 0 weight to a subset of the variables) see here for a link and the sPCAgrid() function in the pcaPP R package.
Identifying outlier data in high-dimensional settings (classical) Mahalanobis distances cannot be used to find outliers in data because the Mahalanobis distance themselves are sensitive to outliers (i.e., they will always by construction sum to $(n-1)\t
45,486
Identifying outlier data in high-dimensional settings
A basic approach is to use Mahalanobis distance, and look for data that are more extreme than you would expect. Mahalanobis distance is a multidimensional measure that takes into account the pattern of intercorrelations amongst your variables. One issue to bear in mind, is that this assumes your data are continuous; I don't think it would be appropriate if you had a discrete variable (e.g., male vs. female). As for what is more extreme than you expect, that depends in part on your sample size. For example, a lot of people think you should trim data that are more that 2 z's, but realistically, if you have 100 data points, it's reasonable to expect that 5 should be beyond that threshold without anything being amiss. It's also worth your while to think hard about your variables without (i.e., before) looking at your data. For example, it's often the case that you can simply intuit the proper range of values. (If you have a person whose height is listed as 7'10", that's probably a typo.)
Identifying outlier data in high-dimensional settings
A basic approach is to use Mahalanobis distance, and look for data that are more extreme than you would expect. Mahalanobis distance is a multidimensional measure that takes into account the pattern
Identifying outlier data in high-dimensional settings A basic approach is to use Mahalanobis distance, and look for data that are more extreme than you would expect. Mahalanobis distance is a multidimensional measure that takes into account the pattern of intercorrelations amongst your variables. One issue to bear in mind, is that this assumes your data are continuous; I don't think it would be appropriate if you had a discrete variable (e.g., male vs. female). As for what is more extreme than you expect, that depends in part on your sample size. For example, a lot of people think you should trim data that are more that 2 z's, but realistically, if you have 100 data points, it's reasonable to expect that 5 should be beyond that threshold without anything being amiss. It's also worth your while to think hard about your variables without (i.e., before) looking at your data. For example, it's often the case that you can simply intuit the proper range of values. (If you have a person whose height is listed as 7'10", that's probably a typo.)
Identifying outlier data in high-dimensional settings A basic approach is to use Mahalanobis distance, and look for data that are more extreme than you would expect. Mahalanobis distance is a multidimensional measure that takes into account the pattern
45,487
Identifying outlier data in high-dimensional settings
It might be worth looking at one-class-SVM, which attempts to construct the smallest hypersphere that encloses as large a proportion of the data as possible, which has been used successfully in the machine learning community for novelty detection, so its use for outlier detection seems reasonable. I suspect there are non-linear versions (being a kernel method), which means that the sphere in the kernel-induced feature space corresponds to the exterior of the manifold containing the data in the attribute space, which doesn't necessarily have to be hyper-spherical. Caveat: I've seen this method described in conference and journal papers, but have not used it in anger myself, so your mileage may vary, but probably worth looking into.
Identifying outlier data in high-dimensional settings
It might be worth looking at one-class-SVM, which attempts to construct the smallest hypersphere that encloses as large a proportion of the data as possible, which has been used successfully in the ma
Identifying outlier data in high-dimensional settings It might be worth looking at one-class-SVM, which attempts to construct the smallest hypersphere that encloses as large a proportion of the data as possible, which has been used successfully in the machine learning community for novelty detection, so its use for outlier detection seems reasonable. I suspect there are non-linear versions (being a kernel method), which means that the sphere in the kernel-induced feature space corresponds to the exterior of the manifold containing the data in the attribute space, which doesn't necessarily have to be hyper-spherical. Caveat: I've seen this method described in conference and journal papers, but have not used it in anger myself, so your mileage may vary, but probably worth looking into.
Identifying outlier data in high-dimensional settings It might be worth looking at one-class-SVM, which attempts to construct the smallest hypersphere that encloses as large a proportion of the data as possible, which has been used successfully in the ma
45,488
Is there a fast algorithm to check for AR(p) stationarity?
The Schur-Cohn algorithm has $d=2$; this is what I learned in a computational statistics class at Berkeley some years ago.
Is there a fast algorithm to check for AR(p) stationarity?
The Schur-Cohn algorithm has $d=2$; this is what I learned in a computational statistics class at Berkeley some years ago.
Is there a fast algorithm to check for AR(p) stationarity? The Schur-Cohn algorithm has $d=2$; this is what I learned in a computational statistics class at Berkeley some years ago.
Is there a fast algorithm to check for AR(p) stationarity? The Schur-Cohn algorithm has $d=2$; this is what I learned in a computational statistics class at Berkeley some years ago.
45,489
Is there a fast algorithm to check for AR(p) stationarity?
It is unnecessary to find the $p$ complex roots as far as these are not to be used for themselves. Moreover, most (if not all) root finding processes can fail for large $p$. Another solution is as follows. The $\mathrm{AR}(p)$ model can be reparametrised thanks to its $p$ partial autocorrelations (PACs) $\zeta_k$ for $1 \le k \le p$. The PACs are often denoted as $\phi_{k,k}$ because their computation involves an array $\phi_{k,\ell}$. There is a one-to-one correspondence between the vector $\boldsymbol{\rho}$ of the $p$ coefficients in the stationarity region and the vector $\boldsymbol{\zeta}$ in the region defined by the $p$ conditions $|\zeta_k | < 1$ for $1 \le k \le p$. The transformation "AR to PAC" $\boldsymbol{\rho} \mapsto \boldsymbol{\zeta}$ is quite simple and is given as a pretty recursion formula due to Barndorff-Nielsen and Schou. Testing stationarity from the vector of coefficients boils down to computing the $\zeta_k$ and stop as soon as one condition $| \zeta_k | \ge 1$ is found. The less well-known inverse transform "PAC to AR" $\boldsymbol{\zeta} \mapsto \boldsymbol{\rho}$ is available explicitly (due to Monahan), and is as simple as is the direct one. It might also be useful in some cases. The two transformations are implemented (in R) in a CRAN R package named FitAR which provides as well an efficient invertibleQ function to test stationarity. The package is described in the following article where list of references is provided. McLeod, A.I. and Zhang Y., "Improved Subset Autoregression: With R Package" Journal of Statistical Software, vol. 28, Issue 2, Oct 2008. http://www.jstatsoft.org/v28/i02
Is there a fast algorithm to check for AR(p) stationarity?
It is unnecessary to find the $p$ complex roots as far as these are not to be used for themselves. Moreover, most (if not all) root finding processes can fail for large $p$. Another solution is as fol
Is there a fast algorithm to check for AR(p) stationarity? It is unnecessary to find the $p$ complex roots as far as these are not to be used for themselves. Moreover, most (if not all) root finding processes can fail for large $p$. Another solution is as follows. The $\mathrm{AR}(p)$ model can be reparametrised thanks to its $p$ partial autocorrelations (PACs) $\zeta_k$ for $1 \le k \le p$. The PACs are often denoted as $\phi_{k,k}$ because their computation involves an array $\phi_{k,\ell}$. There is a one-to-one correspondence between the vector $\boldsymbol{\rho}$ of the $p$ coefficients in the stationarity region and the vector $\boldsymbol{\zeta}$ in the region defined by the $p$ conditions $|\zeta_k | < 1$ for $1 \le k \le p$. The transformation "AR to PAC" $\boldsymbol{\rho} \mapsto \boldsymbol{\zeta}$ is quite simple and is given as a pretty recursion formula due to Barndorff-Nielsen and Schou. Testing stationarity from the vector of coefficients boils down to computing the $\zeta_k$ and stop as soon as one condition $| \zeta_k | \ge 1$ is found. The less well-known inverse transform "PAC to AR" $\boldsymbol{\zeta} \mapsto \boldsymbol{\rho}$ is available explicitly (due to Monahan), and is as simple as is the direct one. It might also be useful in some cases. The two transformations are implemented (in R) in a CRAN R package named FitAR which provides as well an efficient invertibleQ function to test stationarity. The package is described in the following article where list of references is provided. McLeod, A.I. and Zhang Y., "Improved Subset Autoregression: With R Package" Journal of Statistical Software, vol. 28, Issue 2, Oct 2008. http://www.jstatsoft.org/v28/i02
Is there a fast algorithm to check for AR(p) stationarity? It is unnecessary to find the $p$ complex roots as far as these are not to be used for themselves. Moreover, most (if not all) root finding processes can fail for large $p$. Another solution is as fol
45,490
Is it possible to compute a covariance matrix with unequal sample sizes?
A covariance matrix relies on the idea that, in the case of two vectors, the observations are paired - each observation in vector $x$ corresponds in some logical manner to an observation in vector $y$ and vice versa. If there's no pairing of elements, you can't construct a covariance matrix. If there is a pairing of elements, and the vectors are of different lengths, then you have missing data. I'll assume for simplicity of exposition that there's no data missing from the longer vector (i.e., observations in the shorter vector with no corresponding observation in the longer vector.) If the presence or absence of data in the shorter vector is unrelated to the values (in both vectors) that would have been observed if you'd had the full-length vector, then you can form the covariance estimates based on the data you do see. Otherwise, you have a missing data problem, and I'll refer you to the link for more information on that.
Is it possible to compute a covariance matrix with unequal sample sizes?
A covariance matrix relies on the idea that, in the case of two vectors, the observations are paired - each observation in vector $x$ corresponds in some logical manner to an observation in vector $y$
Is it possible to compute a covariance matrix with unequal sample sizes? A covariance matrix relies on the idea that, in the case of two vectors, the observations are paired - each observation in vector $x$ corresponds in some logical manner to an observation in vector $y$ and vice versa. If there's no pairing of elements, you can't construct a covariance matrix. If there is a pairing of elements, and the vectors are of different lengths, then you have missing data. I'll assume for simplicity of exposition that there's no data missing from the longer vector (i.e., observations in the shorter vector with no corresponding observation in the longer vector.) If the presence or absence of data in the shorter vector is unrelated to the values (in both vectors) that would have been observed if you'd had the full-length vector, then you can form the covariance estimates based on the data you do see. Otherwise, you have a missing data problem, and I'll refer you to the link for more information on that.
Is it possible to compute a covariance matrix with unequal sample sizes? A covariance matrix relies on the idea that, in the case of two vectors, the observations are paired - each observation in vector $x$ corresponds in some logical manner to an observation in vector $y$
45,491
One component in PCA is always the mean vector in two-dimensions but not three [duplicate]
The answer is elaboration of my comment, because you asked. The core action of PCA is singular-value decomposition of data matrix X. It is the same thing as eigen-decomposition of square symmetrical matrix X'X: both actions will leave you the same matrix of eigenvectors (which within SVD you call V matrix). This matrix of eigenvectors is the matrix of orthogonal rotation of old axes (columns of X) into new axes (principal components), and its elements are cosines between these and those. When columns of X are standardized then X'X is a correlation matrix (multiplied by N-1; this multiplication will have no effect on the matrix of eigenvectors). Thus, PCA of standardized data columns is eigen-decomposition of correlation matrix between the data columns. You have 2 standardized data columns. Whenever correlation between them is not exactly zero you will always get eigenvector matrix which is the 45 degree rotation. If the correlation is exactly zero, no rotation is needed and eigenvector matrix is {1,0;0,1}.
One component in PCA is always the mean vector in two-dimensions but not three [duplicate]
The answer is elaboration of my comment, because you asked. The core action of PCA is singular-value decomposition of data matrix X. It is the same thing as eigen-decomposition of square symmetrical m
One component in PCA is always the mean vector in two-dimensions but not three [duplicate] The answer is elaboration of my comment, because you asked. The core action of PCA is singular-value decomposition of data matrix X. It is the same thing as eigen-decomposition of square symmetrical matrix X'X: both actions will leave you the same matrix of eigenvectors (which within SVD you call V matrix). This matrix of eigenvectors is the matrix of orthogonal rotation of old axes (columns of X) into new axes (principal components), and its elements are cosines between these and those. When columns of X are standardized then X'X is a correlation matrix (multiplied by N-1; this multiplication will have no effect on the matrix of eigenvectors). Thus, PCA of standardized data columns is eigen-decomposition of correlation matrix between the data columns. You have 2 standardized data columns. Whenever correlation between them is not exactly zero you will always get eigenvector matrix which is the 45 degree rotation. If the correlation is exactly zero, no rotation is needed and eigenvector matrix is {1,0;0,1}.
One component in PCA is always the mean vector in two-dimensions but not three [duplicate] The answer is elaboration of my comment, because you asked. The core action of PCA is singular-value decomposition of data matrix X. It is the same thing as eigen-decomposition of square symmetrical m
45,492
One component in PCA is always the mean vector in two-dimensions but not three [duplicate]
Your $\bf{}X^TX$ matrix is a (multiple of a) correlation matrix when the inputs have been standardised. So we can do this analysis for a correlation matrix. 2 dimensions Take a $2\times 2$ correlation matrix: $$R_2=\begin{pmatrix} 1 & r \\ r & 1\end{pmatrix}$$ The characteristic polynomial is given by: $$p(\lambda)=det(R_2-\lambda I)=(1-\lambda)^2-r^2=(1-\lambda+r)(1-\lambda-r)$$ This means that the (ordered) eigenvalues are given by $\lambda_1=1+|r|\geq \lambda_2=1-|r|$. Note that we can also use $tr(R_2)=2=\lambda_1+\lambda_2$ and $det(R_2)=1-r^2=\lambda_1\lambda_2$ to solve for the $2$ dimensional case (this would not work in higher dimensions). Now we need the eigenvectors $e_1,e_2$, which satisfy $$\begin{pmatrix} 1 & r \\ r & 1\end{pmatrix}e_j=\begin{pmatrix} e_{j1}+re_{j2} \\ re_{j1}+e_{j2}\end{pmatrix}=\lambda_je_j$$ Now this means that $e_{11}=\frac{r}{|r|}e_{12}=sgn(r)e_{12}$ and, similarly, $e_{21}=-sgn(r)e_{22}$, provided that $r\neq 0$ (note that they are orthogonal, as $e_{11}e_{21}+e_{12}e_{22}=e_{12}e_{22}(sgn(r)-sgn(r))=0$). If $r=0$, then the above argument is invalid (because we have divided by $0$). However, the correlation matrix is already diagonalised, and the eigenvectors are just $e_1=(1,0)$ and $e_2=(0,1)$. The eigenvalues now become tied at $\lambda_1=\lambda_2=1$, consistent with the previous formula. This shows that the first principal component is one of three lines: the $y=x$ line if $r>0$, the $y=-x$ line if $r<0$ and it is not unique if $r=0$, being indetermininant between $y=x$ and $y=-x$. The second principal component is the "other" line. 3 dimensions Now in $3$ dimensions, things aren't so easy mathematically, we have a $3\times 3$ correlation matrix $$R_3=\begin{pmatrix} 1 & q & r \\ q & 1 & s \\ r & s & 1\end{pmatrix}$$ The characteristic polynomial is given by: $$p(\lambda)=det(R_3-\lambda I)=(1-\lambda)^3-(1-\lambda)(s^2+q^2+r^2)+2qrs$$ Using the formula for solving cubic polynomials (e.g. here). The characteristic polynomial is almost of the form of equation (2) in the link, but with $u=1-\lambda$. Hence we can use the solution given for $u$ in (7)-(9), with $a=-(q^2+r^2+s^2)$ and $b=2qrs$, $A$ from equation (5) and $B$ from equation (6) and we get: $$\begin{array}{c c} \lambda=1-(A+B) \\ \lambda'=1+\frac{1}{2}(A+B)-i\sqrt{3}\frac{A-B}{2} \\ \lambda''=1+\frac{1}{2}(A+B)+i\sqrt{3}\frac{A-B}{2} \end{array}$$ Where $i=\sqrt{-1}$ is the imaginary unit. Now for this to be real in all three solutions, we require $\Im (A+B)=0$ (else the first solution is complex), and $\Re (A-B)=0$ (else the second and third solutions are complex). Writing out $A=c_{A}+d_{A}i$ and $B=c_{B}+d_{B}i$, this means that we require $c_{A}=c_{B}=c$, and $d_{A}=-d_{B}=d$. In other words, $A$ and $B$ are complex conjugates. The condition required for $A,B$ being of this form means: $$\frac{b^2}{4}+\frac{a^3}{27}\leq 0\implies 27q^2r^2s^2\leq (q^2+r^2+s^2)^3$$ We then get $A+B=2c$ and $A-B=2di$. Re-writing out the eigenvalues, we find that $|d|\sqrt{3}-1\leq c \leq\frac{1}{2}$ for $R_3$ to be positive semi-definite. We then get the ordered eigenvalues: $$\begin{array}{c c} \lambda_1=1-2c & \lambda_2=1+c+|d|\sqrt{3} & \lambda_3=1+c-|d|\sqrt{3} & \text{if } c\leq-\frac{|d|}{\sqrt{3}}\\ \lambda_1=1+c+|d|\sqrt{3} & \lambda_2=1-2c & \lambda_3=1+c-|d|\sqrt{3} & \text{if } |c| \leq\frac{|d|}{\sqrt{3}}\\ \lambda_1=1+c+|d|\sqrt{3} & \lambda_2=1+c-|d|\sqrt{3} & \lambda_3=1-2c & \text{if } c\geq\frac{|d|}{\sqrt{3}} \end{array}$$ If any of the above inequalities are not strict, or $d=0$, then some or all eigenvalues are tied and the principal components for those eigenvalues are not unique (more like a principal "hyperplane"). The first principal component follow at once by solving the equation: $$(R_3-\lambda_1I)e_1=0\implies \begin{array}{c c} (1-\lambda_1)e_{11}+qe_{12}+re_{13}=0 \\ qe_{11}+(1-\lambda_1)e_{12}+se_{13}=0 \\ re_{11}+se_{12}+(1-\lambda_1)e_{13}=0 \end{array}$$ A general solution can be: $$e_1=(qs-r(1-\lambda_1),\;qr-s(1-\lambda_1),\;(1-\lambda_1)^2-q^2)^T$$ This solution works, so long as all the entries aren't zero (which means implicitly dividing by zero). This solution is also valid for $e_2$ and $e_3$ (e.g. $e_{23}=(1-\lambda_2)^2-q^2$ etc...). If we want the mean vector to be the solution, then we require $(1-\lambda_1+q)(s-r)=q(s-q)+(1-\lambda_1-r)(1-\lambda_1)=0$. The first implies $s=r$ or $\lambda_1=1+q$. The second is impossible, because this implies $e_{13}=0$ (not a mean vector). Plugging $s=r$ into the equations, we get $e_{11}=e_{12}=-r(1-\lambda_1-q)$. To get equality for $e_{13}$ requires that $1+r+q=\lambda_1$. Note that if all correlations are equal, $q=r=s$, we get real solutions for $A=B=(-\frac{b}{2})^{1/3}=-r$, and a similar form for the largest eigenvalue as in 2 dimensions, $\lambda_1=1+2r>\lambda_2=\lambda_3=1-r$, provided $r>0$, and $\lambda_1=\lambda_2=1-r>\lambda_3=1+2r$ if $r<0$. Taking the $r>0$ case, we then get an eigenvector of: $$e_1=(3r^2,3r^2,3r^2)^T\propto (1/3,1/3,1/3)^{T}$$ Taking the $r<0$ case, the above solution gives the trivial $e_1=(0,0,0)^T$ (same for $e_2$). Note that if we go back to the three equations, we find they are all identical, giving $r(e_{11}+e_{12}+e_{13})=0$ (same for $e_2$). This is due to the multiplicity of the largest eigenvalue. The mean vector is now moved down to principal component 3. Note that the first 2PCs are still orthogonal to the mean vector. The first principal component is not unique if all correlations are equal and negative. The first two PCs span the subspace orthogonal to the mean vector, but apart from this are arbitrary.
One component in PCA is always the mean vector in two-dimensions but not three [duplicate]
Your $\bf{}X^TX$ matrix is a (multiple of a) correlation matrix when the inputs have been standardised. So we can do this analysis for a correlation matrix. 2 dimensions Take a $2\times 2$ correlatio
One component in PCA is always the mean vector in two-dimensions but not three [duplicate] Your $\bf{}X^TX$ matrix is a (multiple of a) correlation matrix when the inputs have been standardised. So we can do this analysis for a correlation matrix. 2 dimensions Take a $2\times 2$ correlation matrix: $$R_2=\begin{pmatrix} 1 & r \\ r & 1\end{pmatrix}$$ The characteristic polynomial is given by: $$p(\lambda)=det(R_2-\lambda I)=(1-\lambda)^2-r^2=(1-\lambda+r)(1-\lambda-r)$$ This means that the (ordered) eigenvalues are given by $\lambda_1=1+|r|\geq \lambda_2=1-|r|$. Note that we can also use $tr(R_2)=2=\lambda_1+\lambda_2$ and $det(R_2)=1-r^2=\lambda_1\lambda_2$ to solve for the $2$ dimensional case (this would not work in higher dimensions). Now we need the eigenvectors $e_1,e_2$, which satisfy $$\begin{pmatrix} 1 & r \\ r & 1\end{pmatrix}e_j=\begin{pmatrix} e_{j1}+re_{j2} \\ re_{j1}+e_{j2}\end{pmatrix}=\lambda_je_j$$ Now this means that $e_{11}=\frac{r}{|r|}e_{12}=sgn(r)e_{12}$ and, similarly, $e_{21}=-sgn(r)e_{22}$, provided that $r\neq 0$ (note that they are orthogonal, as $e_{11}e_{21}+e_{12}e_{22}=e_{12}e_{22}(sgn(r)-sgn(r))=0$). If $r=0$, then the above argument is invalid (because we have divided by $0$). However, the correlation matrix is already diagonalised, and the eigenvectors are just $e_1=(1,0)$ and $e_2=(0,1)$. The eigenvalues now become tied at $\lambda_1=\lambda_2=1$, consistent with the previous formula. This shows that the first principal component is one of three lines: the $y=x$ line if $r>0$, the $y=-x$ line if $r<0$ and it is not unique if $r=0$, being indetermininant between $y=x$ and $y=-x$. The second principal component is the "other" line. 3 dimensions Now in $3$ dimensions, things aren't so easy mathematically, we have a $3\times 3$ correlation matrix $$R_3=\begin{pmatrix} 1 & q & r \\ q & 1 & s \\ r & s & 1\end{pmatrix}$$ The characteristic polynomial is given by: $$p(\lambda)=det(R_3-\lambda I)=(1-\lambda)^3-(1-\lambda)(s^2+q^2+r^2)+2qrs$$ Using the formula for solving cubic polynomials (e.g. here). The characteristic polynomial is almost of the form of equation (2) in the link, but with $u=1-\lambda$. Hence we can use the solution given for $u$ in (7)-(9), with $a=-(q^2+r^2+s^2)$ and $b=2qrs$, $A$ from equation (5) and $B$ from equation (6) and we get: $$\begin{array}{c c} \lambda=1-(A+B) \\ \lambda'=1+\frac{1}{2}(A+B)-i\sqrt{3}\frac{A-B}{2} \\ \lambda''=1+\frac{1}{2}(A+B)+i\sqrt{3}\frac{A-B}{2} \end{array}$$ Where $i=\sqrt{-1}$ is the imaginary unit. Now for this to be real in all three solutions, we require $\Im (A+B)=0$ (else the first solution is complex), and $\Re (A-B)=0$ (else the second and third solutions are complex). Writing out $A=c_{A}+d_{A}i$ and $B=c_{B}+d_{B}i$, this means that we require $c_{A}=c_{B}=c$, and $d_{A}=-d_{B}=d$. In other words, $A$ and $B$ are complex conjugates. The condition required for $A,B$ being of this form means: $$\frac{b^2}{4}+\frac{a^3}{27}\leq 0\implies 27q^2r^2s^2\leq (q^2+r^2+s^2)^3$$ We then get $A+B=2c$ and $A-B=2di$. Re-writing out the eigenvalues, we find that $|d|\sqrt{3}-1\leq c \leq\frac{1}{2}$ for $R_3$ to be positive semi-definite. We then get the ordered eigenvalues: $$\begin{array}{c c} \lambda_1=1-2c & \lambda_2=1+c+|d|\sqrt{3} & \lambda_3=1+c-|d|\sqrt{3} & \text{if } c\leq-\frac{|d|}{\sqrt{3}}\\ \lambda_1=1+c+|d|\sqrt{3} & \lambda_2=1-2c & \lambda_3=1+c-|d|\sqrt{3} & \text{if } |c| \leq\frac{|d|}{\sqrt{3}}\\ \lambda_1=1+c+|d|\sqrt{3} & \lambda_2=1+c-|d|\sqrt{3} & \lambda_3=1-2c & \text{if } c\geq\frac{|d|}{\sqrt{3}} \end{array}$$ If any of the above inequalities are not strict, or $d=0$, then some or all eigenvalues are tied and the principal components for those eigenvalues are not unique (more like a principal "hyperplane"). The first principal component follow at once by solving the equation: $$(R_3-\lambda_1I)e_1=0\implies \begin{array}{c c} (1-\lambda_1)e_{11}+qe_{12}+re_{13}=0 \\ qe_{11}+(1-\lambda_1)e_{12}+se_{13}=0 \\ re_{11}+se_{12}+(1-\lambda_1)e_{13}=0 \end{array}$$ A general solution can be: $$e_1=(qs-r(1-\lambda_1),\;qr-s(1-\lambda_1),\;(1-\lambda_1)^2-q^2)^T$$ This solution works, so long as all the entries aren't zero (which means implicitly dividing by zero). This solution is also valid for $e_2$ and $e_3$ (e.g. $e_{23}=(1-\lambda_2)^2-q^2$ etc...). If we want the mean vector to be the solution, then we require $(1-\lambda_1+q)(s-r)=q(s-q)+(1-\lambda_1-r)(1-\lambda_1)=0$. The first implies $s=r$ or $\lambda_1=1+q$. The second is impossible, because this implies $e_{13}=0$ (not a mean vector). Plugging $s=r$ into the equations, we get $e_{11}=e_{12}=-r(1-\lambda_1-q)$. To get equality for $e_{13}$ requires that $1+r+q=\lambda_1$. Note that if all correlations are equal, $q=r=s$, we get real solutions for $A=B=(-\frac{b}{2})^{1/3}=-r$, and a similar form for the largest eigenvalue as in 2 dimensions, $\lambda_1=1+2r>\lambda_2=\lambda_3=1-r$, provided $r>0$, and $\lambda_1=\lambda_2=1-r>\lambda_3=1+2r$ if $r<0$. Taking the $r>0$ case, we then get an eigenvector of: $$e_1=(3r^2,3r^2,3r^2)^T\propto (1/3,1/3,1/3)^{T}$$ Taking the $r<0$ case, the above solution gives the trivial $e_1=(0,0,0)^T$ (same for $e_2$). Note that if we go back to the three equations, we find they are all identical, giving $r(e_{11}+e_{12}+e_{13})=0$ (same for $e_2$). This is due to the multiplicity of the largest eigenvalue. The mean vector is now moved down to principal component 3. Note that the first 2PCs are still orthogonal to the mean vector. The first principal component is not unique if all correlations are equal and negative. The first two PCs span the subspace orthogonal to the mean vector, but apart from this are arbitrary.
One component in PCA is always the mean vector in two-dimensions but not three [duplicate] Your $\bf{}X^TX$ matrix is a (multiple of a) correlation matrix when the inputs have been standardised. So we can do this analysis for a correlation matrix. 2 dimensions Take a $2\times 2$ correlatio
45,493
How should I deal with the consequences of proportional hazards violations in log-rank (and related) tests?
The log-rank test is valid whatever the true situation with the hazards is. You are correct that only its power is affected. So if it rejects, then the hazards are not equal. If it does not reject, then you have to worry about the proportionality of hazards and power. The principled approach would be trying to estimate the difference/ratio of the two hazards in a time-dependent matter. This is not simple, but doable. I would recommend the book by Martinussen and Schalke: Dynamic Regression Models for Survival Data, and the corresponding R package timereg. The support of a knowledgeable statistician would probably also be needed. Note that this is beyond standard survival analysis fare, so not everybody would know these techniques. A last note: if the hazards are not proportional, then you just cannot have one value for the hazard ratio.
How should I deal with the consequences of proportional hazards violations in log-rank (and related)
The log-rank test is valid whatever the true situation with the hazards is. You are correct that only its power is affected. So if it rejects, then the hazards are not equal. If it does not reject, th
How should I deal with the consequences of proportional hazards violations in log-rank (and related) tests? The log-rank test is valid whatever the true situation with the hazards is. You are correct that only its power is affected. So if it rejects, then the hazards are not equal. If it does not reject, then you have to worry about the proportionality of hazards and power. The principled approach would be trying to estimate the difference/ratio of the two hazards in a time-dependent matter. This is not simple, but doable. I would recommend the book by Martinussen and Schalke: Dynamic Regression Models for Survival Data, and the corresponding R package timereg. The support of a knowledgeable statistician would probably also be needed. Note that this is beyond standard survival analysis fare, so not everybody would know these techniques. A last note: if the hazards are not proportional, then you just cannot have one value for the hazard ratio.
How should I deal with the consequences of proportional hazards violations in log-rank (and related) The log-rank test is valid whatever the true situation with the hazards is. You are correct that only its power is affected. So if it rejects, then the hazards are not equal. If it does not reject, th
45,494
How should I deal with the consequences of proportional hazards violations in log-rank (and related) tests?
Indeed- only power will be affected when the log-rank test is used without proportional hazards. However, if one chooses a new test/model post-hoc (i.e. after having determined that the hazards are not proportional), the results may not be valid. This paper shows how type-I error rates could be inflated: http://onlinelibrary.wiley.com/doi/10.1002/sim.6021/abstract
How should I deal with the consequences of proportional hazards violations in log-rank (and related)
Indeed- only power will be affected when the log-rank test is used without proportional hazards. However, if one chooses a new test/model post-hoc (i.e. after having determined that the hazards are n
How should I deal with the consequences of proportional hazards violations in log-rank (and related) tests? Indeed- only power will be affected when the log-rank test is used without proportional hazards. However, if one chooses a new test/model post-hoc (i.e. after having determined that the hazards are not proportional), the results may not be valid. This paper shows how type-I error rates could be inflated: http://onlinelibrary.wiley.com/doi/10.1002/sim.6021/abstract
How should I deal with the consequences of proportional hazards violations in log-rank (and related) Indeed- only power will be affected when the log-rank test is used without proportional hazards. However, if one chooses a new test/model post-hoc (i.e. after having determined that the hazards are n
45,495
What is an elegant way of visualising two time series with many data points?
Partial transparency ("alpha") might help you here, e.g.: > temp11=runif(100) > temp22=runif(100) > plot(temp11, type="p", col=rgb(0.2, 0.2, 1, 0.6), pch=19, xlab="Time", ylab="price") > lines(temp11, lwd=3, col=rgb(0.2, 0.2, 1, 0.3)) > points(temp22, pch=19, col=rgb(1, 0.2, 0.2, 0.6)) > lines(temp22, lwd=3, col=rgb(1, 0.2, 0.2, 0.3)) Here is an example of the image: It doesn't look that great with runif data, but on your data I think it would work a bit better. Alpha support is device-dependent, but PDF does support it.
What is an elegant way of visualising two time series with many data points?
Partial transparency ("alpha") might help you here, e.g.: > temp11=runif(100) > temp22=runif(100) > plot(temp11, type="p", col=rgb(0.2, 0.2, 1, 0.6), pch=19, xlab="Time", ylab="price") > lines(temp11,
What is an elegant way of visualising two time series with many data points? Partial transparency ("alpha") might help you here, e.g.: > temp11=runif(100) > temp22=runif(100) > plot(temp11, type="p", col=rgb(0.2, 0.2, 1, 0.6), pch=19, xlab="Time", ylab="price") > lines(temp11, lwd=3, col=rgb(0.2, 0.2, 1, 0.3)) > points(temp22, pch=19, col=rgb(1, 0.2, 0.2, 0.6)) > lines(temp22, lwd=3, col=rgb(1, 0.2, 0.2, 0.3)) Here is an example of the image: It doesn't look that great with runif data, but on your data I think it would work a bit better. Alpha support is device-dependent, but PDF does support it.
What is an elegant way of visualising two time series with many data points? Partial transparency ("alpha") might help you here, e.g.: > temp11=runif(100) > temp22=runif(100) > plot(temp11, type="p", col=rgb(0.2, 0.2, 1, 0.6), pch=19, xlab="Time", ylab="price") > lines(temp11,
45,496
What is an elegant way of visualising two time series with many data points?
Here's what I was trying to say in the comment, with a little bit more detail (though this might not be the answer to your question). First, get some data. x <- arima.sim(200, model = list(ar = 0.6)) + 3 y <- arima.sim(200, model = list(ar = -0.7)) - 3 A plot with two columns would look something like this: par(mfrow = c(1,2)) plot(x) plot(y) with a graph like so: while a plot with two rows would look something like this: par(mfrow = c(2,1)) plot(x) plot(y) with a graph like so: And if you'd like to keep both series on the same axes then you could do like this: par(mfrow = c(1,1)) ts.plot(x, y) which would look something like this: I was trying to communicate that if you make the plot wider rather than taller then it helps to see what's happening inside the lengthy time series better. You can manually resize the graphics device to get the aspect you like, or if you use RStudio, when you export the image you can set whatever dimensions desired.
What is an elegant way of visualising two time series with many data points?
Here's what I was trying to say in the comment, with a little bit more detail (though this might not be the answer to your question). First, get some data. x <- arima.sim(200, model = list(ar = 0.6))
What is an elegant way of visualising two time series with many data points? Here's what I was trying to say in the comment, with a little bit more detail (though this might not be the answer to your question). First, get some data. x <- arima.sim(200, model = list(ar = 0.6)) + 3 y <- arima.sim(200, model = list(ar = -0.7)) - 3 A plot with two columns would look something like this: par(mfrow = c(1,2)) plot(x) plot(y) with a graph like so: while a plot with two rows would look something like this: par(mfrow = c(2,1)) plot(x) plot(y) with a graph like so: And if you'd like to keep both series on the same axes then you could do like this: par(mfrow = c(1,1)) ts.plot(x, y) which would look something like this: I was trying to communicate that if you make the plot wider rather than taller then it helps to see what's happening inside the lengthy time series better. You can manually resize the graphics device to get the aspect you like, or if you use RStudio, when you export the image you can set whatever dimensions desired.
What is an elegant way of visualising two time series with many data points? Here's what I was trying to say in the comment, with a little bit more detail (though this might not be the answer to your question). First, get some data. x <- arima.sim(200, model = list(ar = 0.6))
45,497
How to specify labels per facet in ggplot2? [closed]
The answer is no. However, as you saw in the link you posted, there is grid.arrange::gridExtra. Another option is to use something that's originally from the ggplot2 book (I think that's the source, but examples abound on the internet) p1 <- ggplot(diamonds, aes(depth, carat)) + geom_point() p2 <- ggplot(diamonds, aes(price, carat)) + geom_point() vplayout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y) grid.newpage() pushViewport(viewport(layout=grid.layout(4,6))) print(p1,vp=vplayout(1:4,1:3)) print(p2,vp=vplayout(1:4,4:6)) This setup essentially plots a "dashboard". And you can control each plot individually, yet, keep them "beside eachother in any arrangement that you feel reasonable by changing the squares they fill (mess with the numbers 4, 6, 1:4, 1:3, 4:6)
How to specify labels per facet in ggplot2? [closed]
The answer is no. However, as you saw in the link you posted, there is grid.arrange::gridExtra. Another option is to use something that's originally from the ggplot2 book (I think that's the source, b
How to specify labels per facet in ggplot2? [closed] The answer is no. However, as you saw in the link you posted, there is grid.arrange::gridExtra. Another option is to use something that's originally from the ggplot2 book (I think that's the source, but examples abound on the internet) p1 <- ggplot(diamonds, aes(depth, carat)) + geom_point() p2 <- ggplot(diamonds, aes(price, carat)) + geom_point() vplayout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y) grid.newpage() pushViewport(viewport(layout=grid.layout(4,6))) print(p1,vp=vplayout(1:4,1:3)) print(p2,vp=vplayout(1:4,4:6)) This setup essentially plots a "dashboard". And you can control each plot individually, yet, keep them "beside eachother in any arrangement that you feel reasonable by changing the squares they fill (mess with the numbers 4, 6, 1:4, 1:3, 4:6)
How to specify labels per facet in ggplot2? [closed] The answer is no. However, as you saw in the link you posted, there is grid.arrange::gridExtra. Another option is to use something that's originally from the ggplot2 book (I think that's the source, b
45,498
How to specify labels per facet in ggplot2? [closed]
You can use labeller option to specify labels for each facet. See this link Question
How to specify labels per facet in ggplot2? [closed]
You can use labeller option to specify labels for each facet. See this link Question
How to specify labels per facet in ggplot2? [closed] You can use labeller option to specify labels for each facet. See this link Question
How to specify labels per facet in ggplot2? [closed] You can use labeller option to specify labels for each facet. See this link Question
45,499
How is Google+ population estimated?
Two assumptions are made: (1) the rate of US citizens to all people is the same within the Google+ population as in the global population, and (2) for US citizens, the rate of people with any surname to all US citizens is (on average) the same within the Google+ population as in the global population. So: you take, say, 200 surnames, and count how many US Google+ subscribers there are with these surnames ($USG_s$). Given assumption (2) (say the rate is $r_s$, found by dividing the number of US citizens with these surnames by the total number of US citizens), an estimate for the total number of US subscribers is found like this: $USG\sim USG_s/r_s$ Then, using assumption (1) you can use the same 'trick' to find an estimate of the total number of Google+ users. Simply put: if there are less people that are Google+ subscribers, there will be less US citizens that are Google+ subscribers (assumption (1)). By this and assumption (2), there will also be less US citizens with a given surname that are Google subscribers.
How is Google+ population estimated?
Two assumptions are made: (1) the rate of US citizens to all people is the same within the Google+ population as in the global population, and (2) for US citizens, the rate of people with any surname
How is Google+ population estimated? Two assumptions are made: (1) the rate of US citizens to all people is the same within the Google+ population as in the global population, and (2) for US citizens, the rate of people with any surname to all US citizens is (on average) the same within the Google+ population as in the global population. So: you take, say, 200 surnames, and count how many US Google+ subscribers there are with these surnames ($USG_s$). Given assumption (2) (say the rate is $r_s$, found by dividing the number of US citizens with these surnames by the total number of US citizens), an estimate for the total number of US subscribers is found like this: $USG\sim USG_s/r_s$ Then, using assumption (1) you can use the same 'trick' to find an estimate of the total number of Google+ users. Simply put: if there are less people that are Google+ subscribers, there will be less US citizens that are Google+ subscribers (assumption (1)). By this and assumption (2), there will also be less US citizens with a given surname that are Google subscribers.
How is Google+ population estimated? Two assumptions are made: (1) the rate of US citizens to all people is the same within the Google+ population as in the global population, and (2) for US citizens, the rate of people with any surname
45,500
How is Google+ population estimated?
This exercise will be pretty useless unless the sample of the surnames is statistically sound, i.e., a random sample with known probabilities of selection. Otherwise, you are estimating the number of female drivers by first picking a color (say yellow), counting the fraction of female drivers in the yellow cars, and then obtaining the estimate of the population total as the (total # of cars) * (fraction of women drivers based on the red cars). If you did not pick up your color at random (and preferably repeated this selection a bunch of times to ensure better coverage of different types of cars), God only knows how good your estimate might be. Getting a good sample of US surnames is far from a trivial task. The studied distributions of surnames are very odd, to say the least. Most of the surnames will be unique, with just a handful of people having this last name (mine is an example). On the other hand, a few surnames (Smith, Johnson, Williams) may cover as much as 1% of the population). The problem of weird distributions is frequently encountered in establishment surveys where you have monstrous corporations like Microsoft and Adobe, and millions shops-on-the-corner with two-three local geeks. One practice in working with the distributions like that is to perform probability proportional to size sampling: you take the whole list, but you will sample the surnames (or companies) with greater probabilities if they represent a greater share of the total. You then control for unequal probabilities of selection with weights. Another approach is to use cut-off sampling: you sample all the surnames with frequency greater than (businesses with sales greater than) 0.1% of the total, and then wave hands about the potential non-sampling error for the remaining surnames.
How is Google+ population estimated?
This exercise will be pretty useless unless the sample of the surnames is statistically sound, i.e., a random sample with known probabilities of selection. Otherwise, you are estimating the number of
How is Google+ population estimated? This exercise will be pretty useless unless the sample of the surnames is statistically sound, i.e., a random sample with known probabilities of selection. Otherwise, you are estimating the number of female drivers by first picking a color (say yellow), counting the fraction of female drivers in the yellow cars, and then obtaining the estimate of the population total as the (total # of cars) * (fraction of women drivers based on the red cars). If you did not pick up your color at random (and preferably repeated this selection a bunch of times to ensure better coverage of different types of cars), God only knows how good your estimate might be. Getting a good sample of US surnames is far from a trivial task. The studied distributions of surnames are very odd, to say the least. Most of the surnames will be unique, with just a handful of people having this last name (mine is an example). On the other hand, a few surnames (Smith, Johnson, Williams) may cover as much as 1% of the population). The problem of weird distributions is frequently encountered in establishment surveys where you have monstrous corporations like Microsoft and Adobe, and millions shops-on-the-corner with two-three local geeks. One practice in working with the distributions like that is to perform probability proportional to size sampling: you take the whole list, but you will sample the surnames (or companies) with greater probabilities if they represent a greater share of the total. You then control for unequal probabilities of selection with weights. Another approach is to use cut-off sampling: you sample all the surnames with frequency greater than (businesses with sales greater than) 0.1% of the total, and then wave hands about the potential non-sampling error for the remaining surnames.
How is Google+ population estimated? This exercise will be pretty useless unless the sample of the surnames is statistically sound, i.e., a random sample with known probabilities of selection. Otherwise, you are estimating the number of