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
38,601
What does the assumption: "The independent variable is not random." in OLS mean?
Let's start with what the assumption means. OLS usually motivates the outcome as random. We usually write $$ y \vert x \sim \mathcal{N}(x^T\beta, \sigma^2) $$ The $y \vert x$ is a bit of an abuse of notation. It means that, assuming I already know $x$, then I can consider $y$ as a random draw from a normal distribution with specified mean and variance. So the assumption here is not really that $x$ isn't random, its just that whatever distribution that $x$ has will not affect our inferences about $y$ because we are to know what $x$ is. We are talking about the conditional distribution of $y$. Conditioned on what? $x$. Verification of this assumption is not required. In fact, it is patently false! But that doesn't matter for OLS, because OLS takes $x$ as given. We know it at the time of doing inference on $y$.
What does the assumption: "The independent variable is not random." in OLS mean?
Let's start with what the assumption means. OLS usually motivates the outcome as random. We usually write $$ y \vert x \sim \mathcal{N}(x^T\beta, \sigma^2) $$ The $y \vert x$ is a bit of an abuse of
What does the assumption: "The independent variable is not random." in OLS mean? Let's start with what the assumption means. OLS usually motivates the outcome as random. We usually write $$ y \vert x \sim \mathcal{N}(x^T\beta, \sigma^2) $$ The $y \vert x$ is a bit of an abuse of notation. It means that, assuming I already know $x$, then I can consider $y$ as a random draw from a normal distribution with specified mean and variance. So the assumption here is not really that $x$ isn't random, its just that whatever distribution that $x$ has will not affect our inferences about $y$ because we are to know what $x$ is. We are talking about the conditional distribution of $y$. Conditioned on what? $x$. Verification of this assumption is not required. In fact, it is patently false! But that doesn't matter for OLS, because OLS takes $x$ as given. We know it at the time of doing inference on $y$.
What does the assumption: "The independent variable is not random." in OLS mean? Let's start with what the assumption means. OLS usually motivates the outcome as random. We usually write $$ y \vert x \sim \mathcal{N}(x^T\beta, \sigma^2) $$ The $y \vert x$ is a bit of an abuse of
38,602
What does the assumption: "The independent variable is not random." in OLS mean?
Regression analysis is always done conditional on the explanatory ("independent") variables. Thus, these latter variables are always observed quantities. Mathematically, the theory of probability results in regression analysis are all conditional on these values, so they do not involve treatment of the $x_i$ valeus as random variables. Rather than saying that "the independent variable is not random" it is simpler just to say that "the independent variable is an observed value (so its value is known)". Probability theory and statistics go to great pains to avoid getting into the weeds on what "randomness" actually is (which is a matter in the domain of philosophy). In probability theory we simply refer to a "random variable" as a particular type of function that gives rise to events to which probability statements are applied. In operational terms, in both probability and statistics, once you observe a random variable its value is then known, and so you now treat it as a fixed value rather than a random variable.
What does the assumption: "The independent variable is not random." in OLS mean?
Regression analysis is always done conditional on the explanatory ("independent") variables. Thus, these latter variables are always observed quantities. Mathematically, the theory of probability re
What does the assumption: "The independent variable is not random." in OLS mean? Regression analysis is always done conditional on the explanatory ("independent") variables. Thus, these latter variables are always observed quantities. Mathematically, the theory of probability results in regression analysis are all conditional on these values, so they do not involve treatment of the $x_i$ valeus as random variables. Rather than saying that "the independent variable is not random" it is simpler just to say that "the independent variable is an observed value (so its value is known)". Probability theory and statistics go to great pains to avoid getting into the weeds on what "randomness" actually is (which is a matter in the domain of philosophy). In probability theory we simply refer to a "random variable" as a particular type of function that gives rise to events to which probability statements are applied. In operational terms, in both probability and statistics, once you observe a random variable its value is then known, and so you now treat it as a fixed value rather than a random variable.
What does the assumption: "The independent variable is not random." in OLS mean? Regression analysis is always done conditional on the explanatory ("independent") variables. Thus, these latter variables are always observed quantities. Mathematically, the theory of probability re
38,603
How do you program a custom hypothesis test in R?
Here's what you need to do in general Hypothesis testing functions in R create and output a list object of class h.test. This type of object has a specific set of required components set out in its documentation, and it also has a special method of printing under the print.htest setting in the global environment. That printing method draws out information from the list, but prints it in the user-friendly way you see in the output in the question. The list should contain the components set out below, including naming several of the objects with a names attribute. (You are some other optional components shown in the linked documentation.) Textual description of test method: A character string giving the name of the hypothesis test. This will appear as the first sentence of the print output. data.name: A character string giving a description of the data, which usually includes reference to the names of the data vectors used in the test. For this part it is useful to use the substitute and deparse functions to extract the names of the user inputs to the function as the appropriate names (example shown below). Specification of hypotheses null.value: A numeric variable giving the value of the parameter under the null hypothesis (with a names attribute). alternative: A character string set to greater, less or two-sided, to specify the direction of the alternative hypothesis relative to the null value. Test statistic and p-value estimate: The estimated value of the parameter (with a names attribute). This value will be a function of the data inputs for the testing function. statistic: The value of the test statistic (with a names attribute). This value will either be a direct function of the data inputs for the testing function, or a function of the parameter estimate. p.value: The p-value for the test (which should be a number between zero and one). This value will be a function of the test statistic. Confidence interval (optional) conf.int: A confidence interval represented by a vector with two elements, where the first is the lower bound and the second is the upper bound (with a conf.level attribute giving the confidence level). If you are using this component, it is desirable to require the function to take a significance level as an input, in order to specify the desired confidence level. In order to create a custom hypothesis-testing function, you will need to create a function that produces a list containing the required components shown above, customised to your particular test. For the substantive parts of the test (i.e., the estimate, test statistic, p-value, and confidence interval), you will need to use the appropriate formulae for your particular test. Note that you can put these elements in any order in your list, so long as all the required elements are there. You can also add other components to the list if you wish. It is good practice to add an initial part of your function to check the inputs to the function, to ensure that they are of the correct form, and to stop the function and give error messages if the input is defective in some way. Once your list is created, you set the class of the object to h.test and output the object at the end of the function. Here's an example of implementation for a particular test In a related question I gave an example of code for a hypothesis test taken from Tarone (1979). Below is a slightly modified version of that code that serves as an example for how you can program a function for a custom hypothesis test. Observe that the code first checks the inputs, and then builds up each of the required components of the test, using the appropriate names and formulae for that specific test. Once these components have been computed, we create a list object called TEST, composed of these elements, and we set its class to h.test. We output this object at the end of the function. (It is also worth observing the code for data.name, which extracts the variable names that are input by the user.) Tarone.test <- function(N, M) { #Check validity of inputs if(!(all(N == as.integer(N)))) { stop("Error: Number of trials should be integers"); } if(min(N) < 1) { stop("Error: Number of trials should be positive"); } if(!(all(M == as.integer(M)))) { stop("Error: Count values should be integers"); } if(min(M) < 0) { stop("Error: Count values cannot be negative"); } if(any(M > N)) { stop("Error: Observed count value exceeds number of trials"); } #Set description of test and data method <- "Tarone's Z test"; data.name <- paste0(deparse(substitute(M)), " successes from ", deparse(substitute(N)), " trials"); #Set null and alternative hypotheses null.value <- 0; attr(null.value, "names") <- "dispersion parameter"; alternative <- "greater"; #Calculate test statistics estimate <- sum(M)/sum(N); attr(estimate, "names") <- "proportion parameter"; S <- ifelse(estimate == 1, sum(N), sum((M - N*estimate)^2/(estimate*(1 - estimate)))); statistic <- (S - sum(N))/sqrt(2*sum(N*(N-1))); attr(statistic, "names") <- "z"; #Calculate p-value p.value <- 2*pnorm(-abs(statistic), 0, 1); attr(p.value, "names") <- NULL; #Create htest object TEST <- list(method = method, data.name = data.name, null.value = null.value, alternative = alternative, estimate = estimate, statistic = statistic, p.value = p.value); class(TEST) <- "htest"; TEST; } Below we create some count data to implement this test and see what the output looks like. As you can see, the output is the same user-friendly output you get for other hypothesis tests in R, where the components of the test have been pulled out of the list and presented in a nice simple manner. The output shows the name of the test and describes the data, and then it gives the test statistic and p-value for the test. It also describes the alternative hypothesis and gives the sample estimate of the parameter. #Generate example data TRIALS <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39); COUNTS <- c( 9, 10, 22, 15, 8, 19, 16, 19, 15, 10); #Apply Tarone's test to the example data TEST <- Tarone.test(TRIALS, COUNTS); TEST; Tarone's Z test data: COUNTS successes from TRIALS trials z = 2.5988, p-value = 0.009355 alternative hypothesis: true dispersion parameter is greater than 0 sample estimates: proportion parameter 0.4359756
How do you program a custom hypothesis test in R?
Here's what you need to do in general Hypothesis testing functions in R create and output a list object of class h.test. This type of object has a specific set of required components set out in its d
How do you program a custom hypothesis test in R? Here's what you need to do in general Hypothesis testing functions in R create and output a list object of class h.test. This type of object has a specific set of required components set out in its documentation, and it also has a special method of printing under the print.htest setting in the global environment. That printing method draws out information from the list, but prints it in the user-friendly way you see in the output in the question. The list should contain the components set out below, including naming several of the objects with a names attribute. (You are some other optional components shown in the linked documentation.) Textual description of test method: A character string giving the name of the hypothesis test. This will appear as the first sentence of the print output. data.name: A character string giving a description of the data, which usually includes reference to the names of the data vectors used in the test. For this part it is useful to use the substitute and deparse functions to extract the names of the user inputs to the function as the appropriate names (example shown below). Specification of hypotheses null.value: A numeric variable giving the value of the parameter under the null hypothesis (with a names attribute). alternative: A character string set to greater, less or two-sided, to specify the direction of the alternative hypothesis relative to the null value. Test statistic and p-value estimate: The estimated value of the parameter (with a names attribute). This value will be a function of the data inputs for the testing function. statistic: The value of the test statistic (with a names attribute). This value will either be a direct function of the data inputs for the testing function, or a function of the parameter estimate. p.value: The p-value for the test (which should be a number between zero and one). This value will be a function of the test statistic. Confidence interval (optional) conf.int: A confidence interval represented by a vector with two elements, where the first is the lower bound and the second is the upper bound (with a conf.level attribute giving the confidence level). If you are using this component, it is desirable to require the function to take a significance level as an input, in order to specify the desired confidence level. In order to create a custom hypothesis-testing function, you will need to create a function that produces a list containing the required components shown above, customised to your particular test. For the substantive parts of the test (i.e., the estimate, test statistic, p-value, and confidence interval), you will need to use the appropriate formulae for your particular test. Note that you can put these elements in any order in your list, so long as all the required elements are there. You can also add other components to the list if you wish. It is good practice to add an initial part of your function to check the inputs to the function, to ensure that they are of the correct form, and to stop the function and give error messages if the input is defective in some way. Once your list is created, you set the class of the object to h.test and output the object at the end of the function. Here's an example of implementation for a particular test In a related question I gave an example of code for a hypothesis test taken from Tarone (1979). Below is a slightly modified version of that code that serves as an example for how you can program a function for a custom hypothesis test. Observe that the code first checks the inputs, and then builds up each of the required components of the test, using the appropriate names and formulae for that specific test. Once these components have been computed, we create a list object called TEST, composed of these elements, and we set its class to h.test. We output this object at the end of the function. (It is also worth observing the code for data.name, which extracts the variable names that are input by the user.) Tarone.test <- function(N, M) { #Check validity of inputs if(!(all(N == as.integer(N)))) { stop("Error: Number of trials should be integers"); } if(min(N) < 1) { stop("Error: Number of trials should be positive"); } if(!(all(M == as.integer(M)))) { stop("Error: Count values should be integers"); } if(min(M) < 0) { stop("Error: Count values cannot be negative"); } if(any(M > N)) { stop("Error: Observed count value exceeds number of trials"); } #Set description of test and data method <- "Tarone's Z test"; data.name <- paste0(deparse(substitute(M)), " successes from ", deparse(substitute(N)), " trials"); #Set null and alternative hypotheses null.value <- 0; attr(null.value, "names") <- "dispersion parameter"; alternative <- "greater"; #Calculate test statistics estimate <- sum(M)/sum(N); attr(estimate, "names") <- "proportion parameter"; S <- ifelse(estimate == 1, sum(N), sum((M - N*estimate)^2/(estimate*(1 - estimate)))); statistic <- (S - sum(N))/sqrt(2*sum(N*(N-1))); attr(statistic, "names") <- "z"; #Calculate p-value p.value <- 2*pnorm(-abs(statistic), 0, 1); attr(p.value, "names") <- NULL; #Create htest object TEST <- list(method = method, data.name = data.name, null.value = null.value, alternative = alternative, estimate = estimate, statistic = statistic, p.value = p.value); class(TEST) <- "htest"; TEST; } Below we create some count data to implement this test and see what the output looks like. As you can see, the output is the same user-friendly output you get for other hypothesis tests in R, where the components of the test have been pulled out of the list and presented in a nice simple manner. The output shows the name of the test and describes the data, and then it gives the test statistic and p-value for the test. It also describes the alternative hypothesis and gives the sample estimate of the parameter. #Generate example data TRIALS <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39); COUNTS <- c( 9, 10, 22, 15, 8, 19, 16, 19, 15, 10); #Apply Tarone's test to the example data TEST <- Tarone.test(TRIALS, COUNTS); TEST; Tarone's Z test data: COUNTS successes from TRIALS trials z = 2.5988, p-value = 0.009355 alternative hypothesis: true dispersion parameter is greater than 0 sample estimates: proportion parameter 0.4359756
How do you program a custom hypothesis test in R? Here's what you need to do in general Hypothesis testing functions in R create and output a list object of class h.test. This type of object has a specific set of required components set out in its d
38,604
How do you program a custom hypothesis test in R?
The hypothesis test functions in the stats package use classic S3 object-orientated programming. You write a function that creates a "htest" object, which is a list with a standard set of components, and R has a built-in print method for objects of that class. The user-level function is traditionally called something like yourname.test but can have any name. It can have any appropriate arguments. Type ?t.test to see the definition of a "htest" object. See stats:::t.test.default to see an example of a function that creates a "htest" object. See stats:::print.htest to see how the user-friendly output is created. Here is a toy example that performs a very simple chisquare test: demo.test <- function(s2, df=1) { pval <- pchisq(s2, df, lower.tail=FALSE) out <- list( statistic=s2, parameter=NULL, p.value=pval, null.value=NULL, alternative="greater", method="demo", data.name="s2") class(out) <- "htest" out } Then > TEST <- demo.test(30, df=10) > TEST demo data: s2 = 30, p-value = 0.0008566 alternative hypothesis: greater If you want to be fancier, you can make your function S3 generic (like the stats package functions) in order to handle different types of input (e.g., a formula instead of data vectors). But an ordinary function like the above example might satisfy your needs.
How do you program a custom hypothesis test in R?
The hypothesis test functions in the stats package use classic S3 object-orientated programming. You write a function that creates a "htest" object, which is a list with a standard set of components,
How do you program a custom hypothesis test in R? The hypothesis test functions in the stats package use classic S3 object-orientated programming. You write a function that creates a "htest" object, which is a list with a standard set of components, and R has a built-in print method for objects of that class. The user-level function is traditionally called something like yourname.test but can have any name. It can have any appropriate arguments. Type ?t.test to see the definition of a "htest" object. See stats:::t.test.default to see an example of a function that creates a "htest" object. See stats:::print.htest to see how the user-friendly output is created. Here is a toy example that performs a very simple chisquare test: demo.test <- function(s2, df=1) { pval <- pchisq(s2, df, lower.tail=FALSE) out <- list( statistic=s2, parameter=NULL, p.value=pval, null.value=NULL, alternative="greater", method="demo", data.name="s2") class(out) <- "htest" out } Then > TEST <- demo.test(30, df=10) > TEST demo data: s2 = 30, p-value = 0.0008566 alternative hypothesis: greater If you want to be fancier, you can make your function S3 generic (like the stats package functions) in order to handle different types of input (e.g., a formula instead of data vectors). But an ordinary function like the above example might satisfy your needs.
How do you program a custom hypothesis test in R? The hypothesis test functions in the stats package use classic S3 object-orientated programming. You write a function that creates a "htest" object, which is a list with a standard set of components,
38,605
How to find maximum likelihood estimates of an integer parameter?
You started well by writing down an expression for the likelihood. It is simpler to recognize that $Y,$ being the sum of $N$ independent Normal$(\mu,\sigma^2)$ variables, has a Normal distribution with mean $N\mu$ and variance $N\sigma^2,$ whence its likelihood is $$\mathcal{L}(y,N) = \frac{1}{\sqrt{2\pi N\sigma^2}} \exp\left(-\frac{(y-N\mu)^2}{2N\sigma^2}\right).$$ Let's work with its negative logarithm $\Lambda = -\log \mathcal{L},$ whose minima correspond to maxima of the likelihood: $$2\Lambda(N) = \log(2\pi) + \log(\sigma^2) + \log(N) + \frac{(y-N\mu)^2}{N\sigma^2}.$$ We need to find all whole numbers that minimize this expression. Pretend for a moment that $N$ could be any positive real number. As such, $2\Lambda$ is a continuously differentiable function of $N$ with derivative $$\frac{d}{dN} 2\Lambda(N) = \frac{1}{N} - \frac{(y-N\mu)^2}{\sigma^2N^2} - \frac{2\mu(y-N\mu)}{N\sigma^2}.$$ Equate this to zero to look for critical points, clear the denominators, and do a little algebra to simplify the result, giving $$\mu^2 N^2 + \sigma^2 N -y^2 = 0\tag{1}$$ with a unique positive solution (when $\mu\ne 0$) $$\hat N = \frac{1}{2\mu^2}\left(-\sigma^2 + \sqrt{\sigma^4 + 4\mu^2 y^2}\right).$$ It's straightforward to check that as $N$ approaches $0$ or grows large, $2\Lambda(N)$ grows large, so we know there's no global minimum near $N\approx 0$ nor near $N\approx \infty.$ That leaves just the one critical point we found, which therefore must be the global minimum. Moreover, $2\Lambda$ must decrease as $\hat N$ is approached from below or above. Thus, The global minima of $\Lambda$ must be among the two integers on either side of $\hat N.$ This gives an effective procedure to find the Maximum Likelihood estimator: it's either the floor or the ceiling of $\hat N$ (or, occasionally, both of them!), so compute $\hat N$ and simply choose which of these integers makes $2\Lambda$ smallest. Let's pause to check that this result makes sense. In two situations there is an intuitive solution: When $\mu$ is much greater than $\sigma$, $Y$ is going to be close to $\mu,$ whence a decent estimate of $N$ would simply be $|Y/\mu|.$ In such cases we may approximate the MLE by neglecting $\sigma^2,$ giving (as expected) $$\hat N = \frac{1}{2\mu^2}\left(-\sigma^2 + \sqrt{\sigma^4 + 4\mu^2 y^2}\right) \approx \frac{1}{2\mu^2}\sqrt{4\mu^2 y^2} = \left|\frac{y}{\mu}\right|.$$ When $\sigma$ is much greater than $\mu,$ $Y$ could be spread all over the place, but on average $Y^2$ should be close to $\sigma^2,$ whence an intuitive estimate of $N$ would simply be $y^2/\sigma^2.$ Indeed, neglecting $\mu$ in equation $(1)$ gives the expected solution $$\hat N \approx \frac{y^2}{\sigma^2}.$$ In both cases, the MLE accords with intuition, indicating we have probably worked it out correctly. The interesting situations, then, occur when $\mu$ and $\sigma$ are of comparable sizes. Intuition may be of little help here. To explore this further, I simulated three situations where $\sigma/\mu$ is $1/3,$ $1,$ or $3.$ It doesn't matter what $\mu$ is (so long as it is nonzero), so I took $\mu=1.$ In each situation I generated a random $Y$ for the cases $N=2,4,8,16,$ doing this independently five thousand times. These histograms summarize the MLEs of $N$. The vertical lines mark the true values of $N$. On average, the MLE appears to be about right. When $\sigma$ is relatively small, the MLE tends to be accurate: that's what the narrow histograms in the top row indicate. When $\sigma \approx |\mu|,$ the MLE is rather uncertain. When $\sigma \gg |\mu|,$ the MLE can often be $\hat N=1$ and sometimes can be several times $N$ (especially when $N$ is small). These observations accord with what was predicted in the preceding intuitive analysis. The key to the simulation is to implement the MLE. It requires solving $(1)$ as well as evaluating $\Lambda$ for given values of $Y,$ $\mu,$ and $\sigma.$ The only new idea reflected here is checking the integers on either side of $\hat N.$ The last two lines of the function f carry out this calculation, with the help of lambda to evaluate the log likelihood. lambda <- Vectorize(function(y, N, mu, sigma) { (log(N) + (y-mu*N)^2 / (N * sigma^2))/2 }, "N") # The negative log likelihood (without additive constant terms) f <- function(y, mu, sigma) { if (mu==0) { N.hat <- y^2 / sigma^2 } else { N.hat <- (sqrt(sigma^4 + 4*mu^2*y^2) - sigma^2) / (2*mu^2) } N.hat <- c(floor(N.hat), ceiling(N.hat)) q <- lambda(y, N.hat, mu, sigma) N.hat[which.min(q)] } # The ML estimator
How to find maximum likelihood estimates of an integer parameter?
You started well by writing down an expression for the likelihood. It is simpler to recognize that $Y,$ being the sum of $N$ independent Normal$(\mu,\sigma^2)$ variables, has a Normal distribution wi
How to find maximum likelihood estimates of an integer parameter? You started well by writing down an expression for the likelihood. It is simpler to recognize that $Y,$ being the sum of $N$ independent Normal$(\mu,\sigma^2)$ variables, has a Normal distribution with mean $N\mu$ and variance $N\sigma^2,$ whence its likelihood is $$\mathcal{L}(y,N) = \frac{1}{\sqrt{2\pi N\sigma^2}} \exp\left(-\frac{(y-N\mu)^2}{2N\sigma^2}\right).$$ Let's work with its negative logarithm $\Lambda = -\log \mathcal{L},$ whose minima correspond to maxima of the likelihood: $$2\Lambda(N) = \log(2\pi) + \log(\sigma^2) + \log(N) + \frac{(y-N\mu)^2}{N\sigma^2}.$$ We need to find all whole numbers that minimize this expression. Pretend for a moment that $N$ could be any positive real number. As such, $2\Lambda$ is a continuously differentiable function of $N$ with derivative $$\frac{d}{dN} 2\Lambda(N) = \frac{1}{N} - \frac{(y-N\mu)^2}{\sigma^2N^2} - \frac{2\mu(y-N\mu)}{N\sigma^2}.$$ Equate this to zero to look for critical points, clear the denominators, and do a little algebra to simplify the result, giving $$\mu^2 N^2 + \sigma^2 N -y^2 = 0\tag{1}$$ with a unique positive solution (when $\mu\ne 0$) $$\hat N = \frac{1}{2\mu^2}\left(-\sigma^2 + \sqrt{\sigma^4 + 4\mu^2 y^2}\right).$$ It's straightforward to check that as $N$ approaches $0$ or grows large, $2\Lambda(N)$ grows large, so we know there's no global minimum near $N\approx 0$ nor near $N\approx \infty.$ That leaves just the one critical point we found, which therefore must be the global minimum. Moreover, $2\Lambda$ must decrease as $\hat N$ is approached from below or above. Thus, The global minima of $\Lambda$ must be among the two integers on either side of $\hat N.$ This gives an effective procedure to find the Maximum Likelihood estimator: it's either the floor or the ceiling of $\hat N$ (or, occasionally, both of them!), so compute $\hat N$ and simply choose which of these integers makes $2\Lambda$ smallest. Let's pause to check that this result makes sense. In two situations there is an intuitive solution: When $\mu$ is much greater than $\sigma$, $Y$ is going to be close to $\mu,$ whence a decent estimate of $N$ would simply be $|Y/\mu|.$ In such cases we may approximate the MLE by neglecting $\sigma^2,$ giving (as expected) $$\hat N = \frac{1}{2\mu^2}\left(-\sigma^2 + \sqrt{\sigma^4 + 4\mu^2 y^2}\right) \approx \frac{1}{2\mu^2}\sqrt{4\mu^2 y^2} = \left|\frac{y}{\mu}\right|.$$ When $\sigma$ is much greater than $\mu,$ $Y$ could be spread all over the place, but on average $Y^2$ should be close to $\sigma^2,$ whence an intuitive estimate of $N$ would simply be $y^2/\sigma^2.$ Indeed, neglecting $\mu$ in equation $(1)$ gives the expected solution $$\hat N \approx \frac{y^2}{\sigma^2}.$$ In both cases, the MLE accords with intuition, indicating we have probably worked it out correctly. The interesting situations, then, occur when $\mu$ and $\sigma$ are of comparable sizes. Intuition may be of little help here. To explore this further, I simulated three situations where $\sigma/\mu$ is $1/3,$ $1,$ or $3.$ It doesn't matter what $\mu$ is (so long as it is nonzero), so I took $\mu=1.$ In each situation I generated a random $Y$ for the cases $N=2,4,8,16,$ doing this independently five thousand times. These histograms summarize the MLEs of $N$. The vertical lines mark the true values of $N$. On average, the MLE appears to be about right. When $\sigma$ is relatively small, the MLE tends to be accurate: that's what the narrow histograms in the top row indicate. When $\sigma \approx |\mu|,$ the MLE is rather uncertain. When $\sigma \gg |\mu|,$ the MLE can often be $\hat N=1$ and sometimes can be several times $N$ (especially when $N$ is small). These observations accord with what was predicted in the preceding intuitive analysis. The key to the simulation is to implement the MLE. It requires solving $(1)$ as well as evaluating $\Lambda$ for given values of $Y,$ $\mu,$ and $\sigma.$ The only new idea reflected here is checking the integers on either side of $\hat N.$ The last two lines of the function f carry out this calculation, with the help of lambda to evaluate the log likelihood. lambda <- Vectorize(function(y, N, mu, sigma) { (log(N) + (y-mu*N)^2 / (N * sigma^2))/2 }, "N") # The negative log likelihood (without additive constant terms) f <- function(y, mu, sigma) { if (mu==0) { N.hat <- y^2 / sigma^2 } else { N.hat <- (sqrt(sigma^4 + 4*mu^2*y^2) - sigma^2) / (2*mu^2) } N.hat <- c(floor(N.hat), ceiling(N.hat)) q <- lambda(y, N.hat, mu, sigma) N.hat[which.min(q)] } # The ML estimator
How to find maximum likelihood estimates of an integer parameter? You started well by writing down an expression for the likelihood. It is simpler to recognize that $Y,$ being the sum of $N$ independent Normal$(\mu,\sigma^2)$ variables, has a Normal distribution wi
38,606
How to find maximum likelihood estimates of an integer parameter?
The method whuber has used in his excellent answer is a common optimisation "trick" that involves extending the likelihood function to allow real values of $N$, and then using the concavity of the log-likelihood to show that the discrete maximising value is one of the discrete values on either side of a continuous optima. This is one commonly used method in discrete MLE problems involving a concave log-likelihood function. Its value lies in the fact that it is usually possible to get a simple closed-form expression for the continuous optima. For completeness, in this answer I will show you an alternative method, which uses discrete calculus using the forward-difference operator. The log-likelihood function for this problem is the discrete function: $$\ell_y(N) = -\frac{1}{2} \Bigg[ \ln (2 \pi) + \ln (\sigma^2) + \ln (N) + \frac{(y-N\mu)^2}{N\sigma^2} \Bigg] \quad \quad \quad \text{for } N \in \mathbb{N}.$$ The first forward-difference of the log-likelihood is: $$\begin{equation} \begin{aligned} \Delta \ell_y(N) &= -\frac{1}{2} \Bigg[ \ln (N+1) - \ln (N) + \frac{(y-N\mu - \mu)^2}{(N+1)\sigma^2} - \frac{(y-N\mu)^2}{N\sigma^2} \Bigg] \\[6pt] &= -\frac{1}{2} \Bigg[ \ln \Big( \frac{N+1}{N} \Big) + \frac{N(y-N\mu - \mu)^2 - (N+1)(y-N\mu)^2}{N(N+1)\sigma^2} \Bigg] \\[6pt] &= -\frac{1}{2} \Bigg[ \ln \Big( \frac{N+1}{N} \Big) + \frac{[N(y-N\mu)^2 -2N(y-N\mu) \mu + N \mu^2] - [N(y-N\mu)^2 + (y-N\mu)^2]}{N(N+1)\sigma^2} \Bigg] \\[6pt] &= -\frac{1}{2} \Bigg[ \ln \Big( \frac{N+1}{N} \Big) - \frac{(y + N \mu)(y-N\mu) - N \mu^2}{N(N+1)\sigma^2} \Bigg]. \\[6pt] \end{aligned} \end{equation}$$ With a bit of algebra, the second forward-difference can be shown to be: $$\begin{equation} \begin{aligned} \Delta^2 \ell_y(N) &= -\frac{1}{2} \Bigg[ \ln \Big( \frac{N+2}{N} \Big) + \frac{2 N (N+1) \mu^2 + 2(y + N \mu)(y-N\mu)}{N(N+1)(N+2)\sigma^2} \Bigg] < 0. \\[6pt] \end{aligned} \end{equation}$$ This shows that the log-likelihood function is concave, so its smallest maximising point $\hat{N}$ will be: $$\begin{equation} \begin{aligned} \hat{N} &= \min \{ N \in \mathbb{N} | \Delta \ell_y(N) \leqslant 0 \} \\[6pt] &= \min \Big\{ N \in \mathbb{N} \Big| \ln \Big( \frac{N+1}{N} \Big) \geqslant \frac{(y + N \mu)(y-N\mu) - N \mu^2}{N(N+1)\sigma^2} \Big\}. \end{aligned} \end{equation}$$ (The next value will also be a maximising point if and only if $\Delta \ell_y(\hat{N}) = 0$.) The MLE (either the smallest, or the whole set) can be programmed as a function via a simple while loop, and this should be able to give you the solution pretty quickly. I will leave the programming part as an exercise.
How to find maximum likelihood estimates of an integer parameter?
The method whuber has used in his excellent answer is a common optimisation "trick" that involves extending the likelihood function to allow real values of $N$, and then using the concavity of the log
How to find maximum likelihood estimates of an integer parameter? The method whuber has used in his excellent answer is a common optimisation "trick" that involves extending the likelihood function to allow real values of $N$, and then using the concavity of the log-likelihood to show that the discrete maximising value is one of the discrete values on either side of a continuous optima. This is one commonly used method in discrete MLE problems involving a concave log-likelihood function. Its value lies in the fact that it is usually possible to get a simple closed-form expression for the continuous optima. For completeness, in this answer I will show you an alternative method, which uses discrete calculus using the forward-difference operator. The log-likelihood function for this problem is the discrete function: $$\ell_y(N) = -\frac{1}{2} \Bigg[ \ln (2 \pi) + \ln (\sigma^2) + \ln (N) + \frac{(y-N\mu)^2}{N\sigma^2} \Bigg] \quad \quad \quad \text{for } N \in \mathbb{N}.$$ The first forward-difference of the log-likelihood is: $$\begin{equation} \begin{aligned} \Delta \ell_y(N) &= -\frac{1}{2} \Bigg[ \ln (N+1) - \ln (N) + \frac{(y-N\mu - \mu)^2}{(N+1)\sigma^2} - \frac{(y-N\mu)^2}{N\sigma^2} \Bigg] \\[6pt] &= -\frac{1}{2} \Bigg[ \ln \Big( \frac{N+1}{N} \Big) + \frac{N(y-N\mu - \mu)^2 - (N+1)(y-N\mu)^2}{N(N+1)\sigma^2} \Bigg] \\[6pt] &= -\frac{1}{2} \Bigg[ \ln \Big( \frac{N+1}{N} \Big) + \frac{[N(y-N\mu)^2 -2N(y-N\mu) \mu + N \mu^2] - [N(y-N\mu)^2 + (y-N\mu)^2]}{N(N+1)\sigma^2} \Bigg] \\[6pt] &= -\frac{1}{2} \Bigg[ \ln \Big( \frac{N+1}{N} \Big) - \frac{(y + N \mu)(y-N\mu) - N \mu^2}{N(N+1)\sigma^2} \Bigg]. \\[6pt] \end{aligned} \end{equation}$$ With a bit of algebra, the second forward-difference can be shown to be: $$\begin{equation} \begin{aligned} \Delta^2 \ell_y(N) &= -\frac{1}{2} \Bigg[ \ln \Big( \frac{N+2}{N} \Big) + \frac{2 N (N+1) \mu^2 + 2(y + N \mu)(y-N\mu)}{N(N+1)(N+2)\sigma^2} \Bigg] < 0. \\[6pt] \end{aligned} \end{equation}$$ This shows that the log-likelihood function is concave, so its smallest maximising point $\hat{N}$ will be: $$\begin{equation} \begin{aligned} \hat{N} &= \min \{ N \in \mathbb{N} | \Delta \ell_y(N) \leqslant 0 \} \\[6pt] &= \min \Big\{ N \in \mathbb{N} \Big| \ln \Big( \frac{N+1}{N} \Big) \geqslant \frac{(y + N \mu)(y-N\mu) - N \mu^2}{N(N+1)\sigma^2} \Big\}. \end{aligned} \end{equation}$$ (The next value will also be a maximising point if and only if $\Delta \ell_y(\hat{N}) = 0$.) The MLE (either the smallest, or the whole set) can be programmed as a function via a simple while loop, and this should be able to give you the solution pretty quickly. I will leave the programming part as an exercise.
How to find maximum likelihood estimates of an integer parameter? The method whuber has used in his excellent answer is a common optimisation "trick" that involves extending the likelihood function to allow real values of $N$, and then using the concavity of the log
38,607
How to find maximum likelihood estimates of an integer parameter?
Comment: Here is a brief simulation in R for $\mu = 50, \sigma = 3,$ which should be accurate to 2 or three places, approximating the mean and SD of $Y.$ You should be able to find $E(Y)$ and $Var(Y)$ by elementary analytic methods as indicated in my earlier Comment. If we had $N = 100$ then $E(\hat N)$ seems unbiased for $N.$ N = 100; mu = 50; sg = 3 y = replicate( 10^6, sum(rnorm(N, mu, sg))/mu ) mean(y); sd(y) [1] 99.99997 [1] 0.6001208 N.est = round(y); mean(N.est); sd(N.est) [1] 99.9998 [1] 0.6649131
How to find maximum likelihood estimates of an integer parameter?
Comment: Here is a brief simulation in R for $\mu = 50, \sigma = 3,$ which should be accurate to 2 or three places, approximating the mean and SD of $Y.$ You should be able to find $E(Y)$ and $Var(Y)$
How to find maximum likelihood estimates of an integer parameter? Comment: Here is a brief simulation in R for $\mu = 50, \sigma = 3,$ which should be accurate to 2 or three places, approximating the mean and SD of $Y.$ You should be able to find $E(Y)$ and $Var(Y)$ by elementary analytic methods as indicated in my earlier Comment. If we had $N = 100$ then $E(\hat N)$ seems unbiased for $N.$ N = 100; mu = 50; sg = 3 y = replicate( 10^6, sum(rnorm(N, mu, sg))/mu ) mean(y); sd(y) [1] 99.99997 [1] 0.6001208 N.est = round(y); mean(N.est); sd(N.est) [1] 99.9998 [1] 0.6649131
How to find maximum likelihood estimates of an integer parameter? Comment: Here is a brief simulation in R for $\mu = 50, \sigma = 3,$ which should be accurate to 2 or three places, approximating the mean and SD of $Y.$ You should be able to find $E(Y)$ and $Var(Y)$
38,608
Why are contours of a multivariate Gaussian distribution elliptical?
You can understand the shape of the ellipsoid better if you look at the spectral/eigen decomposition of the precision matrix (inverse of the covariance matrix). You want to look at the eigenvalues of this inverse, not the diagonal elements. Just a supplement to the other answers: for a multivariate Normal with dimension $k$, you can see why algebraically if you follow this. Set the density equal to some level $l$, then: \begin{align*} (2\pi)^{-k/2} |\Sigma|^{-1/2} \exp\left(-\frac{1}{2}(x-\mu)'\Sigma^{-1}(x-\mu) \right) &= l\\ \iff \exp\left(-\frac{1}{2}(x-\mu)'\Sigma^{-1}(x-\mu) \right) &= l'\\ \iff (x-\mu)'\Sigma^{-1}(x-\mu) &= l''.\tag{*} \end{align*} (*) is the formula for an ellipsoid centered at $\mu$. The For your first covariance matrix, the spectral decomposition of its inverse is $\Sigma^{-1} = P\Lambda P'$, where $$P = \left[\begin{array}{cc} P_1 & P_2 \end{array}\right] = \left[\begin{array}{cc} .707 & -.707\\ .707 & .707 \end{array}\right] $$ and $$ \Lambda = \left[\begin{array}{cc} \lambda_1 & 0 \\ 0 & \lambda_2 \end{array}\right] = \left[\begin{array}{cc} 2 & 0 \\ 0 & 2/3 \end{array}\right]. $$ The reason why it looks "squished" is because the diagonals of $\Lambda$ are not the same. This is because the semi-axes are $P_1/\lambda_1$ (the up and to the right vector) and $P_2/\lambda_2$ (up and to the left). Because $\lambda_1$ is bigger, that means $P_1/\lambda_1$ is a shorter vector. What if we're used to looking at the covariance matrix, instead of its inverse? Well their spectral decompositions are pretty related. Because $\Sigma^{-1} = P\Lambda P'$ and because $P$ is orthogonal, we have $$ \Sigma = P \Lambda^{-1}P'. $$ Just try multiplying these two decompositions together, and you should get the identity matrix. What this tells us is that these two matrices have the same eigenvectors (and so they have the same principal axes), and the eigenvalues are reciprocals. However, I started off with the precision matrix because that's what is in the formula for the density. More examples: If the elements of $x$ are independent, then $\Sigma$ is diagonal, then $\Sigma^{-1}$ is diagonal, then (*) is $$ \frac{(x_1 - \mu_1)^2}{\sigma_1^2} + \frac{(x_2 - \mu_2)^2}{\sigma_2^2} = l''\tag{**} $$ which is still an ellipse, but it's not tilted/rotated. If the elements of $x$ are independent and moreover they are identical, then $\sigma_1 = \sigma_2$ and (**) turns into a circle.
Why are contours of a multivariate Gaussian distribution elliptical?
You can understand the shape of the ellipsoid better if you look at the spectral/eigen decomposition of the precision matrix (inverse of the covariance matrix). You want to look at the eigenvalues of
Why are contours of a multivariate Gaussian distribution elliptical? You can understand the shape of the ellipsoid better if you look at the spectral/eigen decomposition of the precision matrix (inverse of the covariance matrix). You want to look at the eigenvalues of this inverse, not the diagonal elements. Just a supplement to the other answers: for a multivariate Normal with dimension $k$, you can see why algebraically if you follow this. Set the density equal to some level $l$, then: \begin{align*} (2\pi)^{-k/2} |\Sigma|^{-1/2} \exp\left(-\frac{1}{2}(x-\mu)'\Sigma^{-1}(x-\mu) \right) &= l\\ \iff \exp\left(-\frac{1}{2}(x-\mu)'\Sigma^{-1}(x-\mu) \right) &= l'\\ \iff (x-\mu)'\Sigma^{-1}(x-\mu) &= l''.\tag{*} \end{align*} (*) is the formula for an ellipsoid centered at $\mu$. The For your first covariance matrix, the spectral decomposition of its inverse is $\Sigma^{-1} = P\Lambda P'$, where $$P = \left[\begin{array}{cc} P_1 & P_2 \end{array}\right] = \left[\begin{array}{cc} .707 & -.707\\ .707 & .707 \end{array}\right] $$ and $$ \Lambda = \left[\begin{array}{cc} \lambda_1 & 0 \\ 0 & \lambda_2 \end{array}\right] = \left[\begin{array}{cc} 2 & 0 \\ 0 & 2/3 \end{array}\right]. $$ The reason why it looks "squished" is because the diagonals of $\Lambda$ are not the same. This is because the semi-axes are $P_1/\lambda_1$ (the up and to the right vector) and $P_2/\lambda_2$ (up and to the left). Because $\lambda_1$ is bigger, that means $P_1/\lambda_1$ is a shorter vector. What if we're used to looking at the covariance matrix, instead of its inverse? Well their spectral decompositions are pretty related. Because $\Sigma^{-1} = P\Lambda P'$ and because $P$ is orthogonal, we have $$ \Sigma = P \Lambda^{-1}P'. $$ Just try multiplying these two decompositions together, and you should get the identity matrix. What this tells us is that these two matrices have the same eigenvectors (and so they have the same principal axes), and the eigenvalues are reciprocals. However, I started off with the precision matrix because that's what is in the formula for the density. More examples: If the elements of $x$ are independent, then $\Sigma$ is diagonal, then $\Sigma^{-1}$ is diagonal, then (*) is $$ \frac{(x_1 - \mu_1)^2}{\sigma_1^2} + \frac{(x_2 - \mu_2)^2}{\sigma_2^2} = l''\tag{**} $$ which is still an ellipse, but it's not tilted/rotated. If the elements of $x$ are independent and moreover they are identical, then $\sigma_1 = \sigma_2$ and (**) turns into a circle.
Why are contours of a multivariate Gaussian distribution elliptical? You can understand the shape of the ellipsoid better if you look at the spectral/eigen decomposition of the precision matrix (inverse of the covariance matrix). You want to look at the eigenvalues of
38,609
Why are contours of a multivariate Gaussian distribution elliptical?
Assume you are visualizing the distribution of a vector called $(X,Y)$ (assumed to have a bivariate normal distribution). When $X$ and $Y$ have the same variance, the projections of the ellipse on both axes have the same length. This does mean it's a circle. It can be oblique. It's not a circle when $X$ and $Y$ are not independent. When $X$ and $Y$ are independent, the major and minor axes of the ellipse are aligned with the axes. This does not mean it's a circle either, it can be flattened. A circle requires both: independence of $X$ and $Y$ $X$ and $Y$ having the same variance This is when the covariance matrix $\Sigma$ is diagonal with a constant diagonal.
Why are contours of a multivariate Gaussian distribution elliptical?
Assume you are visualizing the distribution of a vector called $(X,Y)$ (assumed to have a bivariate normal distribution). When $X$ and $Y$ have the same variance, the projections of the ellipse on bo
Why are contours of a multivariate Gaussian distribution elliptical? Assume you are visualizing the distribution of a vector called $(X,Y)$ (assumed to have a bivariate normal distribution). When $X$ and $Y$ have the same variance, the projections of the ellipse on both axes have the same length. This does mean it's a circle. It can be oblique. It's not a circle when $X$ and $Y$ are not independent. When $X$ and $Y$ are independent, the major and minor axes of the ellipse are aligned with the axes. This does not mean it's a circle either, it can be flattened. A circle requires both: independence of $X$ and $Y$ $X$ and $Y$ having the same variance This is when the covariance matrix $\Sigma$ is diagonal with a constant diagonal.
Why are contours of a multivariate Gaussian distribution elliptical? Assume you are visualizing the distribution of a vector called $(X,Y)$ (assumed to have a bivariate normal distribution). When $X$ and $Y$ have the same variance, the projections of the ellipse on bo
38,610
Why are contours of a multivariate Gaussian distribution elliptical?
Consider this figure. Notice how both the circle and the dashed diagonal are inside the square. So, the circle is how the contours of the multivariate Gaussian looks when correlation is zero. The dashed diagonal is the contour of the perfectly correlated variables. The ovals (ellipses) are in between, when correlation is not equal zero or one. The length of the square sides represents the variance (standard deviation) of the variables (marginals). Here, I resized your picture to make the x- and y-axis scales equal, and you can see how the oval fits into a square. I think that the fact that Andrew Ng's plot was not scaled equally just added to the confusion. You can fit all kinds of ovals into the same square. You can have all kinds of contours for the same variances of variables depending on the correlation between them. The image is from this web site, which has nothing to do with a question asked :)
Why are contours of a multivariate Gaussian distribution elliptical?
Consider this figure. Notice how both the circle and the dashed diagonal are inside the square. So, the circle is how the contours of the multivariate Gaussian looks when correlation is zero. The dash
Why are contours of a multivariate Gaussian distribution elliptical? Consider this figure. Notice how both the circle and the dashed diagonal are inside the square. So, the circle is how the contours of the multivariate Gaussian looks when correlation is zero. The dashed diagonal is the contour of the perfectly correlated variables. The ovals (ellipses) are in between, when correlation is not equal zero or one. The length of the square sides represents the variance (standard deviation) of the variables (marginals). Here, I resized your picture to make the x- and y-axis scales equal, and you can see how the oval fits into a square. I think that the fact that Andrew Ng's plot was not scaled equally just added to the confusion. You can fit all kinds of ovals into the same square. You can have all kinds of contours for the same variances of variables depending on the correlation between them. The image is from this web site, which has nothing to do with a question asked :)
Why are contours of a multivariate Gaussian distribution elliptical? Consider this figure. Notice how both the circle and the dashed diagonal are inside the square. So, the circle is how the contours of the multivariate Gaussian looks when correlation is zero. The dash
38,611
Time series prediction: Neural Network (nnetar) vs. exponential smoothing (ets)
which is the appropriate neuronal network / function for time series prediction? Please consider, that above example is just a simplified data-example. Well, this totally depends on your data. In your example data you have a small univariate time series (only 14 observations) a linear trend no white noise no seasonality no cycle non non-linearity nnetar() Neural networks are generally very data savvy/ data hungry. That means that you need a lot of data to implement an accurate forecast. 14 observations are definitely not enough you rather need some ten or hundred thousands. In general, I do not recommend using neural networks for forecasting univariate time series. One benefit of neural networks is that they can capture nonlinearities, but your data does not exhibit any nonlinearity. Note that nnetar() uses a feed-forward neural network; in recent time series forecasting many researchers use recurrent neural networks instead of feed-forward neural networks. You can also read this discussion. As far as I know nnetar() is based on the discussion here If you print fit you will see the model. It is an average of 20 different neural networks and therefore not deterministic. Series: df Model: NNAR(1,1) Call: nnetar(y = df) Average of 20 networks, each of which is a 1-1-1 network with 4 weights options were - linear output units sigma^2 estimated as 0.003636 ets() This function uses exponential smoothing. Exponential smoothing models require fewer parameters. Therefore they perform better on your tiny dataset. It might help to have a closer look at the equations of simple exponential smoothing: $s_0 = x_0$ $s_t = \alpha x_t + (1- \alpha) s_{t-1}$ In your case $s_0$ and $x_0$ are 0. If you print fit2 you can see that the information criteria are all equal to minus infinity which states that there is no better model than the one you have chosen. ETS(A,A,N) Call: ets(y = df) Smoothing parameters: alpha = 0.5445 beta = 0.1009 Initial states: l = 0 b = 1 sigma: 0 AIC AICc BIC -Inf -Inf -Inf
Time series prediction: Neural Network (nnetar) vs. exponential smoothing (ets)
which is the appropriate neuronal network / function for time series prediction? Please consider, that above example is just a simplified data-example. Well, this totally depends on your data. In you
Time series prediction: Neural Network (nnetar) vs. exponential smoothing (ets) which is the appropriate neuronal network / function for time series prediction? Please consider, that above example is just a simplified data-example. Well, this totally depends on your data. In your example data you have a small univariate time series (only 14 observations) a linear trend no white noise no seasonality no cycle non non-linearity nnetar() Neural networks are generally very data savvy/ data hungry. That means that you need a lot of data to implement an accurate forecast. 14 observations are definitely not enough you rather need some ten or hundred thousands. In general, I do not recommend using neural networks for forecasting univariate time series. One benefit of neural networks is that they can capture nonlinearities, but your data does not exhibit any nonlinearity. Note that nnetar() uses a feed-forward neural network; in recent time series forecasting many researchers use recurrent neural networks instead of feed-forward neural networks. You can also read this discussion. As far as I know nnetar() is based on the discussion here If you print fit you will see the model. It is an average of 20 different neural networks and therefore not deterministic. Series: df Model: NNAR(1,1) Call: nnetar(y = df) Average of 20 networks, each of which is a 1-1-1 network with 4 weights options were - linear output units sigma^2 estimated as 0.003636 ets() This function uses exponential smoothing. Exponential smoothing models require fewer parameters. Therefore they perform better on your tiny dataset. It might help to have a closer look at the equations of simple exponential smoothing: $s_0 = x_0$ $s_t = \alpha x_t + (1- \alpha) s_{t-1}$ In your case $s_0$ and $x_0$ are 0. If you print fit2 you can see that the information criteria are all equal to minus infinity which states that there is no better model than the one you have chosen. ETS(A,A,N) Call: ets(y = df) Smoothing parameters: alpha = 0.5445 beta = 0.1009 Initial states: l = 0 b = 1 sigma: 0 AIC AICc BIC -Inf -Inf -Inf
Time series prediction: Neural Network (nnetar) vs. exponential smoothing (ets) which is the appropriate neuronal network / function for time series prediction? Please consider, that above example is just a simplified data-example. Well, this totally depends on your data. In you
38,612
Time series prediction: Neural Network (nnetar) vs. exponential smoothing (ets)
That's because the data generating process is a deterministic model. This is a special case of an ARIMA(0,1,1) process, also known as exponential smoothing. Therefore the exponential smoothing model generates forecasts that match your expectation. The autoregressive neural network does not model this type of process.
Time series prediction: Neural Network (nnetar) vs. exponential smoothing (ets)
That's because the data generating process is a deterministic model. This is a special case of an ARIMA(0,1,1) process, also known as exponential smoothing. Therefore the exponential smoothing model g
Time series prediction: Neural Network (nnetar) vs. exponential smoothing (ets) That's because the data generating process is a deterministic model. This is a special case of an ARIMA(0,1,1) process, also known as exponential smoothing. Therefore the exponential smoothing model generates forecasts that match your expectation. The autoregressive neural network does not model this type of process.
Time series prediction: Neural Network (nnetar) vs. exponential smoothing (ets) That's because the data generating process is a deterministic model. This is a special case of an ARIMA(0,1,1) process, also known as exponential smoothing. Therefore the exponential smoothing model g
38,613
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test?
There have been a number of papers which examine this issue. Most of them come to the conclusion that Welch's version of the t-test can be safely used in most circumstances. The only situation in which the test seems to have undesirable performance is in very small sample sizes. Here are some quotes from two papers which examine t-test performance with small sample sizes: The t-test with the unequal variances option (i.e., the Welch test) was generally not preferred either. Only in the case of unequal variances combined with unequal sample sizes, where the small sample was drawn from the small variance population, did this approach provide a power advantage compared to the regular ttest. In the other cases, a substantial amount of statistical power was lost compared to the regular t-test. The power loss of the Welch test can be explained by its lower degrees of freedom determined from the Welch-Satterthwaite equation.$^1$ Results suggest that the Welch t test is indeed inflated, according to Bradley's (1978) fairly stringent criterion, when sample sizes are unequal – even when assumptions for the t test are met in the population. The inflation rate seems to be dependent more on the size of the smaller group than on the total sample size, but sample size ratio does seem to play a small role$^2$ If you read through those papers though, you'll see that it's really only in the specific case with very small sample sizes (in particular, when the smaller of the two groups is very small) that it's much of an issue. "Small" meaning the effects are really only troublesome when a group contains around 5 subjects or less as posited by both papers, but take a closer look at the references for a more thorough discussion. In that case, you might (obviously) suggest collecting more data. But this can of course be an issue with prohibitively expensive experiments. Otherwise Welch's is probably fine. $^1$ : Using the Student’s t-test with extremely small sample sizes, J.C.F. de Winter 2013 $^2$ : Type I Error Inflation of the Separate-Variances Welch t test with Very Small Sample Sizes when Assumptions Are Met, Albert K. Adusah and Gordon P. Brooks 2011
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test?
There have been a number of papers which examine this issue. Most of them come to the conclusion that Welch's version of the t-test can be safely used in most circumstances. The only situation in whi
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test? There have been a number of papers which examine this issue. Most of them come to the conclusion that Welch's version of the t-test can be safely used in most circumstances. The only situation in which the test seems to have undesirable performance is in very small sample sizes. Here are some quotes from two papers which examine t-test performance with small sample sizes: The t-test with the unequal variances option (i.e., the Welch test) was generally not preferred either. Only in the case of unequal variances combined with unequal sample sizes, where the small sample was drawn from the small variance population, did this approach provide a power advantage compared to the regular ttest. In the other cases, a substantial amount of statistical power was lost compared to the regular t-test. The power loss of the Welch test can be explained by its lower degrees of freedom determined from the Welch-Satterthwaite equation.$^1$ Results suggest that the Welch t test is indeed inflated, according to Bradley's (1978) fairly stringent criterion, when sample sizes are unequal – even when assumptions for the t test are met in the population. The inflation rate seems to be dependent more on the size of the smaller group than on the total sample size, but sample size ratio does seem to play a small role$^2$ If you read through those papers though, you'll see that it's really only in the specific case with very small sample sizes (in particular, when the smaller of the two groups is very small) that it's much of an issue. "Small" meaning the effects are really only troublesome when a group contains around 5 subjects or less as posited by both papers, but take a closer look at the references for a more thorough discussion. In that case, you might (obviously) suggest collecting more data. But this can of course be an issue with prohibitively expensive experiments. Otherwise Welch's is probably fine. $^1$ : Using the Student’s t-test with extremely small sample sizes, J.C.F. de Winter 2013 $^2$ : Type I Error Inflation of the Separate-Variances Welch t test with Very Small Sample Sizes when Assumptions Are Met, Albert K. Adusah and Gordon P. Brooks 2011
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test? There have been a number of papers which examine this issue. Most of them come to the conclusion that Welch's version of the t-test can be safely used in most circumstances. The only situation in whi
38,614
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test?
Do you see any drawbacks in always using the Welch-t test instead of the Student-t test or Mann-Whitney test? Welch t-tests are inherently made for unpaired samples. If you have paired samples because you measured the same subjects twice, you should use that information. Paired sample t-tests are more powerful. This one is the most common exception, paired data can occur in most if not all fields of research. There are also specific variants of t-tests that correct for specific kinds of pseudo-replication in specific contexts. For example, there are corrected resampled t-tests for data that comes from repeated cross validation. Those variants don't usually integrate with Welch's approach either.
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test?
Do you see any drawbacks in always using the Welch-t test instead of the Student-t test or Mann-Whitney test? Welch t-tests are inherently made for unpaired samples. If you have paired samples becaus
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test? Do you see any drawbacks in always using the Welch-t test instead of the Student-t test or Mann-Whitney test? Welch t-tests are inherently made for unpaired samples. If you have paired samples because you measured the same subjects twice, you should use that information. Paired sample t-tests are more powerful. This one is the most common exception, paired data can occur in most if not all fields of research. There are also specific variants of t-tests that correct for specific kinds of pseudo-replication in specific contexts. For example, there are corrected resampled t-tests for data that comes from repeated cross validation. Those variants don't usually integrate with Welch's approach either.
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test? Do you see any drawbacks in always using the Welch-t test instead of the Student-t test or Mann-Whitney test? Welch t-tests are inherently made for unpaired samples. If you have paired samples becaus
38,615
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test?
As an aside, Mann-Whitney U is NOT a test of central tendency (aka median). It is a test of stochastic dominance (a random value from one sample is, on average, more likely to be higher that a random value from the other sample). Only in some very specific (and hard to verify) cases does it become a test of the medians: either when the 2 samples are symmetric (and then median=mean and it becomes also a test of means), or when the 2 samples are NOT symmetric, but they have exactly the same shape (how to prove this? An exercise "left to the student"?)
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test?
As an aside, Mann-Whitney U is NOT a test of central tendency (aka median). It is a test of stochastic dominance (a random value from one sample is, on average, more likely to be higher that a random
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test? As an aside, Mann-Whitney U is NOT a test of central tendency (aka median). It is a test of stochastic dominance (a random value from one sample is, on average, more likely to be higher that a random value from the other sample). Only in some very specific (and hard to verify) cases does it become a test of the medians: either when the 2 samples are symmetric (and then median=mean and it becomes also a test of means), or when the 2 samples are NOT symmetric, but they have exactly the same shape (how to prove this? An exercise "left to the student"?)
Always use Welch-t test (unequal variances t-test) instead of Student-t or Mann-Whitney test? As an aside, Mann-Whitney U is NOT a test of central tendency (aka median). It is a test of stochastic dominance (a random value from one sample is, on average, more likely to be higher that a random
38,616
Machine learning courses: maths explained
To add on to @Digio, I would recommend Abu-Mostafa's Learning From Data, which contains enough statistical learning mathematics to get you excited and wanting more.
Machine learning courses: maths explained
To add on to @Digio, I would recommend Abu-Mostafa's Learning From Data, which contains enough statistical learning mathematics to get you excited and wanting more.
Machine learning courses: maths explained To add on to @Digio, I would recommend Abu-Mostafa's Learning From Data, which contains enough statistical learning mathematics to get you excited and wanting more.
Machine learning courses: maths explained To add on to @Digio, I would recommend Abu-Mostafa's Learning From Data, which contains enough statistical learning mathematics to get you excited and wanting more.
38,617
Machine learning courses: maths explained
Note, Andrew Ng has a more mathematical course in Stanford Online not Coursera. Recommendations would always be subjective, for me, I personally like The Elements of Statistical Learning Convex Optimization Both books are classical books in machine learning community and freely available. Related question can be found here. Machine learning cookbook / reference card / cheatsheet?
Machine learning courses: maths explained
Note, Andrew Ng has a more mathematical course in Stanford Online not Coursera. Recommendations would always be subjective, for me, I personally like The Elements of Statistical Learning Convex Optim
Machine learning courses: maths explained Note, Andrew Ng has a more mathematical course in Stanford Online not Coursera. Recommendations would always be subjective, for me, I personally like The Elements of Statistical Learning Convex Optimization Both books are classical books in machine learning community and freely available. Related question can be found here. Machine learning cookbook / reference card / cheatsheet?
Machine learning courses: maths explained Note, Andrew Ng has a more mathematical course in Stanford Online not Coursera. Recommendations would always be subjective, for me, I personally like The Elements of Statistical Learning Convex Optim
38,618
Machine learning courses: maths explained
Try to dig deeper in a specific topic. Ngs course only scratches the surface, but other more specific courses are more theoretical/mathematical. Bayesian networks/ Markov networks: Probability graphical models is a theoretical advanced coursera course on Bayesian networks/Markov networks. The book is even more theoretical. It is full of proofs. Neural Networks: Neural Networks for Machine Learning is also a rather theoretical course as it is really profound. Nonetheless it is not as mathematical as the PGM course I mentioned above. However if you want to understand the theory of Machine Learning itself and not the algorithms you can go for a textbook. In this case go for what @digio proposed.
Machine learning courses: maths explained
Try to dig deeper in a specific topic. Ngs course only scratches the surface, but other more specific courses are more theoretical/mathematical. Bayesian networks/ Markov networks: Probability graphic
Machine learning courses: maths explained Try to dig deeper in a specific topic. Ngs course only scratches the surface, but other more specific courses are more theoretical/mathematical. Bayesian networks/ Markov networks: Probability graphical models is a theoretical advanced coursera course on Bayesian networks/Markov networks. The book is even more theoretical. It is full of proofs. Neural Networks: Neural Networks for Machine Learning is also a rather theoretical course as it is really profound. Nonetheless it is not as mathematical as the PGM course I mentioned above. However if you want to understand the theory of Machine Learning itself and not the algorithms you can go for a textbook. In this case go for what @digio proposed.
Machine learning courses: maths explained Try to dig deeper in a specific topic. Ngs course only scratches the surface, but other more specific courses are more theoretical/mathematical. Bayesian networks/ Markov networks: Probability graphic
38,619
Machine learning courses: maths explained
This (archived) edX machine learning course from Columbia explains a lot of underlying math. For example they show regularized linear regression and probabilistic matrix factorization from Bayesian (Maximum A Posteriori) perspective. Understanding Machine Learning is a (freely available) textbook that takes computational learning theory approach, and contains derivations and calculations/estimation of VC dimension of classifiers.
Machine learning courses: maths explained
This (archived) edX machine learning course from Columbia explains a lot of underlying math. For example they show regularized linear regression and probabilistic matrix factorization from Bayesian (M
Machine learning courses: maths explained This (archived) edX machine learning course from Columbia explains a lot of underlying math. For example they show regularized linear regression and probabilistic matrix factorization from Bayesian (Maximum A Posteriori) perspective. Understanding Machine Learning is a (freely available) textbook that takes computational learning theory approach, and contains derivations and calculations/estimation of VC dimension of classifiers.
Machine learning courses: maths explained This (archived) edX machine learning course from Columbia explains a lot of underlying math. For example they show regularized linear regression and probabilistic matrix factorization from Bayesian (M
38,620
Expected Value and Most Likely Outcome
It's not true in general that the expected value is the most likely outcome. Even for binomial distributions. For example, say we flip a fair coin 5 times. The number of heads has a binomial distribution with expected value 2.5. It's not even possible to obtain this outcome (similar to what Zen mentioned in the comments about rolling a die). Or, say we draw a value from a bimodal distribution like this: The expected value is zero, but the probability density associated with this outcome is quite low.
Expected Value and Most Likely Outcome
It's not true in general that the expected value is the most likely outcome. Even for binomial distributions. For example, say we flip a fair coin 5 times. The number of heads has a binomial distribut
Expected Value and Most Likely Outcome It's not true in general that the expected value is the most likely outcome. Even for binomial distributions. For example, say we flip a fair coin 5 times. The number of heads has a binomial distribution with expected value 2.5. It's not even possible to obtain this outcome (similar to what Zen mentioned in the comments about rolling a die). Or, say we draw a value from a bimodal distribution like this: The expected value is zero, but the probability density associated with this outcome is quite low.
Expected Value and Most Likely Outcome It's not true in general that the expected value is the most likely outcome. Even for binomial distributions. For example, say we flip a fair coin 5 times. The number of heads has a binomial distribut
38,621
Is it possible to get a z-score greater than 3?
I will assume that you mean variables that are standardized by their own sample statistics. Z-values larger than $3$ are certainly possible at $n=361$ for normally distributed data. Indeed, the largest-magnitude z-score should exceed 3 more than half the time. (If the data were drawn from a non-normal distribution, it can happen as low as $n=11$.) Here is the distribution of the largest absolute z-score from samples of size 361 from normally-distributed populations (by simulation). If you were looking at a single variable, values for the largest magnitude of z-score much past $4$ would be somewhat surprising for samples of this size drawn from a normal distribution. If you're looking at say $20$ variables you would expect some to be bigger than $4$ but you might find a value like say $4.6$ or so somewhat surprising. Values much beyond $5$ are usually not credible for samples of size $361$ from a normal distribution (in the sense that a value at least that large would be an extremely rare occurrence), unless you looked at very large numbers of variables. However, it's not clear why you would care whether any of these variables might be normally distributed (in fact I'd be surprised if any were actually drawn from normal distributions but that shouldn't usually be of any consequence). Why would it matter if the distribution that some variable was drawn from was a normal distribution? (What are you doing that would require normal distributions for any of these variables?)
Is it possible to get a z-score greater than 3?
I will assume that you mean variables that are standardized by their own sample statistics. Z-values larger than $3$ are certainly possible at $n=361$ for normally distributed data. Indeed, the large
Is it possible to get a z-score greater than 3? I will assume that you mean variables that are standardized by their own sample statistics. Z-values larger than $3$ are certainly possible at $n=361$ for normally distributed data. Indeed, the largest-magnitude z-score should exceed 3 more than half the time. (If the data were drawn from a non-normal distribution, it can happen as low as $n=11$.) Here is the distribution of the largest absolute z-score from samples of size 361 from normally-distributed populations (by simulation). If you were looking at a single variable, values for the largest magnitude of z-score much past $4$ would be somewhat surprising for samples of this size drawn from a normal distribution. If you're looking at say $20$ variables you would expect some to be bigger than $4$ but you might find a value like say $4.6$ or so somewhat surprising. Values much beyond $5$ are usually not credible for samples of size $361$ from a normal distribution (in the sense that a value at least that large would be an extremely rare occurrence), unless you looked at very large numbers of variables. However, it's not clear why you would care whether any of these variables might be normally distributed (in fact I'd be surprised if any were actually drawn from normal distributions but that shouldn't usually be of any consequence). Why would it matter if the distribution that some variable was drawn from was a normal distribution? (What are you doing that would require normal distributions for any of these variables?)
Is it possible to get a z-score greater than 3? I will assume that you mean variables that are standardized by their own sample statistics. Z-values larger than $3$ are certainly possible at $n=361$ for normally distributed data. Indeed, the large
38,622
Is it possible to get a z-score greater than 3?
For a data point $x$ and a distribution with mean $\mu$ and standard deviation $\sigma$, the z-score is just $(x-\mu) / \sigma$. So, a high z-score means the data point is many standard deviations away from the mean. This could happen as a matter of course with heavy/long tailed distributions, or could signify outliers. A good first step would be good to plot a histogram or other density estimator and take a look at the distribution.
Is it possible to get a z-score greater than 3?
For a data point $x$ and a distribution with mean $\mu$ and standard deviation $\sigma$, the z-score is just $(x-\mu) / \sigma$. So, a high z-score means the data point is many standard deviations awa
Is it possible to get a z-score greater than 3? For a data point $x$ and a distribution with mean $\mu$ and standard deviation $\sigma$, the z-score is just $(x-\mu) / \sigma$. So, a high z-score means the data point is many standard deviations away from the mean. This could happen as a matter of course with heavy/long tailed distributions, or could signify outliers. A good first step would be good to plot a histogram or other density estimator and take a look at the distribution.
Is it possible to get a z-score greater than 3? For a data point $x$ and a distribution with mean $\mu$ and standard deviation $\sigma$, the z-score is just $(x-\mu) / \sigma$. So, a high z-score means the data point is many standard deviations awa
38,623
Is it possible to get a z-score greater than 3?
This is an old question, but just to add another example here to illustrate how this can happen. Lets randomly generate a set of data on IQ scores that is normally distributed but has one extreme outlier: a really, really smart kid: #### Load Libary and Set Random Seed #### library(tidyverse) set.seed(123) #### Create Data #### data <- tibble(subject = 1:50, iq = round(rnorm(n=50, mean=120, sd=15))) #### Assign Very Smart Subject #### data[1,2] <- 300 Running a density plot of the data: #### Plot Density of Scores #### data %>% ggplot(aes(x=iq))+ geom_density(fill = "steelblue", alpha = .4)+ labs(x="Intelligence Quotient", y="Density", title = "Normal Density vs IQ = 300")+ scale_x_continuous(limits = c(80,320)) You can see that the original normal distribution still exists but the person with 300 IQ is very much an outlier now: To figure out just how much of an outlier, we can create a variable called z_score which gets the number of standard deviations above/below the mean for each subject and then filter for those equal to or above 3 SD: #### Create Z Scores #### data %>% mutate(z_score = (iq-mean(iq))/sd(iq)) %>% filter(z_score >= 3) We can see this person has a crazy z-score...its 6 standard deviations above the mean: # A tibble: 1 × 3 subject iq z_score <int> <dbl> <dbl> 1 1 300 6.09 We can visualize just how extreme by plotting the same data but now with 3 standard deviations above and below the mean marked with red dashed lines: #### Plot Z Score Limits #### data %>% mutate(z_score = (iq-mean(iq))/sd(iq), sd = sd(iq), mean = mean(iq)) %>% ggplot(aes(x=iq))+ geom_density(fill = "steelblue", alpha = .4)+ labs(x="Intelligence Quotient", y="Density", title = "Normal Density vs IQ = 300")+ geom_vline(aes(xintercept=mean+(3*sd)), color="red", linetype="dashed")+ geom_vline(aes(xintercept=mean-(3*sd)), color="red", linetype="dashed")+ scale_x_continuous(limits = c(0,320)) And here you can see that the smart kid is far above the metric we set:
Is it possible to get a z-score greater than 3?
This is an old question, but just to add another example here to illustrate how this can happen. Lets randomly generate a set of data on IQ scores that is normally distributed but has one extreme outl
Is it possible to get a z-score greater than 3? This is an old question, but just to add another example here to illustrate how this can happen. Lets randomly generate a set of data on IQ scores that is normally distributed but has one extreme outlier: a really, really smart kid: #### Load Libary and Set Random Seed #### library(tidyverse) set.seed(123) #### Create Data #### data <- tibble(subject = 1:50, iq = round(rnorm(n=50, mean=120, sd=15))) #### Assign Very Smart Subject #### data[1,2] <- 300 Running a density plot of the data: #### Plot Density of Scores #### data %>% ggplot(aes(x=iq))+ geom_density(fill = "steelblue", alpha = .4)+ labs(x="Intelligence Quotient", y="Density", title = "Normal Density vs IQ = 300")+ scale_x_continuous(limits = c(80,320)) You can see that the original normal distribution still exists but the person with 300 IQ is very much an outlier now: To figure out just how much of an outlier, we can create a variable called z_score which gets the number of standard deviations above/below the mean for each subject and then filter for those equal to or above 3 SD: #### Create Z Scores #### data %>% mutate(z_score = (iq-mean(iq))/sd(iq)) %>% filter(z_score >= 3) We can see this person has a crazy z-score...its 6 standard deviations above the mean: # A tibble: 1 × 3 subject iq z_score <int> <dbl> <dbl> 1 1 300 6.09 We can visualize just how extreme by plotting the same data but now with 3 standard deviations above and below the mean marked with red dashed lines: #### Plot Z Score Limits #### data %>% mutate(z_score = (iq-mean(iq))/sd(iq), sd = sd(iq), mean = mean(iq)) %>% ggplot(aes(x=iq))+ geom_density(fill = "steelblue", alpha = .4)+ labs(x="Intelligence Quotient", y="Density", title = "Normal Density vs IQ = 300")+ geom_vline(aes(xintercept=mean+(3*sd)), color="red", linetype="dashed")+ geom_vline(aes(xintercept=mean-(3*sd)), color="red", linetype="dashed")+ scale_x_continuous(limits = c(0,320)) And here you can see that the smart kid is far above the metric we set:
Is it possible to get a z-score greater than 3? This is an old question, but just to add another example here to illustrate how this can happen. Lets randomly generate a set of data on IQ scores that is normally distributed but has one extreme outl
38,624
Lasso Regression for predicting Continuous Variable + Variable Selection?
Be sure to install and load the glmnet package. install.packages("glmnet") library(glmnet) First you need to form a matrix with all your predictors, we call that matrix $\mathbf{X}$. I have done this for three variables I have created but since you have more you will need to change the predictor matrix accordingly. set.seed(1) x1 <- rnorm(30) x2 <- rnorm(30) x3 <- rnorm(30) X <- matrix( c(x1, x2, x3), byrow = F, ncol = 3) Then we need a response as well. This needs to be a vector as you know so let's form a linear combination of the predictors and corrupt it with some noise. y <- 3 + 4*x1 + 3*x2 + 5*x3 + rnorm(30) We have everything we need now to begin. Here is our first attempt with glmnet. fit <-glmnet(x = X, y = y, alpha = 1) # different values of alpha return different estimators, alpha = 1 is the lasso. plot(fit, xvar = "lambda") which should produce To interpet this plot, recall the optimization problem the lasso solves $$\hat{\boldsymbol{\beta}}_{LASSO} = \min_{\beta} \left( \mathbf{y} - \mathbf{X} \boldsymbol{\beta} \right) ^{\prime} \left( \mathbf{y} - \mathbf{X} \boldsymbol{\beta} \right) + \lambda \sum_j \left|\beta_j \right| $$ so $\lambda$ is the penalty or the Lagrange multiplier if you prefer and is always positive. Setting $\lambda = 0 $ yields the familiar minimization of squared residuals while for greater values, some of the coefficients will be set to zero. As $\lambda \to \infty$, all the coefficents will be set to zero. This is exactly what this plot shows then, the coefficient path for different values of lambda. For reasons beyond me the creators of this package have opted to present lambda on the log scale, thus values between zero and one are now negative. Pick the value of lambda you like and you can extract the coefficients with the command coef(fit, s = 0.3) # s is the value of lambda To locate the point on the plot, simply do log(0.3) and as you can see since lambda is quite close to zero there is not much shrinkage. Of course now we have to select one of these values of $\lambda$ and visual inspection is not good enough. We do this by the crossvalidation function of glmnet. If you have never heard of crossvalidation, all you need to know is that it is a predictive criterion that evaluates the sample performance by splitting the sample into training and validation sets and choosing the value of lambda with which the error of prediction is minimal. crossval <- cv.glmnet(x = X, y = y) plot(crossval) penalty <- crossval$lambda.min #optimal lambda penalty #minimal shrinkage fit1 <-glmnet(x = X, y = y, alpha = 1, lambda = penalty ) #estimate the model with that coef(fit1) I have chosen to plot the crossvalidation results just so you can see how this method works. We finally estimate the lasso with the optimal CV parameter and extract the coefficients. You will notice in my example that the shrinkage is minimal. This occurs because there is no multicollinearity in the sample thanks to the naive generation. I am certain your results will be much much different. Here is a webpage where the creators explain in detail how to use the package. I kept it simple because you are only interested in the lasso and no other estimators. Hope this helps.
Lasso Regression for predicting Continuous Variable + Variable Selection?
Be sure to install and load the glmnet package. install.packages("glmnet") library(glmnet) First you need to form a matrix with all your predictors, we call that matrix $\mathbf{X}$. I have done this
Lasso Regression for predicting Continuous Variable + Variable Selection? Be sure to install and load the glmnet package. install.packages("glmnet") library(glmnet) First you need to form a matrix with all your predictors, we call that matrix $\mathbf{X}$. I have done this for three variables I have created but since you have more you will need to change the predictor matrix accordingly. set.seed(1) x1 <- rnorm(30) x2 <- rnorm(30) x3 <- rnorm(30) X <- matrix( c(x1, x2, x3), byrow = F, ncol = 3) Then we need a response as well. This needs to be a vector as you know so let's form a linear combination of the predictors and corrupt it with some noise. y <- 3 + 4*x1 + 3*x2 + 5*x3 + rnorm(30) We have everything we need now to begin. Here is our first attempt with glmnet. fit <-glmnet(x = X, y = y, alpha = 1) # different values of alpha return different estimators, alpha = 1 is the lasso. plot(fit, xvar = "lambda") which should produce To interpet this plot, recall the optimization problem the lasso solves $$\hat{\boldsymbol{\beta}}_{LASSO} = \min_{\beta} \left( \mathbf{y} - \mathbf{X} \boldsymbol{\beta} \right) ^{\prime} \left( \mathbf{y} - \mathbf{X} \boldsymbol{\beta} \right) + \lambda \sum_j \left|\beta_j \right| $$ so $\lambda$ is the penalty or the Lagrange multiplier if you prefer and is always positive. Setting $\lambda = 0 $ yields the familiar minimization of squared residuals while for greater values, some of the coefficients will be set to zero. As $\lambda \to \infty$, all the coefficents will be set to zero. This is exactly what this plot shows then, the coefficient path for different values of lambda. For reasons beyond me the creators of this package have opted to present lambda on the log scale, thus values between zero and one are now negative. Pick the value of lambda you like and you can extract the coefficients with the command coef(fit, s = 0.3) # s is the value of lambda To locate the point on the plot, simply do log(0.3) and as you can see since lambda is quite close to zero there is not much shrinkage. Of course now we have to select one of these values of $\lambda$ and visual inspection is not good enough. We do this by the crossvalidation function of glmnet. If you have never heard of crossvalidation, all you need to know is that it is a predictive criterion that evaluates the sample performance by splitting the sample into training and validation sets and choosing the value of lambda with which the error of prediction is minimal. crossval <- cv.glmnet(x = X, y = y) plot(crossval) penalty <- crossval$lambda.min #optimal lambda penalty #minimal shrinkage fit1 <-glmnet(x = X, y = y, alpha = 1, lambda = penalty ) #estimate the model with that coef(fit1) I have chosen to plot the crossvalidation results just so you can see how this method works. We finally estimate the lasso with the optimal CV parameter and extract the coefficients. You will notice in my example that the shrinkage is minimal. This occurs because there is no multicollinearity in the sample thanks to the naive generation. I am certain your results will be much much different. Here is a webpage where the creators explain in detail how to use the package. I kept it simple because you are only interested in the lasso and no other estimators. Hope this helps.
Lasso Regression for predicting Continuous Variable + Variable Selection? Be sure to install and load the glmnet package. install.packages("glmnet") library(glmnet) First you need to form a matrix with all your predictors, we call that matrix $\mathbf{X}$. I have done this
38,625
Lasso Regression for predicting Continuous Variable + Variable Selection?
You might be better off using ridge regression rather than LASSO, or devising a scale that combines some of the correlated variables in an intelligent way, based on your knowledge of the subject matter. LASSO will not select the variables that are "driving the system," just a subset that happens to work on this data sample and which could be a good deal different from the variables selected on a different sample. Once you get glmnet working, it will be trivial to try ridge regression instead of LASSO. If your interest is in prediction then including all variables with ridge regression will tend to work better, particularly with so few predictors.
Lasso Regression for predicting Continuous Variable + Variable Selection?
You might be better off using ridge regression rather than LASSO, or devising a scale that combines some of the correlated variables in an intelligent way, based on your knowledge of the subject matte
Lasso Regression for predicting Continuous Variable + Variable Selection? You might be better off using ridge regression rather than LASSO, or devising a scale that combines some of the correlated variables in an intelligent way, based on your knowledge of the subject matter. LASSO will not select the variables that are "driving the system," just a subset that happens to work on this data sample and which could be a good deal different from the variables selected on a different sample. Once you get glmnet working, it will be trivial to try ridge regression instead of LASSO. If your interest is in prediction then including all variables with ridge regression will tend to work better, particularly with so few predictors.
Lasso Regression for predicting Continuous Variable + Variable Selection? You might be better off using ridge regression rather than LASSO, or devising a scale that combines some of the correlated variables in an intelligent way, based on your knowledge of the subject matte
38,626
Lasso Regression for predicting Continuous Variable + Variable Selection?
The one thing that I hate about glmnet is that it doesn't use data frames as an argument. In order to use glmnet, a data frame needs to be transformed into a model matrix and a response vector. Most model functions, like lm and glm, allow for formulas and data frames. The caret package is a wrapper for many modelling packages. Here's some sample code that uses caret to fit a glmnet model. Note that elastic net is a generalization of ridge and lasso regression. https://stats.stackexchange.com/a/188780/24030
Lasso Regression for predicting Continuous Variable + Variable Selection?
The one thing that I hate about glmnet is that it doesn't use data frames as an argument. In order to use glmnet, a data frame needs to be transformed into a model matrix and a response vector. Most m
Lasso Regression for predicting Continuous Variable + Variable Selection? The one thing that I hate about glmnet is that it doesn't use data frames as an argument. In order to use glmnet, a data frame needs to be transformed into a model matrix and a response vector. Most model functions, like lm and glm, allow for formulas and data frames. The caret package is a wrapper for many modelling packages. Here's some sample code that uses caret to fit a glmnet model. Note that elastic net is a generalization of ridge and lasso regression. https://stats.stackexchange.com/a/188780/24030
Lasso Regression for predicting Continuous Variable + Variable Selection? The one thing that I hate about glmnet is that it doesn't use data frames as an argument. In order to use glmnet, a data frame needs to be transformed into a model matrix and a response vector. Most m
38,627
How to interpret ridge regression plot
The ridge regression will penalize your coefficients, such that those that are the least effective in your estimation will "shrink" the fastest. Imagine you have a budget allocated and each coefficient can take some to play a role in the estimation. Naturally those who are more important will take more of the budget. As you increase the lambda, you are decreasing the budget, i.e. penalizing more. For your plot, each line represents a coefficient whose value is going to zero as you are decreasing the budget or as you are penalizing more(increasing the lambda). To choose the best lambda, you should consult the MSE vs lambda plot. I would say though the faster a coefficient is shrinking the less important it is in prediction; e.g. I think the dotted dashed blue one should have more information than the solid black one. Try plotting a summary, a legend and an MSE vs lambda too. If you choose your best lambda and then look at your betas you can see which betas are more important by looking at their values at the optimum lambda.
How to interpret ridge regression plot
The ridge regression will penalize your coefficients, such that those that are the least effective in your estimation will "shrink" the fastest. Imagine you have a budget allocated and each coefficien
How to interpret ridge regression plot The ridge regression will penalize your coefficients, such that those that are the least effective in your estimation will "shrink" the fastest. Imagine you have a budget allocated and each coefficient can take some to play a role in the estimation. Naturally those who are more important will take more of the budget. As you increase the lambda, you are decreasing the budget, i.e. penalizing more. For your plot, each line represents a coefficient whose value is going to zero as you are decreasing the budget or as you are penalizing more(increasing the lambda). To choose the best lambda, you should consult the MSE vs lambda plot. I would say though the faster a coefficient is shrinking the less important it is in prediction; e.g. I think the dotted dashed blue one should have more information than the solid black one. Try plotting a summary, a legend and an MSE vs lambda too. If you choose your best lambda and then look at your betas you can see which betas are more important by looking at their values at the optimum lambda.
How to interpret ridge regression plot The ridge regression will penalize your coefficients, such that those that are the least effective in your estimation will "shrink" the fastest. Imagine you have a budget allocated and each coefficien
38,628
How to interpret ridge regression plot
I know you say I am interested in explanation and not prediction but this is a road fraught with dangers. A model that does not predict its response well is not useful for explanation. Explanation and prediction are not independent desires, one should complement and enhance the other at all times, in both directions. So given that, if you want to draw some explanation from a ridge regression, first find the most predictive model. Tune your regularization parameter $\lambda$ with cross validation or a hold out data set, there is lots of fantastic advice in this forum on how to do that. Once you have the most predictive $\lambda$, examine the coefficients of that model. If you want confidence intervals on these coefficients, bootstrap fit your fixed $\lambda$ model on your dataset, and empirically estimate the variance in the parameters. Also what is the output of select(mod)? The documentation of ridgelm is spotty, and doesn't say what select does, but you can get some clue from: GCV: vector of GCV values kHKB: HKB estimate of the ridge constant kLW: L-W estimate of the ridge constant So it looks like it's pulling out these three attributes (well the minimum of the first attribute) and wrapping them in a nice display. I can't recover the value it has for the minimum GCV though: > min(mod$GCV) / nrow(longley) [1] 0.007473027 so that remains a mystery.
How to interpret ridge regression plot
I know you say I am interested in explanation and not prediction but this is a road fraught with dangers. A model that does not predict its response well is not useful for explanation. Explanation
How to interpret ridge regression plot I know you say I am interested in explanation and not prediction but this is a road fraught with dangers. A model that does not predict its response well is not useful for explanation. Explanation and prediction are not independent desires, one should complement and enhance the other at all times, in both directions. So given that, if you want to draw some explanation from a ridge regression, first find the most predictive model. Tune your regularization parameter $\lambda$ with cross validation or a hold out data set, there is lots of fantastic advice in this forum on how to do that. Once you have the most predictive $\lambda$, examine the coefficients of that model. If you want confidence intervals on these coefficients, bootstrap fit your fixed $\lambda$ model on your dataset, and empirically estimate the variance in the parameters. Also what is the output of select(mod)? The documentation of ridgelm is spotty, and doesn't say what select does, but you can get some clue from: GCV: vector of GCV values kHKB: HKB estimate of the ridge constant kLW: L-W estimate of the ridge constant So it looks like it's pulling out these three attributes (well the minimum of the first attribute) and wrapping them in a nice display. I can't recover the value it has for the minimum GCV though: > min(mod$GCV) / nrow(longley) [1] 0.007473027 so that remains a mystery.
How to interpret ridge regression plot I know you say I am interested in explanation and not prediction but this is a road fraught with dangers. A model that does not predict its response well is not useful for explanation. Explanation
38,629
How to interpret ridge regression plot
Better check this? http://www.mathworks.com/help/stats/ridge.html There is a better picture an several more examples..... Though i dont know if you have Matlab... EDIT - Command execution Both the plot on the question and the image on the link show the ridge traces, showing the $k$ regularization coefficient on the x-axis, and the estimated coefficients on the y-axis. As reference, the ridge regresion plot comes by doing regularization on linear regression $b=AX$ for improving conditioning, by placing a Ridge (Tikhonov Regularization) Matrix $K$: $$x_e=(A^TA+K^TK)^{-1}A^Tb$$ When having $K=kI$, we reduce the matrix selection to a scalar $k^2I$, which is done in both Matlab and R packages. I tried to reproduce the results, for the same data, but apparently R do not make regularization on the constant term, and Matlab does it. Or R is lying you.... Regarding the question, it appears none of these algorithms deliver the p-values, the t-test or the MSE traces, so a coefficient assessment can't be done right away from there without an additional piece of code...
How to interpret ridge regression plot
Better check this? http://www.mathworks.com/help/stats/ridge.html There is a better picture an several more examples..... Though i dont know if you have Matlab... EDIT - Command execution Both the plo
How to interpret ridge regression plot Better check this? http://www.mathworks.com/help/stats/ridge.html There is a better picture an several more examples..... Though i dont know if you have Matlab... EDIT - Command execution Both the plot on the question and the image on the link show the ridge traces, showing the $k$ regularization coefficient on the x-axis, and the estimated coefficients on the y-axis. As reference, the ridge regresion plot comes by doing regularization on linear regression $b=AX$ for improving conditioning, by placing a Ridge (Tikhonov Regularization) Matrix $K$: $$x_e=(A^TA+K^TK)^{-1}A^Tb$$ When having $K=kI$, we reduce the matrix selection to a scalar $k^2I$, which is done in both Matlab and R packages. I tried to reproduce the results, for the same data, but apparently R do not make regularization on the constant term, and Matlab does it. Or R is lying you.... Regarding the question, it appears none of these algorithms deliver the p-values, the t-test or the MSE traces, so a coefficient assessment can't be done right away from there without an additional piece of code...
How to interpret ridge regression plot Better check this? http://www.mathworks.com/help/stats/ridge.html There is a better picture an several more examples..... Though i dont know if you have Matlab... EDIT - Command execution Both the plo
38,630
How to interpret ridge regression plot
One thing to watch out for is when a coefficient crosses zero, as Year does in the example. If you made future predictions without regularization $(\lambda = 0)$, you have a negative trend over time; however, this is an artifact of multicollinearity in the data. With not very much regularization $(\lambda > 0.005)$, the effect reverses, so we would expect $y$ to increase in the future, everything else being equal.
How to interpret ridge regression plot
One thing to watch out for is when a coefficient crosses zero, as Year does in the example. If you made future predictions without regularization $(\lambda = 0)$, you have a negative trend over time
How to interpret ridge regression plot One thing to watch out for is when a coefficient crosses zero, as Year does in the example. If you made future predictions without regularization $(\lambda = 0)$, you have a negative trend over time; however, this is an artifact of multicollinearity in the data. With not very much regularization $(\lambda > 0.005)$, the effect reverses, so we would expect $y$ to increase in the future, everything else being equal.
How to interpret ridge regression plot One thing to watch out for is when a coefficient crosses zero, as Year does in the example. If you made future predictions without regularization $(\lambda = 0)$, you have a negative trend over time
38,631
versus (vs.): how to properly use this word in data analysis
On plotting: I regard it as natural and conventional to say -- for scatter plots, line plots, and so forth -- that I plot Y versus X and in each case always to mention the response first and the other variable second. Thus I (say that I) plot temperature versus or against time, and wheat yield versus or against rainfall. Why natural? Whenever you assert that such a relationship exists, the idea is that (in the examples given) temperature depends on, or is a function of, time, rather than vice versa; and wheat yield depends on, or is a function of, rainfall, rather than vice versa. (Relationships involving feedback loops may be an exception to this principle without undermining it.) Thus the distinction is tied up with a strong convention that response (outcome, result, effect, dependent variable) is plotted on the vertical or $y$ axis and the other variable on the horizontal or $x$ axis. It is also tied up with a strong convention in mathematical discussions to use wording such as $y$ is a function of $x$, where the outcome is mentioned first. However, we are, admittedly, at least in part talking about conventions here, rather than questions on which an inescapable logic can be identified. I was surprised to start hearing the opposite usage of versus about a decade ago. I have no precise recollection of when I first heard versus being used in the sense identified here, but I suspect it was in secondary school (high school) science in the 1960s: as with many such usages, my science teachers tended to use language as was natural to them, rather to reflect on usage or to explain it. This is the way that much scientific language is handed down, despite the thousands and thousands of textbooks. Also on plotting: There are many exceptions even with scatter and line plots to the convention of response on $y$ axis. In the Earth and environmental sciences, it is common that depth below or height above the surface is on the $y$ axis: what could be more vertical? This is the way that people in those fields think about cores, bores and similar traces below ground or in the atmosphere. Detail: vs for versus is a contraction, not an abbreviation; many (British) English style guides advise not using a stop or period in such cases. EDIT 12 April 2018/14 May 2020 Wild and Seber (2000, pp.107-108) in their outstandingly good introductory text explain it in this way: 'In plotting it is conventional to use the vertical axis to represent the response variable $Y$ and the horizontal axis to represent the explanatory variable $X$. (This is what is conventionally meant when we say that "We plot $Y$ versus $X$.")' Yet in the same chapter they use the opposite convention for versus in captions on p.102 and p.111 and the convention they urge on p.109. See also pp.140, 527, 534, 537. From this I take three points: (a) There are explanations of the convention I urge in the literature. (b) We are talking conventions, not rules. (c) First-rate authors can be just as inconsistent as anyone else over minor details. Wild, C.J. and Seber, G.A.F. 2000. Chance Encounters: A First Course in Data Analysis and Inference. New York: John Wiley.
versus (vs.): how to properly use this word in data analysis
On plotting: I regard it as natural and conventional to say -- for scatter plots, line plots, and so forth -- that I plot Y versus X and in each case always to mention the response first and the other
versus (vs.): how to properly use this word in data analysis On plotting: I regard it as natural and conventional to say -- for scatter plots, line plots, and so forth -- that I plot Y versus X and in each case always to mention the response first and the other variable second. Thus I (say that I) plot temperature versus or against time, and wheat yield versus or against rainfall. Why natural? Whenever you assert that such a relationship exists, the idea is that (in the examples given) temperature depends on, or is a function of, time, rather than vice versa; and wheat yield depends on, or is a function of, rainfall, rather than vice versa. (Relationships involving feedback loops may be an exception to this principle without undermining it.) Thus the distinction is tied up with a strong convention that response (outcome, result, effect, dependent variable) is plotted on the vertical or $y$ axis and the other variable on the horizontal or $x$ axis. It is also tied up with a strong convention in mathematical discussions to use wording such as $y$ is a function of $x$, where the outcome is mentioned first. However, we are, admittedly, at least in part talking about conventions here, rather than questions on which an inescapable logic can be identified. I was surprised to start hearing the opposite usage of versus about a decade ago. I have no precise recollection of when I first heard versus being used in the sense identified here, but I suspect it was in secondary school (high school) science in the 1960s: as with many such usages, my science teachers tended to use language as was natural to them, rather to reflect on usage or to explain it. This is the way that much scientific language is handed down, despite the thousands and thousands of textbooks. Also on plotting: There are many exceptions even with scatter and line plots to the convention of response on $y$ axis. In the Earth and environmental sciences, it is common that depth below or height above the surface is on the $y$ axis: what could be more vertical? This is the way that people in those fields think about cores, bores and similar traces below ground or in the atmosphere. Detail: vs for versus is a contraction, not an abbreviation; many (British) English style guides advise not using a stop or period in such cases. EDIT 12 April 2018/14 May 2020 Wild and Seber (2000, pp.107-108) in their outstandingly good introductory text explain it in this way: 'In plotting it is conventional to use the vertical axis to represent the response variable $Y$ and the horizontal axis to represent the explanatory variable $X$. (This is what is conventionally meant when we say that "We plot $Y$ versus $X$.")' Yet in the same chapter they use the opposite convention for versus in captions on p.102 and p.111 and the convention they urge on p.109. See also pp.140, 527, 534, 537. From this I take three points: (a) There are explanations of the convention I urge in the literature. (b) We are talking conventions, not rules. (c) First-rate authors can be just as inconsistent as anyone else over minor details. Wild, C.J. and Seber, G.A.F. 2000. Chance Encounters: A First Course in Data Analysis and Inference. New York: John Wiley.
versus (vs.): how to properly use this word in data analysis On plotting: I regard it as natural and conventional to say -- for scatter plots, line plots, and so forth -- that I plot Y versus X and in each case always to mention the response first and the other
38,632
versus (vs.): how to properly use this word in data analysis
On meta.CV, @Glen_b argues that "versus" isn't really a technical term in statistics. I agree. I think it is typically used in a loose and colloquial way. When used in a statistical context, the term mostly denotes comparison (as opposed to its sports-related competitive meaning). Thus, it is natural to apply "versus" when discussing the comparison of conditions or groups. With regard to the issue of interpreting the sign on the effect size (mean difference), I would argue that our understanding that the treatment mean is higher when 'treatment vs. control' is positive comes mainly from our understanding of the nature of treatments and controls rather than this understanding being carried by the meaning of "versus". If you refer to the comparison of 'group A vs. group B', there is nothing intrinsic to group A-ness to indicate whether its status is the default or the contrasting condition. As a result, that situation would be ambiguous. Because subtraction is not commutative / moves from left to right, I think the interpretation of a positive difference meaning that first group listed is larger would have preference. Nonetheless, I think the situation is intrinsically ambiguous and we should be careful to explicitly state which is larger. For example, 'we compared A vs. B and found that A is significantly larger with a standardized mean difference of d'. On the other hand, when we make a scatterplot, we aren't actually comparing X and Y. In truth, we are examining the relationship between them. As a result, it is a bit of a misnomer to use "versus" in that context. (N.B., I say it all the time.) Regarding my own personal usage, I think of 'X vs. Y' as more analogous to correlation (i.e., non-directional) than regression1 (where the order is meaningful). Again, I think this usage is ambiguous and that it is incumbent upon us to be explicit via the use of axis labels and figure captions, etc. My general point here is that all of this language is, or potentially is, ambiguous. I think it is fine to say, but we should supplement these somehow to make the meaning clear. 1. I do use the term "against" (as in 'I plotted Y against X') more purposefully. In that case, Y goes on the y-axis and/or is the response variable.
versus (vs.): how to properly use this word in data analysis
On meta.CV, @Glen_b argues that "versus" isn't really a technical term in statistics. I agree. I think it is typically used in a loose and colloquial way. When used in a statistical context, the te
versus (vs.): how to properly use this word in data analysis On meta.CV, @Glen_b argues that "versus" isn't really a technical term in statistics. I agree. I think it is typically used in a loose and colloquial way. When used in a statistical context, the term mostly denotes comparison (as opposed to its sports-related competitive meaning). Thus, it is natural to apply "versus" when discussing the comparison of conditions or groups. With regard to the issue of interpreting the sign on the effect size (mean difference), I would argue that our understanding that the treatment mean is higher when 'treatment vs. control' is positive comes mainly from our understanding of the nature of treatments and controls rather than this understanding being carried by the meaning of "versus". If you refer to the comparison of 'group A vs. group B', there is nothing intrinsic to group A-ness to indicate whether its status is the default or the contrasting condition. As a result, that situation would be ambiguous. Because subtraction is not commutative / moves from left to right, I think the interpretation of a positive difference meaning that first group listed is larger would have preference. Nonetheless, I think the situation is intrinsically ambiguous and we should be careful to explicitly state which is larger. For example, 'we compared A vs. B and found that A is significantly larger with a standardized mean difference of d'. On the other hand, when we make a scatterplot, we aren't actually comparing X and Y. In truth, we are examining the relationship between them. As a result, it is a bit of a misnomer to use "versus" in that context. (N.B., I say it all the time.) Regarding my own personal usage, I think of 'X vs. Y' as more analogous to correlation (i.e., non-directional) than regression1 (where the order is meaningful). Again, I think this usage is ambiguous and that it is incumbent upon us to be explicit via the use of axis labels and figure captions, etc. My general point here is that all of this language is, or potentially is, ambiguous. I think it is fine to say, but we should supplement these somehow to make the meaning clear. 1. I do use the term "against" (as in 'I plotted Y against X') more purposefully. In that case, Y goes on the y-axis and/or is the response variable.
versus (vs.): how to properly use this word in data analysis On meta.CV, @Glen_b argues that "versus" isn't really a technical term in statistics. I agree. I think it is typically used in a loose and colloquial way. When used in a statistical context, the te
38,633
versus (vs.): how to properly use this word in data analysis
Versus just means "difference." It does not imply any kind of baseline-treatment relationship. You have a mean for Group A and mean for Group B. Testing A vs. B tests if the differences in the means is significantly greater than zero. Testing B vs. A is the same thing. Casual relationships or identifying one of the groups as the baseline involves extra-statistical qualitative information.
versus (vs.): how to properly use this word in data analysis
Versus just means "difference." It does not imply any kind of baseline-treatment relationship. You have a mean for Group A and mean for Group B. Testing A vs. B tests if the differences in the means i
versus (vs.): how to properly use this word in data analysis Versus just means "difference." It does not imply any kind of baseline-treatment relationship. You have a mean for Group A and mean for Group B. Testing A vs. B tests if the differences in the means is significantly greater than zero. Testing B vs. A is the same thing. Casual relationships or identifying one of the groups as the baseline involves extra-statistical qualitative information.
versus (vs.): how to properly use this word in data analysis Versus just means "difference." It does not imply any kind of baseline-treatment relationship. You have a mean for Group A and mean for Group B. Testing A vs. B tests if the differences in the means i
38,634
Conceptual understanding of standard deviation vs average distance from the mean
The standard deviation is the square root of the variance, as you might know. The variance is calculated by summing up the squared deviation from the mean, and dividing it by $n$. $$\sigma^2 = \frac{\sum_{i}^{n} (x_i-\mu)^2 }{n}$$ Every difference $(x-\mu)$ is squared. When you take the square root of the variance, it is not the same as taking the square root of every $(x-\mu)^2$ and sum it up afterwards... Because of the square term, the variance (and thus the standard deviation) gives more weight to more distant values and can't be negative, as positive and negative values get both positive when squared. It is also wrong to calculate the standard deviation for all positive and negative values separately. The values lose their sign when they get squared. Hope this helps,
Conceptual understanding of standard deviation vs average distance from the mean
The standard deviation is the square root of the variance, as you might know. The variance is calculated by summing up the squared deviation from the mean, and dividing it by $n$. $$\sigma^2 = \frac{
Conceptual understanding of standard deviation vs average distance from the mean The standard deviation is the square root of the variance, as you might know. The variance is calculated by summing up the squared deviation from the mean, and dividing it by $n$. $$\sigma^2 = \frac{\sum_{i}^{n} (x_i-\mu)^2 }{n}$$ Every difference $(x-\mu)$ is squared. When you take the square root of the variance, it is not the same as taking the square root of every $(x-\mu)^2$ and sum it up afterwards... Because of the square term, the variance (and thus the standard deviation) gives more weight to more distant values and can't be negative, as positive and negative values get both positive when squared. It is also wrong to calculate the standard deviation for all positive and negative values separately. The values lose their sign when they get squared. Hope this helps,
Conceptual understanding of standard deviation vs average distance from the mean The standard deviation is the square root of the variance, as you might know. The variance is calculated by summing up the squared deviation from the mean, and dividing it by $n$. $$\sigma^2 = \frac{
38,635
Conceptual understanding of standard deviation vs average distance from the mean
Basil covered the essential issue (that the average distance from the mean is not the same thing as the standard deviation), but I think there's some additional points that should be added to that. The mean of the absolute deviations (from the mean) - which is the average distance from the mean - will always be $\leq$ than the root-mean-square deviation from the mean, which is the standard deviation This follows from the triangle inequality, for example, or from Jensen's inequality. In the case of data drawn from a normal distribution, in large samples the mean deviation is $\sqrt{2/\pi}$ times the standard deviation ... which is about 0.798, so that's your 80%.
Conceptual understanding of standard deviation vs average distance from the mean
Basil covered the essential issue (that the average distance from the mean is not the same thing as the standard deviation), but I think there's some additional points that should be added to that. Th
Conceptual understanding of standard deviation vs average distance from the mean Basil covered the essential issue (that the average distance from the mean is not the same thing as the standard deviation), but I think there's some additional points that should be added to that. The mean of the absolute deviations (from the mean) - which is the average distance from the mean - will always be $\leq$ than the root-mean-square deviation from the mean, which is the standard deviation This follows from the triangle inequality, for example, or from Jensen's inequality. In the case of data drawn from a normal distribution, in large samples the mean deviation is $\sqrt{2/\pi}$ times the standard deviation ... which is about 0.798, so that's your 80%.
Conceptual understanding of standard deviation vs average distance from the mean Basil covered the essential issue (that the average distance from the mean is not the same thing as the standard deviation), but I think there's some additional points that should be added to that. Th
38,636
Covariance greater than Variance?
I am not quite sure what the question is asking. The absolute value of $\operatorname{cov}(X,Y)$, the covariance of $X$ and $Y$ is no larger than $\sigma_X\sigma_Y$ which is the geometric mean of the variances of $X$ and $Y$. Since $$\min\{\sigma^2_X,\, \sigma^2_Y\} \leq \sigma_X\sigma_Y \leq \max\{\sigma^2_X,\, \sigma^2_Y\},$$ it is certainly possible for the covariance to exceed $\min\{\sigma^2_X,\, \sigma^2_Y\}$. In other words, the question Is it not true in general that $\big|\operatorname{cov}(X, Y)\big| \leq \min\{\sigma^2_X,\, \sigma^2_Y\}$? has the answer that the desired relationship is not always feasible. Consider, for example, $X$ and $Y$ having variances $6^2$ and $8^2$ respectively. Suppose that the correlation coefficient $\rho$ is $\displaystyle \frac 56$. Then, $\displaystyle\operatorname{cov}(X, Y) = \rho\sigma_X\sigma_Y = \frac 56 \times 6 \times 8 = 40 > \min \{\sigma^2_X,\, \sigma^2_Y\} = 36,$ and $\displaystyle \frac{\sigma_X}{\sigma_Y} = \frac{6}{8} < \rho = \frac 56.$ With a smaller correlation coefficient $\displaystyle \frac 34$, we have that the covariance is $36$, same as $\sigma_X^2$, and of course $\displaystyle \frac{\sigma_X}{\sigma_Y} = \frac{6}{8} = \rho$. If $\rho$ were even smaller, say $\displaystyle\rho = \frac 12$, the covariance is $24$ which is smaller than $\sigma_X^2$. So it would appear that the OP is asking whether most real-life data sets that people have encountered (with $\sigma_X < \sigma_Y$) happen to have correlation coefficients that do not exceed $\displaystyle\frac{\sigma_X}{\sigma_Y}$ in magnitude.
Covariance greater than Variance?
I am not quite sure what the question is asking. The absolute value of $\operatorname{cov}(X,Y)$, the covariance of $X$ and $Y$ is no larger than $\sigma_X\sigma_Y$ which is the geometric mean of the
Covariance greater than Variance? I am not quite sure what the question is asking. The absolute value of $\operatorname{cov}(X,Y)$, the covariance of $X$ and $Y$ is no larger than $\sigma_X\sigma_Y$ which is the geometric mean of the variances of $X$ and $Y$. Since $$\min\{\sigma^2_X,\, \sigma^2_Y\} \leq \sigma_X\sigma_Y \leq \max\{\sigma^2_X,\, \sigma^2_Y\},$$ it is certainly possible for the covariance to exceed $\min\{\sigma^2_X,\, \sigma^2_Y\}$. In other words, the question Is it not true in general that $\big|\operatorname{cov}(X, Y)\big| \leq \min\{\sigma^2_X,\, \sigma^2_Y\}$? has the answer that the desired relationship is not always feasible. Consider, for example, $X$ and $Y$ having variances $6^2$ and $8^2$ respectively. Suppose that the correlation coefficient $\rho$ is $\displaystyle \frac 56$. Then, $\displaystyle\operatorname{cov}(X, Y) = \rho\sigma_X\sigma_Y = \frac 56 \times 6 \times 8 = 40 > \min \{\sigma^2_X,\, \sigma^2_Y\} = 36,$ and $\displaystyle \frac{\sigma_X}{\sigma_Y} = \frac{6}{8} < \rho = \frac 56.$ With a smaller correlation coefficient $\displaystyle \frac 34$, we have that the covariance is $36$, same as $\sigma_X^2$, and of course $\displaystyle \frac{\sigma_X}{\sigma_Y} = \frac{6}{8} = \rho$. If $\rho$ were even smaller, say $\displaystyle\rho = \frac 12$, the covariance is $24$ which is smaller than $\sigma_X^2$. So it would appear that the OP is asking whether most real-life data sets that people have encountered (with $\sigma_X < \sigma_Y$) happen to have correlation coefficients that do not exceed $\displaystyle\frac{\sigma_X}{\sigma_Y}$ in magnitude.
Covariance greater than Variance? I am not quite sure what the question is asking. The absolute value of $\operatorname{cov}(X,Y)$, the covariance of $X$ and $Y$ is no larger than $\sigma_X\sigma_Y$ which is the geometric mean of the
38,637
Covariance greater than Variance?
Unless I've made some mistake (which I may have, I'm not clear-headed right now): $\text{Cov}(X,Y)/\text{Var}(X) = \rho \sigma_y/\sigma_x$ can be made smaller or larger by choosing different units for $x$ or $y$ (e.g. going from dollars to cents or meters to millimeters or vice-versa). As a result, I think you can do it simply by changing units.
Covariance greater than Variance?
Unless I've made some mistake (which I may have, I'm not clear-headed right now): $\text{Cov}(X,Y)/\text{Var}(X) = \rho \sigma_y/\sigma_x$ can be made smaller or larger by choosing different units for
Covariance greater than Variance? Unless I've made some mistake (which I may have, I'm not clear-headed right now): $\text{Cov}(X,Y)/\text{Var}(X) = \rho \sigma_y/\sigma_x$ can be made smaller or larger by choosing different units for $x$ or $y$ (e.g. going from dollars to cents or meters to millimeters or vice-versa). As a result, I think you can do it simply by changing units.
Covariance greater than Variance? Unless I've made some mistake (which I may have, I'm not clear-headed right now): $\text{Cov}(X,Y)/\text{Var}(X) = \rho \sigma_y/\sigma_x$ can be made smaller or larger by choosing different units for
38,638
Covariance greater than Variance?
The trees data from the R datasets package: This data set provides measurements of the girth, height and volume of timber in 31 felled black cherry trees. Note that girth is the diameter of the tree (in inches) measured at 4 ft 6 in above the ground. The correlation between girth & height is $0.52$, while the ratio of the standard deviations of girth to height is only $\frac{3.14''}{76.4''}=0.04$. It's rather common to measure correlations between measurements of large magnitude to measurements of small magnitude with roughly similar coefficients of variation, & there's no particular reason such correlations should be small. Note that if girth were expressed as circumference rather than diameter the ratio of standard deviations would be 0.13; in fact some queer way of expressing the observations might always be found to raise the value of the ratio over that of the correlation. So the question's about not just what's likely to be observed, but what's likely to be written down.
Covariance greater than Variance?
The trees data from the R datasets package: This data set provides measurements of the girth, height and volume of timber in 31 felled black cherry trees. Note that girth is the diameter of the
Covariance greater than Variance? The trees data from the R datasets package: This data set provides measurements of the girth, height and volume of timber in 31 felled black cherry trees. Note that girth is the diameter of the tree (in inches) measured at 4 ft 6 in above the ground. The correlation between girth & height is $0.52$, while the ratio of the standard deviations of girth to height is only $\frac{3.14''}{76.4''}=0.04$. It's rather common to measure correlations between measurements of large magnitude to measurements of small magnitude with roughly similar coefficients of variation, & there's no particular reason such correlations should be small. Note that if girth were expressed as circumference rather than diameter the ratio of standard deviations would be 0.13; in fact some queer way of expressing the observations might always be found to raise the value of the ratio over that of the correlation. So the question's about not just what's likely to be observed, but what's likely to be written down.
Covariance greater than Variance? The trees data from the R datasets package: This data set provides measurements of the girth, height and volume of timber in 31 felled black cherry trees. Note that girth is the diameter of the
38,639
Distribution of linear combination of OLS regression coefficients
It's actually not true that your variables need to be independent so that their sum will be normal. If X and Y are jointly normally distributed with mean $\mu_{1} $ and $\mu_{2} $ and variance $\sigma_{1}^{2}$ and $\sigma_{2}^{2}$ with correlation $\rho $ then Z is still normally distributed with mean $\mu_{1}+\mu_{2} $ and variance $\sqrt { \sigma_{2}^{2}+ \sigma_{1}^{2}+2 \rho \sigma_{2} \sigma_{1}}$ Hopefully that gives you what you need.
Distribution of linear combination of OLS regression coefficients
It's actually not true that your variables need to be independent so that their sum will be normal. If X and Y are jointly normally distributed with mean $\mu_{1} $ and $\mu_{2} $ and variance $\sigm
Distribution of linear combination of OLS regression coefficients It's actually not true that your variables need to be independent so that their sum will be normal. If X and Y are jointly normally distributed with mean $\mu_{1} $ and $\mu_{2} $ and variance $\sigma_{1}^{2}$ and $\sigma_{2}^{2}$ with correlation $\rho $ then Z is still normally distributed with mean $\mu_{1}+\mu_{2} $ and variance $\sqrt { \sigma_{2}^{2}+ \sigma_{1}^{2}+2 \rho \sigma_{2} \sigma_{1}}$ Hopefully that gives you what you need.
Distribution of linear combination of OLS regression coefficients It's actually not true that your variables need to be independent so that their sum will be normal. If X and Y are jointly normally distributed with mean $\mu_{1} $ and $\mu_{2} $ and variance $\sigm
38,640
Distribution of linear combination of OLS regression coefficients
it would be better to explain this in matrix notation. Suppose the general Gauss-Markov linear model $$\mathbf{y = X \boldsymbol \beta + \boldsymbol \epsilon}$$For your case, $\mathbf{X}$ = ($\mathbf{1}$, $\mathbf{x_1}$, $\mathbf{x_2}$) and $\mathbf{\boldsymbol \beta} = (\alpha, \; \beta_1 \; \beta_2)'.$ The OLS estimator is $$\hat{\boldsymbol \beta} = \left(\mathbf{X}'\mathbf{X} \right)^{-1}\mathbf{X}'\mathbf{y}.$$ Since $\mathbf{y} \ \sim \ N(\mathbf{X \boldsymbol \beta}, \sigma^2)$, then $$\hat{\boldsymbol \beta} \ \sim \ N \left(\mathbf{X \boldsymbol \beta}, \sigma^2(\mathbf{X}'\mathbf{X})^{-1} \right).$$ Based on the above result, you are able to derive the distribution of $Z = \alpha_1 \beta_1 + \alpha_2 \beta_2$ if you write $Z = \boldsymbol \lambda' \boldsymbol \beta$, where $\lambda' = (0, \alpha_1, \alpha_2)$. Denote correspondingly that $$\hat{Z} = \alpha_1 \hat{\beta}_1 + \alpha_2 \hat{\beta}_2 = \boldsymbol \lambda' \hat{\boldsymbol \beta},$$ then you can easily get that $$\frac{\hat{Z} - Z}{\sigma\sqrt{\boldsymbol \lambda' (\mathbf{X}' \mathbf{X})^{-1} \boldsymbol \lambda}} \ \sim \ N(0, 1).$$ Note that $\sigma$ is unknown, so you cannot construct the confidence interval based on the normal distribution. A rigorous approach is to derive the confidence interval based on a $t$-test statistic (I just ignore the derivation but give the result, you should be able to find details in any linear model book or through website). Specifically,$$\frac{\hat{Z} - Z}{\hat{\sigma} \sqrt{\boldsymbol \lambda' (\mathbf{X}' \mathbf{X})^{-1} \boldsymbol \lambda}} \ \sim \ t(n-p),$$ where $\hat{\sigma}^2 = \frac{\mathbf{y}'(\mathbf{I - P_X}) \mathbf{y}}{n-p}$, $\mathbf{P_X}$ is the projection matrix, and $p = rank(\mathbf{X})$.
Distribution of linear combination of OLS regression coefficients
it would be better to explain this in matrix notation. Suppose the general Gauss-Markov linear model $$\mathbf{y = X \boldsymbol \beta + \boldsymbol \epsilon}$$For your case, $\mathbf{X}$ = ($\mathbf{
Distribution of linear combination of OLS regression coefficients it would be better to explain this in matrix notation. Suppose the general Gauss-Markov linear model $$\mathbf{y = X \boldsymbol \beta + \boldsymbol \epsilon}$$For your case, $\mathbf{X}$ = ($\mathbf{1}$, $\mathbf{x_1}$, $\mathbf{x_2}$) and $\mathbf{\boldsymbol \beta} = (\alpha, \; \beta_1 \; \beta_2)'.$ The OLS estimator is $$\hat{\boldsymbol \beta} = \left(\mathbf{X}'\mathbf{X} \right)^{-1}\mathbf{X}'\mathbf{y}.$$ Since $\mathbf{y} \ \sim \ N(\mathbf{X \boldsymbol \beta}, \sigma^2)$, then $$\hat{\boldsymbol \beta} \ \sim \ N \left(\mathbf{X \boldsymbol \beta}, \sigma^2(\mathbf{X}'\mathbf{X})^{-1} \right).$$ Based on the above result, you are able to derive the distribution of $Z = \alpha_1 \beta_1 + \alpha_2 \beta_2$ if you write $Z = \boldsymbol \lambda' \boldsymbol \beta$, where $\lambda' = (0, \alpha_1, \alpha_2)$. Denote correspondingly that $$\hat{Z} = \alpha_1 \hat{\beta}_1 + \alpha_2 \hat{\beta}_2 = \boldsymbol \lambda' \hat{\boldsymbol \beta},$$ then you can easily get that $$\frac{\hat{Z} - Z}{\sigma\sqrt{\boldsymbol \lambda' (\mathbf{X}' \mathbf{X})^{-1} \boldsymbol \lambda}} \ \sim \ N(0, 1).$$ Note that $\sigma$ is unknown, so you cannot construct the confidence interval based on the normal distribution. A rigorous approach is to derive the confidence interval based on a $t$-test statistic (I just ignore the derivation but give the result, you should be able to find details in any linear model book or through website). Specifically,$$\frac{\hat{Z} - Z}{\hat{\sigma} \sqrt{\boldsymbol \lambda' (\mathbf{X}' \mathbf{X})^{-1} \boldsymbol \lambda}} \ \sim \ t(n-p),$$ where $\hat{\sigma}^2 = \frac{\mathbf{y}'(\mathbf{I - P_X}) \mathbf{y}}{n-p}$, $\mathbf{P_X}$ is the projection matrix, and $p = rank(\mathbf{X})$.
Distribution of linear combination of OLS regression coefficients it would be better to explain this in matrix notation. Suppose the general Gauss-Markov linear model $$\mathbf{y = X \boldsymbol \beta + \boldsymbol \epsilon}$$For your case, $\mathbf{X}$ = ($\mathbf{
38,641
How to get a valid distance metric?
First of all, in many applications you do not need a distance metric, but a dissimilarity will be okay. So make sure that triangle inequality is needed. In mathematics, triangle inequality is part of the definition of a metric, and distances in mathematics are synonymous to metrics. But in database literature, often distances are not required to be metric. Second, we cannot recommend a metric for your data, if we don't know your data. Third, Cosine is closely related to Euclidean distance. Assuming that all your data is normalized to unit length ($||x||=1=||y||$), then \begin{align*} \text{Euclid}^2(x,y)&=\sum_i (x_i-y_i)^2\\ &=\sum_ix^2+\sum_iy^2-2\sum_i x_iy_i\\ &=1+1-2\cdot x\cdot y\\ &=2(1-x\cdot y) \end{align*} Therefore, if your data is normalized to unit length, $$ \sqrt{1-x\cdot y} $$ is a metric. Because as just shown, $\sqrt{1-x\cdot y}=\sqrt{\frac{1}{2}}\text{Euclid}(x,y)$. While this may get you overly excited that there is a metric based on the dot product, recall that this only holds if all your data lives on the unit circle and this is just Euclidean metric. If this is the behaviour you want, normalize your data and use Euclidean distance... Cosine distance is exactly this normalization. It includes normalization terms for the length of the vectors to ensure they are of unit length... If your data is sparse, and you can afford to keep all vector lengths in memory, then this may be a faster way to compute Euclidean distance. If you have a sparsity of $s$, the expected sparsity of the dot product is $s^2$, so this can yield a substantial performance benefit of $1/s$, if you have a good implementation. Update: it was pointed out to me that computing Euclidean this way can suffer from a numerical instability called "catastrophic cancellation".
How to get a valid distance metric?
First of all, in many applications you do not need a distance metric, but a dissimilarity will be okay. So make sure that triangle inequality is needed. In mathematics, triangle inequality is part of
How to get a valid distance metric? First of all, in many applications you do not need a distance metric, but a dissimilarity will be okay. So make sure that triangle inequality is needed. In mathematics, triangle inequality is part of the definition of a metric, and distances in mathematics are synonymous to metrics. But in database literature, often distances are not required to be metric. Second, we cannot recommend a metric for your data, if we don't know your data. Third, Cosine is closely related to Euclidean distance. Assuming that all your data is normalized to unit length ($||x||=1=||y||$), then \begin{align*} \text{Euclid}^2(x,y)&=\sum_i (x_i-y_i)^2\\ &=\sum_ix^2+\sum_iy^2-2\sum_i x_iy_i\\ &=1+1-2\cdot x\cdot y\\ &=2(1-x\cdot y) \end{align*} Therefore, if your data is normalized to unit length, $$ \sqrt{1-x\cdot y} $$ is a metric. Because as just shown, $\sqrt{1-x\cdot y}=\sqrt{\frac{1}{2}}\text{Euclid}(x,y)$. While this may get you overly excited that there is a metric based on the dot product, recall that this only holds if all your data lives on the unit circle and this is just Euclidean metric. If this is the behaviour you want, normalize your data and use Euclidean distance... Cosine distance is exactly this normalization. It includes normalization terms for the length of the vectors to ensure they are of unit length... If your data is sparse, and you can afford to keep all vector lengths in memory, then this may be a faster way to compute Euclidean distance. If you have a sparsity of $s$, the expected sparsity of the dot product is $s^2$, so this can yield a substantial performance benefit of $1/s$, if you have a good implementation. Update: it was pointed out to me that computing Euclidean this way can suffer from a numerical instability called "catastrophic cancellation".
How to get a valid distance metric? First of all, in many applications you do not need a distance metric, but a dissimilarity will be okay. So make sure that triangle inequality is needed. In mathematics, triangle inequality is part of
38,642
How to get a valid distance metric?
What are the proper distance metric? Please name some examples. Euclidean distance, Levenshtein distance, Manhattan distance. As you write, any distance metric satisfies the definition of a distance, so there are quite a number of them. In one of Gunnar Carlsson's articles on topological data analysis, he uses (what I believe are) original distance metrics for use in analysis of the particular subject matter of the paper. The only limitations are the constraints of the definition of a distance. Are Dice's coefficient and Jaccard index proper distance metric? Dice's coefficient violates the triangle inequality. From Wikipedia: The simplest counterexample of this is given by the three sets {a}, {b}, and {a,b}, the distance between the first two being 1, and the difference between the third and each of the others being one-third. To satisfy the triangle inequality, the sum of any two of these three sides must be greater than or equal to the remaining side. However, the distance between {a} and {a,b} plus the distance between {b} and {a,b} equals 2/3 and is therefore less than the distance between {a} and {b} which is 1. The Jaccard index is not a distance metric. But subtracting the Jaccard index from 1 yields a distance metric. Are there any disadvantages of using dot product? (One of the reasons for the popularity of dot product is that it is very efficient to evaluate). It's impossible to answer this question comprehensively without additional context. If your application requires a proper distance function, then perhaps you'll get into some trouble.
How to get a valid distance metric?
What are the proper distance metric? Please name some examples. Euclidean distance, Levenshtein distance, Manhattan distance. As you write, any distance metric satisfies the definition of a distance,
How to get a valid distance metric? What are the proper distance metric? Please name some examples. Euclidean distance, Levenshtein distance, Manhattan distance. As you write, any distance metric satisfies the definition of a distance, so there are quite a number of them. In one of Gunnar Carlsson's articles on topological data analysis, he uses (what I believe are) original distance metrics for use in analysis of the particular subject matter of the paper. The only limitations are the constraints of the definition of a distance. Are Dice's coefficient and Jaccard index proper distance metric? Dice's coefficient violates the triangle inequality. From Wikipedia: The simplest counterexample of this is given by the three sets {a}, {b}, and {a,b}, the distance between the first two being 1, and the difference between the third and each of the others being one-third. To satisfy the triangle inequality, the sum of any two of these three sides must be greater than or equal to the remaining side. However, the distance between {a} and {a,b} plus the distance between {b} and {a,b} equals 2/3 and is therefore less than the distance between {a} and {b} which is 1. The Jaccard index is not a distance metric. But subtracting the Jaccard index from 1 yields a distance metric. Are there any disadvantages of using dot product? (One of the reasons for the popularity of dot product is that it is very efficient to evaluate). It's impossible to answer this question comprehensively without additional context. If your application requires a proper distance function, then perhaps you'll get into some trouble.
How to get a valid distance metric? What are the proper distance metric? Please name some examples. Euclidean distance, Levenshtein distance, Manhattan distance. As you write, any distance metric satisfies the definition of a distance,
38,643
How to get a valid distance metric?
The choice of the metric depends on your problem. See this answer for a discussion on the cosine similarity and how to build a distance function based on it. Also, there is a reference on a paper discussing the issue of distance functions in a high dimensional setting. The problem with cross product is that you need to use it with care. For example, it is usually a good idea to whiten your data (center and scale variance to 1) so that different scaling in features do not bias your results.
How to get a valid distance metric?
The choice of the metric depends on your problem. See this answer for a discussion on the cosine similarity and how to build a distance function based on it. Also, there is a reference on a paper disc
How to get a valid distance metric? The choice of the metric depends on your problem. See this answer for a discussion on the cosine similarity and how to build a distance function based on it. Also, there is a reference on a paper discussing the issue of distance functions in a high dimensional setting. The problem with cross product is that you need to use it with care. For example, it is usually a good idea to whiten your data (center and scale variance to 1) so that different scaling in features do not bias your results.
How to get a valid distance metric? The choice of the metric depends on your problem. See this answer for a discussion on the cosine similarity and how to build a distance function based on it. Also, there is a reference on a paper disc
38,644
What is the name of a distribution within $[a, b]$ but with a sloped straight line density?
A distribution with a linear PDF can be considered a special case of a (truncated) Pareto distribution, Beta distribution, or power distribution. Only particular values of the parameters in these distribution families will give a linear PDF, of course. Among other things, such a distribution is a truncated Generalized Pareto Distribution. The Wikipedia parameterization of the PDF (for the case where the endpoints $a$ and $b$ are finite, as they must be for a linear graph) can be expressed in terms of the basic function $$f(x; \eta) = (1 - \eta x)^{1/\eta - 1}$$ for $0\le x \le 1/\eta$. (This can then be rescaled by $\sigma\ne 0$ and shifted by $\mu$ to obtain the most general form. Here I have set $\eta = -\xi$ which will be a positive number.) Evidently this function is linear in $x$ if and only if $1/\eta - 1=1$; that is, $\eta = 1/2$ (and so $\xi=-1/2$). Its graph equals zero at the endpoint $x=1/\eta = 2$. By truncating it, though, we would obtain the general form stated in the question. The same thing can be obtained by truncating a generalized Beta Distribution. Its PDF is proportional to $$x^{\alpha-1}(1-x)^{\beta-1}$$ for $0\le x \le 1$, whence the Beta$(2,1)$ and Beta$(1,2)$ distributions are linear. As with the Pareto$(\xi=-1/2)$ distribution, the graphs of these PDFs are zero at one endpoint. The general linear PDF described in question is obtained in the same way via truncation, rescaling, and shifting. Finally, Mathematica defines a "power distribution" as one having a PDF proportional to $$f(x; k, a) = x^{a-1}$$ for $0 \le x \le 1/k$. The case $a=2$ gives a linear PDF, identical to Beta$(2,1)$. Rescaling it by $k$ and recentering it with a parameter $\mu$, and (once again) truncating it will yield the general PDF described in the question.
What is the name of a distribution within $[a, b]$ but with a sloped straight line density?
A distribution with a linear PDF can be considered a special case of a (truncated) Pareto distribution, Beta distribution, or power distribution. Only particular values of the parameters in these dis
What is the name of a distribution within $[a, b]$ but with a sloped straight line density? A distribution with a linear PDF can be considered a special case of a (truncated) Pareto distribution, Beta distribution, or power distribution. Only particular values of the parameters in these distribution families will give a linear PDF, of course. Among other things, such a distribution is a truncated Generalized Pareto Distribution. The Wikipedia parameterization of the PDF (for the case where the endpoints $a$ and $b$ are finite, as they must be for a linear graph) can be expressed in terms of the basic function $$f(x; \eta) = (1 - \eta x)^{1/\eta - 1}$$ for $0\le x \le 1/\eta$. (This can then be rescaled by $\sigma\ne 0$ and shifted by $\mu$ to obtain the most general form. Here I have set $\eta = -\xi$ which will be a positive number.) Evidently this function is linear in $x$ if and only if $1/\eta - 1=1$; that is, $\eta = 1/2$ (and so $\xi=-1/2$). Its graph equals zero at the endpoint $x=1/\eta = 2$. By truncating it, though, we would obtain the general form stated in the question. The same thing can be obtained by truncating a generalized Beta Distribution. Its PDF is proportional to $$x^{\alpha-1}(1-x)^{\beta-1}$$ for $0\le x \le 1$, whence the Beta$(2,1)$ and Beta$(1,2)$ distributions are linear. As with the Pareto$(\xi=-1/2)$ distribution, the graphs of these PDFs are zero at one endpoint. The general linear PDF described in question is obtained in the same way via truncation, rescaling, and shifting. Finally, Mathematica defines a "power distribution" as one having a PDF proportional to $$f(x; k, a) = x^{a-1}$$ for $0 \le x \le 1/k$. The case $a=2$ gives a linear PDF, identical to Beta$(2,1)$. Rescaling it by $k$ and recentering it with a parameter $\mu$, and (once again) truncating it will yield the general PDF described in the question.
What is the name of a distribution within $[a, b]$ but with a sloped straight line density? A distribution with a linear PDF can be considered a special case of a (truncated) Pareto distribution, Beta distribution, or power distribution. Only particular values of the parameters in these dis
38,645
What is the name of a distribution within $[a, b]$ but with a sloped straight line density?
It might be the triangular distribution. The general triangular distribution with support $[a,b]$ has 1 parameter $c\in[a,b]$ corresponding to the mode. When $c=a$ or $c=b$, the p.d.f. is a straight line segment.
What is the name of a distribution within $[a, b]$ but with a sloped straight line density?
It might be the triangular distribution. The general triangular distribution with support $[a,b]$ has 1 parameter $c\in[a,b]$ corresponding to the mode. When $c=a$ or $c=b$, the p.d.f. is a straight l
What is the name of a distribution within $[a, b]$ but with a sloped straight line density? It might be the triangular distribution. The general triangular distribution with support $[a,b]$ has 1 parameter $c\in[a,b]$ corresponding to the mode. When $c=a$ or $c=b$, the p.d.f. is a straight line segment.
What is the name of a distribution within $[a, b]$ but with a sloped straight line density? It might be the triangular distribution. The general triangular distribution with support $[a,b]$ has 1 parameter $c\in[a,b]$ corresponding to the mode. When $c=a$ or $c=b$, the p.d.f. is a straight l
38,646
Why does Fisher's method yield $p\gg 0.5$ when combining several p-values all equal to $0.5$?
The way that Fisher's approach measures the combined effect of p-values is to effectively look at their product (the ordering of possible statistics when adding the logs is the same as when taking the product). It then asks whether this is unusually low compared to what you'd find with random p-values when the null is true (which would be draws from a uniform distribution in that case). In the product, very small values "pull down" the value more than very large values push it up (compared to a typical value). A large probability can't be above 1, but a small one can be very small indeed. By that product metric, a product of many 0.5's is unusual compared to a product of random uniform values. If your results were really showing nothing, you should really see some small p's in there, but you don't have any. By collecting a lot of 0.5's you're basically getting into the 'even less discrepant than randomness' territory ... which still wouldn't cause you to reject, of course. The histogram is of the Fisher combined p-value for a sample of 1000 sets of 10 random (uniform) p-values, the green curve is the true density, that for a $\chi^2_{20}$, while the brown line marks the position for the combined $p$ when there are 10 values, each with $p=0.5$. Note that large values - values in the right tail - are highly significant. The set of ten $0.5$ values is well into the left tail, so they don't indicate significance. While Fisher's method has much to commend it (not least that it makes a lot of intuitive sense to work with a product of independent p-values), there's nothing actually sacrosanct about that metric. You could, for example, add p-values, and compare that sum to the distribution of a sum of random p-values. By that metric, a lot of p=0.5's would give you a value right in the middle. (There are many other ways one might combine p-values. I mostly just go with Fisher, though, it usually captures what I want a "combined p-value" to capture.)
Why does Fisher's method yield $p\gg 0.5$ when combining several p-values all equal to $0.5$?
The way that Fisher's approach measures the combined effect of p-values is to effectively look at their product (the ordering of possible statistics when adding the logs is the same as when taking the
Why does Fisher's method yield $p\gg 0.5$ when combining several p-values all equal to $0.5$? The way that Fisher's approach measures the combined effect of p-values is to effectively look at their product (the ordering of possible statistics when adding the logs is the same as when taking the product). It then asks whether this is unusually low compared to what you'd find with random p-values when the null is true (which would be draws from a uniform distribution in that case). In the product, very small values "pull down" the value more than very large values push it up (compared to a typical value). A large probability can't be above 1, but a small one can be very small indeed. By that product metric, a product of many 0.5's is unusual compared to a product of random uniform values. If your results were really showing nothing, you should really see some small p's in there, but you don't have any. By collecting a lot of 0.5's you're basically getting into the 'even less discrepant than randomness' territory ... which still wouldn't cause you to reject, of course. The histogram is of the Fisher combined p-value for a sample of 1000 sets of 10 random (uniform) p-values, the green curve is the true density, that for a $\chi^2_{20}$, while the brown line marks the position for the combined $p$ when there are 10 values, each with $p=0.5$. Note that large values - values in the right tail - are highly significant. The set of ten $0.5$ values is well into the left tail, so they don't indicate significance. While Fisher's method has much to commend it (not least that it makes a lot of intuitive sense to work with a product of independent p-values), there's nothing actually sacrosanct about that metric. You could, for example, add p-values, and compare that sum to the distribution of a sum of random p-values. By that metric, a lot of p=0.5's would give you a value right in the middle. (There are many other ways one might combine p-values. I mostly just go with Fisher, though, it usually captures what I want a "combined p-value" to capture.)
Why does Fisher's method yield $p\gg 0.5$ when combining several p-values all equal to $0.5$? The way that Fisher's approach measures the combined effect of p-values is to effectively look at their product (the ordering of possible statistics when adding the logs is the same as when taking the
38,647
Why does Fisher's method yield $p\gg 0.5$ when combining several p-values all equal to $0.5$?
A p-value of 0.5 is not the "most insignificant p-value". It says that if the null hypothesis is true, than 50% of the time you would expect a result that is at least as extreme as the observed result. You could call that a "typical" result under the null hypothesis, but certainly not "most insignificant". A p-value of 1 would be the "most insignificant p-value".
Why does Fisher's method yield $p\gg 0.5$ when combining several p-values all equal to $0.5$?
A p-value of 0.5 is not the "most insignificant p-value". It says that if the null hypothesis is true, than 50% of the time you would expect a result that is at least as extreme as the observed result
Why does Fisher's method yield $p\gg 0.5$ when combining several p-values all equal to $0.5$? A p-value of 0.5 is not the "most insignificant p-value". It says that if the null hypothesis is true, than 50% of the time you would expect a result that is at least as extreme as the observed result. You could call that a "typical" result under the null hypothesis, but certainly not "most insignificant". A p-value of 1 would be the "most insignificant p-value".
Why does Fisher's method yield $p\gg 0.5$ when combining several p-values all equal to $0.5$? A p-value of 0.5 is not the "most insignificant p-value". It says that if the null hypothesis is true, than 50% of the time you would expect a result that is at least as extreme as the observed result
38,648
How to smear a histogram
There appears to be a difference in terminology (as so often is the case with a discipline used in so many areas), so I'm not 100% sure, but I think they're referring to kernel density estimation, with a Gaussian kernel, but performed on binned data. [Edit: if someone familiar with how the term "Gaussian smearing" is used in physics - and how it would apply in relation to a histogram - could chime in, that would be good] In that case, each observation is replaced with a scaled density (or more generally, a kernel, which needn't necessarily be positive), which has been scaled to area $\frac{1}{n}$, centered on the observation. The scale (the standard deviation in the case of a Gaussian) of the kernel is a tunable smoothing parameter. Presumably the intent is to place observations at bin-centers before smoothing (this discreteness leads to a need for larger kernel bandwidth to achieve a given amount of smoothness, though if the bins are small relative to the default bandwidth the effect is very small); another alternative would be to spread the observations throughout their bins, though I suspect this isn't the intent of the request in your case. In the unbinned case, here's an illustration of the idea. Below are 7 observations (5.996 22.687 8.868 15.883 14.727 5.896 9.397) marked with "+" symbols (there are two almost coincident at the far left), with one point (14.727) marked in bold red. The little red density there is the gaussian kernel of bandwidth 2.5; there are gray kernels placed above each of the other points. The green dashed curve is the kernel density estimate, which came from summing up the densities at a fine grid of points and joining to give a smooth curve. The bandwidth I used in my illustration is a little small. There are automatic methods for choosing the bandwidth that usually do pretty well. I did my calculations in R; like many other stats packages, it comes with a function to automate the whole procedure, so I could do the following to get a plot like the green dashed one: a = c(5.996, 22.687, 8.868, 15.883, 14.727, 5.896, 9.397) plot(density(a,bw=2.5)) Below is the kernel density estimate generated by the default bandwidth in the same program (i.e. by using density(a)): As you see, it's wider, and achieves a smoother looking result. Of course, 7 observations is unrealistic; here's a histogram and kernel density estimate for 200 observations from a gamma(10,1): If you click on the kde tag that your post has (I believe it was added in an edit), you'll see many posts on the topic here. There's also a kernel tag by the look of it, which mostly seems to be doing the same job (though kernel can refer to other things than density estimation), and that has more hits still.
How to smear a histogram
There appears to be a difference in terminology (as so often is the case with a discipline used in so many areas), so I'm not 100% sure, but I think they're referring to kernel density estimation, wit
How to smear a histogram There appears to be a difference in terminology (as so often is the case with a discipline used in so many areas), so I'm not 100% sure, but I think they're referring to kernel density estimation, with a Gaussian kernel, but performed on binned data. [Edit: if someone familiar with how the term "Gaussian smearing" is used in physics - and how it would apply in relation to a histogram - could chime in, that would be good] In that case, each observation is replaced with a scaled density (or more generally, a kernel, which needn't necessarily be positive), which has been scaled to area $\frac{1}{n}$, centered on the observation. The scale (the standard deviation in the case of a Gaussian) of the kernel is a tunable smoothing parameter. Presumably the intent is to place observations at bin-centers before smoothing (this discreteness leads to a need for larger kernel bandwidth to achieve a given amount of smoothness, though if the bins are small relative to the default bandwidth the effect is very small); another alternative would be to spread the observations throughout their bins, though I suspect this isn't the intent of the request in your case. In the unbinned case, here's an illustration of the idea. Below are 7 observations (5.996 22.687 8.868 15.883 14.727 5.896 9.397) marked with "+" symbols (there are two almost coincident at the far left), with one point (14.727) marked in bold red. The little red density there is the gaussian kernel of bandwidth 2.5; there are gray kernels placed above each of the other points. The green dashed curve is the kernel density estimate, which came from summing up the densities at a fine grid of points and joining to give a smooth curve. The bandwidth I used in my illustration is a little small. There are automatic methods for choosing the bandwidth that usually do pretty well. I did my calculations in R; like many other stats packages, it comes with a function to automate the whole procedure, so I could do the following to get a plot like the green dashed one: a = c(5.996, 22.687, 8.868, 15.883, 14.727, 5.896, 9.397) plot(density(a,bw=2.5)) Below is the kernel density estimate generated by the default bandwidth in the same program (i.e. by using density(a)): As you see, it's wider, and achieves a smoother looking result. Of course, 7 observations is unrealistic; here's a histogram and kernel density estimate for 200 observations from a gamma(10,1): If you click on the kde tag that your post has (I believe it was added in an edit), you'll see many posts on the topic here. There's also a kernel tag by the look of it, which mostly seems to be doing the same job (though kernel can refer to other things than density estimation), and that has more hits still.
How to smear a histogram There appears to be a difference in terminology (as so often is the case with a discipline used in so many areas), so I'm not 100% sure, but I think they're referring to kernel density estimation, wit
38,649
How to smear a histogram
The requester is probably referring to a kernel density smoother as Glen_b notes, but "smearing" is evocative of the shadowgram featured in the book Visual Statistics. To address the issue of choosing the right bin or kernel width, the shadowgram is a overlay of many different width choices.
How to smear a histogram
The requester is probably referring to a kernel density smoother as Glen_b notes, but "smearing" is evocative of the shadowgram featured in the book Visual Statistics. To address the issue of choosing
How to smear a histogram The requester is probably referring to a kernel density smoother as Glen_b notes, but "smearing" is evocative of the shadowgram featured in the book Visual Statistics. To address the issue of choosing the right bin or kernel width, the shadowgram is a overlay of many different width choices.
How to smear a histogram The requester is probably referring to a kernel density smoother as Glen_b notes, but "smearing" is evocative of the shadowgram featured in the book Visual Statistics. To address the issue of choosing
38,650
When using linear regression analysis to get the fitted values of an outcome, why do the more extreme values tend to be predicted closer to the mean?
Basically, it's because the regression isn't perfect. Suppose you had purely random data - no relation between the dependent and independent variables. Then the best prediction of the DV for every subject would be the mean of the DV. Suppose you had a perfect relationship; then you be able to exactly predict the DV. In reality, it's always somewhere in between, and the predicted values are between the mean and the actual values.
When using linear regression analysis to get the fitted values of an outcome, why do the more extrem
Basically, it's because the regression isn't perfect. Suppose you had purely random data - no relation between the dependent and independent variables. Then the best prediction of the DV for every sub
When using linear regression analysis to get the fitted values of an outcome, why do the more extreme values tend to be predicted closer to the mean? Basically, it's because the regression isn't perfect. Suppose you had purely random data - no relation between the dependent and independent variables. Then the best prediction of the DV for every subject would be the mean of the DV. Suppose you had a perfect relationship; then you be able to exactly predict the DV. In reality, it's always somewhere in between, and the predicted values are between the mean and the actual values.
When using linear regression analysis to get the fitted values of an outcome, why do the more extrem Basically, it's because the regression isn't perfect. Suppose you had purely random data - no relation between the dependent and independent variables. Then the best prediction of the DV for every sub
38,651
When using linear regression analysis to get the fitted values of an outcome, why do the more extreme values tend to be predicted closer to the mean?
Usual conventions The usual conventional name and definition are residuals = outcome $-$ fitted Similarly, the usual conventional plot is residuals (y axis) versus fitted (x axis). In R, given something like mymodel = lm(outcome ~ predictor1 + predictor2 + predictor3) then plot(mymodel) gives that plot as one of a portfolio. That's usually a much easier plot to think about your plot. You can also plot outcome versus fitted. The first is critical, in exposing weaknesses of the model, and the second is positive, in focusing on the strength of the model. What you originally did The usual set-up is that of observed $y$, fitted $\hat y$, and residual $e$ linked by $y = \hat y + e$ With this set-up a plot of $y$ versus $e$ has an overall slope of $+1$. There is variability around that overall slope, but it is not correlated on the whole with the residuals. Your original difference variable contained negated residuals, so the overall slope became $-1$. Note on $R^2$ In your case, note that the two values of $R^2$ add to 1, i.e. $0.42 + 0.58 = 1$, which follows from the fact that the proportion of variance "explained" by the model and the proportion of variance "not explained" are mutually exclusive. (The correlation between residual and fitted is zero, so the covariance term is zero.) Summary The spirit of your original plot (now deleted) was right, but it's better just to plot residuals versus fitted. Indeed what you did puzzled or confused some people because they misread a procedure that is not standard for one that is. The pattern of your plot makes sense and is not incorrect or anomalous.
When using linear regression analysis to get the fitted values of an outcome, why do the more extrem
Usual conventions The usual conventional name and definition are residuals = outcome $-$ fitted Similarly, the usual conventional plot is residuals (y axis) versus fitted (x axis). In R, given so
When using linear regression analysis to get the fitted values of an outcome, why do the more extreme values tend to be predicted closer to the mean? Usual conventions The usual conventional name and definition are residuals = outcome $-$ fitted Similarly, the usual conventional plot is residuals (y axis) versus fitted (x axis). In R, given something like mymodel = lm(outcome ~ predictor1 + predictor2 + predictor3) then plot(mymodel) gives that plot as one of a portfolio. That's usually a much easier plot to think about your plot. You can also plot outcome versus fitted. The first is critical, in exposing weaknesses of the model, and the second is positive, in focusing on the strength of the model. What you originally did The usual set-up is that of observed $y$, fitted $\hat y$, and residual $e$ linked by $y = \hat y + e$ With this set-up a plot of $y$ versus $e$ has an overall slope of $+1$. There is variability around that overall slope, but it is not correlated on the whole with the residuals. Your original difference variable contained negated residuals, so the overall slope became $-1$. Note on $R^2$ In your case, note that the two values of $R^2$ add to 1, i.e. $0.42 + 0.58 = 1$, which follows from the fact that the proportion of variance "explained" by the model and the proportion of variance "not explained" are mutually exclusive. (The correlation between residual and fitted is zero, so the covariance term is zero.) Summary The spirit of your original plot (now deleted) was right, but it's better just to plot residuals versus fitted. Indeed what you did puzzled or confused some people because they misread a procedure that is not standard for one that is. The pattern of your plot makes sense and is not incorrect or anomalous.
When using linear regression analysis to get the fitted values of an outcome, why do the more extrem Usual conventions The usual conventional name and definition are residuals = outcome $-$ fitted Similarly, the usual conventional plot is residuals (y axis) versus fitted (x axis). In R, given so
38,652
When using linear regression analysis to get the fitted values of an outcome, why do the more extreme values tend to be predicted closer to the mean?
This figure shows that there seems to be a significant variable you are missing. Because the residuals have a clear trend, i.e containing important information. If you have not more variable on the data, maybe you could try the interactions.
When using linear regression analysis to get the fitted values of an outcome, why do the more extrem
This figure shows that there seems to be a significant variable you are missing. Because the residuals have a clear trend, i.e containing important information. If you have not more variable on the da
When using linear regression analysis to get the fitted values of an outcome, why do the more extreme values tend to be predicted closer to the mean? This figure shows that there seems to be a significant variable you are missing. Because the residuals have a clear trend, i.e containing important information. If you have not more variable on the data, maybe you could try the interactions.
When using linear regression analysis to get the fitted values of an outcome, why do the more extrem This figure shows that there seems to be a significant variable you are missing. Because the residuals have a clear trend, i.e containing important information. If you have not more variable on the da
38,653
When using linear regression analysis to get the fitted values of an outcome, why do the more extreme values tend to be predicted closer to the mean?
The concept is not new and is called Regression to the Mean, or Regression towards the Mean, see here for history and detail. In fact the story goes that this is how regression analysis (linear models, least squares, etc.) ended up being called "regression".
When using linear regression analysis to get the fitted values of an outcome, why do the more extrem
The concept is not new and is called Regression to the Mean, or Regression towards the Mean, see here for history and detail. In fact the story goes that this is how regression analysis (linear model
When using linear regression analysis to get the fitted values of an outcome, why do the more extreme values tend to be predicted closer to the mean? The concept is not new and is called Regression to the Mean, or Regression towards the Mean, see here for history and detail. In fact the story goes that this is how regression analysis (linear models, least squares, etc.) ended up being called "regression".
When using linear regression analysis to get the fitted values of an outcome, why do the more extrem The concept is not new and is called Regression to the Mean, or Regression towards the Mean, see here for history and detail. In fact the story goes that this is how regression analysis (linear model
38,654
Performance evaluation of a model: MAPE in R
You could always code it yourself: mape <- function(y, yhat) mean(abs((y - yhat)/y))
Performance evaluation of a model: MAPE in R
You could always code it yourself: mape <- function(y, yhat) mean(abs((y - yhat)/y))
Performance evaluation of a model: MAPE in R You could always code it yourself: mape <- function(y, yhat) mean(abs((y - yhat)/y))
Performance evaluation of a model: MAPE in R You could always code it yourself: mape <- function(y, yhat) mean(abs((y - yhat)/y))
38,655
Performance evaluation of a model: MAPE in R
For MAPE, use the following function: mape <- function(actual,pred){ mape <- mean(abs((actual - pred)/actual))*100 return (mape) } For the formula, you can refer to the following link: http://www.forecastpro.com/Trends/forecasting101August2011.html
Performance evaluation of a model: MAPE in R
For MAPE, use the following function: mape <- function(actual,pred){ mape <- mean(abs((actual - pred)/actual))*100 return (mape) } For the formula, you can refer to the
Performance evaluation of a model: MAPE in R For MAPE, use the following function: mape <- function(actual,pred){ mape <- mean(abs((actual - pred)/actual))*100 return (mape) } For the formula, you can refer to the following link: http://www.forecastpro.com/Trends/forecasting101August2011.html
Performance evaluation of a model: MAPE in R For MAPE, use the following function: mape <- function(actual,pred){ mape <- mean(abs((actual - pred)/actual))*100 return (mape) } For the formula, you can refer to the
38,656
Are there examples of more informative PCA plots? [duplicate]
In my humble opinion, it depends on what you want out of the PCA, but that there are two simple plots that are quite common and might be helpful: To know which variables have high loadings in which principal component, a simple barplot of loadings (as small multiples) will display this pretty clearly. To look for patterns between samples a scatterplot of scores can sometimes help (e.g. in genetics when you've genotyped a bunch of individuals, a scatterplot of PC1 and PC2 is usually used to look for population patterns). If you know variable or sample groupings a priori, colour the dots and bars. Cheers, m. ps. I hope it's not bad form to include links, but I've written a small post about these plots and making them in my favourite software. http://martinsbioblogg.wordpress.com/2013/06/26/using-r-two-plots-of-principal-component-analysis/
Are there examples of more informative PCA plots? [duplicate]
In my humble opinion, it depends on what you want out of the PCA, but that there are two simple plots that are quite common and might be helpful: To know which variables have high loadings in which p
Are there examples of more informative PCA plots? [duplicate] In my humble opinion, it depends on what you want out of the PCA, but that there are two simple plots that are quite common and might be helpful: To know which variables have high loadings in which principal component, a simple barplot of loadings (as small multiples) will display this pretty clearly. To look for patterns between samples a scatterplot of scores can sometimes help (e.g. in genetics when you've genotyped a bunch of individuals, a scatterplot of PC1 and PC2 is usually used to look for population patterns). If you know variable or sample groupings a priori, colour the dots and bars. Cheers, m. ps. I hope it's not bad form to include links, but I've written a small post about these plots and making them in my favourite software. http://martinsbioblogg.wordpress.com/2013/06/26/using-r-two-plots-of-principal-component-analysis/
Are there examples of more informative PCA plots? [duplicate] In my humble opinion, it depends on what you want out of the PCA, but that there are two simple plots that are quite common and might be helpful: To know which variables have high loadings in which p
38,657
Are there examples of more informative PCA plots? [duplicate]
Here are a few clues. Depending on what the variables are, the loadings themselves can be very informative. For example, in PCAs derived from gene expression data, I can use the loadings in combination with Gene Ontology to test for enrichment of particular terms in the variables with large absolute loadings. Biplots are very useful if you have just a few variables, as they can neatly visualise which variables are important for which component. However, they are not very practical if there are too many variables (my package, pca3d, allows to select N "top" variables from each component to be shown of the plot; it's called "pca3d" but also has a "pca2d" function for regular 2D plots). If you have categorical variables that group the samples into different groups, then simply colouring the points on a standard plot can be very informative (this is the main purpose of pca3d).
Are there examples of more informative PCA plots? [duplicate]
Here are a few clues. Depending on what the variables are, the loadings themselves can be very informative. For example, in PCAs derived from gene expression data, I can use the loadings in combinati
Are there examples of more informative PCA plots? [duplicate] Here are a few clues. Depending on what the variables are, the loadings themselves can be very informative. For example, in PCAs derived from gene expression data, I can use the loadings in combination with Gene Ontology to test for enrichment of particular terms in the variables with large absolute loadings. Biplots are very useful if you have just a few variables, as they can neatly visualise which variables are important for which component. However, they are not very practical if there are too many variables (my package, pca3d, allows to select N "top" variables from each component to be shown of the plot; it's called "pca3d" but also has a "pca2d" function for regular 2D plots). If you have categorical variables that group the samples into different groups, then simply colouring the points on a standard plot can be very informative (this is the main purpose of pca3d).
Are there examples of more informative PCA plots? [duplicate] Here are a few clues. Depending on what the variables are, the loadings themselves can be very informative. For example, in PCAs derived from gene expression data, I can use the loadings in combinati
38,658
Are there examples of more informative PCA plots? [duplicate]
I find biplots very useful. A biplot represents both the variables and the observations in a space defined by two (or three) components. The length and direction of the vector representing each variable tell you how much it loads on these two components, directly addressing the question at the end of the first paragraph. You can find more information on Wikipedia and many examples/code through google.
Are there examples of more informative PCA plots? [duplicate]
I find biplots very useful. A biplot represents both the variables and the observations in a space defined by two (or three) components. The length and direction of the vector representing each variab
Are there examples of more informative PCA plots? [duplicate] I find biplots very useful. A biplot represents both the variables and the observations in a space defined by two (or three) components. The length and direction of the vector representing each variable tell you how much it loads on these two components, directly addressing the question at the end of the first paragraph. You can find more information on Wikipedia and many examples/code through google.
Are there examples of more informative PCA plots? [duplicate] I find biplots very useful. A biplot represents both the variables and the observations in a space defined by two (or three) components. The length and direction of the vector representing each variab
38,659
Rounding when making a histogram
I don't believe there is any convention (see summary of statistical packages below.) For considering the distribution of a set of data (e.g. examining rough normality of residuals in a linear regression with a histogram), this decision is somewhat arbitrary (but will potentially change the shape of the figure, depending on how many observations fall on the breakpoints and the size of the dataset). Different computer packages handle values on the breakpoints in different ways by default. If you're wanting to present your histogram in e.g. a paper/thesis, then it would of course be helpful to describe which type of interval you are using. To look at interval terminology (see Wikipedia for more consideration of this, or this StackOverflow question for an R specific example): The first example you give would be described as left closed, right open intervals, where the first bin is $0 \leq x < 10$; second bin is $10 \leq x < 20$; etc. So 10 would go in the second bin. The second example are right closed, left open intervals, where the first bin is $0 < x \leq 10$; second bin is $10 < x \leq 20$; etc. And here 10 would go in the first bin. By default, R plots histograms with right closed, left open intervals (see the right=TRUE option for this function); SAS defaults to left-closed, right open (see rtinclude option on that page). I think Stata does left-closed, right open intervals too. I have a preference for left closed, right open intervals as I find these histograms more intuitive to read/explain. But for data exploration I'd usually just go with the defaults in my package (nowadays, R). QUICK EDIT AFTER POSTING: I'll just add, apropos of your labelling point, that standard practice is to just label the boundaries/breaks in the x-axis (0, 10, 20, etc.), rather than both interval ends (0-9, 10-19 etc.) with the latter having the disadvantage that it is more cluttered, and ambiguous what happens to a 9.5, or a 9.9999 (and so forth.)
Rounding when making a histogram
I don't believe there is any convention (see summary of statistical packages below.) For considering the distribution of a set of data (e.g. examining rough normality of residuals in a linear regressi
Rounding when making a histogram I don't believe there is any convention (see summary of statistical packages below.) For considering the distribution of a set of data (e.g. examining rough normality of residuals in a linear regression with a histogram), this decision is somewhat arbitrary (but will potentially change the shape of the figure, depending on how many observations fall on the breakpoints and the size of the dataset). Different computer packages handle values on the breakpoints in different ways by default. If you're wanting to present your histogram in e.g. a paper/thesis, then it would of course be helpful to describe which type of interval you are using. To look at interval terminology (see Wikipedia for more consideration of this, or this StackOverflow question for an R specific example): The first example you give would be described as left closed, right open intervals, where the first bin is $0 \leq x < 10$; second bin is $10 \leq x < 20$; etc. So 10 would go in the second bin. The second example are right closed, left open intervals, where the first bin is $0 < x \leq 10$; second bin is $10 < x \leq 20$; etc. And here 10 would go in the first bin. By default, R plots histograms with right closed, left open intervals (see the right=TRUE option for this function); SAS defaults to left-closed, right open (see rtinclude option on that page). I think Stata does left-closed, right open intervals too. I have a preference for left closed, right open intervals as I find these histograms more intuitive to read/explain. But for data exploration I'd usually just go with the defaults in my package (nowadays, R). QUICK EDIT AFTER POSTING: I'll just add, apropos of your labelling point, that standard practice is to just label the boundaries/breaks in the x-axis (0, 10, 20, etc.), rather than both interval ends (0-9, 10-19 etc.) with the latter having the disadvantage that it is more cluttered, and ambiguous what happens to a 9.5, or a 9.9999 (and so forth.)
Rounding when making a histogram I don't believe there is any convention (see summary of statistical packages below.) For considering the distribution of a set of data (e.g. examining rough normality of residuals in a linear regressi
38,660
Rounding when making a histogram
Pretty late to the party here, but I think that there is a convention. The convention seems to be that lower (left) bounds are included in a class. [1-3] Specifically answering your example question - the value of 20 should go into the 20-30 bin. However, as observed by James already - the convention isn't always observed (notably the Excel data analysis histogram tool which works opposite by including upper bounds instead of lower bounds). I've also found references that describe both (left or right inclusion) as conventions [4] and at least one reference that says to specify which you are using [5] implying that either is acceptable (as long as the audience knows which you have used). Note: I was specifically looking for conventions exactly because I'm trying to determine how important it is to modify Excel histograms to match the convention when I found this question. I did find a lot of other links by googling histogram conventions. References: Analyzing Data and Making Decisions, Statistics for Business. Judith Skuce, Pearson, 2013. http://www.oswego.edu/~srp/stats/hist_con.htm http://www.math.ntua.gr/~fouskakis/SS/graphical%20summaries.pdf http://www.stat.berkeley.edu/~stark/SticiGui/Text/gloss.htm#e http://sites.stat.psu.edu/~ajw13/stat500/notes/lesson01/lesson01_03.html
Rounding when making a histogram
Pretty late to the party here, but I think that there is a convention. The convention seems to be that lower (left) bounds are included in a class. [1-3] Specifically answering your example question -
Rounding when making a histogram Pretty late to the party here, but I think that there is a convention. The convention seems to be that lower (left) bounds are included in a class. [1-3] Specifically answering your example question - the value of 20 should go into the 20-30 bin. However, as observed by James already - the convention isn't always observed (notably the Excel data analysis histogram tool which works opposite by including upper bounds instead of lower bounds). I've also found references that describe both (left or right inclusion) as conventions [4] and at least one reference that says to specify which you are using [5] implying that either is acceptable (as long as the audience knows which you have used). Note: I was specifically looking for conventions exactly because I'm trying to determine how important it is to modify Excel histograms to match the convention when I found this question. I did find a lot of other links by googling histogram conventions. References: Analyzing Data and Making Decisions, Statistics for Business. Judith Skuce, Pearson, 2013. http://www.oswego.edu/~srp/stats/hist_con.htm http://www.math.ntua.gr/~fouskakis/SS/graphical%20summaries.pdf http://www.stat.berkeley.edu/~stark/SticiGui/Text/gloss.htm#e http://sites.stat.psu.edu/~ajw13/stat500/notes/lesson01/lesson01_03.html
Rounding when making a histogram Pretty late to the party here, but I think that there is a convention. The convention seems to be that lower (left) bounds are included in a class. [1-3] Specifically answering your example question -
38,661
Rounding when making a histogram
While there's no particularly broad convention, to me it would make some sense to follow the convention used for right-continuous CDFs, and so in general make histograms include their left boundary but not their right, so the $i$-th interval is $[l_i,l_{i+1})$. This at least seems to be done slightly more commonly, but I have no solid evidence to support that impression.
Rounding when making a histogram
While there's no particularly broad convention, to me it would make some sense to follow the convention used for right-continuous CDFs, and so in general make histograms include their left boundary bu
Rounding when making a histogram While there's no particularly broad convention, to me it would make some sense to follow the convention used for right-continuous CDFs, and so in general make histograms include their left boundary but not their right, so the $i$-th interval is $[l_i,l_{i+1})$. This at least seems to be done slightly more commonly, but I have no solid evidence to support that impression.
Rounding when making a histogram While there's no particularly broad convention, to me it would make some sense to follow the convention used for right-continuous CDFs, and so in general make histograms include their left boundary bu
38,662
Decision Tree as variable selection for Logistic Regression
If you have access to LASSO and your predictors are all numeric then that is a good choice as Peter mentioned. If you have a massive number of predictors as experienced often in fields like marketing - then this can be computationally too expensive. In that case, a tree can be used, but a random forest or gradient boosted regression tree would likely be better choices as variable importance is more robust (for the same reason boosted and bagged trees are expected to be more stable). The party package in R might be another good choice, as the conditional inference trees and associated forests and variable importance measures are purported to be less biased. Party VI Outside of statistics, Googling "Feature Selection" might give you more ideas.
Decision Tree as variable selection for Logistic Regression
If you have access to LASSO and your predictors are all numeric then that is a good choice as Peter mentioned. If you have a massive number of predictors as experienced often in fields like marketing
Decision Tree as variable selection for Logistic Regression If you have access to LASSO and your predictors are all numeric then that is a good choice as Peter mentioned. If you have a massive number of predictors as experienced often in fields like marketing - then this can be computationally too expensive. In that case, a tree can be used, but a random forest or gradient boosted regression tree would likely be better choices as variable importance is more robust (for the same reason boosted and bagged trees are expected to be more stable). The party package in R might be another good choice, as the conditional inference trees and associated forests and variable importance measures are purported to be less biased. Party VI Outside of statistics, Googling "Feature Selection" might give you more ideas.
Decision Tree as variable selection for Logistic Regression If you have access to LASSO and your predictors are all numeric then that is a good choice as Peter mentioned. If you have a massive number of predictors as experienced often in fields like marketing
38,663
Decision Tree as variable selection for Logistic Regression
In addition to the usual problems with automatically choosing variables, this uses trees for a purpose they were not designed for. To me, there are two big advantages to classification trees: 1) They are intuitively very clear. 2) They allow you to look at interactions in ways that would be very difficult in a regression model, because the interactions can be different in different branches of the tree. Variable selection is a big topic and has been often discussed here. I am partial to LASSO and or LAR, myself.
Decision Tree as variable selection for Logistic Regression
In addition to the usual problems with automatically choosing variables, this uses trees for a purpose they were not designed for. To me, there are two big advantages to classification trees: 1) They
Decision Tree as variable selection for Logistic Regression In addition to the usual problems with automatically choosing variables, this uses trees for a purpose they were not designed for. To me, there are two big advantages to classification trees: 1) They are intuitively very clear. 2) They allow you to look at interactions in ways that would be very difficult in a regression model, because the interactions can be different in different branches of the tree. Variable selection is a big topic and has been often discussed here. I am partial to LASSO and or LAR, myself.
Decision Tree as variable selection for Logistic Regression In addition to the usual problems with automatically choosing variables, this uses trees for a purpose they were not designed for. To me, there are two big advantages to classification trees: 1) They
38,664
Decision Tree as variable selection for Logistic Regression
The random forest technique is related to decision trees. A metric that it outputs is a variable importance measure. This measure of often used for feature selection, which is a technique to select a subset of variables. They key aspect to understand is that there are many ways to go wrong with feature selection (subset selection). For example, if your model is assessed with a resampling plan (cross validation/bootstrap), you must repeat the variable selection at each iteration. This requires a good amount of background reading to fully appreciate. But searching this site and others for "randomForest", "variable importance", "variable selection", "cross-validation", and "overfitting" will get you started.
Decision Tree as variable selection for Logistic Regression
The random forest technique is related to decision trees. A metric that it outputs is a variable importance measure. This measure of often used for feature selection, which is a technique to select a
Decision Tree as variable selection for Logistic Regression The random forest technique is related to decision trees. A metric that it outputs is a variable importance measure. This measure of often used for feature selection, which is a technique to select a subset of variables. They key aspect to understand is that there are many ways to go wrong with feature selection (subset selection). For example, if your model is assessed with a resampling plan (cross validation/bootstrap), you must repeat the variable selection at each iteration. This requires a good amount of background reading to fully appreciate. But searching this site and others for "randomForest", "variable importance", "variable selection", "cross-validation", and "overfitting" will get you started.
Decision Tree as variable selection for Logistic Regression The random forest technique is related to decision trees. A metric that it outputs is a variable importance measure. This measure of often used for feature selection, which is a technique to select a
38,665
Decision Tree as variable selection for Logistic Regression
One of the problems with this approach is that logistic regression and decision trees are very different algorithms, so the set of features that work well with a decision tree are not necessarily going to be the features that work well with a logistic regression model (and vice versa). So my advice would be that this approach is a bit of a hack and there are likely to be better approaches. There is a good tutorial on feature selection: Isabelle Guyon, André Elisseeff, "An Introduction to Variable and Feature Selection", Journal of Machine Learning Research, 3(Mar):1157-1182, 2003. (www) I, like Peter Flom (+1) and B_Miner (+1), am quite keen on LASSO/LARS based methods (The Random Forest is also a good algorithm), my own contribution to this can be found here: Gavin C. Cawley and Nicola L. C. Talbot, Gene selection in cancer classification using sparse logistic regression with Bayesian regularization, Bioinformatics, (2006) 22 (19): 2348-2355. (www) where the regularisation parameter for a LASSO type penalty is integrated out analytically, so there are no hyper-parameters to tune. As @julieth points out (+1) if you use feature selection, you must perform the feature selection step independently in each fold of the cross-validation procedure, or you will end up with an optimistically biased performance estimate. See this paper for details Christophe Ambroise and Geoffrey J. McLachlan, Selection bias in gene extraction on the basis of microarray gene-expression data, PNAS, vol. 99, no. 10, pp 6562–6566, 2002 (www) This paper is a "must read" for anybody that is interested in feature selection!
Decision Tree as variable selection for Logistic Regression
One of the problems with this approach is that logistic regression and decision trees are very different algorithms, so the set of features that work well with a decision tree are not necessarily goin
Decision Tree as variable selection for Logistic Regression One of the problems with this approach is that logistic regression and decision trees are very different algorithms, so the set of features that work well with a decision tree are not necessarily going to be the features that work well with a logistic regression model (and vice versa). So my advice would be that this approach is a bit of a hack and there are likely to be better approaches. There is a good tutorial on feature selection: Isabelle Guyon, André Elisseeff, "An Introduction to Variable and Feature Selection", Journal of Machine Learning Research, 3(Mar):1157-1182, 2003. (www) I, like Peter Flom (+1) and B_Miner (+1), am quite keen on LASSO/LARS based methods (The Random Forest is also a good algorithm), my own contribution to this can be found here: Gavin C. Cawley and Nicola L. C. Talbot, Gene selection in cancer classification using sparse logistic regression with Bayesian regularization, Bioinformatics, (2006) 22 (19): 2348-2355. (www) where the regularisation parameter for a LASSO type penalty is integrated out analytically, so there are no hyper-parameters to tune. As @julieth points out (+1) if you use feature selection, you must perform the feature selection step independently in each fold of the cross-validation procedure, or you will end up with an optimistically biased performance estimate. See this paper for details Christophe Ambroise and Geoffrey J. McLachlan, Selection bias in gene extraction on the basis of microarray gene-expression data, PNAS, vol. 99, no. 10, pp 6562–6566, 2002 (www) This paper is a "must read" for anybody that is interested in feature selection!
Decision Tree as variable selection for Logistic Regression One of the problems with this approach is that logistic regression and decision trees are very different algorithms, so the set of features that work well with a decision tree are not necessarily goin
38,666
In regression analysis what does taking the log of a variable do?
There are two sorts of reasons for taking the log of a variable in a regression, one statistical, one substantive. Statistically, OLS regression assumes that the errors, as estimated by the residuals, are normally distributed. When they are positively skewed (long right tail) taking logs can sometimes help. Sometimes logs are taken of the dependent variable, sometimes of one or more independent variables. Substantively, sometimes the meaning of a change in a variable is more multiplicative than additive. For example, income. If you make \$20,000 a year, a \$5,000 raise is huge. If you make \$200,000 a year, it is small. Taking logs reflects this: log(20,000) = 9.90 log(25,000) = 10.12 log(200,000) = 12.20 log(205,000) = 12.23 The gaps are then 0.22 and 0.03. In terms of interpretation, you are now saying that each change of 1 unit on the log scale has the same effect on the DV, rather than each change of 1 unit on the raw scale.
In regression analysis what does taking the log of a variable do?
There are two sorts of reasons for taking the log of a variable in a regression, one statistical, one substantive. Statistically, OLS regression assumes that the errors, as estimated by the residuals,
In regression analysis what does taking the log of a variable do? There are two sorts of reasons for taking the log of a variable in a regression, one statistical, one substantive. Statistically, OLS regression assumes that the errors, as estimated by the residuals, are normally distributed. When they are positively skewed (long right tail) taking logs can sometimes help. Sometimes logs are taken of the dependent variable, sometimes of one or more independent variables. Substantively, sometimes the meaning of a change in a variable is more multiplicative than additive. For example, income. If you make \$20,000 a year, a \$5,000 raise is huge. If you make \$200,000 a year, it is small. Taking logs reflects this: log(20,000) = 9.90 log(25,000) = 10.12 log(200,000) = 12.20 log(205,000) = 12.23 The gaps are then 0.22 and 0.03. In terms of interpretation, you are now saying that each change of 1 unit on the log scale has the same effect on the DV, rather than each change of 1 unit on the raw scale.
In regression analysis what does taking the log of a variable do? There are two sorts of reasons for taking the log of a variable in a regression, one statistical, one substantive. Statistically, OLS regression assumes that the errors, as estimated by the residuals,
38,667
In regression analysis what does taking the log of a variable do?
Taking logs will make certain forms of relationship that look curved look linear or more nearly linear. Think of introducing new variables, $X_5 = \log(X_3)$ and $X_6 = \log(X_4)$ and then your model is linear in $X_1, X_2, X_5$ and $X_6$. Sometimes these transformations are obvious from subject-matter considerations. Sometimes they're just chosen empirically.
In regression analysis what does taking the log of a variable do?
Taking logs will make certain forms of relationship that look curved look linear or more nearly linear. Think of introducing new variables, $X_5 = \log(X_3)$ and $X_6 = \log(X_4)$ and then your model
In regression analysis what does taking the log of a variable do? Taking logs will make certain forms of relationship that look curved look linear or more nearly linear. Think of introducing new variables, $X_5 = \log(X_3)$ and $X_6 = \log(X_4)$ and then your model is linear in $X_1, X_2, X_5$ and $X_6$. Sometimes these transformations are obvious from subject-matter considerations. Sometimes they're just chosen empirically.
In regression analysis what does taking the log of a variable do? Taking logs will make certain forms of relationship that look curved look linear or more nearly linear. Think of introducing new variables, $X_5 = \log(X_3)$ and $X_6 = \log(X_4)$ and then your model
38,668
In regression analysis what does taking the log of a variable do?
This is an old question, but I often found myself looking for this specific interpretation in the past so I will add it here. Another substantive example is in the field of econometrics, when regression analysis is used to calculate the elasticities (relative percentage change of one variable with respect to another). In this case, the log-log functional form, where both the dependent and independent variables are log-transformed, is very convenient because the coefficients obtained directly give the respective elasticities instead of having to take the partial derivatives. For the mathematical formulation, I refer to @Charlie's answer here Interpretation of log transformed predictor
In regression analysis what does taking the log of a variable do?
This is an old question, but I often found myself looking for this specific interpretation in the past so I will add it here. Another substantive example is in the field of econometrics, when regressi
In regression analysis what does taking the log of a variable do? This is an old question, but I often found myself looking for this specific interpretation in the past so I will add it here. Another substantive example is in the field of econometrics, when regression analysis is used to calculate the elasticities (relative percentage change of one variable with respect to another). In this case, the log-log functional form, where both the dependent and independent variables are log-transformed, is very convenient because the coefficients obtained directly give the respective elasticities instead of having to take the partial derivatives. For the mathematical formulation, I refer to @Charlie's answer here Interpretation of log transformed predictor
In regression analysis what does taking the log of a variable do? This is an old question, but I often found myself looking for this specific interpretation in the past so I will add it here. Another substantive example is in the field of econometrics, when regressi
38,669
Odds of drawing at least k identical values among m after n draws?
There are almost certainly easier ways, but one way of computing the value precisely is compute the number of ways of placing $n$ labeled balls in $m$ labeled bins such that no bin contains $k$ or more balls. We can compute this using a simple recurrence. Let $W(n,j,m',k)$ be the number of ways of placing exactly $j$ of the $n$ labeled balls in $m'$ of the $m$ labeled bins. Then the number we seek is $W(n,n,m,k)$. We have the following recurrence: $$W(n,j,m',k)=\sum_{i=0}^{k-1}\binom{n-j+i}{i}W(n,j-i,m'-1,k)$$ where $W(n,j,m',k)=0$ when $j<0$ and $W(n,0,0,k)=1$ as there is one way to pace no balls in no bins. This follows from the fact that there are $\binom{n-j+i}{i}$ ways to choose $i$ out of $n-j+i$ balls to put in the $m'$th bin, and there are $W(n,j-i,m'-1,k)$ ways to put $j-i$ balls in $m'-1$ bins. The essence of this recurrence if that we can compute the number of ways of placing $j$ out of $n$ balls in $m'$ bins by looking at the number of balls placed in the $m'$th bin. If we placed $i$ balls in the $m'$th bin, then there were $j-i$ balls in the previous $m'-1$ bins, and we have already calculated the number of ways of doing that as $W(n,j-i,m'-1,k)$, and we have $\binom{n-j+i}{i}$ ways of choosing the $i$ balls to put in the $m'$th bin (there were $n-j+i$ balls left after we put $j-i$ balls in the first $m'-1$ bins, and we choose $i$ of them.) So $W(n,j,m',k)$ is just the sum over $i$ from $0$ to $k-1$ of $\binom{n-j+i}{i}W(n,j-i,m'-1,k)$. Once we have computed $W(n,n,m,k)$ the probability that at least one bin has at least $k$ balls is $1-\frac{W(n,n,m,k)}{m^n}$. Coding in Python because it has multiple precision arithmetic we have import sympy # to get the decimal approximation #compute the binomial coefficient def binomial(n, k): if k > n or k < 0: return 0 if k > n / 2: k = n - k if k == 0: return 1 bin = n - (k - 1) for i in range(k - 2, -1, -1): bin = bin * (n - i) / (k - i) return bin #compute the number of ways that balls can be put in cells such that no # cell contains fullbin (or more) balls. def numways(cells, balls, fullbin): x = [1 if i==0 else 0 for i in range(balls + 1)] for j in range(cells): x = [sum(binomial(balls - (i - k), k) * x[i - k] if i - k >= 0 else 0 for k in range(fullbin)) for i in range(balls + 1)] return x[balls] x = sympy.Integer(numways(300, 3000, 20))/sympy.Integer(300**3000) print sympy.N(1 - x, 50) (sympy is just used to get the decimal approximation). I get the following answer to 50 decimal places 0.64731643604975767318804860342485318214921593659347 This method would not be feasible for much larger values of $m$ and $n$. ADDED As there appears to be some skepticism as to the accuracy of this answer, I ran my own Monte-Carlo approximation (in C using the GSL, I used something other than R to avoid any problems that R may have provided, and avoided python because the heat death of the universe is happening any time now). In $10^7$ runs I got 6471264 hits. This seems to agree with my count, and is considerably at odds with whubers. The code for the Monte-carlo is attached. I have finished a run of 10^8 trials and have gotten 64733136 successes for a probability of 0.64733136. I am fairly certain that things are working correctly. #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_rng.h> const gsl_rng_type * T; gsl_rng * r; int testrand(int cells, int balls, int limit, int runs) { int run; int count = 0; int *array = malloc(cells * sizeof(int)); for (run =0; run < runs; run++) { int i; int hit = 0; for (i = 0; i < cells; i++) array[i] = 0; for (i = 0; i < balls; i++) { array[gsl_rng_uniform_int(r, cells)]++; } for (i = 0; i < cells; i++) { if (array[i] >= limit) { hit = 1; break; } } count += hit; } free(array); return count; } int main (void) { int i, n = 10; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); for (i = 0; i < n; i++) { printf("%d\n", testrand(300, 3000, 20, 10000000)); } gsl_rng_free (r); return 0; } EVEN MORE Note: this should be a comment to probabilityislogic's answer, but it won't fit. Reifying probabilityislogic's answer (mainly out of curiosity), this time in R because a foolish inconsistency is the hobgoblin of great minds, or something like that. This is the normal approximation from the Levin paper (the Edgeworth expansion should be straightforward, but it is more typing than I'm willing to expend) # an implementation of the Bruce Levin article here limit is the upper limit on # bin size that does not count approxNorm <- function(balls, cells, limit) { # using N=s sp <- balls / cells mu <- sp * (1 - dpois(limit, sp) / ppois(limit, sp)) sig2 <- mu - (limit - mu) * (sp - mu) x <- (balls - cells * mu) / sqrt(cells * sig2) p2 <- exp(-x^2 / 2)/sqrt(2 * pi * cells * sig2) p1 <- exp(ppois(limit, sp, log.p=TRUE) * cells) sqrt(2 * pi * balls) * p1 * p2 } and 1 - approxNorm(3000, 300, 19) gives us $p(3000, 300, 20) \approx 0.6468276$ which is not too bad at all.
Odds of drawing at least k identical values among m after n draws?
There are almost certainly easier ways, but one way of computing the value precisely is compute the number of ways of placing $n$ labeled balls in $m$ labeled bins such that no bin contains $k$ or mor
Odds of drawing at least k identical values among m after n draws? There are almost certainly easier ways, but one way of computing the value precisely is compute the number of ways of placing $n$ labeled balls in $m$ labeled bins such that no bin contains $k$ or more balls. We can compute this using a simple recurrence. Let $W(n,j,m',k)$ be the number of ways of placing exactly $j$ of the $n$ labeled balls in $m'$ of the $m$ labeled bins. Then the number we seek is $W(n,n,m,k)$. We have the following recurrence: $$W(n,j,m',k)=\sum_{i=0}^{k-1}\binom{n-j+i}{i}W(n,j-i,m'-1,k)$$ where $W(n,j,m',k)=0$ when $j<0$ and $W(n,0,0,k)=1$ as there is one way to pace no balls in no bins. This follows from the fact that there are $\binom{n-j+i}{i}$ ways to choose $i$ out of $n-j+i$ balls to put in the $m'$th bin, and there are $W(n,j-i,m'-1,k)$ ways to put $j-i$ balls in $m'-1$ bins. The essence of this recurrence if that we can compute the number of ways of placing $j$ out of $n$ balls in $m'$ bins by looking at the number of balls placed in the $m'$th bin. If we placed $i$ balls in the $m'$th bin, then there were $j-i$ balls in the previous $m'-1$ bins, and we have already calculated the number of ways of doing that as $W(n,j-i,m'-1,k)$, and we have $\binom{n-j+i}{i}$ ways of choosing the $i$ balls to put in the $m'$th bin (there were $n-j+i$ balls left after we put $j-i$ balls in the first $m'-1$ bins, and we choose $i$ of them.) So $W(n,j,m',k)$ is just the sum over $i$ from $0$ to $k-1$ of $\binom{n-j+i}{i}W(n,j-i,m'-1,k)$. Once we have computed $W(n,n,m,k)$ the probability that at least one bin has at least $k$ balls is $1-\frac{W(n,n,m,k)}{m^n}$. Coding in Python because it has multiple precision arithmetic we have import sympy # to get the decimal approximation #compute the binomial coefficient def binomial(n, k): if k > n or k < 0: return 0 if k > n / 2: k = n - k if k == 0: return 1 bin = n - (k - 1) for i in range(k - 2, -1, -1): bin = bin * (n - i) / (k - i) return bin #compute the number of ways that balls can be put in cells such that no # cell contains fullbin (or more) balls. def numways(cells, balls, fullbin): x = [1 if i==0 else 0 for i in range(balls + 1)] for j in range(cells): x = [sum(binomial(balls - (i - k), k) * x[i - k] if i - k >= 0 else 0 for k in range(fullbin)) for i in range(balls + 1)] return x[balls] x = sympy.Integer(numways(300, 3000, 20))/sympy.Integer(300**3000) print sympy.N(1 - x, 50) (sympy is just used to get the decimal approximation). I get the following answer to 50 decimal places 0.64731643604975767318804860342485318214921593659347 This method would not be feasible for much larger values of $m$ and $n$. ADDED As there appears to be some skepticism as to the accuracy of this answer, I ran my own Monte-Carlo approximation (in C using the GSL, I used something other than R to avoid any problems that R may have provided, and avoided python because the heat death of the universe is happening any time now). In $10^7$ runs I got 6471264 hits. This seems to agree with my count, and is considerably at odds with whubers. The code for the Monte-carlo is attached. I have finished a run of 10^8 trials and have gotten 64733136 successes for a probability of 0.64733136. I am fairly certain that things are working correctly. #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_rng.h> const gsl_rng_type * T; gsl_rng * r; int testrand(int cells, int balls, int limit, int runs) { int run; int count = 0; int *array = malloc(cells * sizeof(int)); for (run =0; run < runs; run++) { int i; int hit = 0; for (i = 0; i < cells; i++) array[i] = 0; for (i = 0; i < balls; i++) { array[gsl_rng_uniform_int(r, cells)]++; } for (i = 0; i < cells; i++) { if (array[i] >= limit) { hit = 1; break; } } count += hit; } free(array); return count; } int main (void) { int i, n = 10; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); for (i = 0; i < n; i++) { printf("%d\n", testrand(300, 3000, 20, 10000000)); } gsl_rng_free (r); return 0; } EVEN MORE Note: this should be a comment to probabilityislogic's answer, but it won't fit. Reifying probabilityislogic's answer (mainly out of curiosity), this time in R because a foolish inconsistency is the hobgoblin of great minds, or something like that. This is the normal approximation from the Levin paper (the Edgeworth expansion should be straightforward, but it is more typing than I'm willing to expend) # an implementation of the Bruce Levin article here limit is the upper limit on # bin size that does not count approxNorm <- function(balls, cells, limit) { # using N=s sp <- balls / cells mu <- sp * (1 - dpois(limit, sp) / ppois(limit, sp)) sig2 <- mu - (limit - mu) * (sp - mu) x <- (balls - cells * mu) / sqrt(cells * sig2) p2 <- exp(-x^2 / 2)/sqrt(2 * pi * cells * sig2) p1 <- exp(ppois(limit, sp, log.p=TRUE) * cells) sqrt(2 * pi * balls) * p1 * p2 } and 1 - approxNorm(3000, 300, 19) gives us $p(3000, 300, 20) \approx 0.6468276$ which is not too bad at all.
Odds of drawing at least k identical values among m after n draws? There are almost certainly easier ways, but one way of computing the value precisely is compute the number of ways of placing $n$ labeled balls in $m$ labeled bins such that no bin contains $k$ or mor
38,670
Odds of drawing at least k identical values among m after n draws?
(Responding to the simulation question) In R: n <- 3000; m <- 300; k <- 20 # Problem parameters nIterations <- 10000 # Number of iterations in the simulation set.seed(17) # Make the output reproducible # # All the work is done in the following line. # t <- table(replicate(nIterations, any(tabulate(floor(runif(n, min=1, max=m+1))) >= k))) t[["TRUE"]]/nIterations # Convert the count to a proportion Expected output: [1] 0.6453 To see more deeply into what's going on, look at the detailed distribution in several experiments by executing this command several times: table(tabulate(floor(runif(n, min=1, max=m+1)))) Typical output is 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 21 2 5 11 23 23 32 48 37 33 21 19 21 9 6 5 1 2 1 In this experiment, two values in the range 0..299 were observed 19 times (among 3000 independent draws) and one value was observed 21 times. You will find that most of the time, at least one value occurs 20 or more times. Because $1/m$ is small and $n$ is large, you should be seeing a Poisson distribution here. Indeed, 1 - ppois(k-1, n/m)^m returns [1] 0.6458719
Odds of drawing at least k identical values among m after n draws?
(Responding to the simulation question) In R: n <- 3000; m <- 300; k <- 20 # Problem parameters nIterations <- 10000 # Number of iterations in the simulation set.seed(17) # Mak
Odds of drawing at least k identical values among m after n draws? (Responding to the simulation question) In R: n <- 3000; m <- 300; k <- 20 # Problem parameters nIterations <- 10000 # Number of iterations in the simulation set.seed(17) # Make the output reproducible # # All the work is done in the following line. # t <- table(replicate(nIterations, any(tabulate(floor(runif(n, min=1, max=m+1))) >= k))) t[["TRUE"]]/nIterations # Convert the count to a proportion Expected output: [1] 0.6453 To see more deeply into what's going on, look at the detailed distribution in several experiments by executing this command several times: table(tabulate(floor(runif(n, min=1, max=m+1)))) Typical output is 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 21 2 5 11 23 23 32 48 37 33 21 19 21 9 6 5 1 2 1 In this experiment, two values in the range 0..299 were observed 19 times (among 3000 independent draws) and one value was observed 21 times. You will find that most of the time, at least one value occurs 20 or more times. Because $1/m$ is small and $n$ is large, you should be seeing a Poisson distribution here. Indeed, 1 - ppois(k-1, n/m)^m returns [1] 0.6458719
Odds of drawing at least k identical values among m after n draws? (Responding to the simulation question) In R: n <- 3000; m <- 300; k <- 20 # Problem parameters nIterations <- 10000 # Number of iterations in the simulation set.seed(17) # Mak
38,671
Odds of drawing at least k identical values among m after n draws?
This is a harder question if you don't have the $n\gg k$ and assuming that this makes them 'close enough' to independent to not affect the answer non-trivially. Lets proceed with these assumptions. Let $X_j \sim Binomial(n,\frac{1}{m})$ $\forall j = 1,..,m$. $$P(\max_j X_j \geq k) = 1 - P(\max_j X_j < k)$$ $$ = 1 - P(X_1 < k,...,X_m < k)$$ and, assuming independence of the $m$ random variables, $$ = 1 - \prod^m_{j=1}P(X_j < k)$$ $$ = 1 - [P(X_1 < k)]^m$$ $$ = 1 - [\sum^{k-1}_{i=0} {n \choose i}(\frac{1}{m})^i(1-\frac{1}{m})^{n-i}]^m$$ or, if you have the binomial cdf function in the language you are using: $$ = 1 - [Binomial\_cdf(k-1;n,\frac{1}{m})]^m$$
Odds of drawing at least k identical values among m after n draws?
This is a harder question if you don't have the $n\gg k$ and assuming that this makes them 'close enough' to independent to not affect the answer non-trivially. Lets proceed with these assumptions. Le
Odds of drawing at least k identical values among m after n draws? This is a harder question if you don't have the $n\gg k$ and assuming that this makes them 'close enough' to independent to not affect the answer non-trivially. Lets proceed with these assumptions. Let $X_j \sim Binomial(n,\frac{1}{m})$ $\forall j = 1,..,m$. $$P(\max_j X_j \geq k) = 1 - P(\max_j X_j < k)$$ $$ = 1 - P(X_1 < k,...,X_m < k)$$ and, assuming independence of the $m$ random variables, $$ = 1 - \prod^m_{j=1}P(X_j < k)$$ $$ = 1 - [P(X_1 < k)]^m$$ $$ = 1 - [\sum^{k-1}_{i=0} {n \choose i}(\frac{1}{m})^i(1-\frac{1}{m})^{n-i}]^m$$ or, if you have the binomial cdf function in the language you are using: $$ = 1 - [Binomial\_cdf(k-1;n,\frac{1}{m})]^m$$
Odds of drawing at least k identical values among m after n draws? This is a harder question if you don't have the $n\gg k$ and assuming that this makes them 'close enough' to independent to not affect the answer non-trivially. Lets proceed with these assumptions. Le
38,672
Odds of drawing at least k identical values among m after n draws?
The collection of numbers has a multinomial distribution with $m$ categories and $n$ sample size. Letting $N_i$ be the number of times the $i$th category is chosen/repeated, we have $$(N_1,\dots,N_m)\sim multinomial\left(n;\frac{1}{m},\frac{1}{m},\dots,\frac{1}{m}\right)$$ Now leveraging off of @danieljohnson's answer the probability we are after is $$p(n,m,k)=1-Pr(N_1<k,\dots,N_m<k)$$ i.e. if all numbers are repeated less than $k$ times, then none are repeated at least $k$ times. And "not none" is the same as "at least one" so we can take the probability away from one. This could be computed via a "brute force" approach, as the pmf we have is particularly simple: $$p(n,m,k)=1-m^{-n}\sum_{N_1<k,\dots,N_m<k|N_1+\dots+N_m=n}{n\choose N_1\dots N_m}$$ $$=1-\frac{n!}{m^{n}}\sum_{N_1=0}^{k-1}\sum_{N_2=0}^{k-1}\dots\sum_{N_{m-1}=0}^{k-1}\frac{1}{N_1!N_2!\dots N_{m-1}!(n-N_1-N_2-\dots-N_{m-1})!}$$ The last formula is correct provided we interpret a negative factorial as $\pm\infty$ (consistent with the gamma function) which eliminates these from the summation. On doing a quick google search came up with Bruce Levin's article. This gives a representation of the multinomial distribution as a collection of poisson random variables, with their sum being fixed. (note this might explain why @whuber has found that poisson approximation works better than binomial). Now, using the representation given in theorem 1 of the paper, we have: $$p(n,m,k)=1-\frac{n!}{s^n\exp(-s)}\left[\prod_{j=1}^{m}Pr(X_j\leq k-1)\right]Pr(W=n)$$ Where $X_j\sim Poisson\left(\frac{s}{m}\right)$ and are independent, and $W=\sum_{j=1}^{m}Y_j$ is a sum of independent truncated poisson distributions - basically $Y_j$ is $X_j$ conditioned to be less than or equal to $k-1$. Note that we can simplify the general formula by noting that the terms in the product do not depend on the index $j$, and so is just a single poisson cdf raised to the power of $m$. Thus we have: $$p(n,m,k)=1-\frac{n!}{s^n}\left[e_{k-1}\left(\frac{s}{m}\right)\right]^mPr(W=n)$$ Where $e_k(x)=\sum_{j=0}^{k}\frac{x^j}{j!}$ denotes the exponential sum function. note that because we have factorial an powers of potentially large numbers, numerically it will probably be better to work in terms of the logarithm of the second term, and then exponentiate back at the end of the calculation. Alternatively, we can choose the recommended $s=N$ as our algorithm parameter, and then make use of the stirling approximation to $n!$ - this is recommended in the paper and corresponds to "mean matching" of each poisson distribution with the multinomial cell (i.e. $E(X_i)=E(N_i)$). Then we get $\frac{n!}{n^n}\approx\sqrt{2\pi n}$. The paper provides two approximations for $Pr(W=n)$ on based on normal approximation, and another based on edgeworth expansion. details are in the paper (see equation 4). Note though that his method allows for different probability parameters, so terms like $\frac{1}{t}\sum_{1}^t\sigma_l^2$ can be replaced with $\sigma_1^2$ and so on, which avoid unecessary computation. Note that we also have the mallows bounds provided in the paper - which can be used to check the accuracy of the approximations.
Odds of drawing at least k identical values among m after n draws?
The collection of numbers has a multinomial distribution with $m$ categories and $n$ sample size. Letting $N_i$ be the number of times the $i$th category is chosen/repeated, we have $$(N_1,\dots,N_m)
Odds of drawing at least k identical values among m after n draws? The collection of numbers has a multinomial distribution with $m$ categories and $n$ sample size. Letting $N_i$ be the number of times the $i$th category is chosen/repeated, we have $$(N_1,\dots,N_m)\sim multinomial\left(n;\frac{1}{m},\frac{1}{m},\dots,\frac{1}{m}\right)$$ Now leveraging off of @danieljohnson's answer the probability we are after is $$p(n,m,k)=1-Pr(N_1<k,\dots,N_m<k)$$ i.e. if all numbers are repeated less than $k$ times, then none are repeated at least $k$ times. And "not none" is the same as "at least one" so we can take the probability away from one. This could be computed via a "brute force" approach, as the pmf we have is particularly simple: $$p(n,m,k)=1-m^{-n}\sum_{N_1<k,\dots,N_m<k|N_1+\dots+N_m=n}{n\choose N_1\dots N_m}$$ $$=1-\frac{n!}{m^{n}}\sum_{N_1=0}^{k-1}\sum_{N_2=0}^{k-1}\dots\sum_{N_{m-1}=0}^{k-1}\frac{1}{N_1!N_2!\dots N_{m-1}!(n-N_1-N_2-\dots-N_{m-1})!}$$ The last formula is correct provided we interpret a negative factorial as $\pm\infty$ (consistent with the gamma function) which eliminates these from the summation. On doing a quick google search came up with Bruce Levin's article. This gives a representation of the multinomial distribution as a collection of poisson random variables, with their sum being fixed. (note this might explain why @whuber has found that poisson approximation works better than binomial). Now, using the representation given in theorem 1 of the paper, we have: $$p(n,m,k)=1-\frac{n!}{s^n\exp(-s)}\left[\prod_{j=1}^{m}Pr(X_j\leq k-1)\right]Pr(W=n)$$ Where $X_j\sim Poisson\left(\frac{s}{m}\right)$ and are independent, and $W=\sum_{j=1}^{m}Y_j$ is a sum of independent truncated poisson distributions - basically $Y_j$ is $X_j$ conditioned to be less than or equal to $k-1$. Note that we can simplify the general formula by noting that the terms in the product do not depend on the index $j$, and so is just a single poisson cdf raised to the power of $m$. Thus we have: $$p(n,m,k)=1-\frac{n!}{s^n}\left[e_{k-1}\left(\frac{s}{m}\right)\right]^mPr(W=n)$$ Where $e_k(x)=\sum_{j=0}^{k}\frac{x^j}{j!}$ denotes the exponential sum function. note that because we have factorial an powers of potentially large numbers, numerically it will probably be better to work in terms of the logarithm of the second term, and then exponentiate back at the end of the calculation. Alternatively, we can choose the recommended $s=N$ as our algorithm parameter, and then make use of the stirling approximation to $n!$ - this is recommended in the paper and corresponds to "mean matching" of each poisson distribution with the multinomial cell (i.e. $E(X_i)=E(N_i)$). Then we get $\frac{n!}{n^n}\approx\sqrt{2\pi n}$. The paper provides two approximations for $Pr(W=n)$ on based on normal approximation, and another based on edgeworth expansion. details are in the paper (see equation 4). Note though that his method allows for different probability parameters, so terms like $\frac{1}{t}\sum_{1}^t\sigma_l^2$ can be replaced with $\sigma_1^2$ and so on, which avoid unecessary computation. Note that we also have the mallows bounds provided in the paper - which can be used to check the accuracy of the approximations.
Odds of drawing at least k identical values among m after n draws? The collection of numbers has a multinomial distribution with $m$ categories and $n$ sample size. Letting $N_i$ be the number of times the $i$th category is chosen/repeated, we have $$(N_1,\dots,N_m)
38,673
Is there a term for min + (max - min) / 2?
min + (max - min) / 2 = (min + max) / 2 It's called the mid-range. I don't know of an existing function in R.
Is there a term for min + (max - min) / 2?
min + (max - min) / 2 = (min + max) / 2 It's called the mid-range. I don't know of an existing function in R.
Is there a term for min + (max - min) / 2? min + (max - min) / 2 = (min + max) / 2 It's called the mid-range. I don't know of an existing function in R.
Is there a term for min + (max - min) / 2? min + (max - min) / 2 = (min + max) / 2 It's called the mid-range. I don't know of an existing function in R.
38,674
Is there a term for min + (max - min) / 2?
Isn’t mean what you want? > mean(c(5, 11)) 8 Note that the result of course differs as soon as you have a range with more than two values. I’m assuming that you only have two values, min and max. If you’ve got a vector of more than two values, use range to get their minimum and maximum: > x = 1 : 100 > mean(range(x)) 50.5
Is there a term for min + (max - min) / 2?
Isn’t mean what you want? > mean(c(5, 11)) 8 Note that the result of course differs as soon as you have a range with more than two values. I’m assuming that you only have two values, min and max. If
Is there a term for min + (max - min) / 2? Isn’t mean what you want? > mean(c(5, 11)) 8 Note that the result of course differs as soon as you have a range with more than two values. I’m assuming that you only have two values, min and max. If you’ve got a vector of more than two values, use range to get their minimum and maximum: > x = 1 : 100 > mean(range(x)) 50.5
Is there a term for min + (max - min) / 2? Isn’t mean what you want? > mean(c(5, 11)) 8 Note that the result of course differs as soon as you have a range with more than two values. I’m assuming that you only have two values, min and max. If
38,675
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter?
Your wording is implying causality, which is not what the R^2 represents. "Does price (x) determine square footage (y)?" is implying causality which is not what is captured through a correlation. "Price explains X% of the variation in square footage" describes that there is a relationship between price and square footage, but not a causal one. This only implies that these variables vary together, not that price causes square footage. Its more akin to saying "In general, when price goes up X amount, square footage happens to go up Y amount"
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter?
Your wording is implying causality, which is not what the R^2 represents. "Does price (x) determine square footage (y)?" is implying causality which is not what is captured through a correlation. "Pri
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter? Your wording is implying causality, which is not what the R^2 represents. "Does price (x) determine square footage (y)?" is implying causality which is not what is captured through a correlation. "Price explains X% of the variation in square footage" describes that there is a relationship between price and square footage, but not a causal one. This only implies that these variables vary together, not that price causes square footage. Its more akin to saying "In general, when price goes up X amount, square footage happens to go up Y amount"
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter? Your wording is implying causality, which is not what the R^2 represents. "Does price (x) determine square footage (y)?" is implying causality which is not what is captured through a correlation. "Pri
38,676
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter?
Edited with added material in response to comments by @whuber This is an answer based on probability theory, not statistical estimates, so your mileage may vary. If random variables $X$ and $Y$ have correlation coefficient $\rho$, then the linear least-mean-square error estimate of $Y$ given the value of $X$ is $$\hat{Y} = \mu_Y + \rho\frac{\sigma_Y}{\sigma_X}(X - \mu_X),$$ and similarly, the linear least-mean-square error estimate of $X$ given the value of $Y$ is $$\hat{X} = \mu_X + \rho\frac{\sigma_X}{\sigma_Y}(Y - \mu_Y).$$ Note that $\hat{Y}$ and $\hat{X}$ are random variables that are linear functions of $X$ and $Y$ respectively. Their means are $$\begin{align*} \mu_{\hat{Y}} &=E[\hat{Y}] = E\left[\mu_Y+\rho\frac{\sigma_Y}{\sigma_X}(X - \mu_X)\right] = \mu_Y+ \rho\frac{\sigma_Y}{\sigma_X}E[X - \mu_X] = \mu_Y\\ \mu_{\hat{X}} &= E[\hat{X}] = E\left[\mu_X+\rho\frac{\sigma_X}{\sigma_Y}(Y - \mu_Y)\right] = \mu_Y+ \rho\frac{\sigma_X}{\sigma_Y}E[Y - \mu_Y] = \mu_X \end{align*}$$ while the variances are $$\begin{align*} \sigma_{\hat{Y}}^2 &= E[(\hat{Y} - \mu_{\hat{Y}})^2] = \frac{\rho^2\sigma_Y^2}{\sigma_X^2}E[(X-\mu_X)^2] = \rho^2\sigma_Y^2\\ \sigma_{\hat{X}}^2 &= E[(\hat{X} - \mu_{\hat{X}})^2] = \frac{\rho^2\sigma_X^2}{\sigma_Y^2}E[(Y-\mu_Y)^2] = \rho^2\sigma_X^2 \end{align*}$$ Finally, the variances of the residual errors $Y - \hat{Y}$ and $X - \hat{X}$ are $\sigma_Y^2(1-\rho^2)$ and $\sigma_X^2(1-\rho^2)$ respectively. One can think of these results as follows. If we use the mean $\mu_Y$ as an estimate for $Y$, the mean-square error is $\sigma_Y^2$, but if we know the value of $X$ and use $\mu_Y + \rho\frac{\sigma_Y}{\sigma_X}(X - \mu_X)$ as the estimate of $Y$, the mean-square error is reduced to $\sigma_Y^2(1-\rho^2)$. If we use the mean $\mu_X$ as an estimate for $X$, the mean-square error is $\sigma_X^2$, but if we know the value of $Y$ and use $\mu_X + \rho\frac{\sigma_X}{\sigma_Y}(Y - \mu_Y)$ as the estimate of $X$, the mean-square error is reduced to $\sigma_X^2(1-\rho^2)$. In both cases, the mean-square error is reduced by the same fraction $(1-\rho^2)$. In terms of scatter plots (for discrete random variables or data) on a plane with coordinate axes $x$ and $y$, we have two straight lines $$ \begin{align*} y &= \mu_Y + \rho\frac{\sigma_Y}{\sigma_X}(x - \mu_X),\\ x &= \mu_X + \rho\frac{\sigma_X}{\sigma_Y}(y - \mu_Y), \end{align*} $$ of different slopes $\rho\sigma_Y/\sigma_X$ and $\sigma_Y/\rho\sigma_X$ passing through the mean point $(\mu_X,\mu_Y)$. The reason for the different slopes is that we are choosing the slope to minimize the sum of the squares of the vertical distances of the points from the line in the first case, and to minimize the sum of the squares of the horizontal distances of the points from the line in the second case. These sums of squared distances are $\sigma_Y^2(1-\rho^2)$ and $\sigma_X^2(1-\rho^2)$ respectively. As a simple example, suppose that $(X,Y)$ takes on values $(0,0)$, $(0,1)$ and $(1,1)$ with equal probability $\frac{1}{3}$ each or we have a scatter plot with these three points. One can grind through the calculations if desired, but it should be intuitively obvious that we should estimate $Y$ as $\frac{1}{2}$ if $X = 0$ and as $1$ if $X = 1$, while we should estimate $X$ as $0$ if $Y = 0$ and as $\frac{1}{2}$ if $Y = 1$, that is the two lines have different slopes $\frac{1}{2}$ and $2$ (in fact, reciprocal slopes since $\sigma_X^2 = \sigma_Y^2 = \frac{2}{9}$ in this example). This is what probability theory gives. But if you treat the three points as a small sample from from an unknown population and use estimates of the population means, variances and correlation coefficent, then your results may be different.
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter?
Edited with added material in response to comments by @whuber This is an answer based on probability theory, not statistical estimates, so your mileage may vary. If random variables $X$ and $Y$ have c
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter? Edited with added material in response to comments by @whuber This is an answer based on probability theory, not statistical estimates, so your mileage may vary. If random variables $X$ and $Y$ have correlation coefficient $\rho$, then the linear least-mean-square error estimate of $Y$ given the value of $X$ is $$\hat{Y} = \mu_Y + \rho\frac{\sigma_Y}{\sigma_X}(X - \mu_X),$$ and similarly, the linear least-mean-square error estimate of $X$ given the value of $Y$ is $$\hat{X} = \mu_X + \rho\frac{\sigma_X}{\sigma_Y}(Y - \mu_Y).$$ Note that $\hat{Y}$ and $\hat{X}$ are random variables that are linear functions of $X$ and $Y$ respectively. Their means are $$\begin{align*} \mu_{\hat{Y}} &=E[\hat{Y}] = E\left[\mu_Y+\rho\frac{\sigma_Y}{\sigma_X}(X - \mu_X)\right] = \mu_Y+ \rho\frac{\sigma_Y}{\sigma_X}E[X - \mu_X] = \mu_Y\\ \mu_{\hat{X}} &= E[\hat{X}] = E\left[\mu_X+\rho\frac{\sigma_X}{\sigma_Y}(Y - \mu_Y)\right] = \mu_Y+ \rho\frac{\sigma_X}{\sigma_Y}E[Y - \mu_Y] = \mu_X \end{align*}$$ while the variances are $$\begin{align*} \sigma_{\hat{Y}}^2 &= E[(\hat{Y} - \mu_{\hat{Y}})^2] = \frac{\rho^2\sigma_Y^2}{\sigma_X^2}E[(X-\mu_X)^2] = \rho^2\sigma_Y^2\\ \sigma_{\hat{X}}^2 &= E[(\hat{X} - \mu_{\hat{X}})^2] = \frac{\rho^2\sigma_X^2}{\sigma_Y^2}E[(Y-\mu_Y)^2] = \rho^2\sigma_X^2 \end{align*}$$ Finally, the variances of the residual errors $Y - \hat{Y}$ and $X - \hat{X}$ are $\sigma_Y^2(1-\rho^2)$ and $\sigma_X^2(1-\rho^2)$ respectively. One can think of these results as follows. If we use the mean $\mu_Y$ as an estimate for $Y$, the mean-square error is $\sigma_Y^2$, but if we know the value of $X$ and use $\mu_Y + \rho\frac{\sigma_Y}{\sigma_X}(X - \mu_X)$ as the estimate of $Y$, the mean-square error is reduced to $\sigma_Y^2(1-\rho^2)$. If we use the mean $\mu_X$ as an estimate for $X$, the mean-square error is $\sigma_X^2$, but if we know the value of $Y$ and use $\mu_X + \rho\frac{\sigma_X}{\sigma_Y}(Y - \mu_Y)$ as the estimate of $X$, the mean-square error is reduced to $\sigma_X^2(1-\rho^2)$. In both cases, the mean-square error is reduced by the same fraction $(1-\rho^2)$. In terms of scatter plots (for discrete random variables or data) on a plane with coordinate axes $x$ and $y$, we have two straight lines $$ \begin{align*} y &= \mu_Y + \rho\frac{\sigma_Y}{\sigma_X}(x - \mu_X),\\ x &= \mu_X + \rho\frac{\sigma_X}{\sigma_Y}(y - \mu_Y), \end{align*} $$ of different slopes $\rho\sigma_Y/\sigma_X$ and $\sigma_Y/\rho\sigma_X$ passing through the mean point $(\mu_X,\mu_Y)$. The reason for the different slopes is that we are choosing the slope to minimize the sum of the squares of the vertical distances of the points from the line in the first case, and to minimize the sum of the squares of the horizontal distances of the points from the line in the second case. These sums of squared distances are $\sigma_Y^2(1-\rho^2)$ and $\sigma_X^2(1-\rho^2)$ respectively. As a simple example, suppose that $(X,Y)$ takes on values $(0,0)$, $(0,1)$ and $(1,1)$ with equal probability $\frac{1}{3}$ each or we have a scatter plot with these three points. One can grind through the calculations if desired, but it should be intuitively obvious that we should estimate $Y$ as $\frac{1}{2}$ if $X = 0$ and as $1$ if $X = 1$, while we should estimate $X$ as $0$ if $Y = 0$ and as $\frac{1}{2}$ if $Y = 1$, that is the two lines have different slopes $\frac{1}{2}$ and $2$ (in fact, reciprocal slopes since $\sigma_X^2 = \sigma_Y^2 = \frac{2}{9}$ in this example). This is what probability theory gives. But if you treat the three points as a small sample from from an unknown population and use estimates of the population means, variances and correlation coefficent, then your results may be different.
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter? Edited with added material in response to comments by @whuber This is an answer based on probability theory, not statistical estimates, so your mileage may vary. If random variables $X$ and $Y$ have c
38,677
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter?
Your example can legitimately be run the other way. Why not estimate square footage from price? Suppose price data is publicly available, but square footage is not. Yet you want to estimate square footage (to determine the carpet or furniture market, the likely heating cost, or whatever). It's perfectly valid to model square footage as a function of price. In my opinion, you are getting hung up in the semantics of "independent" and "dependent" variables. Better to use "predictor" and "predicted".
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter?
Your example can legitimately be run the other way. Why not estimate square footage from price? Suppose price data is publicly available, but square footage is not. Yet you want to estimate square f
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter? Your example can legitimately be run the other way. Why not estimate square footage from price? Suppose price data is publicly available, but square footage is not. Yet you want to estimate square footage (to determine the carpet or furniture market, the likely heating cost, or whatever). It's perfectly valid to model square footage as a function of price. In my opinion, you are getting hung up in the semantics of "independent" and "dependent" variables. Better to use "predictor" and "predicted".
R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter? Your example can legitimately be run the other way. Why not estimate square footage from price? Suppose price data is publicly available, but square footage is not. Yet you want to estimate square f
38,678
How can I determine if there's a statistically significant difference between two averages?
If your run time samples for each language are roughly normally distributed* (which is likely the case), then you could use a t-test, in particular, an independent two-sample t-test with unequal variances. If you have R installed, you could do this by running t.test(x = c_sharp_samples, y = java_samples). If, however, you want to run the test by hand, first calculate: $t = \frac{\bar{X_1} - \bar{X_2}}{s_{\bar{X_1} - \bar{X_2}}}$, where $s_{\bar{X_1} - \bar{X_2}} = \sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}}$ and $\bar{X_1}$ is the sample mean of the C# samples, $s_1$ is the sample standard deviation of the C# samples, $n_1$ is the number of C# samples, and so on. $df = \frac{(s_1^2 / n_1 + s_2^2 / n_2)^2}{(s_1^2 / n_1)^2 / (n_1 - 1) + (s_2^2 / n_2)^2 / (n_2 - 1)}$. Then $t$ (approximately) follows a Student's t distribution with $df$ degrees of freedom, so lookup $t$ in the appropriate table (or using some t distribution calculator). *Even if your run time samples for each language aren't normally distributed, 15 samples is probably enough for a normal approximation (i.e., the CLT) to kick in, so you should be fine. But if you want to be formal about it and don't want to make this normal assumption, you could use the (non-parametric) Mann Whitney Test instead.
How can I determine if there's a statistically significant difference between two averages?
If your run time samples for each language are roughly normally distributed* (which is likely the case), then you could use a t-test, in particular, an independent two-sample t-test with unequal varia
How can I determine if there's a statistically significant difference between two averages? If your run time samples for each language are roughly normally distributed* (which is likely the case), then you could use a t-test, in particular, an independent two-sample t-test with unequal variances. If you have R installed, you could do this by running t.test(x = c_sharp_samples, y = java_samples). If, however, you want to run the test by hand, first calculate: $t = \frac{\bar{X_1} - \bar{X_2}}{s_{\bar{X_1} - \bar{X_2}}}$, where $s_{\bar{X_1} - \bar{X_2}} = \sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}}$ and $\bar{X_1}$ is the sample mean of the C# samples, $s_1$ is the sample standard deviation of the C# samples, $n_1$ is the number of C# samples, and so on. $df = \frac{(s_1^2 / n_1 + s_2^2 / n_2)^2}{(s_1^2 / n_1)^2 / (n_1 - 1) + (s_2^2 / n_2)^2 / (n_2 - 1)}$. Then $t$ (approximately) follows a Student's t distribution with $df$ degrees of freedom, so lookup $t$ in the appropriate table (or using some t distribution calculator). *Even if your run time samples for each language aren't normally distributed, 15 samples is probably enough for a normal approximation (i.e., the CLT) to kick in, so you should be fine. But if you want to be formal about it and don't want to make this normal assumption, you could use the (non-parametric) Mann Whitney Test instead.
How can I determine if there's a statistically significant difference between two averages? If your run time samples for each language are roughly normally distributed* (which is likely the case), then you could use a t-test, in particular, an independent two-sample t-test with unequal varia
38,679
How can I determine if there's a statistically significant difference between two averages?
A permutation test is another possibility, although I think for the problem you describe the alternatives that have been mentioned will be superior.
How can I determine if there's a statistically significant difference between two averages?
A permutation test is another possibility, although I think for the problem you describe the alternatives that have been mentioned will be superior.
How can I determine if there's a statistically significant difference between two averages? A permutation test is another possibility, although I think for the problem you describe the alternatives that have been mentioned will be superior.
How can I determine if there's a statistically significant difference between two averages? A permutation test is another possibility, although I think for the problem you describe the alternatives that have been mentioned will be superior.
38,680
How can I determine if there's a statistically significant difference between two averages?
It sounds like what you want is to use a t-test (here is the wikipedia page). If you do not assume your observations distribute normally then try this, the Mann-Whitney U test, (but it can not be computed from mean/sd alone). Make sure that your observations are independent, so that the validity of the t-test is preserved. Good luck, and read more about this before you do things!
How can I determine if there's a statistically significant difference between two averages?
It sounds like what you want is to use a t-test (here is the wikipedia page). If you do not assume your observations distribute normally then try this, the Mann-Whitney U test, (but it can not be com
How can I determine if there's a statistically significant difference between two averages? It sounds like what you want is to use a t-test (here is the wikipedia page). If you do not assume your observations distribute normally then try this, the Mann-Whitney U test, (but it can not be computed from mean/sd alone). Make sure that your observations are independent, so that the validity of the t-test is preserved. Good luck, and read more about this before you do things!
How can I determine if there's a statistically significant difference between two averages? It sounds like what you want is to use a t-test (here is the wikipedia page). If you do not assume your observations distribute normally then try this, the Mann-Whitney U test, (but it can not be com
38,681
Computing average value ignoring outliers
In boxplots, values that are more than 1.5 times the IQR (interquartile range, difference between quartile 1 and 3) away from (as in: in the direction away from the median) the quartiles are typically considered outliers. I cannot say whether this is an appropriate measure for your data, though...
Computing average value ignoring outliers
In boxplots, values that are more than 1.5 times the IQR (interquartile range, difference between quartile 1 and 3) away from (as in: in the direction away from the median) the quartiles are typically
Computing average value ignoring outliers In boxplots, values that are more than 1.5 times the IQR (interquartile range, difference between quartile 1 and 3) away from (as in: in the direction away from the median) the quartiles are typically considered outliers. I cannot say whether this is an appropriate measure for your data, though...
Computing average value ignoring outliers In boxplots, values that are more than 1.5 times the IQR (interquartile range, difference between quartile 1 and 3) away from (as in: in the direction away from the median) the quartiles are typically
38,682
Computing average value ignoring outliers
You could consider using a trimmed mean. This would involve discarding, say, the highest 10% of values and the lowest 10% of values, regardless of whether you consider them to be bad.
Computing average value ignoring outliers
You could consider using a trimmed mean. This would involve discarding, say, the highest 10% of values and the lowest 10% of values, regardless of whether you consider them to be bad.
Computing average value ignoring outliers You could consider using a trimmed mean. This would involve discarding, say, the highest 10% of values and the lowest 10% of values, regardless of whether you consider them to be bad.
Computing average value ignoring outliers You could consider using a trimmed mean. This would involve discarding, say, the highest 10% of values and the lowest 10% of values, regardless of whether you consider them to be bad.
38,683
Computing average value ignoring outliers
I originally posted this on SO before it was deleted: https://stats.stackexchange.com/ will probably help you better with this, and give a more comprehensive answer. I'm not a mathematician, but I suspect there are multiple ways to solve this issue. As a programmer this is how I would tackle the problem. I'm not skilled enough to tell you if this is sound, but for simple data it should be acceptable. Depending on the type of data, it might be acceptable to have cut off amounts. You will probably want a rolling average (often used in stock markets) that takes the average price over the last n months, this helps negate the impact of inflation, and then have a $n cuttoff or a percentage based cutoff, that is, any value that deviates +-20% or +-$n of the rolling average will be ignored. This would work quite well for relatively stable markets, if your entity exists in a volatile market that fluctuates wildly then you probably want to find a different approach. You also need to seriously consider cutting data off, you mention granny's yard sale which is arguably a legitimate cut off, but you need to accept that you will probably be losing legitimate data points as well that could have a significant effect on your results. But again, there will be multiple ways to achieve this.
Computing average value ignoring outliers
I originally posted this on SO before it was deleted: https://stats.stackexchange.com/ will probably help you better with this, and give a more comprehensive answer. I'm not a mathematician, but I sus
Computing average value ignoring outliers I originally posted this on SO before it was deleted: https://stats.stackexchange.com/ will probably help you better with this, and give a more comprehensive answer. I'm not a mathematician, but I suspect there are multiple ways to solve this issue. As a programmer this is how I would tackle the problem. I'm not skilled enough to tell you if this is sound, but for simple data it should be acceptable. Depending on the type of data, it might be acceptable to have cut off amounts. You will probably want a rolling average (often used in stock markets) that takes the average price over the last n months, this helps negate the impact of inflation, and then have a $n cuttoff or a percentage based cutoff, that is, any value that deviates +-20% or +-$n of the rolling average will be ignored. This would work quite well for relatively stable markets, if your entity exists in a volatile market that fluctuates wildly then you probably want to find a different approach. You also need to seriously consider cutting data off, you mention granny's yard sale which is arguably a legitimate cut off, but you need to accept that you will probably be losing legitimate data points as well that could have a significant effect on your results. But again, there will be multiple ways to achieve this.
Computing average value ignoring outliers I originally posted this on SO before it was deleted: https://stats.stackexchange.com/ will probably help you better with this, and give a more comprehensive answer. I'm not a mathematician, but I sus
38,684
Computing average value ignoring outliers
Perhaps a robust estimator like RANSAC could be used here.
Computing average value ignoring outliers
Perhaps a robust estimator like RANSAC could be used here.
Computing average value ignoring outliers Perhaps a robust estimator like RANSAC could be used here.
Computing average value ignoring outliers Perhaps a robust estimator like RANSAC could be used here.
38,685
Computing average value ignoring outliers
hope this helps Simplistic approaches , as suggested here , often fail to their lack of generality. In general you may have a series that has multiple trends and/or multiple levels thus to detect anomalies one has to "control" for these effects. Additionally there may be a seasonal effect that may have started in the last k periods and not present in the first n-k values. Now let's get to the meat of the problem. Assume that there are no mean shifts/no trend changes/no seasonal pulse structure in the data. The data may be autocorrelated causing the simple standard deviation to be over or under estimated depending upon the nature of the autocorrelation. The possible existence of Pulses,Seasonal Pulses,Level Shifts and/or local time trends obfuscates the identification of the "exceptions". Using a "bad standard deviation" to try to identify anomalies is flawed because it is an out of model test as compared to an "in model test" which ultimately is what is used to conclude about the statistical significance of the anomilies. You might Google "how to do statistical intervention detection" to help you find sources/software to do this.
Computing average value ignoring outliers
hope this helps Simplistic approaches , as suggested here , often fail to their lack of generality. In general you may have a series that has multiple trends and/or multiple levels thus to detect anom
Computing average value ignoring outliers hope this helps Simplistic approaches , as suggested here , often fail to their lack of generality. In general you may have a series that has multiple trends and/or multiple levels thus to detect anomalies one has to "control" for these effects. Additionally there may be a seasonal effect that may have started in the last k periods and not present in the first n-k values. Now let's get to the meat of the problem. Assume that there are no mean shifts/no trend changes/no seasonal pulse structure in the data. The data may be autocorrelated causing the simple standard deviation to be over or under estimated depending upon the nature of the autocorrelation. The possible existence of Pulses,Seasonal Pulses,Level Shifts and/or local time trends obfuscates the identification of the "exceptions". Using a "bad standard deviation" to try to identify anomalies is flawed because it is an out of model test as compared to an "in model test" which ultimately is what is used to conclude about the statistical significance of the anomilies. You might Google "how to do statistical intervention detection" to help you find sources/software to do this.
Computing average value ignoring outliers hope this helps Simplistic approaches , as suggested here , often fail to their lack of generality. In general you may have a series that has multiple trends and/or multiple levels thus to detect anom
38,686
Clustering of a matrix (homogeneity measurement)
This question is about spatial correlation. Many methods exist to characterize and quantify this. What they all have in common is comparing values at one location to those at nearby locations. Usually, the reference distribution is some kind of spatial stochastic process where data are generated independently from point to point ("complete spatial randomness"). Some methods only characterize average behavior while others provide more detailed exploratory tools to identify clusters of extreme values. For three different approaches, check out (1) the literature on geostatistics/kriging/variography; (2) other measures of spatial correlation such as Ripley's K and L functions or the Getis-Ord $G_i$ statistics ; and (3) geographically weighted regression. Accessible, non-technical, and sort of correct explanations of all these can be found on ESRI.com . The Wikipedia articles are scanty and of variable quality, unfortunately. The first two approaches are well supported with R packages such as spatstat and geoRglm. There is also free software for (2), of which some of the best known is Geoda and CrimeStat . I know of no free implementation of GWR (#3), but there are good resources maintained by its inventors.
Clustering of a matrix (homogeneity measurement)
This question is about spatial correlation. Many methods exist to characterize and quantify this. What they all have in common is comparing values at one location to those at nearby locations. Usua
Clustering of a matrix (homogeneity measurement) This question is about spatial correlation. Many methods exist to characterize and quantify this. What they all have in common is comparing values at one location to those at nearby locations. Usually, the reference distribution is some kind of spatial stochastic process where data are generated independently from point to point ("complete spatial randomness"). Some methods only characterize average behavior while others provide more detailed exploratory tools to identify clusters of extreme values. For three different approaches, check out (1) the literature on geostatistics/kriging/variography; (2) other measures of spatial correlation such as Ripley's K and L functions or the Getis-Ord $G_i$ statistics ; and (3) geographically weighted regression. Accessible, non-technical, and sort of correct explanations of all these can be found on ESRI.com . The Wikipedia articles are scanty and of variable quality, unfortunately. The first two approaches are well supported with R packages such as spatstat and geoRglm. There is also free software for (2), of which some of the best known is Geoda and CrimeStat . I know of no free implementation of GWR (#3), but there are good resources maintained by its inventors.
Clustering of a matrix (homogeneity measurement) This question is about spatial correlation. Many methods exist to characterize and quantify this. What they all have in common is comparing values at one location to those at nearby locations. Usua
38,687
Clustering of a matrix (homogeneity measurement)
You could also consider Moran's I which is available in the R package "ape". And then simply use a weighting based on distance: nRows <- 30 nCols <- 15 nPixels <- nRows * nCols # Create a Random Image image <- matrix(sample.int(256, nPixels, replace=TRUE), nrow=nRows, ncol=nCols) - 1L # 1D to 2D Index Function reverseIndex <- function ( vectorIdx, nRows, nCols ) { # If you're using row major for some odd reason, you'll # need to flip these. J <- floor((vectorIdx - 1L) / nCols) I <- (vectorIdx - 1L) - nCols*J # Return: c(I+1L, J+1L) } # Distance Function distFunc <- function(I, J) { idx1 <- reverseIndex(I, nRows, nCols) idx2 <- reverseIndex(J, nRows, nCols) idDiff <- idx1 - idx2 # Return: sqrt(idDiff %*% idDiff) } # Create Distance Matrix matrix(mapply(distFunc, rep(seq_len(nPixels), nPixels), rep(seq_len(nPixels), each=nPixels)), nrow=nPixels, ncol=nPixels) # Invert Distance for Moran's I invDist <- 1 / dist diag(invDist) <- 0 # Compute Moran's I: ape::Moran.I(as.vector(image), dist) Note that this will simply provide a measure & test of association, it will not identify where that association is in your matrix.
Clustering of a matrix (homogeneity measurement)
You could also consider Moran's I which is available in the R package "ape". And then simply use a weighting based on distance: nRows <- 30 nCols <- 15 nPixels <- nRows * nCols # Create a Random Im
Clustering of a matrix (homogeneity measurement) You could also consider Moran's I which is available in the R package "ape". And then simply use a weighting based on distance: nRows <- 30 nCols <- 15 nPixels <- nRows * nCols # Create a Random Image image <- matrix(sample.int(256, nPixels, replace=TRUE), nrow=nRows, ncol=nCols) - 1L # 1D to 2D Index Function reverseIndex <- function ( vectorIdx, nRows, nCols ) { # If you're using row major for some odd reason, you'll # need to flip these. J <- floor((vectorIdx - 1L) / nCols) I <- (vectorIdx - 1L) - nCols*J # Return: c(I+1L, J+1L) } # Distance Function distFunc <- function(I, J) { idx1 <- reverseIndex(I, nRows, nCols) idx2 <- reverseIndex(J, nRows, nCols) idDiff <- idx1 - idx2 # Return: sqrt(idDiff %*% idDiff) } # Create Distance Matrix matrix(mapply(distFunc, rep(seq_len(nPixels), nPixels), rep(seq_len(nPixels), each=nPixels)), nrow=nPixels, ncol=nPixels) # Invert Distance for Moran's I invDist <- 1 / dist diag(invDist) <- 0 # Compute Moran's I: ape::Moran.I(as.vector(image), dist) Note that this will simply provide a measure & test of association, it will not identify where that association is in your matrix.
Clustering of a matrix (homogeneity measurement) You could also consider Moran's I which is available in the R package "ape". And then simply use a weighting based on distance: nRows <- 30 nCols <- 15 nPixels <- nRows * nCols # Create a Random Im
38,688
Clustering of a matrix (homogeneity measurement)
Good question. A trivial way to find "cluster of high values in the upper left" (as opposed to correlations) is to split the image into tiles and look at tile means. For example, means of 100 x 100 tiles: [[ 82 78 80 94 99 100] [ 80 53 66 62 80 100] [ 82 61 65 64 72 98] [ 87 83 99 81 80 100] [100 100 100 100 100 100]] means of 50 x 50 tiles: [[100 85 84 100 70 96 100 100 100 100 100] [ 83 59 57 71 67 88 89 86 98 100 100] [ 87 58 54 49 71 74 71 61 61 100 100] [100 76 58 52 59 61 55 59 65 95 100] [100 62 59 60 57 63 60 60 59 97 100] [100 68 65 59 59 82 76 61 61 70 95] [ 83 64 76 66 96 100 96 61 80 67 100] [100 100 97 92 100 100 84 82 83 88 100] [100 100 100 100 100 100 100 100 100 100 100]] (a plot with average height / colour in each tile would be 10x better). (If you're looking for features in images, what's a "feature" ? E.g. a red stop sign, as in Histograms for feature representation )
Clustering of a matrix (homogeneity measurement)
Good question. A trivial way to find "cluster of high values in the upper left" (as opposed to correlations) is to split the image into tiles and look at tile means. For example, means of 100 x 100 t
Clustering of a matrix (homogeneity measurement) Good question. A trivial way to find "cluster of high values in the upper left" (as opposed to correlations) is to split the image into tiles and look at tile means. For example, means of 100 x 100 tiles: [[ 82 78 80 94 99 100] [ 80 53 66 62 80 100] [ 82 61 65 64 72 98] [ 87 83 99 81 80 100] [100 100 100 100 100 100]] means of 50 x 50 tiles: [[100 85 84 100 70 96 100 100 100 100 100] [ 83 59 57 71 67 88 89 86 98 100 100] [ 87 58 54 49 71 74 71 61 61 100 100] [100 76 58 52 59 61 55 59 65 95 100] [100 62 59 60 57 63 60 60 59 97 100] [100 68 65 59 59 82 76 61 61 70 95] [ 83 64 76 66 96 100 96 61 80 67 100] [100 100 97 92 100 100 84 82 83 88 100] [100 100 100 100 100 100 100 100 100 100 100]] (a plot with average height / colour in each tile would be 10x better). (If you're looking for features in images, what's a "feature" ? E.g. a red stop sign, as in Histograms for feature representation )
Clustering of a matrix (homogeneity measurement) Good question. A trivial way to find "cluster of high values in the upper left" (as opposed to correlations) is to split the image into tiles and look at tile means. For example, means of 100 x 100 t
38,689
Clustering of a matrix (homogeneity measurement)
The goal is just to find out a measure that will tell us how mixed up all the pixels are. Given 2 matrices of data with the exact same distribution of values, if the first one's values are ordered or clumped together in spatial groups and the 2nd one's values are well-dispersed (high points and not near other high points, low points not near other lows), what is the method of evaluating this dispersion/ clumpyness? The matrices will have the exact same variance or standard deviation, so that is not a good method. One idea is using the 2D Fourier Transform, because a more clumpy image intuitively has a lower frequency, but I'm not sure if that is actually a common or useful practice for this type of evaluation.
Clustering of a matrix (homogeneity measurement)
The goal is just to find out a measure that will tell us how mixed up all the pixels are. Given 2 matrices of data with the exact same distribution of values, if the first one's values are ordered or
Clustering of a matrix (homogeneity measurement) The goal is just to find out a measure that will tell us how mixed up all the pixels are. Given 2 matrices of data with the exact same distribution of values, if the first one's values are ordered or clumped together in spatial groups and the 2nd one's values are well-dispersed (high points and not near other high points, low points not near other lows), what is the method of evaluating this dispersion/ clumpyness? The matrices will have the exact same variance or standard deviation, so that is not a good method. One idea is using the 2D Fourier Transform, because a more clumpy image intuitively has a lower frequency, but I'm not sure if that is actually a common or useful practice for this type of evaluation.
Clustering of a matrix (homogeneity measurement) The goal is just to find out a measure that will tell us how mixed up all the pixels are. Given 2 matrices of data with the exact same distribution of values, if the first one's values are ordered or
38,690
Gputools for R: how to interpret the experimental procedure?
But, the experimental conditions for the GPU side is unclear (to me). When using a GPU, for efficiency we should simultaneously make use of the CPUs. That is not generally true, and in particular is not true for the gputools R package which offers an 'everything to the GPU' mode with new functions gpuMatMult(), gpuQr(), gpuCor() etc. In other words, it offers you new functions that shift the computations completely to the GPU. But your intuition is good. There should be a mixed mode with hybrid operations between the GPU and the CPU -- and the Magma library aims to offer just that. Better still, the magma R package brings this to R. Moreover, I have a benchmarking paper / vignette / small package almost completed that compares these as well as several BLAS such as Atlas, Goto and the MKL. I'll update this entry with a URL in a couple of days. Edit on 16 Sep: The paper I mentioned is now out and on CRAN with its own package gcbd; I and I wrote a brief blog entry about it too.
Gputools for R: how to interpret the experimental procedure?
But, the experimental conditions for the GPU side is unclear (to me). When using a GPU, for efficiency we should simultaneously make use of the CPUs. That is not generally true, and in particular is
Gputools for R: how to interpret the experimental procedure? But, the experimental conditions for the GPU side is unclear (to me). When using a GPU, for efficiency we should simultaneously make use of the CPUs. That is not generally true, and in particular is not true for the gputools R package which offers an 'everything to the GPU' mode with new functions gpuMatMult(), gpuQr(), gpuCor() etc. In other words, it offers you new functions that shift the computations completely to the GPU. But your intuition is good. There should be a mixed mode with hybrid operations between the GPU and the CPU -- and the Magma library aims to offer just that. Better still, the magma R package brings this to R. Moreover, I have a benchmarking paper / vignette / small package almost completed that compares these as well as several BLAS such as Atlas, Goto and the MKL. I'll update this entry with a URL in a couple of days. Edit on 16 Sep: The paper I mentioned is now out and on CRAN with its own package gcbd; I and I wrote a brief blog entry about it too.
Gputools for R: how to interpret the experimental procedure? But, the experimental conditions for the GPU side is unclear (to me). When using a GPU, for efficiency we should simultaneously make use of the CPUs. That is not generally true, and in particular is
38,691
Gputools for R: how to interpret the experimental procedure?
There is fundamental difference between parallel computing in CPUs and GPUs. Essentially, the CPU has been designed to do clever things on behalf of the programmer. For example, Instruction level parallelism. The GPU on the other hand, stips away this useful stuff and instead contains many more cores. It's a trade off between the processor helping you out and giving you more cores. Therefore, to use the GPU effectively, you need to submit as many threads (as memory allows as possible). The reason for this is because the GPU doesn't do any clever scheduling. So when it requests data for one thread, you want to have another one in the thread queue waiting to take over. Example Suppose you have a for loop that you want to make parallel: #f(i) does not depend on f(j) #for any j != i for(i in 1:100000) w[i] = f(i) You can submit N=1000000 threads (spread over the number cores) to the GPU. Now you may think that you could let n threads be done on the multi-core CPU, but: There's quite a lot of extra programming baggage for at most little gain. GPU programming is hard (at least I think so), so combing it with multi-core CPUs is something you want to avoid. The f(i) that you submit to the GPU tends to be a very simple function, say multiplying two elements of a matrix together. You will get a time penalty if you use the GPU and CPU together since they both have to ask each other if they are finished. By reducing the number of threads used on the GPU, you could easily be reducing efficiency, i.e. it takes the same amount of time to do N-n operations as it does for N operations! Of course there are situations when you may want to use both the GPU and CPU, but typically you don't use them for the same operation. Unfortunately, I don't have access to the paper at the moment. It's on my (long) list of things to read. So the above is more a general discussion on CPU and GPUs. I'll try and read it in the next day or two.
Gputools for R: how to interpret the experimental procedure?
There is fundamental difference between parallel computing in CPUs and GPUs. Essentially, the CPU has been designed to do clever things on behalf of the programmer. For example, Instruction level para
Gputools for R: how to interpret the experimental procedure? There is fundamental difference between parallel computing in CPUs and GPUs. Essentially, the CPU has been designed to do clever things on behalf of the programmer. For example, Instruction level parallelism. The GPU on the other hand, stips away this useful stuff and instead contains many more cores. It's a trade off between the processor helping you out and giving you more cores. Therefore, to use the GPU effectively, you need to submit as many threads (as memory allows as possible). The reason for this is because the GPU doesn't do any clever scheduling. So when it requests data for one thread, you want to have another one in the thread queue waiting to take over. Example Suppose you have a for loop that you want to make parallel: #f(i) does not depend on f(j) #for any j != i for(i in 1:100000) w[i] = f(i) You can submit N=1000000 threads (spread over the number cores) to the GPU. Now you may think that you could let n threads be done on the multi-core CPU, but: There's quite a lot of extra programming baggage for at most little gain. GPU programming is hard (at least I think so), so combing it with multi-core CPUs is something you want to avoid. The f(i) that you submit to the GPU tends to be a very simple function, say multiplying two elements of a matrix together. You will get a time penalty if you use the GPU and CPU together since they both have to ask each other if they are finished. By reducing the number of threads used on the GPU, you could easily be reducing efficiency, i.e. it takes the same amount of time to do N-n operations as it does for N operations! Of course there are situations when you may want to use both the GPU and CPU, but typically you don't use them for the same operation. Unfortunately, I don't have access to the paper at the moment. It's on my (long) list of things to read. So the above is more a general discussion on CPU and GPUs. I'll try and read it in the next day or two.
Gputools for R: how to interpret the experimental procedure? There is fundamental difference between parallel computing in CPUs and GPUs. Essentially, the CPU has been designed to do clever things on behalf of the programmer. For example, Instruction level para
38,692
Measurement level of percentile scores
Background to understand my answer The critical property that distinguishes between ordinal and interval scale is whether we can take ratio of differences. While you cannot take ratio of direct measures for either scale the ratio of differences is meaningful for interval but not ordinal (See: http://en.wikipedia.org/wiki/Level_of_measurement#Interval_scale). Temperature is the classic example for an interval scale. Consider the following: 80 f = 26.67 c 40 f = 4.44 c and 20 f = -6.67 c Differences between the first and the second is: 40 f and 22.23 c Difference between the second and the third is: 20 f and 11.11 c Notice that the ratio is the same irrespective of the scale on which we measure temperature. A classic example of ordinal data is ranks. If three teams, A, B, and C are ranked 1st, 2nd, and 4th, respectively, then a statement like so does not make sense: "Team A's difference in strength vis-a-vis team B is half of team B's difference in strength relative to team C." Answer to your question Is ratio of differences in percentiles meaningful? In other words, is the ratio of difference in percentiles invariant to the underlying scale? Consider, for example: (P70-P50) / (P50-P30)? Suppose that these percentiles are based on an underlying score between 0-100 and we compute the above ratio. Clearly, we would obtain the same ratio of percentile differences under arbitrary linear transformation of the score (e.g., multiply all scores by 10 so that the range is between 0-1000 and compute the percentiles). Thus, my answer: Interval
Measurement level of percentile scores
Background to understand my answer The critical property that distinguishes between ordinal and interval scale is whether we can take ratio of differences. While you cannot take ratio of direct measur
Measurement level of percentile scores Background to understand my answer The critical property that distinguishes between ordinal and interval scale is whether we can take ratio of differences. While you cannot take ratio of direct measures for either scale the ratio of differences is meaningful for interval but not ordinal (See: http://en.wikipedia.org/wiki/Level_of_measurement#Interval_scale). Temperature is the classic example for an interval scale. Consider the following: 80 f = 26.67 c 40 f = 4.44 c and 20 f = -6.67 c Differences between the first and the second is: 40 f and 22.23 c Difference between the second and the third is: 20 f and 11.11 c Notice that the ratio is the same irrespective of the scale on which we measure temperature. A classic example of ordinal data is ranks. If three teams, A, B, and C are ranked 1st, 2nd, and 4th, respectively, then a statement like so does not make sense: "Team A's difference in strength vis-a-vis team B is half of team B's difference in strength relative to team C." Answer to your question Is ratio of differences in percentiles meaningful? In other words, is the ratio of difference in percentiles invariant to the underlying scale? Consider, for example: (P70-P50) / (P50-P30)? Suppose that these percentiles are based on an underlying score between 0-100 and we compute the above ratio. Clearly, we would obtain the same ratio of percentile differences under arbitrary linear transformation of the score (e.g., multiply all scores by 10 so that the range is between 0-1000 and compute the percentiles). Thus, my answer: Interval
Measurement level of percentile scores Background to understand my answer The critical property that distinguishes between ordinal and interval scale is whether we can take ratio of differences. While you cannot take ratio of direct measur
38,693
Measurement level of percentile scores
John Tukey strongly and cogently argued for a proportion type of measurement in his book on EDA. One thing that makes proportions special and different from the classical "nominal, ordinal, interval, ratio" taxonomy is that frequently they enjoy an obvious symmetry: A proportion can be thought of as the average of a binary (0/1) indicator variable. Because it should not make any meaningful difference to recode the indicator, the data analysis should remain essentially unchanged when you re-express the proportion as its complement. Specifically, recoding $0\to 1$ and $1\to0$ changes the original proportion $p$ to $1-p$. For example, it should make no difference to talk about 60% of people voting "yes" or 40% voting "no" in a referendum; the two numbers 0.6 and 0.4 represent exactly the same thing. Thus, statistics, tests, decisions, summaries, etc., should give the same results (mutatis mutandis) regardless of which form of expression is used. Accordingly, Tukey used re-expressions of proportions, and analyses based on those re-expressions, that are (almost) invariant under the conversion $p\longleftrightarrow 1-p$. They are of the form $f(p) \pm f(1-p)$ for various functions $f$. (Taking the minus sign is usually best because it continues to distinguish between $p$ and $1-p$: only their signs differ when re-expressed.) When scaled so that the differential change near $p=1/2$ equals $1$, he called these the "folded" values. Among them are the folded logarithm ("flog"), proportional to $\log(p) - \log(1-p)$ = $\log(p/(1-p)$ = $\text{logit}(p)$, and the folded root ("froot"), proportional to $\sqrt{p} - \sqrt{1-p}$. A mathematical exposition of this topic is less convincing than seeing the statistics in action, so I recommend reading chapter 17 of EDA and studying the examples therein. In sum, then, I am suggesting that the question itself is too limiting and that one should be open to possibilities that go beyond those suggested by the classical taxonomy of variables. Addendum: Why "Interval" and "Ratio" are not quite correct answers Stevens created the nominal-ordinal-interval-ratio typonymy in a cogently argued 1946 paper in Science (New Series, Vol. 103, No. 2684, pp 677-680). The basis for the distinctions is explicitly invariance of the "basic empirical operations" under group actions. His Table 1 describes the relationship between scale and group thus: $$\begin{array}{ll} \text{Scale}&\text{Mathematical Group Structure} \\ \hline\text{Nominal}&\text{Permutation Group } x^\prime = f(x);\ f(x) \text{ means any one-to-one substitution} \\ \text{Ordinal}&\text{Isotonic Group } x^\prime = f(x);\ f(x) \text{ means any monotonic increasing function} \\ \text{Interval}&\text{General Linear Group } x^\prime = ax + b \\ \text{Ratio}&\text{Similarity Group } x^\prime = ax \end{array}$$ (This is a direct quotation, with some columns not shown.) This must be read with some latitude, because we always have the option of choosing a model that is not exactly correct. (For example, a Normal distribution as a model of variation can be extremely useful and quite accurate even when applied to, say, the heights of people, which can never be negative even though all Normal distributions assign some probability to negative values.) Thus, for instance, data of extremely small proportions could arguably be considered as being of ratio type because the upper limit of $1$ is practically irrelevant. Data of very closely spaced proportions that approach neither of the limits $0$ or $1$ might conceivably be considered of interval type. Limiting the scope of the questions to either of these special cases would (partially) justify some of the other answers in this thread which insist that proportions are on an interval scale or ratio scale. However, when proportions in a dataset can be both large (greater than $1/2$) and small (less than $1/2$) and some of them approach $1$ or $0$, then obviously neither the general linear group nor the similarity group can apply, because they do not preserve the interval $[0,1]$. This is why Stevens' classification is incomplete and why usually it cannot be applied to proportions.
Measurement level of percentile scores
John Tukey strongly and cogently argued for a proportion type of measurement in his book on EDA. One thing that makes proportions special and different from the classical "nominal, ordinal, interval,
Measurement level of percentile scores John Tukey strongly and cogently argued for a proportion type of measurement in his book on EDA. One thing that makes proportions special and different from the classical "nominal, ordinal, interval, ratio" taxonomy is that frequently they enjoy an obvious symmetry: A proportion can be thought of as the average of a binary (0/1) indicator variable. Because it should not make any meaningful difference to recode the indicator, the data analysis should remain essentially unchanged when you re-express the proportion as its complement. Specifically, recoding $0\to 1$ and $1\to0$ changes the original proportion $p$ to $1-p$. For example, it should make no difference to talk about 60% of people voting "yes" or 40% voting "no" in a referendum; the two numbers 0.6 and 0.4 represent exactly the same thing. Thus, statistics, tests, decisions, summaries, etc., should give the same results (mutatis mutandis) regardless of which form of expression is used. Accordingly, Tukey used re-expressions of proportions, and analyses based on those re-expressions, that are (almost) invariant under the conversion $p\longleftrightarrow 1-p$. They are of the form $f(p) \pm f(1-p)$ for various functions $f$. (Taking the minus sign is usually best because it continues to distinguish between $p$ and $1-p$: only their signs differ when re-expressed.) When scaled so that the differential change near $p=1/2$ equals $1$, he called these the "folded" values. Among them are the folded logarithm ("flog"), proportional to $\log(p) - \log(1-p)$ = $\log(p/(1-p)$ = $\text{logit}(p)$, and the folded root ("froot"), proportional to $\sqrt{p} - \sqrt{1-p}$. A mathematical exposition of this topic is less convincing than seeing the statistics in action, so I recommend reading chapter 17 of EDA and studying the examples therein. In sum, then, I am suggesting that the question itself is too limiting and that one should be open to possibilities that go beyond those suggested by the classical taxonomy of variables. Addendum: Why "Interval" and "Ratio" are not quite correct answers Stevens created the nominal-ordinal-interval-ratio typonymy in a cogently argued 1946 paper in Science (New Series, Vol. 103, No. 2684, pp 677-680). The basis for the distinctions is explicitly invariance of the "basic empirical operations" under group actions. His Table 1 describes the relationship between scale and group thus: $$\begin{array}{ll} \text{Scale}&\text{Mathematical Group Structure} \\ \hline\text{Nominal}&\text{Permutation Group } x^\prime = f(x);\ f(x) \text{ means any one-to-one substitution} \\ \text{Ordinal}&\text{Isotonic Group } x^\prime = f(x);\ f(x) \text{ means any monotonic increasing function} \\ \text{Interval}&\text{General Linear Group } x^\prime = ax + b \\ \text{Ratio}&\text{Similarity Group } x^\prime = ax \end{array}$$ (This is a direct quotation, with some columns not shown.) This must be read with some latitude, because we always have the option of choosing a model that is not exactly correct. (For example, a Normal distribution as a model of variation can be extremely useful and quite accurate even when applied to, say, the heights of people, which can never be negative even though all Normal distributions assign some probability to negative values.) Thus, for instance, data of extremely small proportions could arguably be considered as being of ratio type because the upper limit of $1$ is practically irrelevant. Data of very closely spaced proportions that approach neither of the limits $0$ or $1$ might conceivably be considered of interval type. Limiting the scope of the questions to either of these special cases would (partially) justify some of the other answers in this thread which insist that proportions are on an interval scale or ratio scale. However, when proportions in a dataset can be both large (greater than $1/2$) and small (less than $1/2$) and some of them approach $1$ or $0$, then obviously neither the general linear group nor the similarity group can apply, because they do not preserve the interval $[0,1]$. This is why Stevens' classification is incomplete and why usually it cannot be applied to proportions.
Measurement level of percentile scores John Tukey strongly and cogently argued for a proportion type of measurement in his book on EDA. One thing that makes proportions special and different from the classical "nominal, ordinal, interval,
38,694
Measurement level of percentile scores
Continuous (interval); this is a method how to convert ordinal data to something that may have some distribution that makes sense.
Measurement level of percentile scores
Continuous (interval); this is a method how to convert ordinal data to something that may have some distribution that makes sense.
Measurement level of percentile scores Continuous (interval); this is a method how to convert ordinal data to something that may have some distribution that makes sense.
Measurement level of percentile scores Continuous (interval); this is a method how to convert ordinal data to something that may have some distribution that makes sense.
38,695
The distribution function of the min of two random variables which are dependent via a common term
The distribution of $Y$ can also be written as $$Y = \min(Z_1,Z_2) = \min(U_1,U_2) - X_1 = Q-X_1$$ This contains two parts: The distribution of a minimum of iid variables $Q=\min(U_1,U_2)$ whose cdf can be expressed in terms of the cdf of $U_i$, $$P(\min(U_1,U_2)> x) = P(U_i > x)^2$$ The distribution of a sum $Q-X_1$, which can be found with a convolution.
The distribution function of the min of two random variables which are dependent via a common term
The distribution of $Y$ can also be written as $$Y = \min(Z_1,Z_2) = \min(U_1,U_2) - X_1 = Q-X_1$$ This contains two parts: The distribution of a minimum of iid variables $Q=\min(U_1,U_2)$ whose cdf
The distribution function of the min of two random variables which are dependent via a common term The distribution of $Y$ can also be written as $$Y = \min(Z_1,Z_2) = \min(U_1,U_2) - X_1 = Q-X_1$$ This contains two parts: The distribution of a minimum of iid variables $Q=\min(U_1,U_2)$ whose cdf can be expressed in terms of the cdf of $U_i$, $$P(\min(U_1,U_2)> x) = P(U_i > x)^2$$ The distribution of a sum $Q-X_1$, which can be found with a convolution.
The distribution function of the min of two random variables which are dependent via a common term The distribution of $Y$ can also be written as $$Y = \min(Z_1,Z_2) = \min(U_1,U_2) - X_1 = Q-X_1$$ This contains two parts: The distribution of a minimum of iid variables $Q=\min(U_1,U_2)$ whose cdf
38,696
The distribution function of the min of two random variables which are dependent via a common term
As noted by @YashaswiMohanty the expectation of $Y$ can sometimes be found without explicting the probability distribution function. Assume that all r.vs are of continuous type and $X_1$ is exponential with rate $\lambda >0$. We can consider the survival function $\bar{F}_Y(y) := 1 - F_Y(y)$ $$ \bar{F}_Y(y) = \text{Pr}\{ \min(Z_1,\,Z_2) > y\} =\text{Pr}\{[Z_1 > y] \cap [Z_2 > y] \}. $$ Then by conditioning on $X_1$ we can use the independence \begin{align*} \bar{F}_Y(y) &=\int_0^\infty \text{Pr}\{[Z_1 > y] \cap [Z_2 > y] \, \vert \, X_1 = x_1\} f_{X_1}(x_1) \,\text{d}x_1\\ &= \int_0^\infty \text{Pr}\{[U_1 > y + x_1] \cap [U_2 > y + x_1] \, \vert \, X_1 = x_1\} \, f_{X_1}(x_1) \,\text{d}x_1\\ &= \int_0^\infty \bar{F}_U(y + x_1)^2 \lambda \, e^{-\lambda x_1}\, \text{d}x_1 \end{align*} There are some cases where we can get a closed form expression. For instance if $U_i$ are exponential with rate $\gamma$ i.e., $\bar{F}_U(u) = e^{-\gamma u}$ for $u >0$. Interestingly, this is a simple and efficient way to generate a couple of random variables with tail dependence.
The distribution function of the min of two random variables which are dependent via a common term
As noted by @YashaswiMohanty the expectation of $Y$ can sometimes be found without explicting the probability distribution function. Assume that all r.vs are of continuous type and $X_1$ is exponentia
The distribution function of the min of two random variables which are dependent via a common term As noted by @YashaswiMohanty the expectation of $Y$ can sometimes be found without explicting the probability distribution function. Assume that all r.vs are of continuous type and $X_1$ is exponential with rate $\lambda >0$. We can consider the survival function $\bar{F}_Y(y) := 1 - F_Y(y)$ $$ \bar{F}_Y(y) = \text{Pr}\{ \min(Z_1,\,Z_2) > y\} =\text{Pr}\{[Z_1 > y] \cap [Z_2 > y] \}. $$ Then by conditioning on $X_1$ we can use the independence \begin{align*} \bar{F}_Y(y) &=\int_0^\infty \text{Pr}\{[Z_1 > y] \cap [Z_2 > y] \, \vert \, X_1 = x_1\} f_{X_1}(x_1) \,\text{d}x_1\\ &= \int_0^\infty \text{Pr}\{[U_1 > y + x_1] \cap [U_2 > y + x_1] \, \vert \, X_1 = x_1\} \, f_{X_1}(x_1) \,\text{d}x_1\\ &= \int_0^\infty \bar{F}_U(y + x_1)^2 \lambda \, e^{-\lambda x_1}\, \text{d}x_1 \end{align*} There are some cases where we can get a closed form expression. For instance if $U_i$ are exponential with rate $\gamma$ i.e., $\bar{F}_U(u) = e^{-\gamma u}$ for $u >0$. Interestingly, this is a simple and efficient way to generate a couple of random variables with tail dependence.
The distribution function of the min of two random variables which are dependent via a common term As noted by @YashaswiMohanty the expectation of $Y$ can sometimes be found without explicting the probability distribution function. Assume that all r.vs are of continuous type and $X_1$ is exponentia
38,697
Can age ever be confounded if it is the independent variable in an observational study?
First image below: With variables 'health' and 'wealth' you describe a situation with mediators. Age has a causal effect on health and wealth, and these in their turn have an effect on happiness. Second image below: Controlling would relate to a (confounding) variable that has a causal effect on both the exposure variable (age in the example) and the outcome variable (happiness). Since there are few parameters that cause age, there is not much to control for. I agree that the example is not so strong and in the example this is also nuanced by the sentence: (as long as they remain alive) There might be a confounding survivorship bias if one would argue that age causes happiness because we observe older people are more happy. The bias is that one assumes that there is no causal relationship from happiness to age which might be false.
Can age ever be confounded if it is the independent variable in an observational study?
First image below: With variables 'health' and 'wealth' you describe a situation with mediators. Age has a causal effect on health and wealth, and these in their turn have an effect on happiness. Seco
Can age ever be confounded if it is the independent variable in an observational study? First image below: With variables 'health' and 'wealth' you describe a situation with mediators. Age has a causal effect on health and wealth, and these in their turn have an effect on happiness. Second image below: Controlling would relate to a (confounding) variable that has a causal effect on both the exposure variable (age in the example) and the outcome variable (happiness). Since there are few parameters that cause age, there is not much to control for. I agree that the example is not so strong and in the example this is also nuanced by the sentence: (as long as they remain alive) There might be a confounding survivorship bias if one would argue that age causes happiness because we observe older people are more happy. The bias is that one assumes that there is no causal relationship from happiness to age which might be false.
Can age ever be confounded if it is the independent variable in an observational study? First image below: With variables 'health' and 'wealth' you describe a situation with mediators. Age has a causal effect on health and wealth, and these in their turn have an effect on happiness. Seco
38,698
Can age ever be confounded if it is the independent variable in an observational study?
Observational studies adjust for age all the time! I would not be surprised if age was the most common adjustment variable in observational studies. If age is the exposure (as in both examples of @SextusEmpiricus), the variable of interest, then you must include it in the model (how else are you going to estimate its effect?) and it - by definition - cannot be a confounding variable and be "adjusted for". Adjusting for just means that you include the variable in some model or condition on it in some other way (e.g. stratified analysis). You would adjust for age if it isn't the variable of interest and lies on a backdoor path between your exposure and outcome in the DAG. An extremely simple example is shown below: Here, we're interested in the causal effect of physical activity (PA) on cardiovascular disease (CVD). If age is both causally related to physical activity and cardiovascular disease, there is a backdoor path from PA <- Age -> CVD. By adjusting for age (conditioning on it), you block the path. So in this example, you must adjust for age to get the unbiased causal effect of PA on CVD.
Can age ever be confounded if it is the independent variable in an observational study?
Observational studies adjust for age all the time! I would not be surprised if age was the most common adjustment variable in observational studies. If age is the exposure (as in both examples of @Sex
Can age ever be confounded if it is the independent variable in an observational study? Observational studies adjust for age all the time! I would not be surprised if age was the most common adjustment variable in observational studies. If age is the exposure (as in both examples of @SextusEmpiricus), the variable of interest, then you must include it in the model (how else are you going to estimate its effect?) and it - by definition - cannot be a confounding variable and be "adjusted for". Adjusting for just means that you include the variable in some model or condition on it in some other way (e.g. stratified analysis). You would adjust for age if it isn't the variable of interest and lies on a backdoor path between your exposure and outcome in the DAG. An extremely simple example is shown below: Here, we're interested in the causal effect of physical activity (PA) on cardiovascular disease (CVD). If age is both causally related to physical activity and cardiovascular disease, there is a backdoor path from PA <- Age -> CVD. By adjusting for age (conditioning on it), you block the path. So in this example, you must adjust for age to get the unbiased causal effect of PA on CVD.
Can age ever be confounded if it is the independent variable in an observational study? Observational studies adjust for age all the time! I would not be surprised if age was the most common adjustment variable in observational studies. If age is the exposure (as in both examples of @Sex
38,699
Is variance the area under the curve of the distribution of a population?
The area is the width times the height, but the variance is the width squared times the height. In statistics, we speak of "moments". The n-th moment is the integral of x the n-power times the function. The 0-th moment is $\int x^0 f(x)dx$, or just $\int f(x) dx$. For a PDF, that should be 1 no matter what. The 1st moment is $\int x^1f(x) dx$, which is the mean. The second moment is $\int x^2f(x) dx$, which for a centered distribution, is the variance. You can get a visual by imagining the function rotated about a vertical line that goes through the mean. The volume that results will be proportional to the variance; if you have probability mass far from the mean, then it will rotate through a larger circle and contribute more to the volume.
Is variance the area under the curve of the distribution of a population?
The area is the width times the height, but the variance is the width squared times the height. In statistics, we speak of "moments". The n-th moment is the integral of x the n-power times the functio
Is variance the area under the curve of the distribution of a population? The area is the width times the height, but the variance is the width squared times the height. In statistics, we speak of "moments". The n-th moment is the integral of x the n-power times the function. The 0-th moment is $\int x^0 f(x)dx$, or just $\int f(x) dx$. For a PDF, that should be 1 no matter what. The 1st moment is $\int x^1f(x) dx$, which is the mean. The second moment is $\int x^2f(x) dx$, which for a centered distribution, is the variance. You can get a visual by imagining the function rotated about a vertical line that goes through the mean. The volume that results will be proportional to the variance; if you have probability mass far from the mean, then it will rotate through a larger circle and contribute more to the volume.
Is variance the area under the curve of the distribution of a population? The area is the width times the height, but the variance is the width squared times the height. In statistics, we speak of "moments". The n-th moment is the integral of x the n-power times the functio
38,700
Is variance the area under the curve of the distribution of a population?
While both the comments are correct, whuber ♦'s articulated it in a more comprehensive sense that can be conjured up as a "visual entity". Variances are defined for those random variables which are residing in the space $\mathcal L^2$ where $\mathbb EX^2<\infty.$ It is a measure of spreadness. For an intuitive take, the concept of moment of inertia comes handy. $\rm [I]$ expounded it distinctly (emphasis mine): Variance provides a 'quadratic' measure of how widely the distribution of an RV is spread about its mean. The 'moment of inertia' idea makes this precise. Suppose that $X$ is 'continuous'. Imagine that we make a very thin sheet of metal the shape of the area under the graph of $f_x,$ of unit mass per unit area. The variance of $X$ measures how hard it is to spin this metal sheet about a vertical axis through the mean — see Figure $\rm E(i).$ One precise form of this statement is that if the sheet is spinning, at $1$ complete revolution per second, then its total kinetic energy is a certain constant $(2\pi^2)$ times $\operatorname{Var}(X).$ Experience shows that variance provides a much more useful measure of spread than, for example, $\mathbb E (|X — \mu_X|).$ Reference: $\rm [I]$ Weighing the Odds: A Course in Probability and Statistics, David Williams, Cambridge University Press, $2001,$ sec. $3.5,$ pp. $67-68.$
Is variance the area under the curve of the distribution of a population?
While both the comments are correct, whuber ♦'s articulated it in a more comprehensive sense that can be conjured up as a "visual entity". Variances are defined for those random variables which are re
Is variance the area under the curve of the distribution of a population? While both the comments are correct, whuber ♦'s articulated it in a more comprehensive sense that can be conjured up as a "visual entity". Variances are defined for those random variables which are residing in the space $\mathcal L^2$ where $\mathbb EX^2<\infty.$ It is a measure of spreadness. For an intuitive take, the concept of moment of inertia comes handy. $\rm [I]$ expounded it distinctly (emphasis mine): Variance provides a 'quadratic' measure of how widely the distribution of an RV is spread about its mean. The 'moment of inertia' idea makes this precise. Suppose that $X$ is 'continuous'. Imagine that we make a very thin sheet of metal the shape of the area under the graph of $f_x,$ of unit mass per unit area. The variance of $X$ measures how hard it is to spin this metal sheet about a vertical axis through the mean — see Figure $\rm E(i).$ One precise form of this statement is that if the sheet is spinning, at $1$ complete revolution per second, then its total kinetic energy is a certain constant $(2\pi^2)$ times $\operatorname{Var}(X).$ Experience shows that variance provides a much more useful measure of spread than, for example, $\mathbb E (|X — \mu_X|).$ Reference: $\rm [I]$ Weighing the Odds: A Course in Probability and Statistics, David Williams, Cambridge University Press, $2001,$ sec. $3.5,$ pp. $67-68.$
Is variance the area under the curve of the distribution of a population? While both the comments are correct, whuber ♦'s articulated it in a more comprehensive sense that can be conjured up as a "visual entity". Variances are defined for those random variables which are re