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 |
|---|---|---|---|---|---|---|
36,301 | Neuron saturation occurs only in last layer or all layers? | As the problem with quadratic loss is that it learns slowly when it reaches saturation and it does not happen in the case of cross-entropy because of the σ′ term in the formula of the quadratic cost. And as the σ′ term vanishes in the cross-entropy this prevents this slow learning at saturation in the cross-entropy.
Sigmoid functions in hidden layers are likely to cause vanishing gradients, but for sigmoid in the output layer, it can be avoided by using the cross-entropy loss.And this might be the answer for your question! | Neuron saturation occurs only in last layer or all layers? | As the problem with quadratic loss is that it learns slowly when it reaches saturation and it does not happen in the case of cross-entropy because of the σ′ term in the formula of the quadratic cost. | Neuron saturation occurs only in last layer or all layers?
As the problem with quadratic loss is that it learns slowly when it reaches saturation and it does not happen in the case of cross-entropy because of the σ′ term in the formula of the quadratic cost. And as the σ′ term vanishes in the cross-entropy this prevents this slow learning at saturation in the cross-entropy.
Sigmoid functions in hidden layers are likely to cause vanishing gradients, but for sigmoid in the output layer, it can be avoided by using the cross-entropy loss.And this might be the answer for your question! | Neuron saturation occurs only in last layer or all layers?
As the problem with quadratic loss is that it learns slowly when it reaches saturation and it does not happen in the case of cross-entropy because of the σ′ term in the formula of the quadratic cost. |
36,302 | Why divide RSS by n-2 to get RSE? | The reason is based on trying to get an unbiased estimator of the underlying error variance in the regression. In a simple linear regression with normal error terms it can be shown that:
$$\text{RSS}(\mathbf{x},\mathbf{Y}) \equiv \sum_{i=1}^n (Y_i - \hat{Y}_i) \sim \sigma^2 \cdot \text{Chi-Sq}(df = n-2).$$
That is, under the standard assumption of normally distributed errors, the residual sum-of-squares has a chi-squared distribution with $n-2$ degrees of freedom. (This is called the residual degrees-of-freedom.) One consequence of this distributional result is that the residual sum-of-squares has expected value $\mathbb{E} ( \text{RSS}(\mathbf{x},\mathbf{Y}) ) = \sigma^2 (n-2)$. You can see from this result that the residual sum-of-squares will tend to be larger for larger data sets (i.e., it is an increasing function of $n$) and it is not a useful estimator of the error variance.
Unbiased estimation of the error variance: To get an unbiased estimator of the error variance, we divide by the residual degrees-of-freedom to get the residual mean-square:
$$\text{RMS}(\mathbf{x},\mathbf{Y}) \equiv \frac{\text{RSS}(\mathbf{x},\mathbf{Y})}{n-2} \sim \sigma^2 \cdot \frac{\text{Chi-Sq}(df = n-2)}{n-2}.$$
This statistic has expected value $\mathbb{E} ( \text{RMS}(\mathbf{x},\mathbf{Y}) ) = \sigma^2$, so it gives an unbiased estimator for the error variance in the regression. The corresponding statistic $\text{RME} = \sqrt{\text{RMS}}$ gives an estimator for $\sigma$, which is the standard deviation of the error term. (Note that the latter is not unbiased, since unbiased estimation of the variance leads to biased estimation of the standard deviation.)
Extension to multiple regression: This result is easily extended to multiple regression (with an intercept term and $m$ explanatory variables) where we have:
$$\text{RSS}(\mathbf{x},\mathbf{Y}) \equiv \sum_{i=1}^n (Y_i - \hat{Y}_i) \sim \sigma^2 \cdot \text{Chi-Sq}(df = n-m-1).$$
In this case the regression mean-square (which estimates the error variance) is:
$$\text{RMS}(\mathbf{x},\mathbf{Y}) \equiv \frac{\text{RSS}(\mathbf{x},\mathbf{Y})}{n-m-1} \sim \sigma^2 \cdot \frac{\text{Chi-Sq}(df = n-m-1)}{n-m-1}.$$
Proof of this general distributional result relies on material relating to quadratic forms of normal distributions, which is beyond the level of mathematics that is usually presented in introductory statistics courses. For information on the derivation of these results you can consult an advanced text on linear regression. | Why divide RSS by n-2 to get RSE? | The reason is based on trying to get an unbiased estimator of the underlying error variance in the regression. In a simple linear regression with normal error terms it can be shown that:
$$\text{RSS} | Why divide RSS by n-2 to get RSE?
The reason is based on trying to get an unbiased estimator of the underlying error variance in the regression. In a simple linear regression with normal error terms it can be shown that:
$$\text{RSS}(\mathbf{x},\mathbf{Y}) \equiv \sum_{i=1}^n (Y_i - \hat{Y}_i) \sim \sigma^2 \cdot \text{Chi-Sq}(df = n-2).$$
That is, under the standard assumption of normally distributed errors, the residual sum-of-squares has a chi-squared distribution with $n-2$ degrees of freedom. (This is called the residual degrees-of-freedom.) One consequence of this distributional result is that the residual sum-of-squares has expected value $\mathbb{E} ( \text{RSS}(\mathbf{x},\mathbf{Y}) ) = \sigma^2 (n-2)$. You can see from this result that the residual sum-of-squares will tend to be larger for larger data sets (i.e., it is an increasing function of $n$) and it is not a useful estimator of the error variance.
Unbiased estimation of the error variance: To get an unbiased estimator of the error variance, we divide by the residual degrees-of-freedom to get the residual mean-square:
$$\text{RMS}(\mathbf{x},\mathbf{Y}) \equiv \frac{\text{RSS}(\mathbf{x},\mathbf{Y})}{n-2} \sim \sigma^2 \cdot \frac{\text{Chi-Sq}(df = n-2)}{n-2}.$$
This statistic has expected value $\mathbb{E} ( \text{RMS}(\mathbf{x},\mathbf{Y}) ) = \sigma^2$, so it gives an unbiased estimator for the error variance in the regression. The corresponding statistic $\text{RME} = \sqrt{\text{RMS}}$ gives an estimator for $\sigma$, which is the standard deviation of the error term. (Note that the latter is not unbiased, since unbiased estimation of the variance leads to biased estimation of the standard deviation.)
Extension to multiple regression: This result is easily extended to multiple regression (with an intercept term and $m$ explanatory variables) where we have:
$$\text{RSS}(\mathbf{x},\mathbf{Y}) \equiv \sum_{i=1}^n (Y_i - \hat{Y}_i) \sim \sigma^2 \cdot \text{Chi-Sq}(df = n-m-1).$$
In this case the regression mean-square (which estimates the error variance) is:
$$\text{RMS}(\mathbf{x},\mathbf{Y}) \equiv \frac{\text{RSS}(\mathbf{x},\mathbf{Y})}{n-m-1} \sim \sigma^2 \cdot \frac{\text{Chi-Sq}(df = n-m-1)}{n-m-1}.$$
Proof of this general distributional result relies on material relating to quadratic forms of normal distributions, which is beyond the level of mathematics that is usually presented in introductory statistics courses. For information on the derivation of these results you can consult an advanced text on linear regression. | Why divide RSS by n-2 to get RSE?
The reason is based on trying to get an unbiased estimator of the underlying error variance in the regression. In a simple linear regression with normal error terms it can be shown that:
$$\text{RSS} |
36,303 | Why divide RSS by n-2 to get RSE? | In linear regression, if you are observing the relationship between a single predictor and its response then the equation is of the form
$$Y = b_0 + b_1 X.$$
Here, $Y$ is the response variable and $X$ is the predictor variable; $b_1$ and $b_0$ are coefficients that need to be found. Now we have two values to be found and so our degrees of freedom are $n-2$.
Degree of freedom is the freedom of selecting a value e.g. if you want to wear a different tie everyday and you have a total of 7 ties then you have the freedom to choose any tie on the first day, but then this freedom will decrease everyday till last day, when you can't choose a tie and have no freedom to choose it. | Why divide RSS by n-2 to get RSE? | In linear regression, if you are observing the relationship between a single predictor and its response then the equation is of the form
$$Y = b_0 + b_1 X.$$
Here, $Y$ is the response variable and $X$ | Why divide RSS by n-2 to get RSE?
In linear regression, if you are observing the relationship between a single predictor and its response then the equation is of the form
$$Y = b_0 + b_1 X.$$
Here, $Y$ is the response variable and $X$ is the predictor variable; $b_1$ and $b_0$ are coefficients that need to be found. Now we have two values to be found and so our degrees of freedom are $n-2$.
Degree of freedom is the freedom of selecting a value e.g. if you want to wear a different tie everyday and you have a total of 7 ties then you have the freedom to choose any tie on the first day, but then this freedom will decrease everyday till last day, when you can't choose a tie and have no freedom to choose it. | Why divide RSS by n-2 to get RSE?
In linear regression, if you are observing the relationship between a single predictor and its response then the equation is of the form
$$Y = b_0 + b_1 X.$$
Here, $Y$ is the response variable and $X$ |
36,304 | Non Linear Endogeneity | I agree that the distinctions here are not easy. I will try to shed some light with an example. It will drop the $t$ index you use as I believe it is immaterial to your problem.
Suppose our model is
$$
y_i=x_i\beta+u_i,
$$
where $x\sim N(0,1)$ and $u_i=x_i^2-1$. Then,
$$
cov(x,u)=E(x^3-x)-E(x)E(x^2-1)=0-0-0\cdot0=0,
$$
due to lack of skewness ($E(x^3)=0$) of the normal distribution and properties of the chi-square random variable with one d.f. $x^2$, viz. $E(x^2)=1$.
So, the assumption is satisfied, although $x$ and $u$ are evidently not independent: $E(u|x)=E(x^2|x)-1=x^2-1$
Standard consistency proofs of OLS then tell us that OLS will be consistent for $\beta$.
Here is a little simulation to confirm:
library(MASS)
n <- 1000
reps <- 2000
beta <- 2
estimates <- matrix(NA,reps)
for (i in 1:reps){
x <- rnorm(n)
u <- x^2-1
y <- beta*x + u
estimates[i] <- summary(lm(y~x))$coefficients[2]
}
summary(estimates)
V1
Min. :1.651
1st Qu.:1.934
Median :2.001
Mean :2.000
3rd Qu.:2.067
Max. :2.380
What it will not do without the stronger assumption $E(u_i|x_i)=0$ is estimate the partial effect of $x$ on $y$, which would be
$$
\frac{\partial E(y|x)}{\partial x}=\beta+2x
$$
Here is a plot of $y$ against $x$ for one realization of the simulation:
What you are then estimating consistently is the linear projection coefficient of a projection of $y$ on a constant and $x$. It is given by
$$
\frac{cov(y,x)}{var(x)}=\frac{E((2x+x^2-1)x)-E(x)E(y)}{1}=E(2x^2)=2
$$ | Non Linear Endogeneity | I agree that the distinctions here are not easy. I will try to shed some light with an example. It will drop the $t$ index you use as I believe it is immaterial to your problem.
Suppose our model is
$ | Non Linear Endogeneity
I agree that the distinctions here are not easy. I will try to shed some light with an example. It will drop the $t$ index you use as I believe it is immaterial to your problem.
Suppose our model is
$$
y_i=x_i\beta+u_i,
$$
where $x\sim N(0,1)$ and $u_i=x_i^2-1$. Then,
$$
cov(x,u)=E(x^3-x)-E(x)E(x^2-1)=0-0-0\cdot0=0,
$$
due to lack of skewness ($E(x^3)=0$) of the normal distribution and properties of the chi-square random variable with one d.f. $x^2$, viz. $E(x^2)=1$.
So, the assumption is satisfied, although $x$ and $u$ are evidently not independent: $E(u|x)=E(x^2|x)-1=x^2-1$
Standard consistency proofs of OLS then tell us that OLS will be consistent for $\beta$.
Here is a little simulation to confirm:
library(MASS)
n <- 1000
reps <- 2000
beta <- 2
estimates <- matrix(NA,reps)
for (i in 1:reps){
x <- rnorm(n)
u <- x^2-1
y <- beta*x + u
estimates[i] <- summary(lm(y~x))$coefficients[2]
}
summary(estimates)
V1
Min. :1.651
1st Qu.:1.934
Median :2.001
Mean :2.000
3rd Qu.:2.067
Max. :2.380
What it will not do without the stronger assumption $E(u_i|x_i)=0$ is estimate the partial effect of $x$ on $y$, which would be
$$
\frac{\partial E(y|x)}{\partial x}=\beta+2x
$$
Here is a plot of $y$ against $x$ for one realization of the simulation:
What you are then estimating consistently is the linear projection coefficient of a projection of $y$ on a constant and $x$. It is given by
$$
\frac{cov(y,x)}{var(x)}=\frac{E((2x+x^2-1)x)-E(x)E(y)}{1}=E(2x^2)=2
$$ | Non Linear Endogeneity
I agree that the distinctions here are not easy. I will try to shed some light with an example. It will drop the $t$ index you use as I believe it is immaterial to your problem.
Suppose our model is
$ |
36,305 | question about bayesian structural time series model | I can see several potential issues with your example:
You don't specify a seed so bsts will use the system clock and serial correlation between successive monte carlo runs will mess up your statistics
Your chosen metric, rsquare might not be what you think it is (see the help for summary.bsts)
Your model is not a great fit to the data, so it might take a LOT of samples to converge
Modifying your code to address 1 and 2...
library(bsts)
data(AirPassengers)
y <- log(AirPassengers)
res <- list()
for (j in c(100,1000,10000)) {
res.inner <- list()
for (i in 1:10) {
ss <- AddLocalLinearTrend(list(), y)
# ss <- AddSeasonal(ss, y, nseasons = 12)
seed <- floor(i*j*(as.numeric(Sys.time()) %% pi))
model_benchmark <- bsts(y, state.specification = ss, niter = j, seed=seed)
x <- summary(model_benchmark)
res.inner[[i]] <- c(x$residual.sd, x$prediction.sd, x$rsquare, x$relative.gof)
}
df.inner <- Reduce(rbind, res.inner)
colnames(df.inner) <- c("residual.sd", "prediction.sd", "rsquare", "relative.gof")
res[[j]] <- df.inner
print(res[[j]])
}
X <- Reduce(rbind, lapply(res, function(x) {if (length(x) > 0) apply(x,2,sd)}))
row.names(X) <- c("100", "1000", "10000")
X
...produces results similar to yours:
residual.sd prediction.sd rsquare relative.gof
100 0.0005273839 2.215716e-05 0.000728682 0.0005939483
1000 0.0163049235 5.001772e-04 0.026663130 0.0133087130
10000 0.0244355253 6.447072e-04 0.042745282 0.0170885684
Now, if we add in the seasonal term by uncommenting this line
# ss <- AddSeasonal(ss, y, nseasons = 12)
We get:
residual.sd prediction.sd rsquare relative.gof
100 0.0022619056 2.987453e-04 0.0007276338 0.0031640530
1000 0.0018138912 1.890575e-04 0.0005448601 0.0020016078
10000 0.0007862781 2.854752e-05 0.0002245090 0.0002997004
So it looks like the culprit is number 3 - a local linear trend is not a good fit of the highly seasonal AirPassenger data set. | question about bayesian structural time series model | I can see several potential issues with your example:
You don't specify a seed so bsts will use the system clock and serial correlation between successive monte carlo runs will mess up your statisti | question about bayesian structural time series model
I can see several potential issues with your example:
You don't specify a seed so bsts will use the system clock and serial correlation between successive monte carlo runs will mess up your statistics
Your chosen metric, rsquare might not be what you think it is (see the help for summary.bsts)
Your model is not a great fit to the data, so it might take a LOT of samples to converge
Modifying your code to address 1 and 2...
library(bsts)
data(AirPassengers)
y <- log(AirPassengers)
res <- list()
for (j in c(100,1000,10000)) {
res.inner <- list()
for (i in 1:10) {
ss <- AddLocalLinearTrend(list(), y)
# ss <- AddSeasonal(ss, y, nseasons = 12)
seed <- floor(i*j*(as.numeric(Sys.time()) %% pi))
model_benchmark <- bsts(y, state.specification = ss, niter = j, seed=seed)
x <- summary(model_benchmark)
res.inner[[i]] <- c(x$residual.sd, x$prediction.sd, x$rsquare, x$relative.gof)
}
df.inner <- Reduce(rbind, res.inner)
colnames(df.inner) <- c("residual.sd", "prediction.sd", "rsquare", "relative.gof")
res[[j]] <- df.inner
print(res[[j]])
}
X <- Reduce(rbind, lapply(res, function(x) {if (length(x) > 0) apply(x,2,sd)}))
row.names(X) <- c("100", "1000", "10000")
X
...produces results similar to yours:
residual.sd prediction.sd rsquare relative.gof
100 0.0005273839 2.215716e-05 0.000728682 0.0005939483
1000 0.0163049235 5.001772e-04 0.026663130 0.0133087130
10000 0.0244355253 6.447072e-04 0.042745282 0.0170885684
Now, if we add in the seasonal term by uncommenting this line
# ss <- AddSeasonal(ss, y, nseasons = 12)
We get:
residual.sd prediction.sd rsquare relative.gof
100 0.0022619056 2.987453e-04 0.0007276338 0.0031640530
1000 0.0018138912 1.890575e-04 0.0005448601 0.0020016078
10000 0.0007862781 2.854752e-05 0.0002245090 0.0002997004
So it looks like the culprit is number 3 - a local linear trend is not a good fit of the highly seasonal AirPassenger data set. | question about bayesian structural time series model
I can see several potential issues with your example:
You don't specify a seed so bsts will use the system clock and serial correlation between successive monte carlo runs will mess up your statisti |
36,306 | Conjecture related to Kolmogorov 0-1 Law (for events) | If you want events $B_n$ that are independent in an interesting manner (not simply because $\mathbb{P}(B_n) = 0$ or $\mathbb{P}(B_n) = 1$) then the conjecture is false.
Here is a pedantic example. Suppose $(\Omega, \mathcal{F},\mathbb{P})$ is a suitably rich probability space.
Let $A \in \mathcal{F}$ be $\mathbb{P}$-null, i.e. $\mathbb{P}(A) =0$. Take $A_i = A$, so that the tail $\sigma$-algebra is $\mathcal{G} = \{\emptyset, A, A^c, \Omega\}$.
Note that in particular $\mathcal{G}$ is finite.
Now, suppose that $B_1, B_2, \ldots$ is an independent sequence of events with $\mathbb{P}(B_n)$ bounded away from $0$ and $1$. Then the tail $\sigma$-algebra $\mathcal{H}$ is not countably generated. (See e.g. Exercise 1.1.18 http://math.mit.edu/~dws/175/prob01.pdf, which uses an argument like I outlined above- any countably generated $\mathbb{P}$-trivial $\sigma$-algebra has an atom of mass $1$, but $\mathcal{H}$ has no such atom).
So, $\mathcal{G}$ is finite but $\mathcal{H}$ is not even countably generated.
Edit 2: if you accept $\mathbb{P}(B_n) = 0$ then you can replicate any countably generated $\mathbb{P}$-trivial $\sigma$-algebra. In more detail, suppose that $\mathcal{G}$ is generated by events $E_1, E_2, \ldots \in \mathcal{G}\subset\mathcal{F}$. If $\mathcal{G}$ is $\mathbb{P}$-trivial then the $E_n$ are all independent, by virtue of being null (or $E_n^c$ being null). Now make a triangular construction for the $B$ events:
$B_{1,1} = E_1$, $B_{2,1} = E_1, B_{2,2} = E_2,\ldots,B_{k,j} = E_j$, $1\le j \le k$.
Then $(B_{k,j})$ is a countable sequence (with natural ordering for the indices) of independent events whose tail $\sigma$-algebra is $\mathcal{G}$.
So, here I think is the key question: suppose that $\mathcal{G}$ is a non-countably-generated $\mathbb{P}$-trivial tail $\sigma$-algebra (coming from non-null events which might be dependent). Can $\mathcal{G}$ be realised as the tail $\sigma$-algebra for some null events?
Edit 1: A gray area is what happens if you accept $\mathbb{P}(B_n)\to 0$, although that doesn't seem to be the thrust of the original question. | Conjecture related to Kolmogorov 0-1 Law (for events) | If you want events $B_n$ that are independent in an interesting manner (not simply because $\mathbb{P}(B_n) = 0$ or $\mathbb{P}(B_n) = 1$) then the conjecture is false.
Here is a pedantic example. Su | Conjecture related to Kolmogorov 0-1 Law (for events)
If you want events $B_n$ that are independent in an interesting manner (not simply because $\mathbb{P}(B_n) = 0$ or $\mathbb{P}(B_n) = 1$) then the conjecture is false.
Here is a pedantic example. Suppose $(\Omega, \mathcal{F},\mathbb{P})$ is a suitably rich probability space.
Let $A \in \mathcal{F}$ be $\mathbb{P}$-null, i.e. $\mathbb{P}(A) =0$. Take $A_i = A$, so that the tail $\sigma$-algebra is $\mathcal{G} = \{\emptyset, A, A^c, \Omega\}$.
Note that in particular $\mathcal{G}$ is finite.
Now, suppose that $B_1, B_2, \ldots$ is an independent sequence of events with $\mathbb{P}(B_n)$ bounded away from $0$ and $1$. Then the tail $\sigma$-algebra $\mathcal{H}$ is not countably generated. (See e.g. Exercise 1.1.18 http://math.mit.edu/~dws/175/prob01.pdf, which uses an argument like I outlined above- any countably generated $\mathbb{P}$-trivial $\sigma$-algebra has an atom of mass $1$, but $\mathcal{H}$ has no such atom).
So, $\mathcal{G}$ is finite but $\mathcal{H}$ is not even countably generated.
Edit 2: if you accept $\mathbb{P}(B_n) = 0$ then you can replicate any countably generated $\mathbb{P}$-trivial $\sigma$-algebra. In more detail, suppose that $\mathcal{G}$ is generated by events $E_1, E_2, \ldots \in \mathcal{G}\subset\mathcal{F}$. If $\mathcal{G}$ is $\mathbb{P}$-trivial then the $E_n$ are all independent, by virtue of being null (or $E_n^c$ being null). Now make a triangular construction for the $B$ events:
$B_{1,1} = E_1$, $B_{2,1} = E_1, B_{2,2} = E_2,\ldots,B_{k,j} = E_j$, $1\le j \le k$.
Then $(B_{k,j})$ is a countable sequence (with natural ordering for the indices) of independent events whose tail $\sigma$-algebra is $\mathcal{G}$.
So, here I think is the key question: suppose that $\mathcal{G}$ is a non-countably-generated $\mathbb{P}$-trivial tail $\sigma$-algebra (coming from non-null events which might be dependent). Can $\mathcal{G}$ be realised as the tail $\sigma$-algebra for some null events?
Edit 1: A gray area is what happens if you accept $\mathbb{P}(B_n)\to 0$, although that doesn't seem to be the thrust of the original question. | Conjecture related to Kolmogorov 0-1 Law (for events)
If you want events $B_n$ that are independent in an interesting manner (not simply because $\mathbb{P}(B_n) = 0$ or $\mathbb{P}(B_n) = 1$) then the conjecture is false.
Here is a pedantic example. Su |
36,307 | What to do with categorical data when calculating standardized z-scores? | Are ordinal data treated the same as continuous data when calculating standardized z-scores?
No, they are not: When dealing with data on different measurement scales it is important that your analysis should not use mathematical operations that are not meaningful within that measurement scale. For ordinal data, only the ranking of the values in the scale is meaningful, and so you should only use operations that are invariant to all changes in the numbering of values that preserve rank-order. This counts out any operation that uses the arithmetic operations $+$, $-$, $\times$ and $\div$.
For ordinal data, the sample mean and sample standard deviation are not invariant to all changes in the numbering of values that preserve rank-order. This means that the sample mean and sample standard deviation are meaningless for ordinal data. Consequently, the z-score is also meaningless.
(Note: In some cases researchers treat apparently ordinal data as if it were interval or ratio data, which amounts to asserting that the differences/ratios in the ordered categories are meaningful. In this case there is often some argument over whether it is justifiable to treat data on a higher measurement level.)
How do I approach nominal variables when calculating standardized z-scores?
Nominal and ordinal variables do not allow use of the arithmetic operations $+$, $-$, $\times$ and $\div$, so the z-score for these variables is meaningless. For a nominal variable the only meaningful measures are those that count frequencies/relative frequencies of the categories and use the operations $=$ and $\neq$. For ordinal variables you also have meaningful measures for cumulative frequencies/relative frequencies using the operations $<$ and $>$ (taken in the order for the ordinal variable). | What to do with categorical data when calculating standardized z-scores? | Are ordinal data treated the same as continuous data when calculating standardized z-scores?
No, they are not: When dealing with data on different measurement scales it is important that your analysi | What to do with categorical data when calculating standardized z-scores?
Are ordinal data treated the same as continuous data when calculating standardized z-scores?
No, they are not: When dealing with data on different measurement scales it is important that your analysis should not use mathematical operations that are not meaningful within that measurement scale. For ordinal data, only the ranking of the values in the scale is meaningful, and so you should only use operations that are invariant to all changes in the numbering of values that preserve rank-order. This counts out any operation that uses the arithmetic operations $+$, $-$, $\times$ and $\div$.
For ordinal data, the sample mean and sample standard deviation are not invariant to all changes in the numbering of values that preserve rank-order. This means that the sample mean and sample standard deviation are meaningless for ordinal data. Consequently, the z-score is also meaningless.
(Note: In some cases researchers treat apparently ordinal data as if it were interval or ratio data, which amounts to asserting that the differences/ratios in the ordered categories are meaningful. In this case there is often some argument over whether it is justifiable to treat data on a higher measurement level.)
How do I approach nominal variables when calculating standardized z-scores?
Nominal and ordinal variables do not allow use of the arithmetic operations $+$, $-$, $\times$ and $\div$, so the z-score for these variables is meaningless. For a nominal variable the only meaningful measures are those that count frequencies/relative frequencies of the categories and use the operations $=$ and $\neq$. For ordinal variables you also have meaningful measures for cumulative frequencies/relative frequencies using the operations $<$ and $>$ (taken in the order for the ordinal variable). | What to do with categorical data when calculating standardized z-scores?
Are ordinal data treated the same as continuous data when calculating standardized z-scores?
No, they are not: When dealing with data on different measurement scales it is important that your analysi |
36,308 | What to do with categorical data when calculating standardized z-scores? | what is performed across a particular feature should be performed across all features to make sure they have a common scale in that sense what is done to a particular featuere has to be done to all the features is that right.
otherwise is it ok to find out a value that represents a feature typically
mean for a normally distributed curve, mode for a categorical feature , median in case of some outliers and so on and then centre the variables is that fine | What to do with categorical data when calculating standardized z-scores? | what is performed across a particular feature should be performed across all features to make sure they have a common scale in that sense what is done to a particular featuere has to be done to all th | What to do with categorical data when calculating standardized z-scores?
what is performed across a particular feature should be performed across all features to make sure they have a common scale in that sense what is done to a particular featuere has to be done to all the features is that right.
otherwise is it ok to find out a value that represents a feature typically
mean for a normally distributed curve, mode for a categorical feature , median in case of some outliers and so on and then centre the variables is that fine | What to do with categorical data when calculating standardized z-scores?
what is performed across a particular feature should be performed across all features to make sure they have a common scale in that sense what is done to a particular featuere has to be done to all th |
36,309 | What to do with categorical data when calculating standardized z-scores? | You state that you need to standardise because otherwise some variables will dominate others. This seems surprising if what you want to do is to calculate correlations or do regression (which from your question seems likely). Similarly if you want to do variable reduction with principal component analysis. If you leave the variables in the original format it is much easier to interpret coefficients as they will be on the natural scale for you. Standardising converts them into an unnatural scale of standard deviations and makes them dependent on how much variability you have. | What to do with categorical data when calculating standardized z-scores? | You state that you need to standardise because otherwise some variables will dominate others. This seems surprising if what you want to do is to calculate correlations or do regression (which from you | What to do with categorical data when calculating standardized z-scores?
You state that you need to standardise because otherwise some variables will dominate others. This seems surprising if what you want to do is to calculate correlations or do regression (which from your question seems likely). Similarly if you want to do variable reduction with principal component analysis. If you leave the variables in the original format it is much easier to interpret coefficients as they will be on the natural scale for you. Standardising converts them into an unnatural scale of standard deviations and makes them dependent on how much variability you have. | What to do with categorical data when calculating standardized z-scores?
You state that you need to standardise because otherwise some variables will dominate others. This seems surprising if what you want to do is to calculate correlations or do regression (which from you |
36,310 | Can ridge regression be used in the presence of categorical predictors? | You are correct to assume that a categorical variable is encoded as indicator function/vector in your design matrix $X$; this is standard. To that respect, usually one of the levels is omitted and subsequently treated as baseline (if not you would have surely a rank-deficient design matrix when incorporating an intercept).
If you have a categorical variable with multiple categories you will once more treat is as an indicator function in your design matrix $X$. Just now you will not have a vector but a smaller submatrix. Lets see and example with R:
set.seed(123)
N = 50; # Sample size
x = rep(1:5, each = 10) # Make a discrete variable with five levels
b = 2
a = 3 # Intercept
epsilon = rnorm(N, sd = 0.1)
y = a + x*b + epsilon; # Your dependant variable
xCat = as.factor(x) # Define a new categorical variable based on 'a'
lm0 = lm(y ~ xCat)
MM = model.matrix(lm0) # The model matrix you use
image(x = 1:ncol(MM), y = 1:N, z=t(MM)) # The matrix image used. / Red is zero
As you see the levels 2,3,4 and 5 are encoded as separate indicator variables along the columns 2 to 5. The columns of ones in the column 1 is your intercept, level 1 is automatically omitted as an individual column and is assumed active alongside the intercept.
OK, so what about the ridge parameter $\lambda$? Remember that ridge regression is essentially using a Tikhonov regularized version of the covariance matrix of $X$. ie. $\hat{\beta} = (X^TX + \lambda I)^{-1} (X^T y)$, to generate the estimates $\hat{\beta}$. That is not problem for you if you have discrete (categorical) or continuous variables in your $X$ matrix. The regularization takes part outside the actual variable definition and essentially "amps" the variance across the diagonal of the matrix $X^TX$ (the matrix $X^TX$ can be thought of as a scaled version of covariance matrix when that the elements of $X$ are centred).
Please note that, as seanv507 and amoeba correctly comment, when using ridge regression it might make sense to standardise all the variables beforehand. If you fail to do that, the effect of regularisation can vary substantially. This is because increasing the observed variance of a particular variable $x$ by $\lambda$ can massively alter your intuition about $x$ depending on the original variance of $x$. This recent thread here shows such a case where regularization made a very observable difference. | Can ridge regression be used in the presence of categorical predictors? | You are correct to assume that a categorical variable is encoded as indicator function/vector in your design matrix $X$; this is standard. To that respect, usually one of the levels is omitted and sub | Can ridge regression be used in the presence of categorical predictors?
You are correct to assume that a categorical variable is encoded as indicator function/vector in your design matrix $X$; this is standard. To that respect, usually one of the levels is omitted and subsequently treated as baseline (if not you would have surely a rank-deficient design matrix when incorporating an intercept).
If you have a categorical variable with multiple categories you will once more treat is as an indicator function in your design matrix $X$. Just now you will not have a vector but a smaller submatrix. Lets see and example with R:
set.seed(123)
N = 50; # Sample size
x = rep(1:5, each = 10) # Make a discrete variable with five levels
b = 2
a = 3 # Intercept
epsilon = rnorm(N, sd = 0.1)
y = a + x*b + epsilon; # Your dependant variable
xCat = as.factor(x) # Define a new categorical variable based on 'a'
lm0 = lm(y ~ xCat)
MM = model.matrix(lm0) # The model matrix you use
image(x = 1:ncol(MM), y = 1:N, z=t(MM)) # The matrix image used. / Red is zero
As you see the levels 2,3,4 and 5 are encoded as separate indicator variables along the columns 2 to 5. The columns of ones in the column 1 is your intercept, level 1 is automatically omitted as an individual column and is assumed active alongside the intercept.
OK, so what about the ridge parameter $\lambda$? Remember that ridge regression is essentially using a Tikhonov regularized version of the covariance matrix of $X$. ie. $\hat{\beta} = (X^TX + \lambda I)^{-1} (X^T y)$, to generate the estimates $\hat{\beta}$. That is not problem for you if you have discrete (categorical) or continuous variables in your $X$ matrix. The regularization takes part outside the actual variable definition and essentially "amps" the variance across the diagonal of the matrix $X^TX$ (the matrix $X^TX$ can be thought of as a scaled version of covariance matrix when that the elements of $X$ are centred).
Please note that, as seanv507 and amoeba correctly comment, when using ridge regression it might make sense to standardise all the variables beforehand. If you fail to do that, the effect of regularisation can vary substantially. This is because increasing the observed variance of a particular variable $x$ by $\lambda$ can massively alter your intuition about $x$ depending on the original variance of $x$. This recent thread here shows such a case where regularization made a very observable difference. | Can ridge regression be used in the presence of categorical predictors?
You are correct to assume that a categorical variable is encoded as indicator function/vector in your design matrix $X$; this is standard. To that respect, usually one of the levels is omitted and sub |
36,311 | Can ridge regression be used in the presence of categorical predictors? | Yes you can, your beta_ridge will be a number that will pop up when gender is 1 and won't have an effect when gender is 0. If you have more than one category, in my experience, make them all binary. e.g. if you have apple, orange, pear, instead of saying 1,2,3 say is_apple = [0,1] is_orange=[0,1] is_pear=[0,1]. | Can ridge regression be used in the presence of categorical predictors? | Yes you can, your beta_ridge will be a number that will pop up when gender is 1 and won't have an effect when gender is 0. If you have more than one category, in my experience, make them all binary. e | Can ridge regression be used in the presence of categorical predictors?
Yes you can, your beta_ridge will be a number that will pop up when gender is 1 and won't have an effect when gender is 0. If you have more than one category, in my experience, make them all binary. e.g. if you have apple, orange, pear, instead of saying 1,2,3 say is_apple = [0,1] is_orange=[0,1] is_pear=[0,1]. | Can ridge regression be used in the presence of categorical predictors?
Yes you can, your beta_ridge will be a number that will pop up when gender is 1 and won't have an effect when gender is 0. If you have more than one category, in my experience, make them all binary. e |
36,312 | Number of parameters in mixed model | fm1
fixed = distance ~ age, random = ~ 1 | Subject
K = 4: the coefficients for intercept, and age; variances for random intercept, and error term.
fm2
fixed = distance ~ age + Sex, random = ~ 1 | Subject
K = 5: the coefficients for intercept, age, and Sex; variances for random intercept, and error term.
fm3
fixed = distance ~ age, random = ~ age | Subject
K = 6: the coefficients for intercept, and age; variances for random intercept, age, and error term; covariance between random effects of intercept and age.
fm4
fixed = distance ~ age + Sex, random = ~ age | Subject
K = 7: the coefficients for intercept, age, and Sex; variances for random intercept, age, and error term; covariance between random effects of intercept and age.
fm5
fixed = distance ~ age + Sex, random = ~ age + Sex | Subject
K = 10: the coefficients for intercept, age, and Sex; variances for random intercept, age, Sex, and error term; covariances between random effects of intercept and age, intercept and Sex, and age and Sex. | Number of parameters in mixed model | fm1
fixed = distance ~ age, random = ~ 1 | Subject
K = 4: the coefficients for intercept, and age; variances for random intercept, and error term.
fm2
fixed = distance ~ age + Sex, random = ~ 1 | S | Number of parameters in mixed model
fm1
fixed = distance ~ age, random = ~ 1 | Subject
K = 4: the coefficients for intercept, and age; variances for random intercept, and error term.
fm2
fixed = distance ~ age + Sex, random = ~ 1 | Subject
K = 5: the coefficients for intercept, age, and Sex; variances for random intercept, and error term.
fm3
fixed = distance ~ age, random = ~ age | Subject
K = 6: the coefficients for intercept, and age; variances for random intercept, age, and error term; covariance between random effects of intercept and age.
fm4
fixed = distance ~ age + Sex, random = ~ age | Subject
K = 7: the coefficients for intercept, age, and Sex; variances for random intercept, age, and error term; covariance between random effects of intercept and age.
fm5
fixed = distance ~ age + Sex, random = ~ age + Sex | Subject
K = 10: the coefficients for intercept, age, and Sex; variances for random intercept, age, Sex, and error term; covariances between random effects of intercept and age, intercept and Sex, and age and Sex. | Number of parameters in mixed model
fm1
fixed = distance ~ age, random = ~ 1 | Subject
K = 4: the coefficients for intercept, and age; variances for random intercept, and error term.
fm2
fixed = distance ~ age + Sex, random = ~ 1 | S |
36,313 | np package kernel density estimation with Epanechnikov kernel | EDIT
This is explained in the FAQ:
I use plot() (npplot()) to plot, say, a density and the resulting plot looks
like an inverted density rather than a density
This can occur when the datadriven
bandwidth is dramatically undersmoothed. Data-driven (i.e., automatic) bandwidth
selection procedures are not guaranteed always to produce good results due to perhaps the
presence of outliers or the rounding/discretization of continuous data, among others. By
default, npplot() takes the two extremes of the data (minimum, maximum i.e., actual data
points) then creates an equally spaced grid of evaluation data (i.e., not actual data points in
general) and computes the density for these points. Since the bandwidth is extremely small,
the density estimate at these evaluation points is correctly zero, while those for the sample
realizations (in this case only two, the min and max) are non-zero, hence we get two peaks
at the edges of the plot and a flat bowl equal to zero everywhere else.
This can also happen when your data is heavily discretized and you treat it as continuous.
In such cases, treating the data as ordered may result in more sensible estimates
As suggested treating the data as ordered, works:
blep<-npudensbw(~ordered(geyser$waiting),
bwmethod="cv.ls", ckertype="epanechnikov", ckerorder=2)
It also succeeds with higher kernel orders, such as with ckerorder=4 in this example: | np package kernel density estimation with Epanechnikov kernel | EDIT
This is explained in the FAQ:
I use plot() (npplot()) to plot, say, a density and the resulting plot looks
like an inverted density rather than a density
This can occur when the datadriven
b | np package kernel density estimation with Epanechnikov kernel
EDIT
This is explained in the FAQ:
I use plot() (npplot()) to plot, say, a density and the resulting plot looks
like an inverted density rather than a density
This can occur when the datadriven
bandwidth is dramatically undersmoothed. Data-driven (i.e., automatic) bandwidth
selection procedures are not guaranteed always to produce good results due to perhaps the
presence of outliers or the rounding/discretization of continuous data, among others. By
default, npplot() takes the two extremes of the data (minimum, maximum i.e., actual data
points) then creates an equally spaced grid of evaluation data (i.e., not actual data points in
general) and computes the density for these points. Since the bandwidth is extremely small,
the density estimate at these evaluation points is correctly zero, while those for the sample
realizations (in this case only two, the min and max) are non-zero, hence we get two peaks
at the edges of the plot and a flat bowl equal to zero everywhere else.
This can also happen when your data is heavily discretized and you treat it as continuous.
In such cases, treating the data as ordered may result in more sensible estimates
As suggested treating the data as ordered, works:
blep<-npudensbw(~ordered(geyser$waiting),
bwmethod="cv.ls", ckertype="epanechnikov", ckerorder=2)
It also succeeds with higher kernel orders, such as with ckerorder=4 in this example: | np package kernel density estimation with Epanechnikov kernel
EDIT
This is explained in the FAQ:
I use plot() (npplot()) to plot, say, a density and the resulting plot looks
like an inverted density rather than a density
This can occur when the datadriven
b |
36,314 | What are Monte Carlo simulations? | Monte Carlo method (there is also Monte Carlo algorithm) is a general name for a broad class of algorithms that use random sampling to obtain numerical results. It is used to solve statistical problems by simulation. It was one of the first methods of computer simulation that was described (see here for broader introduction and references). In plain English, Monte Carlo is drawing random numbers to simulate something and afterwards some kind of aggregation is often used to make conclusions about the simulated phenomenon.
The name, as Metropolis himself recalls (see also here), is inspired by the name of casino,
It was that time I suggested an obvious name for statistical method -
a suggestion not unrelated to the fact that Stan [Ulam] had an uncle
who would borrow money from the relatives because he "just had to go
to Monte Carlo".
Metropolis, N. (1987). The Beginning of Monte Carlo Method. Los Alamos Science, 125-130.
Anderson, H.L. (1986). Metropolis, Monte Carlo, and MANIAC. Los Alamos Science, 96-108. | What are Monte Carlo simulations? | Monte Carlo method (there is also Monte Carlo algorithm) is a general name for a broad class of algorithms that use random sampling to obtain numerical results. It is used to solve statistical problem | What are Monte Carlo simulations?
Monte Carlo method (there is also Monte Carlo algorithm) is a general name for a broad class of algorithms that use random sampling to obtain numerical results. It is used to solve statistical problems by simulation. It was one of the first methods of computer simulation that was described (see here for broader introduction and references). In plain English, Monte Carlo is drawing random numbers to simulate something and afterwards some kind of aggregation is often used to make conclusions about the simulated phenomenon.
The name, as Metropolis himself recalls (see also here), is inspired by the name of casino,
It was that time I suggested an obvious name for statistical method -
a suggestion not unrelated to the fact that Stan [Ulam] had an uncle
who would borrow money from the relatives because he "just had to go
to Monte Carlo".
Metropolis, N. (1987). The Beginning of Monte Carlo Method. Los Alamos Science, 125-130.
Anderson, H.L. (1986). Metropolis, Monte Carlo, and MANIAC. Los Alamos Science, 96-108. | What are Monte Carlo simulations?
Monte Carlo method (there is also Monte Carlo algorithm) is a general name for a broad class of algorithms that use random sampling to obtain numerical results. It is used to solve statistical problem |
36,315 | What are Monte Carlo simulations? | A repeated experiment is a good start .
In finance, for example, we try to plan for a 30 year retirement, with investment returns that are not guaranteed. One model states that each year has a 10% return with 14% standard deviation.
Monte Carlo can help us understand the expected return by treating this return as a random event and running the 30 year return some 1000+ times. | What are Monte Carlo simulations? | A repeated experiment is a good start .
In finance, for example, we try to plan for a 30 year retirement, with investment returns that are not guaranteed. One model states that each year has a 10% re | What are Monte Carlo simulations?
A repeated experiment is a good start .
In finance, for example, we try to plan for a 30 year retirement, with investment returns that are not guaranteed. One model states that each year has a 10% return with 14% standard deviation.
Monte Carlo can help us understand the expected return by treating this return as a random event and running the 30 year return some 1000+ times. | What are Monte Carlo simulations?
A repeated experiment is a good start .
In finance, for example, we try to plan for a 30 year retirement, with investment returns that are not guaranteed. One model states that each year has a 10% re |
36,316 | Grid fineness and overfitting when tuning $\lambda$ in LASSO, ridge, elastic net | Can I say something about the propensity to overfit in (A) versus (B)?
Provided that both grids cover a sufficient range, grid fineness doesn't really have anything to do with overfitting in this problem (though a coarse grid might underfit if it skips over a profitable interval). It's not as if testing too many values will somehow change what out-of-sample looks like.* In the case of these penalized regressions, we definitely want to optimize our penalized likelihood function for values $\lambda$, and it doesn't matter how many values of $\lambda$ we test, because out-of-sample performance for a fixed data set and fixed partitioning is entirely deterministic. More to the point, the out-of-sample metric is not at all altered by how many values $\lambda$ you test. A coarser grid might mean that you skip over the absolute minimum in your out-of-sample metric, but finding the absolute minimum probably isn't desirable in the first place because hyperparameters tend to be poorly estimated, and finite sample properties mean that data limitations will be a source noise in that estimate that will overwhelm slight changes in the distance between adjacent grid points: the standard error of your estimate will tend to swamp differences in grid fineness.
If you're truely concerned that out-of-sample performance metric might be overly optimistic, you could adopt the 1 standard error rule, which picks the most regularized model within 1 standard error of the minimum. That way, you're being slightly more conservative and picking a less complex model.
Can I determine the optimal grid fineness? How?
The LARS algorithm does not a priori define which values of $\lambda$ to check; rather, $\lambda$ is changed continuously and the algorithm checks for values of $\lambda$ for which a coefficient goes from 0 to a nonzero value. Those values of $\lambda$ where a new coefficient is nonzero are retained, with the observation that coefficient paths are piecewise linear in the case of the lasso, so there's no loss of information by just storing off the knots in that case. LARS only works when coefficient paths are piecewise linear, though. The ridge penalty never shrinks a coefficient to precisely zero, so all of your coefficient paths are smooth and always nonzero; likewise elastic net regressions (excluding the case of elastic net regressions which are also lasso regressions).
But most people use GLMNET because it's often faster. In terms of determining what grid of $\lambda$ to search over, I recommend reading the GLMNET article "Regularization Paths for Generalized Linear Models via Coordinate Descent" by Jerome Friedman, Trevor Hastie, and Rob Tibshirani. In it, they develop a very efficient algorithm for estimating ridge, lasso and elastic net regressions. The algorithm checks for a value of $\lambda_\text{max}$ for which $\beta$ is the zero vector, and then identifies a minimum value $\lambda_\text{min}$ relative to $\lambda_\text{max}$. Finally, they generate a sequence of values between the two uniformly on the log scale. This grid is sufficient for most purposes, though it does omit the property that you will know precisely when a coefficient is estimated at a nonzero value. Warm starts are used to provide solutions much more quickly, and it supports many common GLMs.
*You might be thinking about this from the perspective of an artificial neural network, where early stopping is sometimes used to accomplish regularization, but that's an entirely unrelated problem (namely, that the optimization algorithm is prevented from reaching an optimum, so the model is forced to be less complex). | Grid fineness and overfitting when tuning $\lambda$ in LASSO, ridge, elastic net | Can I say something about the propensity to overfit in (A) versus (B)?
Provided that both grids cover a sufficient range, grid fineness doesn't really have anything to do with overfitting in this pro | Grid fineness and overfitting when tuning $\lambda$ in LASSO, ridge, elastic net
Can I say something about the propensity to overfit in (A) versus (B)?
Provided that both grids cover a sufficient range, grid fineness doesn't really have anything to do with overfitting in this problem (though a coarse grid might underfit if it skips over a profitable interval). It's not as if testing too many values will somehow change what out-of-sample looks like.* In the case of these penalized regressions, we definitely want to optimize our penalized likelihood function for values $\lambda$, and it doesn't matter how many values of $\lambda$ we test, because out-of-sample performance for a fixed data set and fixed partitioning is entirely deterministic. More to the point, the out-of-sample metric is not at all altered by how many values $\lambda$ you test. A coarser grid might mean that you skip over the absolute minimum in your out-of-sample metric, but finding the absolute minimum probably isn't desirable in the first place because hyperparameters tend to be poorly estimated, and finite sample properties mean that data limitations will be a source noise in that estimate that will overwhelm slight changes in the distance between adjacent grid points: the standard error of your estimate will tend to swamp differences in grid fineness.
If you're truely concerned that out-of-sample performance metric might be overly optimistic, you could adopt the 1 standard error rule, which picks the most regularized model within 1 standard error of the minimum. That way, you're being slightly more conservative and picking a less complex model.
Can I determine the optimal grid fineness? How?
The LARS algorithm does not a priori define which values of $\lambda$ to check; rather, $\lambda$ is changed continuously and the algorithm checks for values of $\lambda$ for which a coefficient goes from 0 to a nonzero value. Those values of $\lambda$ where a new coefficient is nonzero are retained, with the observation that coefficient paths are piecewise linear in the case of the lasso, so there's no loss of information by just storing off the knots in that case. LARS only works when coefficient paths are piecewise linear, though. The ridge penalty never shrinks a coefficient to precisely zero, so all of your coefficient paths are smooth and always nonzero; likewise elastic net regressions (excluding the case of elastic net regressions which are also lasso regressions).
But most people use GLMNET because it's often faster. In terms of determining what grid of $\lambda$ to search over, I recommend reading the GLMNET article "Regularization Paths for Generalized Linear Models via Coordinate Descent" by Jerome Friedman, Trevor Hastie, and Rob Tibshirani. In it, they develop a very efficient algorithm for estimating ridge, lasso and elastic net regressions. The algorithm checks for a value of $\lambda_\text{max}$ for which $\beta$ is the zero vector, and then identifies a minimum value $\lambda_\text{min}$ relative to $\lambda_\text{max}$. Finally, they generate a sequence of values between the two uniformly on the log scale. This grid is sufficient for most purposes, though it does omit the property that you will know precisely when a coefficient is estimated at a nonzero value. Warm starts are used to provide solutions much more quickly, and it supports many common GLMs.
*You might be thinking about this from the perspective of an artificial neural network, where early stopping is sometimes used to accomplish regularization, but that's an entirely unrelated problem (namely, that the optimization algorithm is prevented from reaching an optimum, so the model is forced to be less complex). | Grid fineness and overfitting when tuning $\lambda$ in LASSO, ridge, elastic net
Can I say something about the propensity to overfit in (A) versus (B)?
Provided that both grids cover a sufficient range, grid fineness doesn't really have anything to do with overfitting in this pro |
36,317 | How to use R anova() results to select best model? | Question 1:
Regarding the difference in p-values (or F-values) for Model 2 in the first ANOVA compared to the second, there is no explanation apparent to me. They should indeed be the same, since we are comparing at that point Model 1 to Model 2 in both instances. It would be very useful to get further input about the reason behind, but in the absence of an explanation, it is probably advisable to only include two models in each ANOVA call. The values calculated "manually" (I presume the correct values) are consistent with the first ANOVA call in your post with an F = 8.2852.
Question 2:
You are comparing 51.692 and 0.126 BUT this bulkier difference in the second case is a good thing: What you should be paying attention to is the difference in the second ANOVA between 246.68 for Model 2 and 194.99 for Model 3, which is much more of a drop in RSS than what you observe in in the first ANOVA, a change from 246.68 to 246.56, tantamount to nothing. So by including the third regressor in the second ANOVA, you shave off a ton of residual (misfitted) information that is now captured, whereas you hardly made a dent in the first set of models.
Question 3:
The question is how to use ANOVA to find the best model, but I think the answer is clear by now - low p-value makes it a good bet that you should include the regressor under consideration. Yet, what is not clear at all is the process by which you move along a series of ANOVA tests. In other words, I know you know because I've taken the Coursera course, that at first you are acquainted with $R^2$, which you can calculate manually, and understand the idea here (among many other places); after the idea of overfitting is introduced, Adjusted-$R^2$ values are explained, shortly followed by, yes, ANOVA (F-test). All these and others, such as the AIC criterion are tests or criteria to select models or include / exclude regressors. For instance, AIC and BIC used for non-nested models, and ANOVA and Likelihood Ratio Tests for nested models (I'm quoting a comment by @f coppens in this post.
The challenge, though, is to come up with models that make sense to test (check this post). Say you have 5 independent variables, and you are doing linear regression, or OLS, you can include or exclude each variable in the any conceivable model for a total of $2^{10}=1,024$ models before considering interactions (remember that mtcars has 10 variables besides mpg). This has its own problems with collinearity for instance. You can resort to your knowledge of cars, or just run with raw computer power through all combinations either with forward or backward stepwise selection as very nicely explained in this document, using R code along the lines of:
fit.full <- lm(mpg ~ ., data = mtcars)
for.aic <- step(lm(mpg ~ 1, data = mtcars), direction = "forward",
scope = formula(fit.full), k = 2, trace = 0) # forward AIC
for.bic <- step(lm(mpg ~ 1, data=mtcars), direction = "forward",
scope = formula(fit.full), k = log(32), trace = 0) # forward BIC
back.aic <- step(fit.full, direction = "backward", k = 2, trace = 0) # backward AIC
back.bic <- step(fit.full, direction = "backward", k = log(32), trace = 0) # backward BIC
(Adjusted_R.square <- data.frame("Method"=c("for.aic", "for.bic", "back.aic", "back.bic"),
"Adj.r.square"=c(summary(for.aic)$adj.r.square, summary(for.bic)$adj.r.square,
summary(back.aic)$adj.r.square, summary(back.bic)$adj.r.square)))
summary(back.bic)
to select the model with the highest adjusted $R^2$ (or you can also run ANOVA) with the idea of later looking into possible interactions, and running residuals diagnostics. | How to use R anova() results to select best model? | Question 1:
Regarding the difference in p-values (or F-values) for Model 2 in the first ANOVA compared to the second, there is no explanation apparent to me. They should indeed be the same, since we | How to use R anova() results to select best model?
Question 1:
Regarding the difference in p-values (or F-values) for Model 2 in the first ANOVA compared to the second, there is no explanation apparent to me. They should indeed be the same, since we are comparing at that point Model 1 to Model 2 in both instances. It would be very useful to get further input about the reason behind, but in the absence of an explanation, it is probably advisable to only include two models in each ANOVA call. The values calculated "manually" (I presume the correct values) are consistent with the first ANOVA call in your post with an F = 8.2852.
Question 2:
You are comparing 51.692 and 0.126 BUT this bulkier difference in the second case is a good thing: What you should be paying attention to is the difference in the second ANOVA between 246.68 for Model 2 and 194.99 for Model 3, which is much more of a drop in RSS than what you observe in in the first ANOVA, a change from 246.68 to 246.56, tantamount to nothing. So by including the third regressor in the second ANOVA, you shave off a ton of residual (misfitted) information that is now captured, whereas you hardly made a dent in the first set of models.
Question 3:
The question is how to use ANOVA to find the best model, but I think the answer is clear by now - low p-value makes it a good bet that you should include the regressor under consideration. Yet, what is not clear at all is the process by which you move along a series of ANOVA tests. In other words, I know you know because I've taken the Coursera course, that at first you are acquainted with $R^2$, which you can calculate manually, and understand the idea here (among many other places); after the idea of overfitting is introduced, Adjusted-$R^2$ values are explained, shortly followed by, yes, ANOVA (F-test). All these and others, such as the AIC criterion are tests or criteria to select models or include / exclude regressors. For instance, AIC and BIC used for non-nested models, and ANOVA and Likelihood Ratio Tests for nested models (I'm quoting a comment by @f coppens in this post.
The challenge, though, is to come up with models that make sense to test (check this post). Say you have 5 independent variables, and you are doing linear regression, or OLS, you can include or exclude each variable in the any conceivable model for a total of $2^{10}=1,024$ models before considering interactions (remember that mtcars has 10 variables besides mpg). This has its own problems with collinearity for instance. You can resort to your knowledge of cars, or just run with raw computer power through all combinations either with forward or backward stepwise selection as very nicely explained in this document, using R code along the lines of:
fit.full <- lm(mpg ~ ., data = mtcars)
for.aic <- step(lm(mpg ~ 1, data = mtcars), direction = "forward",
scope = formula(fit.full), k = 2, trace = 0) # forward AIC
for.bic <- step(lm(mpg ~ 1, data=mtcars), direction = "forward",
scope = formula(fit.full), k = log(32), trace = 0) # forward BIC
back.aic <- step(fit.full, direction = "backward", k = 2, trace = 0) # backward AIC
back.bic <- step(fit.full, direction = "backward", k = log(32), trace = 0) # backward BIC
(Adjusted_R.square <- data.frame("Method"=c("for.aic", "for.bic", "back.aic", "back.bic"),
"Adj.r.square"=c(summary(for.aic)$adj.r.square, summary(for.bic)$adj.r.square,
summary(back.aic)$adj.r.square, summary(back.bic)$adj.r.square)))
summary(back.bic)
to select the model with the highest adjusted $R^2$ (or you can also run ANOVA) with the idea of later looking into possible interactions, and running residuals diagnostics. | How to use R anova() results to select best model?
Question 1:
Regarding the difference in p-values (or F-values) for Model 2 in the first ANOVA compared to the second, there is no explanation apparent to me. They should indeed be the same, since we |
36,318 | How to use R anova() results to select best model? | Question 1: Note, that the anova commands you provided above are equivalent to giving anova() the full model.
If you do the command:
anova(m3) # where m3 is lm(mpg~disp+wt+am,mtcars)
anova(m4) # where m4 is lm(mpg~disp+wt+hp,mtcars)
you will see that the anova is really telling you the significance of each variable in the model. I think you can only compare one nested model to a full model at a time. Incidentally, by testing model 1 against model 2 before, you should already know that you are going to include the first variable, so there is no need to test the model excluding this variable again. This leads to the question of "Which variable do I include first, then?" Model creation is really an art of sorts, but there is a function in the MASS library stepAIC() which allows you to select what could be the most important variables in terms of AIC or some other specified criteria. (Using forward, backward, or stepwise selection.)
Question 2: I believe this is answered above, but to be clear, these significance values are not for the nested model, but for the adding that parameter to the model.
Question 3: Once you get into data that has a very large amount of possible predictors, you are not going to want to use anova() unless you have a general idea of what you want to include. If you want to know the effect of one specific variable (or a specific set of variables in a specific order), it is a good idea to use anova. If you really have no idea and are testing more with more than 10-15 possible combinations of predictors, I would suggest using something like stepAIC. LASSO and ridge regression are other ways to select parameters beyond just trying out with anova one at a time by hand or using stepAIC to automate a similar process. | How to use R anova() results to select best model? | Question 1: Note, that the anova commands you provided above are equivalent to giving anova() the full model.
If you do the command:
anova(m3) # where m3 is lm(mpg~disp+wt+am,mtcars)
anova(m4) # wher | How to use R anova() results to select best model?
Question 1: Note, that the anova commands you provided above are equivalent to giving anova() the full model.
If you do the command:
anova(m3) # where m3 is lm(mpg~disp+wt+am,mtcars)
anova(m4) # where m4 is lm(mpg~disp+wt+hp,mtcars)
you will see that the anova is really telling you the significance of each variable in the model. I think you can only compare one nested model to a full model at a time. Incidentally, by testing model 1 against model 2 before, you should already know that you are going to include the first variable, so there is no need to test the model excluding this variable again. This leads to the question of "Which variable do I include first, then?" Model creation is really an art of sorts, but there is a function in the MASS library stepAIC() which allows you to select what could be the most important variables in terms of AIC or some other specified criteria. (Using forward, backward, or stepwise selection.)
Question 2: I believe this is answered above, but to be clear, these significance values are not for the nested model, but for the adding that parameter to the model.
Question 3: Once you get into data that has a very large amount of possible predictors, you are not going to want to use anova() unless you have a general idea of what you want to include. If you want to know the effect of one specific variable (or a specific set of variables in a specific order), it is a good idea to use anova. If you really have no idea and are testing more with more than 10-15 possible combinations of predictors, I would suggest using something like stepAIC. LASSO and ridge regression are other ways to select parameters beyond just trying out with anova one at a time by hand or using stepAIC to automate a similar process. | How to use R anova() results to select best model?
Question 1: Note, that the anova commands you provided above are equivalent to giving anova() the full model.
If you do the command:
anova(m3) # where m3 is lm(mpg~disp+wt+am,mtcars)
anova(m4) # wher |
36,319 | How to use R anova() results to select best model? | For Question 3 I would like to add to the answer given by Antoni.
It is better to use cross-validation which is a direct method to choose among various models in forward stepwise, backward stepwise or best subset instead of being confused among which to use. This will not require you to use ANOVA() at all. ANOVA is better to use when you are adding terms like interactions, polynomial terms, splines, etc., | How to use R anova() results to select best model? | For Question 3 I would like to add to the answer given by Antoni.
It is better to use cross-validation which is a direct method to choose among various models in forward stepwise, backward stepwise or | How to use R anova() results to select best model?
For Question 3 I would like to add to the answer given by Antoni.
It is better to use cross-validation which is a direct method to choose among various models in forward stepwise, backward stepwise or best subset instead of being confused among which to use. This will not require you to use ANOVA() at all. ANOVA is better to use when you are adding terms like interactions, polynomial terms, splines, etc., | How to use R anova() results to select best model?
For Question 3 I would like to add to the answer given by Antoni.
It is better to use cross-validation which is a direct method to choose among various models in forward stepwise, backward stepwise or |
36,320 | Cohen's d from regression coefficient? | Cohen's d is the mean difference divided by the (pooled) standard deviation of the data within the groups. Indeed, the coefficient for the dummy variable gives you the mean difference, but instead of dividing by the standard deviation of the dependent variable, you should divide by the (pooled) within-group standard deviation. In fact, the residual standard error will give you exactly what you need.
If there are other covariates in the model, then the coefficient for the dummy variable represents an adjusted mean difference and the residual standard error will be reduced to some extent, depending on how much those other covariates account for the within-group variability. So, keeping that in mind, yes, dividing the coefficient for the dummy by the residual standard error will then give you something analogous to Cohen's d. | Cohen's d from regression coefficient? | Cohen's d is the mean difference divided by the (pooled) standard deviation of the data within the groups. Indeed, the coefficient for the dummy variable gives you the mean difference, but instead of | Cohen's d from regression coefficient?
Cohen's d is the mean difference divided by the (pooled) standard deviation of the data within the groups. Indeed, the coefficient for the dummy variable gives you the mean difference, but instead of dividing by the standard deviation of the dependent variable, you should divide by the (pooled) within-group standard deviation. In fact, the residual standard error will give you exactly what you need.
If there are other covariates in the model, then the coefficient for the dummy variable represents an adjusted mean difference and the residual standard error will be reduced to some extent, depending on how much those other covariates account for the within-group variability. So, keeping that in mind, yes, dividing the coefficient for the dummy by the residual standard error will then give you something analogous to Cohen's d. | Cohen's d from regression coefficient?
Cohen's d is the mean difference divided by the (pooled) standard deviation of the data within the groups. Indeed, the coefficient for the dummy variable gives you the mean difference, but instead of |
36,321 | Confidence intervals derived from 'inverted hypothesis test' | The idea is that your hypothesis test is comparing the statistic from you data to some parameter $\theta_0$. The confidence interval consists of all possible values of $\theta_0$ that the test would not reject for the given data. Usually instead of finding every possible value we just invert the equation for the test statistic to give us the boundary values and all values in between will be the interval. | Confidence intervals derived from 'inverted hypothesis test' | The idea is that your hypothesis test is comparing the statistic from you data to some parameter $\theta_0$. The confidence interval consists of all possible values of $\theta_0$ that the test would | Confidence intervals derived from 'inverted hypothesis test'
The idea is that your hypothesis test is comparing the statistic from you data to some parameter $\theta_0$. The confidence interval consists of all possible values of $\theta_0$ that the test would not reject for the given data. Usually instead of finding every possible value we just invert the equation for the test statistic to give us the boundary values and all values in between will be the interval. | Confidence intervals derived from 'inverted hypothesis test'
The idea is that your hypothesis test is comparing the statistic from you data to some parameter $\theta_0$. The confidence interval consists of all possible values of $\theta_0$ that the test would |
36,322 | Power of a Interaction term in R | I do not think there is an R function to calculate this power. My usual suggestion in such cases is to simulate (e.g., here or here or here). Specifically, pick a sample size $n$, simulate your covariate, your binary variable, the dependence of your outcome on both and the noise. Fit your model and assess whether $p<\alpha$. Do this many times and see how often you detect a significant effect. If you want to determine the necessary sample size to reach a target power, change the $n$ until you reach the power you want.
Yes, this means you have to think about many assumptions (e.g., the distributions of your IVs, whether they are independent, whether linearity makes sense, whether your errors will really be homoskedastic, ...). I would argue that this is a feature, not a bug. You will definitely gain more understanding of your problem than if you found a ready-made power calculator, and it's better to gain this understanding before you run your study than afterwards.
(You are asking before you run your study, for sample size determination, right? So-called "post-hoc power" is meaningless.)
One additional advantage is that the flexibility of this approach allows you to vary your assumptions and analyze whether the power degrades. Or you could simulate other data problems, like missing data etc.
Here is some very simple R code, where I am assuming $n=50$, group membership that is random 50-50, a uniformly distributed covariate that is independent of group membership, and an outcome
$$y=\text{covariate}+\text{groups}*\text{covariate}+\epsilon$$
with $\epsilon\sim N(0,1)$. In this case, power comes out to be 0.166. If you want the standard $\beta=0.80$, you can increase $n$ or change your model assumptions - and think about whether the changed assumptions make sense.
n_sims <- 1000
nn <- 50
alpha <- 0.05
result <- rep(FALSE,n_sims)
pb <- winProgressBar(max=n_sims)
for ( ii in 1:n_sims ) {
setWinProgressBar(pb,ii,paste(ii,"of",n_sims))
set.seed(ii) # for reproducibility
# this is where the assumptions enter
covariate <- runif(nn)
groups <- runif(nn)<0.5
outcome <- covariate+groups*covariate+rnorm(nn,1)
# fit the model, determine whether an effect was found
model <- lm(outcome~groups*covariate)
p_value <- anova(model,update(model,.~.-groups:covariate))[2,6]
result[ii] <- p_value<alpha
}
close(pb)
sum(result)/n_sims | Power of a Interaction term in R | I do not think there is an R function to calculate this power. My usual suggestion in such cases is to simulate (e.g., here or here or here). Specifically, pick a sample size $n$, simulate your covari | Power of a Interaction term in R
I do not think there is an R function to calculate this power. My usual suggestion in such cases is to simulate (e.g., here or here or here). Specifically, pick a sample size $n$, simulate your covariate, your binary variable, the dependence of your outcome on both and the noise. Fit your model and assess whether $p<\alpha$. Do this many times and see how often you detect a significant effect. If you want to determine the necessary sample size to reach a target power, change the $n$ until you reach the power you want.
Yes, this means you have to think about many assumptions (e.g., the distributions of your IVs, whether they are independent, whether linearity makes sense, whether your errors will really be homoskedastic, ...). I would argue that this is a feature, not a bug. You will definitely gain more understanding of your problem than if you found a ready-made power calculator, and it's better to gain this understanding before you run your study than afterwards.
(You are asking before you run your study, for sample size determination, right? So-called "post-hoc power" is meaningless.)
One additional advantage is that the flexibility of this approach allows you to vary your assumptions and analyze whether the power degrades. Or you could simulate other data problems, like missing data etc.
Here is some very simple R code, where I am assuming $n=50$, group membership that is random 50-50, a uniformly distributed covariate that is independent of group membership, and an outcome
$$y=\text{covariate}+\text{groups}*\text{covariate}+\epsilon$$
with $\epsilon\sim N(0,1)$. In this case, power comes out to be 0.166. If you want the standard $\beta=0.80$, you can increase $n$ or change your model assumptions - and think about whether the changed assumptions make sense.
n_sims <- 1000
nn <- 50
alpha <- 0.05
result <- rep(FALSE,n_sims)
pb <- winProgressBar(max=n_sims)
for ( ii in 1:n_sims ) {
setWinProgressBar(pb,ii,paste(ii,"of",n_sims))
set.seed(ii) # for reproducibility
# this is where the assumptions enter
covariate <- runif(nn)
groups <- runif(nn)<0.5
outcome <- covariate+groups*covariate+rnorm(nn,1)
# fit the model, determine whether an effect was found
model <- lm(outcome~groups*covariate)
p_value <- anova(model,update(model,.~.-groups:covariate))[2,6]
result[ii] <- p_value<alpha
}
close(pb)
sum(result)/n_sims | Power of a Interaction term in R
I do not think there is an R function to calculate this power. My usual suggestion in such cases is to simulate (e.g., here or here or here). Specifically, pick a sample size $n$, simulate your covari |
36,323 | Power of a Interaction term in R | The R package InteractionPoweR can do a power analysis for this sort of regression.
install.packages("devtools")
devtools::install_github("dbaranger/InteractionPoweR")
library(InteractionPoweR)
test_power<-power_interaction(
n.iter = 1000, # number of simulations per unique combination of input parameters
alpha = 0.05, # alpha, for the power analysis
N = 350, # sample size
r.x1x2.y = .15, # interaction effect to test (correlation between x1*x2 and y)
r.x1.y = .2, # correlation between x1 and y
r.x2.y = .1, # correlation between x2 and y
r.x1.x2 = .2, # correlation between x1 and x2
k.x1 = 2, # x1 is binary
seed = 581827 # seed, for reproducibility
adjust.correlations = TRUE) # Adjust correlations | Power of a Interaction term in R | The R package InteractionPoweR can do a power analysis for this sort of regression.
install.packages("devtools")
devtools::install_github("dbaranger/InteractionPoweR")
library(InteractionPoweR)
test | Power of a Interaction term in R
The R package InteractionPoweR can do a power analysis for this sort of regression.
install.packages("devtools")
devtools::install_github("dbaranger/InteractionPoweR")
library(InteractionPoweR)
test_power<-power_interaction(
n.iter = 1000, # number of simulations per unique combination of input parameters
alpha = 0.05, # alpha, for the power analysis
N = 350, # sample size
r.x1x2.y = .15, # interaction effect to test (correlation between x1*x2 and y)
r.x1.y = .2, # correlation between x1 and y
r.x2.y = .1, # correlation between x2 and y
r.x1.x2 = .2, # correlation between x1 and x2
k.x1 = 2, # x1 is binary
seed = 581827 # seed, for reproducibility
adjust.correlations = TRUE) # Adjust correlations | Power of a Interaction term in R
The R package InteractionPoweR can do a power analysis for this sort of regression.
install.packages("devtools")
devtools::install_github("dbaranger/InteractionPoweR")
library(InteractionPoweR)
test |
36,324 | How to use log probabilities for Gaussian Naive Bayes? [duplicate] | The third option is right one. In general, it is true that:
$$ \log(ab) = \log(a) + \log(b)$$
Plugging in the Naive Bayes equation, you get
$$ \log(P(\text{class }_i| \textbf{ data})) \propto \log(P(\text{class}_i)) + \sum_j \log(P(\textrm{data}_j|\text{class}_i))$$
This value may be negative. If your all of your terms were actual probabilities, they'd be between zero and one, so the logs would all be between $- \infty$ and zero, as would their sum. In fact, you should be concerned if you see a positive log-probability. We often sashay around this fact by calculating the negative log-likelihood of something, which removes the minus-sign.
This doesn't necessarily hold if you're throwing probability densities into the mix, since those values can be larger than 1.
There are a few posts about determining variable importance in Naive Bayes (e.g., this one), so you may want to start there.... | How to use log probabilities for Gaussian Naive Bayes? [duplicate] | The third option is right one. In general, it is true that:
$$ \log(ab) = \log(a) + \log(b)$$
Plugging in the Naive Bayes equation, you get
$$ \log(P(\text{class }_i| \textbf{ data})) \propto \log(P(\ | How to use log probabilities for Gaussian Naive Bayes? [duplicate]
The third option is right one. In general, it is true that:
$$ \log(ab) = \log(a) + \log(b)$$
Plugging in the Naive Bayes equation, you get
$$ \log(P(\text{class }_i| \textbf{ data})) \propto \log(P(\text{class}_i)) + \sum_j \log(P(\textrm{data}_j|\text{class}_i))$$
This value may be negative. If your all of your terms were actual probabilities, they'd be between zero and one, so the logs would all be between $- \infty$ and zero, as would their sum. In fact, you should be concerned if you see a positive log-probability. We often sashay around this fact by calculating the negative log-likelihood of something, which removes the minus-sign.
This doesn't necessarily hold if you're throwing probability densities into the mix, since those values can be larger than 1.
There are a few posts about determining variable importance in Naive Bayes (e.g., this one), so you may want to start there.... | How to use log probabilities for Gaussian Naive Bayes? [duplicate]
The third option is right one. In general, it is true that:
$$ \log(ab) = \log(a) + \log(b)$$
Plugging in the Naive Bayes equation, you get
$$ \log(P(\text{class }_i| \textbf{ data})) \propto \log(P(\ |
36,325 | Lindeberg CLT for exponential independent variables | When $\mu_j=1/j$ (which satisfies the assumptions of the book), it seems that the sequence $\left(\sum^n_{i=1}(e_i-\mu_i)/\sqrt{\sum^n_{j=1}\mu_j^2}\right)_{n\geqslant 1}$ converges to a constant plus a Gumbel distribution (see Subsection 5.3 in A uniform asymptotic expansion for
weighted sums of exponentials by
J.S.H. van Leeuwaarden and N.M. Temme.
Therefore, the condition
$$\tag{C} \lim_{n\to \infty}\max_{1\leqslant i\leqslant n}\frac{\mu_i^ 2}{\sum_{j=1}^n \mu_j^2 } =0$$
seems to be the good one. It can be either derived by the method described in the link of the question, or in a more general way here (in particular, it seems that we do not need to assume the random variables have exponential distribution, but only a finite variance). In both cases, Lindeberg's central limit theorem is used.
In general, if we want to prove a central limit theorem for $s_n^{-1}\sum_{j=1}^nX_{n,j}$, where $(X_{n,j})_{j=1}^n$ are independent and centered, and $s_n^2=\sum_{j=1}^n\operatorname{Var}(X_{n,j})$, we can use Lindeberg's condition, namely,
$$\forall \varepsilon\gt 0, \quad \lim_{n\to \infty} \frac 1{s_n^2}\sum_{j=1}^n\mathbb E\left[X_{n,j}^2\mathbf 1\{|X_{n,j}|\gt \varepsilon s_n \} \right] =0.$$
This implies that $s_n^{-1}\max_{1\leqslant j\leqslant n}\operatorname{Var}(X_{n,j})\to 0$. In our case, this is equivalent to condition (C). | Lindeberg CLT for exponential independent variables | When $\mu_j=1/j$ (which satisfies the assumptions of the book), it seems that the sequence $\left(\sum^n_{i=1}(e_i-\mu_i)/\sqrt{\sum^n_{j=1}\mu_j^2}\right)_{n\geqslant 1}$ converges to a constant plus | Lindeberg CLT for exponential independent variables
When $\mu_j=1/j$ (which satisfies the assumptions of the book), it seems that the sequence $\left(\sum^n_{i=1}(e_i-\mu_i)/\sqrt{\sum^n_{j=1}\mu_j^2}\right)_{n\geqslant 1}$ converges to a constant plus a Gumbel distribution (see Subsection 5.3 in A uniform asymptotic expansion for
weighted sums of exponentials by
J.S.H. van Leeuwaarden and N.M. Temme.
Therefore, the condition
$$\tag{C} \lim_{n\to \infty}\max_{1\leqslant i\leqslant n}\frac{\mu_i^ 2}{\sum_{j=1}^n \mu_j^2 } =0$$
seems to be the good one. It can be either derived by the method described in the link of the question, or in a more general way here (in particular, it seems that we do not need to assume the random variables have exponential distribution, but only a finite variance). In both cases, Lindeberg's central limit theorem is used.
In general, if we want to prove a central limit theorem for $s_n^{-1}\sum_{j=1}^nX_{n,j}$, where $(X_{n,j})_{j=1}^n$ are independent and centered, and $s_n^2=\sum_{j=1}^n\operatorname{Var}(X_{n,j})$, we can use Lindeberg's condition, namely,
$$\forall \varepsilon\gt 0, \quad \lim_{n\to \infty} \frac 1{s_n^2}\sum_{j=1}^n\mathbb E\left[X_{n,j}^2\mathbf 1\{|X_{n,j}|\gt \varepsilon s_n \} \right] =0.$$
This implies that $s_n^{-1}\max_{1\leqslant j\leqslant n}\operatorname{Var}(X_{n,j})\to 0$. In our case, this is equivalent to condition (C). | Lindeberg CLT for exponential independent variables
When $\mu_j=1/j$ (which satisfies the assumptions of the book), it seems that the sequence $\left(\sum^n_{i=1}(e_i-\mu_i)/\sqrt{\sum^n_{j=1}\mu_j^2}\right)_{n\geqslant 1}$ converges to a constant plus |
36,326 | Are group effects in a mixed effects model assumed to have been picked from a normal distribution? | You are correct in saying that in standard linear mixed effects models, the random effects are assumed to be normally distributed. Thus, if this assumption holds (at least approximately), we can use what we know about normal distributions to help describe the distribution of the random effects, such as 95% of the random effects should be within two standard deviations of 0 (since random effects are centered around 0).
That being said, it's important to check these assumptions, and it's not always so easy! If you have a good deal of data about each cluster, you can do something like a stratafied analysis and plot the confidence intervals for each cluster. This can still be a little difficult; suppose you have one extreme outlier, i.e. a tight confidence interval several standard deviations away from 0. Is this because this random effect is really huge and we are very certain about this? Or is this because we don't have a lot of data about this random effect and we've underestimated the variance due to small sample size?
As for the difference between simple linear regression and mixed effects models, the answer is that the mixed effects model is considerably more complicated. The random effects are assumed to have all been generated from the same (typically normal) distribution. As such, the estimate of a random effect is actually pulled in toward 0 (remember that random effects are centered at 0) compared if you had just fit a simple linear regression model with all fixed effects.
Also, another difference is that the random effects are fixed to have mean 0, allowing full identifiability of the model: if you tried to fit the main effect AND all the random effects in a simple linear model, your model would not be identifiable. This is because adding 1 to the main effect and subtracting 1 from the "random" effects (quotes used because you would be fitting them as fixed effects) would lead to the exact same predicted values. This issue is not so important though: one could easily just exclude the main effect from the model, and then if we were interested in examining the main effect, we would just take the average of all the "random" effects. However, as noted above, the estimated "random" effects would be much noisier than if they had been fit by a mixed effects model: the estimate would be based only on that cluster's information, rather than also borrowing off the information provided about the distribution of cluster effects. | Are group effects in a mixed effects model assumed to have been picked from a normal distribution? | You are correct in saying that in standard linear mixed effects models, the random effects are assumed to be normally distributed. Thus, if this assumption holds (at least approximately), we can use w | Are group effects in a mixed effects model assumed to have been picked from a normal distribution?
You are correct in saying that in standard linear mixed effects models, the random effects are assumed to be normally distributed. Thus, if this assumption holds (at least approximately), we can use what we know about normal distributions to help describe the distribution of the random effects, such as 95% of the random effects should be within two standard deviations of 0 (since random effects are centered around 0).
That being said, it's important to check these assumptions, and it's not always so easy! If you have a good deal of data about each cluster, you can do something like a stratafied analysis and plot the confidence intervals for each cluster. This can still be a little difficult; suppose you have one extreme outlier, i.e. a tight confidence interval several standard deviations away from 0. Is this because this random effect is really huge and we are very certain about this? Or is this because we don't have a lot of data about this random effect and we've underestimated the variance due to small sample size?
As for the difference between simple linear regression and mixed effects models, the answer is that the mixed effects model is considerably more complicated. The random effects are assumed to have all been generated from the same (typically normal) distribution. As such, the estimate of a random effect is actually pulled in toward 0 (remember that random effects are centered at 0) compared if you had just fit a simple linear regression model with all fixed effects.
Also, another difference is that the random effects are fixed to have mean 0, allowing full identifiability of the model: if you tried to fit the main effect AND all the random effects in a simple linear model, your model would not be identifiable. This is because adding 1 to the main effect and subtracting 1 from the "random" effects (quotes used because you would be fitting them as fixed effects) would lead to the exact same predicted values. This issue is not so important though: one could easily just exclude the main effect from the model, and then if we were interested in examining the main effect, we would just take the average of all the "random" effects. However, as noted above, the estimated "random" effects would be much noisier than if they had been fit by a mixed effects model: the estimate would be based only on that cluster's information, rather than also borrowing off the information provided about the distribution of cluster effects. | Are group effects in a mixed effects model assumed to have been picked from a normal distribution?
You are correct in saying that in standard linear mixed effects models, the random effects are assumed to be normally distributed. Thus, if this assumption holds (at least approximately), we can use w |
36,327 | Limitations to generalized additive model (GAM) | As mentioned in the comments, a propensity to overfit is a limitation of GAMs. Another limitation is that the model will lose predictability when the smoothed variables have values outside of the range of training dataset. Essentially, you are sacrificing predictability outside of your data range for precision within your data range. | Limitations to generalized additive model (GAM) | As mentioned in the comments, a propensity to overfit is a limitation of GAMs. Another limitation is that the model will lose predictability when the smoothed variables have values outside of the ran | Limitations to generalized additive model (GAM)
As mentioned in the comments, a propensity to overfit is a limitation of GAMs. Another limitation is that the model will lose predictability when the smoothed variables have values outside of the range of training dataset. Essentially, you are sacrificing predictability outside of your data range for precision within your data range. | Limitations to generalized additive model (GAM)
As mentioned in the comments, a propensity to overfit is a limitation of GAMs. Another limitation is that the model will lose predictability when the smoothed variables have values outside of the ran |
36,328 | Limitations to generalized additive model (GAM) | Probably one of the biggest limitations to GAMs is that they cannot model complex regression paths that involve multiple responses or things like mediation paths. Structural equation modeling (SEM) can achieve this, but generally the tools for nonlinear methods don't seem as developed like GAMs.
GAMs also don't allow you to directly model things like skew or kurtosis, which may make them more accurate. While this isn't always a huge concern for people using GAMs given how flexible they are, one alternative if one wants more specificity is GAMLSS. | Limitations to generalized additive model (GAM) | Probably one of the biggest limitations to GAMs is that they cannot model complex regression paths that involve multiple responses or things like mediation paths. Structural equation modeling (SEM) ca | Limitations to generalized additive model (GAM)
Probably one of the biggest limitations to GAMs is that they cannot model complex regression paths that involve multiple responses or things like mediation paths. Structural equation modeling (SEM) can achieve this, but generally the tools for nonlinear methods don't seem as developed like GAMs.
GAMs also don't allow you to directly model things like skew or kurtosis, which may make them more accurate. While this isn't always a huge concern for people using GAMs given how flexible they are, one alternative if one wants more specificity is GAMLSS. | Limitations to generalized additive model (GAM)
Probably one of the biggest limitations to GAMs is that they cannot model complex regression paths that involve multiple responses or things like mediation paths. Structural equation modeling (SEM) ca |
36,329 | Sufficient Statistic for non-exponential family distribution | First this is an exponential family (as shown by the above excerpt from Brown, 1986) since the density writes down as
$$\exp\{\Phi_1(\theta) S_1({\mathbf x})+\Phi_2(\theta) S_2({\mathbf x})-\Psi(\theta)\}$$against a particular dominating measure.
That the two coefficients $\Phi_1(\theta)$ and $\Phi_2(\theta)$ are connected with a functional relation is not an issue: they also both depend deterministically on $\theta$. The fact that $\theta$ is one-dimensional and the family is two-dimensional is a case of curved exponential families (see excerpt below from Brown, 1986). This family can be extended to a (full) truly two-dimensional parameter space, of which the ${\cal N}(\theta, 4\theta²)$ is a special case. Or a curve like $\Psi_1=\Psi_2^2/2$ in the extended (full) parameter space. But curved exponential families are special cases of exponential families, not generalisations.
Another reason for this distribution to be from an exponential family is that there exists a sufficient statistic of dimension two, whatever the sample size $n$ is. By the Darmois-Pitman-Koopman lemma this can only occur in an exponential family.
For the same reason as before, there can be a sufficient statistic of dimension two and a parameter of dimension one and this is not a contradiction, as the same sufficient statistic of dimension two serves for the extended (full) exponential family with two parameters. Examples (or paradoxes) where this happens abound in the literature. See for instance Romano and Siegel (1987). As pointed out by Kjetil B Halvorsen, these "paradoxes" are generally connected with a lack of completeness. | Sufficient Statistic for non-exponential family distribution | First this is an exponential family (as shown by the above excerpt from Brown, 1986) since the density writes down as
$$\exp\{\Phi_1(\theta) S_1({\mathbf x})+\Phi_2(\theta) S_2({\mathbf x})-\Psi(\thet | Sufficient Statistic for non-exponential family distribution
First this is an exponential family (as shown by the above excerpt from Brown, 1986) since the density writes down as
$$\exp\{\Phi_1(\theta) S_1({\mathbf x})+\Phi_2(\theta) S_2({\mathbf x})-\Psi(\theta)\}$$against a particular dominating measure.
That the two coefficients $\Phi_1(\theta)$ and $\Phi_2(\theta)$ are connected with a functional relation is not an issue: they also both depend deterministically on $\theta$. The fact that $\theta$ is one-dimensional and the family is two-dimensional is a case of curved exponential families (see excerpt below from Brown, 1986). This family can be extended to a (full) truly two-dimensional parameter space, of which the ${\cal N}(\theta, 4\theta²)$ is a special case. Or a curve like $\Psi_1=\Psi_2^2/2$ in the extended (full) parameter space. But curved exponential families are special cases of exponential families, not generalisations.
Another reason for this distribution to be from an exponential family is that there exists a sufficient statistic of dimension two, whatever the sample size $n$ is. By the Darmois-Pitman-Koopman lemma this can only occur in an exponential family.
For the same reason as before, there can be a sufficient statistic of dimension two and a parameter of dimension one and this is not a contradiction, as the same sufficient statistic of dimension two serves for the extended (full) exponential family with two parameters. Examples (or paradoxes) where this happens abound in the literature. See for instance Romano and Siegel (1987). As pointed out by Kjetil B Halvorsen, these "paradoxes" are generally connected with a lack of completeness. | Sufficient Statistic for non-exponential family distribution
First this is an exponential family (as shown by the above excerpt from Brown, 1986) since the density writes down as
$$\exp\{\Phi_1(\theta) S_1({\mathbf x})+\Phi_2(\theta) S_2({\mathbf x})-\Psi(\thet |
36,330 | Sufficient Statistic for non-exponential family distribution | There are different definitions of "sufficient statistic(s)" and "exponential family" by different authors. I wish the theoretical statisticians can agree on a single set of definitions to avoid confusing the world.
Most of authors do not require the dimensionality of sufficient statistics to match that of parameters.
Examples: https://en.wikipedia.org/wiki/Sufficient_statistic and "The Theory of Point Estimation" by Lehmann and Casella.
A few authors do. Examples: The great Mr. Fisher himself, and "Econometrics: Statistical Foundations and Applications" by Dhrymes.
Under the "more common" definition of exponential family, OP's example is a curved exponential, where the number of "natural" parameters $s$, exceeds the number of "original" parameters $k$. When $s = k$, it is called full-rank. It should be noted that $s < k$ can never happen, if the original parameters are identified in any open $k$ dimensional rectangle in $R^k$, | Sufficient Statistic for non-exponential family distribution | There are different definitions of "sufficient statistic(s)" and "exponential family" by different authors. I wish the theoretical statisticians can agree on a single set of definitions to avoid conf | Sufficient Statistic for non-exponential family distribution
There are different definitions of "sufficient statistic(s)" and "exponential family" by different authors. I wish the theoretical statisticians can agree on a single set of definitions to avoid confusing the world.
Most of authors do not require the dimensionality of sufficient statistics to match that of parameters.
Examples: https://en.wikipedia.org/wiki/Sufficient_statistic and "The Theory of Point Estimation" by Lehmann and Casella.
A few authors do. Examples: The great Mr. Fisher himself, and "Econometrics: Statistical Foundations and Applications" by Dhrymes.
Under the "more common" definition of exponential family, OP's example is a curved exponential, where the number of "natural" parameters $s$, exceeds the number of "original" parameters $k$. When $s = k$, it is called full-rank. It should be noted that $s < k$ can never happen, if the original parameters are identified in any open $k$ dimensional rectangle in $R^k$, | Sufficient Statistic for non-exponential family distribution
There are different definitions of "sufficient statistic(s)" and "exponential family" by different authors. I wish the theoretical statisticians can agree on a single set of definitions to avoid conf |
36,331 | What is a good way to test a simple Recurrent Neural Network | A very simple time series to validate the correctness of your code is the one caused by the function sin(x). It's periodic nature makes it a good test function imo. Just print out (or plot) the output activations of your network and compare it with the desired values to see the performance.
Alternatively you can just test XOR like Elman did in his original paper:
101 000 011 110 101 ... | What is a good way to test a simple Recurrent Neural Network | A very simple time series to validate the correctness of your code is the one caused by the function sin(x). It's periodic nature makes it a good test function imo. Just print out (or plot) the output | What is a good way to test a simple Recurrent Neural Network
A very simple time series to validate the correctness of your code is the one caused by the function sin(x). It's periodic nature makes it a good test function imo. Just print out (or plot) the output activations of your network and compare it with the desired values to see the performance.
Alternatively you can just test XOR like Elman did in his original paper:
101 000 011 110 101 ... | What is a good way to test a simple Recurrent Neural Network
A very simple time series to validate the correctness of your code is the one caused by the function sin(x). It's periodic nature makes it a good test function imo. Just print out (or plot) the output |
36,332 | What is a good way to test a simple Recurrent Neural Network | There's a good list of tests in Hochreiter's paper here. Also check this and the next slide on Schmidhuber's presentation. | What is a good way to test a simple Recurrent Neural Network | There's a good list of tests in Hochreiter's paper here. Also check this and the next slide on Schmidhuber's presentation. | What is a good way to test a simple Recurrent Neural Network
There's a good list of tests in Hochreiter's paper here. Also check this and the next slide on Schmidhuber's presentation. | What is a good way to test a simple Recurrent Neural Network
There's a good list of tests in Hochreiter's paper here. Also check this and the next slide on Schmidhuber's presentation. |
36,333 | Hierarchical clustering with agnes - how to cut the tree? | Husson et al. (2010) propose an empirical criterion based on the between-cluster inertia gain (see section 3.2 of this paper). Basically, the optimal number of clusters q is the one for which the increase in between-cluster dissimilarity for q clusters to q+1 clusters is significantly less than the increase in between-cluster dissimilarity for q-1 clusters to q clusters. So, it's similar to identifying a plateau in the plots above, but it's automatic and you don't have to "guess".
Still, you should keep in mind that each level of the dendogram corresponds to a valid partitioning of the observations, so there is no absolute best solution. The optimal number of clusters you want to select depends on your task. For example, when hierarchical clustering is used for outlier detection, you want to request a large number of clusters (n/10 in the example provided, where n is the total number of observations). | Hierarchical clustering with agnes - how to cut the tree? | Husson et al. (2010) propose an empirical criterion based on the between-cluster inertia gain (see section 3.2 of this paper). Basically, the optimal number of clusters q is the one for which the incr | Hierarchical clustering with agnes - how to cut the tree?
Husson et al. (2010) propose an empirical criterion based on the between-cluster inertia gain (see section 3.2 of this paper). Basically, the optimal number of clusters q is the one for which the increase in between-cluster dissimilarity for q clusters to q+1 clusters is significantly less than the increase in between-cluster dissimilarity for q-1 clusters to q clusters. So, it's similar to identifying a plateau in the plots above, but it's automatic and you don't have to "guess".
Still, you should keep in mind that each level of the dendogram corresponds to a valid partitioning of the observations, so there is no absolute best solution. The optimal number of clusters you want to select depends on your task. For example, when hierarchical clustering is used for outlier detection, you want to request a large number of clusters (n/10 in the example provided, where n is the total number of observations). | Hierarchical clustering with agnes - how to cut the tree?
Husson et al. (2010) propose an empirical criterion based on the between-cluster inertia gain (see section 3.2 of this paper). Basically, the optimal number of clusters q is the one for which the incr |
36,334 | Hierarchical clustering with agnes - how to cut the tree? | The academic research literature has a lot of information on this.
What I found more readable and easier to understand is section 8.1.3 from the book "Practical Data science with R" by N.Zumel and J.Mount.
From page 186 ff
PICKING THE NUMBER OF CLUSTERS
There are a number of heuristics and
rules-of-thumb for picking clusters; a given heuristic will work
better on some datasets than others. It’s best to take advantage of
domain knowledge to help set the number of clusters, if that’s
possible. Otherwise, try a variety of heuristics, and perhaps a few
different values of k.
They then discuss the "Total within sum of squares" and the "Calinski-Harabasz index" (with R code)
One simple heuristic is to compute the total within sum of squares (
WSS ) for different values of k and look for an “elbow” in the curve.
...
The Calinski-Harabasz index of a clustering is the ratio of the
between-cluster variance (which is essentially the variance of all the
cluster centroids from the dataset’s grand centroid) to the total
within-cluster variance...
But there are many more methods. CHeck out the (difficult) Coursera Course
Cluster Analysis in Data Mining, week 3 | Hierarchical clustering with agnes - how to cut the tree? | The academic research literature has a lot of information on this.
What I found more readable and easier to understand is section 8.1.3 from the book "Practical Data science with R" by N.Zumel and J. | Hierarchical clustering with agnes - how to cut the tree?
The academic research literature has a lot of information on this.
What I found more readable and easier to understand is section 8.1.3 from the book "Practical Data science with R" by N.Zumel and J.Mount.
From page 186 ff
PICKING THE NUMBER OF CLUSTERS
There are a number of heuristics and
rules-of-thumb for picking clusters; a given heuristic will work
better on some datasets than others. It’s best to take advantage of
domain knowledge to help set the number of clusters, if that’s
possible. Otherwise, try a variety of heuristics, and perhaps a few
different values of k.
They then discuss the "Total within sum of squares" and the "Calinski-Harabasz index" (with R code)
One simple heuristic is to compute the total within sum of squares (
WSS ) for different values of k and look for an “elbow” in the curve.
...
The Calinski-Harabasz index of a clustering is the ratio of the
between-cluster variance (which is essentially the variance of all the
cluster centroids from the dataset’s grand centroid) to the total
within-cluster variance...
But there are many more methods. CHeck out the (difficult) Coursera Course
Cluster Analysis in Data Mining, week 3 | Hierarchical clustering with agnes - how to cut the tree?
The academic research literature has a lot of information on this.
What I found more readable and easier to understand is section 8.1.3 from the book "Practical Data science with R" by N.Zumel and J. |
36,335 | Efficient way to compute distances between centroids from distance matrix | Let the points be indexed $x_1, x_2, \ldots, x_n$, all of them in $\mathbb{R}^d$. Let $\mathcal{I}$ be the indexes for one cluster and $\mathcal{J}$ the indexes for another cluster. The centroids are
$$c_\mathcal{I} = \frac{1}{|\mathcal{I}|} \sum_{i\in\mathcal{I}} x_i,\ c_\mathcal{J} = \frac{1}{|\mathcal{J}|} \sum_{j\in\mathcal{J}} x_j$$
and it is desired to find their squared distance $||c_\mathcal{I} - c_\mathcal{J}||^2$ in terms of the squared distances $D_{ij} = ||x_i - x_j||^2$.
Exactly as we would break down sums of squares in ANOVA calculations, an algebraic identity is
$$||c_\mathcal{I} - c_\mathcal{J}||^2 = \frac{1}{|\mathcal{I}||\mathcal{J}|} \left(SS(\mathcal{I \cup J}) -\left(|\mathcal{I}|+|\mathcal{J}|\right) \left(\frac{1}{|\mathcal{I}|}SS(\mathcal{I}) + \frac{1}{|\mathcal{J}|}SS(\mathcal{J})\right)\right)$$
where "$SS$" refers to the sum of squares of distances between each point in a set and their centroid. The polarization identity re-expresses this in terms of squared distances between all points:
$$SS(\mathcal{K}) = \frac{1}{2}\sum_{i,j\,\in\,\mathcal{K}} ||x_i - x_j||^2 = \sum_{i\lt j\,\in\,\mathcal{K}} D_{ij}.$$
The computational effort therefore is $O((|\mathcal{I}|+|\mathcal{J}|)^2)$, with a very small implicit constant. When the clusters are approximately the same size and there are $k$ of them, this is $O(n^2/k^2)$, which is directly proportional to the number of entries in $D$: that would be the best one could hope for.
R code to illustrate and test these calculations follows.
ss <- function(x) {
n <- dim(x)[2]
i <- rep(1:n, n)
j <- as.vector(t(matrix(i,n)))
d <- matrix(c(1,1) %*% (x[,i] - x[,j])^2 , n) # The distance matrix entries for `x`
sum(d[lower.tri(d)])
}
centroid <- function(x) rowMeans(x)
distance2 <- function(x,y) sum((x-y)^2)
#
# Generate two clusters randomly.
#
n.x <- 3; n.y <- 2
x <- matrix(rnorm(2*n.x), 2)
y <- matrix(rnorm(2*n.y), 2)
#
# Compare two formulae.
#
cat("Squared distance between centroids =",
distance2(centroid(x), centroid(y)),
"Equivalent value =",
(ss(cbind(x,y)) - (n.x + n.y) * (ss(x)/n.x + ss(y)/n.y)) / (n.x*n.y),
"\n") | Efficient way to compute distances between centroids from distance matrix | Let the points be indexed $x_1, x_2, \ldots, x_n$, all of them in $\mathbb{R}^d$. Let $\mathcal{I}$ be the indexes for one cluster and $\mathcal{J}$ the indexes for another cluster. The centroids ar | Efficient way to compute distances between centroids from distance matrix
Let the points be indexed $x_1, x_2, \ldots, x_n$, all of them in $\mathbb{R}^d$. Let $\mathcal{I}$ be the indexes for one cluster and $\mathcal{J}$ the indexes for another cluster. The centroids are
$$c_\mathcal{I} = \frac{1}{|\mathcal{I}|} \sum_{i\in\mathcal{I}} x_i,\ c_\mathcal{J} = \frac{1}{|\mathcal{J}|} \sum_{j\in\mathcal{J}} x_j$$
and it is desired to find their squared distance $||c_\mathcal{I} - c_\mathcal{J}||^2$ in terms of the squared distances $D_{ij} = ||x_i - x_j||^2$.
Exactly as we would break down sums of squares in ANOVA calculations, an algebraic identity is
$$||c_\mathcal{I} - c_\mathcal{J}||^2 = \frac{1}{|\mathcal{I}||\mathcal{J}|} \left(SS(\mathcal{I \cup J}) -\left(|\mathcal{I}|+|\mathcal{J}|\right) \left(\frac{1}{|\mathcal{I}|}SS(\mathcal{I}) + \frac{1}{|\mathcal{J}|}SS(\mathcal{J})\right)\right)$$
where "$SS$" refers to the sum of squares of distances between each point in a set and their centroid. The polarization identity re-expresses this in terms of squared distances between all points:
$$SS(\mathcal{K}) = \frac{1}{2}\sum_{i,j\,\in\,\mathcal{K}} ||x_i - x_j||^2 = \sum_{i\lt j\,\in\,\mathcal{K}} D_{ij}.$$
The computational effort therefore is $O((|\mathcal{I}|+|\mathcal{J}|)^2)$, with a very small implicit constant. When the clusters are approximately the same size and there are $k$ of them, this is $O(n^2/k^2)$, which is directly proportional to the number of entries in $D$: that would be the best one could hope for.
R code to illustrate and test these calculations follows.
ss <- function(x) {
n <- dim(x)[2]
i <- rep(1:n, n)
j <- as.vector(t(matrix(i,n)))
d <- matrix(c(1,1) %*% (x[,i] - x[,j])^2 , n) # The distance matrix entries for `x`
sum(d[lower.tri(d)])
}
centroid <- function(x) rowMeans(x)
distance2 <- function(x,y) sum((x-y)^2)
#
# Generate two clusters randomly.
#
n.x <- 3; n.y <- 2
x <- matrix(rnorm(2*n.x), 2)
y <- matrix(rnorm(2*n.y), 2)
#
# Compare two formulae.
#
cat("Squared distance between centroids =",
distance2(centroid(x), centroid(y)),
"Equivalent value =",
(ss(cbind(x,y)) - (n.x + n.y) * (ss(x)/n.x + ss(y)/n.y)) / (n.x*n.y),
"\n") | Efficient way to compute distances between centroids from distance matrix
Let the points be indexed $x_1, x_2, \ldots, x_n$, all of them in $\mathbb{R}^d$. Let $\mathcal{I}$ be the indexes for one cluster and $\mathcal{J}$ the indexes for another cluster. The centroids ar |
36,336 | Why to report R squared? | Under conditions for instance explained here, $R^2$ measures the proportion of the variance in the dependent variable explained by the regression, which is a natural measure. Adjusted $R^2$ does not have this interpretation, as it modifies the $R^2$ value.
So while adjusted $R^2$ has the indisputable advantage of not increasing automatically when the number of regressors goes up, you pay a price in terms of how you can interpret the measure.
Note I am not advocating the use of one or the other, just giving a possible reason for why people still use the standard $R^2$. | Why to report R squared? | Under conditions for instance explained here, $R^2$ measures the proportion of the variance in the dependent variable explained by the regression, which is a natural measure. Adjusted $R^2$ does not h | Why to report R squared?
Under conditions for instance explained here, $R^2$ measures the proportion of the variance in the dependent variable explained by the regression, which is a natural measure. Adjusted $R^2$ does not have this interpretation, as it modifies the $R^2$ value.
So while adjusted $R^2$ has the indisputable advantage of not increasing automatically when the number of regressors goes up, you pay a price in terms of how you can interpret the measure.
Note I am not advocating the use of one or the other, just giving a possible reason for why people still use the standard $R^2$. | Why to report R squared?
Under conditions for instance explained here, $R^2$ measures the proportion of the variance in the dependent variable explained by the regression, which is a natural measure. Adjusted $R^2$ does not h |
36,337 | Why to report R squared? | Adjusted R-squared is useful for comparing different regression models. This task cannot be accomplished by R-squared which, as Others have already said, has another informative goal, that is expressing the proportion of variance of the dependent variable that is explained by the regression model under investigation. | Why to report R squared? | Adjusted R-squared is useful for comparing different regression models. This task cannot be accomplished by R-squared which, as Others have already said, has another informative goal, that is expressi | Why to report R squared?
Adjusted R-squared is useful for comparing different regression models. This task cannot be accomplished by R-squared which, as Others have already said, has another informative goal, that is expressing the proportion of variance of the dependent variable that is explained by the regression model under investigation. | Why to report R squared?
Adjusted R-squared is useful for comparing different regression models. This task cannot be accomplished by R-squared which, as Others have already said, has another informative goal, that is expressi |
36,338 | What is the honesty condition for regression trees? | The meaning of the "fully grown" condition, as the authors elaborate afterwards, is that each terminal node of the tree contains exactly one instance from the training data. The authors remark that this is a "theoretical convenience":
Meanwhile, (C) is a theoretical convenience that lets us simplify the
exposition. In practice, trees are sometimes grown to have terminal
node size $k$ rather rather than $1$ for regularization. In our setup,
however, we already get regularization by drawing subsamples of size
$s$ where $s/n \to 0$ and the regularization effect from using larger
leaf sizes is not as important.
The notation $T(x) = Y_{i^*(x)}$ means that, for any example $x$ that you might want to predict, there's some integer index $i^*(x)$ such that the tree $T$ predicts that $x$ has the same label as the training data point in index $i^*(x)$.
On to their definition of "honesty". This basically means that the tree has to use a different set of points for constructing the splits and for predicting the labels (in contrast to how e.g. CART does it, as the authors note). I agree that that equation is pretty complicated to parse though! Here's how it works.
Suppose you have a point that $x$ in your data set. What the honesty condition says is that: the label that the tree outputs when you drop $x$ down the tree--treated as a random variable (dependent on the random data)--cannot depend on whether $x$ actually ends up inhabiting a leaf of the tree. In other words, the likelihood must be the same as if you had two data points with covariates $x$ in your data (and responses drawn separately, i.i.d.), and you used one of them to determine the splits, but then output the label of the other one. | What is the honesty condition for regression trees? | The meaning of the "fully grown" condition, as the authors elaborate afterwards, is that each terminal node of the tree contains exactly one instance from the training data. The authors remark that th | What is the honesty condition for regression trees?
The meaning of the "fully grown" condition, as the authors elaborate afterwards, is that each terminal node of the tree contains exactly one instance from the training data. The authors remark that this is a "theoretical convenience":
Meanwhile, (C) is a theoretical convenience that lets us simplify the
exposition. In practice, trees are sometimes grown to have terminal
node size $k$ rather rather than $1$ for regularization. In our setup,
however, we already get regularization by drawing subsamples of size
$s$ where $s/n \to 0$ and the regularization effect from using larger
leaf sizes is not as important.
The notation $T(x) = Y_{i^*(x)}$ means that, for any example $x$ that you might want to predict, there's some integer index $i^*(x)$ such that the tree $T$ predicts that $x$ has the same label as the training data point in index $i^*(x)$.
On to their definition of "honesty". This basically means that the tree has to use a different set of points for constructing the splits and for predicting the labels (in contrast to how e.g. CART does it, as the authors note). I agree that that equation is pretty complicated to parse though! Here's how it works.
Suppose you have a point that $x$ in your data set. What the honesty condition says is that: the label that the tree outputs when you drop $x$ down the tree--treated as a random variable (dependent on the random data)--cannot depend on whether $x$ actually ends up inhabiting a leaf of the tree. In other words, the likelihood must be the same as if you had two data points with covariates $x$ in your data (and responses drawn separately, i.i.d.), and you used one of them to determine the splits, but then output the label of the other one. | What is the honesty condition for regression trees?
The meaning of the "fully grown" condition, as the authors elaborate afterwards, is that each terminal node of the tree contains exactly one instance from the training data. The authors remark that th |
36,339 | Simple Question about ROC Curve | The true positive rate is one minus the false negative rate; the false positive rate is one minus the true negative rate: so it doesn't really make any difference which one you pick from each pair to talk about. You're certainly not in any sense giving more importance to classification of positive cases over negative cases (how could you when the classification is dichotomous?) by making this arbitrary choice.
(As a matter of fact the abscissa of an ROC curve is often labelled as one minus specificity—a.k.a. true negative rate.) | Simple Question about ROC Curve | The true positive rate is one minus the false negative rate; the false positive rate is one minus the true negative rate: so it doesn't really make any difference which one you pick from each pair to | Simple Question about ROC Curve
The true positive rate is one minus the false negative rate; the false positive rate is one minus the true negative rate: so it doesn't really make any difference which one you pick from each pair to talk about. You're certainly not in any sense giving more importance to classification of positive cases over negative cases (how could you when the classification is dichotomous?) by making this arbitrary choice.
(As a matter of fact the abscissa of an ROC curve is often labelled as one minus specificity—a.k.a. true negative rate.) | Simple Question about ROC Curve
The true positive rate is one minus the false negative rate; the false positive rate is one minus the true negative rate: so it doesn't really make any difference which one you pick from each pair to |
36,340 | Can I safely use variable importance of a random forest in a paper? | It does not really seem that you can justify the "X, Y and Z are best predictors" sentence in this case. At least because all predictors are best for purpose, i.e. are they so specific that they can be used as the final truth in diagnosis, or are they so sensitive that given some predictor values, no cases will be missed, or maybe those perform better than others on average?
What you can state is exactly what you obtained: X, Y and Z scored best on the scale of variable importance of the RandomForest algorithm.
It looks that you studied the association of various predictors with the outcome, a type of study that many researchers do, so I would encourage you to use the de facto standard of reporting association in medical and biological research, namely the combination of odds ratio (effect size) and the p-value for exact Fisher's test. Such measures are reported very often (if not always) and allow other researchers to compare results between papers.
Of course the importance metric will not hurt anyone if you add it to the most commonly used two. | Can I safely use variable importance of a random forest in a paper? | It does not really seem that you can justify the "X, Y and Z are best predictors" sentence in this case. At least because all predictors are best for purpose, i.e. are they so specific that they can b | Can I safely use variable importance of a random forest in a paper?
It does not really seem that you can justify the "X, Y and Z are best predictors" sentence in this case. At least because all predictors are best for purpose, i.e. are they so specific that they can be used as the final truth in diagnosis, or are they so sensitive that given some predictor values, no cases will be missed, or maybe those perform better than others on average?
What you can state is exactly what you obtained: X, Y and Z scored best on the scale of variable importance of the RandomForest algorithm.
It looks that you studied the association of various predictors with the outcome, a type of study that many researchers do, so I would encourage you to use the de facto standard of reporting association in medical and biological research, namely the combination of odds ratio (effect size) and the p-value for exact Fisher's test. Such measures are reported very often (if not always) and allow other researchers to compare results between papers.
Of course the importance metric will not hurt anyone if you add it to the most commonly used two. | Can I safely use variable importance of a random forest in a paper?
It does not really seem that you can justify the "X, Y and Z are best predictors" sentence in this case. At least because all predictors are best for purpose, i.e. are they so specific that they can b |
36,341 | Can I safely use variable importance of a random forest in a paper? | Would agree with everything coulminer answered above. Would add a few points that I'm not sure are useful:
- It might be hard to justify using RF over more traditional methods. You'd likely need to emphasize a combination of large number of variables + unknown number of interactions + non-linear effects to be convincing.
- The importance measure try to measure the importance within the RF model. Nothing more. Unless you're building the RF model for other reasons they likely won't add anything. gbm will produce different measures of variable importance - again specific to that model.
- Boruta and similar packages try to find a all-relevant subset of features. I would use them for this purpose, and not put too much weight on the variable importance they produce.
- There is more than one RF variable importance measure. There are two in the randomForest package. One in the party package. A separate one in the randomForestSRC package. You could even use the rminer package. Variable importance may change if you change the sampling (internal undersampling) --> don't think there is a perfect variable importance measure, or one you should put too much faith into. | Can I safely use variable importance of a random forest in a paper? | Would agree with everything coulminer answered above. Would add a few points that I'm not sure are useful:
- It might be hard to justify using RF over more traditional methods. You'd likely need to em | Can I safely use variable importance of a random forest in a paper?
Would agree with everything coulminer answered above. Would add a few points that I'm not sure are useful:
- It might be hard to justify using RF over more traditional methods. You'd likely need to emphasize a combination of large number of variables + unknown number of interactions + non-linear effects to be convincing.
- The importance measure try to measure the importance within the RF model. Nothing more. Unless you're building the RF model for other reasons they likely won't add anything. gbm will produce different measures of variable importance - again specific to that model.
- Boruta and similar packages try to find a all-relevant subset of features. I would use them for this purpose, and not put too much weight on the variable importance they produce.
- There is more than one RF variable importance measure. There are two in the randomForest package. One in the party package. A separate one in the randomForestSRC package. You could even use the rminer package. Variable importance may change if you change the sampling (internal undersampling) --> don't think there is a perfect variable importance measure, or one you should put too much faith into. | Can I safely use variable importance of a random forest in a paper?
Would agree with everything coulminer answered above. Would add a few points that I'm not sure are useful:
- It might be hard to justify using RF over more traditional methods. You'd likely need to em |
36,342 | Variance calculation RELU function (deep learning) | In terms of integrals you have:
$$
E[x^2] = \int_{-\infty}^{+\infty} \max(0,y)^2 p(y) dy
$$
where the part $y < 0$ does not contribute to the Integral
$$
= \int_{0}^{+\infty} y^2 p(y) dy
$$
which we can write as half the integral over the entire real domain ($y^2$ is symmetric around 0 and $p(y)$ is assumed to be symmetric around $0$):
$$
= \frac{1}{2}\int_{-\infty}^{+\infty} y^2 p(y) dy
$$
now subtracting zero in the square we get:
$$
= \frac{1}{2}\int_{-\infty}^{+\infty} (y - E[y])^2 p(y) dy
$$
which is
$$
= \frac{1}{2} E[(y - E[y])^2] = \frac{1}{2} Var[y]
$$ | Variance calculation RELU function (deep learning) | In terms of integrals you have:
$$
E[x^2] = \int_{-\infty}^{+\infty} \max(0,y)^2 p(y) dy
$$
where the part $y < 0$ does not contribute to the Integral
$$
= \int_{0}^{+\infty} y^2 p(y) dy
$$
which we | Variance calculation RELU function (deep learning)
In terms of integrals you have:
$$
E[x^2] = \int_{-\infty}^{+\infty} \max(0,y)^2 p(y) dy
$$
where the part $y < 0$ does not contribute to the Integral
$$
= \int_{0}^{+\infty} y^2 p(y) dy
$$
which we can write as half the integral over the entire real domain ($y^2$ is symmetric around 0 and $p(y)$ is assumed to be symmetric around $0$):
$$
= \frac{1}{2}\int_{-\infty}^{+\infty} y^2 p(y) dy
$$
now subtracting zero in the square we get:
$$
= \frac{1}{2}\int_{-\infty}^{+\infty} (y - E[y])^2 p(y) dy
$$
which is
$$
= \frac{1}{2} E[(y - E[y])^2] = \frac{1}{2} Var[y]
$$ | Variance calculation RELU function (deep learning)
In terms of integrals you have:
$$
E[x^2] = \int_{-\infty}^{+\infty} \max(0,y)^2 p(y) dy
$$
where the part $y < 0$ does not contribute to the Integral
$$
= \int_{0}^{+\infty} y^2 p(y) dy
$$
which we |
36,343 | Conditional distribution for Exponential family | I have answered my own question. It turned out to be a rather obvious application of Bayes Rule only after making a somewhat arbitrary assumption. My question was not very clear, mostly due to my own tenuous understanding at that time.
However, this result is used quite a lot in machine learning literature involving integrating out missing variables. I am including the proof in case others find it helpful when seeing the result.
$$ P(x, y|\boldsymbol \theta) = h(x) \exp\left(\eta({\boldsymbol \theta}) . T(x, y) - A({\boldsymbol \theta}) \right) $$
By Bayes Rule,
$$
P(y|x, \theta) = \frac{ P(x|y, \theta)}{ \int_{y^{'}} P(x|{y^{'}}, \theta) P(y^{'}|\theta)d{y^{'}}}
= \frac{ P(x, y| \theta)}{ \int_{y^{'}} P(x,{y^{'}}| \theta) d{y^{'}}}
= \frac{h(x) \exp (\eta (\theta) . T(x,y) - A(\theta))}{ \int_{y^{'}} h(x) \exp (\eta (\theta) . T(x,y^{'}) - A(\theta))dy{'}}
$$
Assumed the $h(x)$ base reference measure to be a function only of $x$ so that we can cancel it from numerator and denominator in the last step above, getting
$$
\frac{\exp ( \eta(\theta).T(x,y))}{\int_{y^{'}} \exp ( \eta(\theta).T(x,y^{'}))dy^{'}} = \exp ( \eta(\theta).T(x,y) - \log(\int_{y^{'}} \exp ( \eta(\theta).T(x,y^{'}))dy^{'}) ) = \exp ( \eta(\theta).T(x,y) - A(\theta|x) )
$$ | Conditional distribution for Exponential family | I have answered my own question. It turned out to be a rather obvious application of Bayes Rule only after making a somewhat arbitrary assumption. My question was not very clear, mostly due to my own | Conditional distribution for Exponential family
I have answered my own question. It turned out to be a rather obvious application of Bayes Rule only after making a somewhat arbitrary assumption. My question was not very clear, mostly due to my own tenuous understanding at that time.
However, this result is used quite a lot in machine learning literature involving integrating out missing variables. I am including the proof in case others find it helpful when seeing the result.
$$ P(x, y|\boldsymbol \theta) = h(x) \exp\left(\eta({\boldsymbol \theta}) . T(x, y) - A({\boldsymbol \theta}) \right) $$
By Bayes Rule,
$$
P(y|x, \theta) = \frac{ P(x|y, \theta)}{ \int_{y^{'}} P(x|{y^{'}}, \theta) P(y^{'}|\theta)d{y^{'}}}
= \frac{ P(x, y| \theta)}{ \int_{y^{'}} P(x,{y^{'}}| \theta) d{y^{'}}}
= \frac{h(x) \exp (\eta (\theta) . T(x,y) - A(\theta))}{ \int_{y^{'}} h(x) \exp (\eta (\theta) . T(x,y^{'}) - A(\theta))dy{'}}
$$
Assumed the $h(x)$ base reference measure to be a function only of $x$ so that we can cancel it from numerator and denominator in the last step above, getting
$$
\frac{\exp ( \eta(\theta).T(x,y))}{\int_{y^{'}} \exp ( \eta(\theta).T(x,y^{'}))dy^{'}} = \exp ( \eta(\theta).T(x,y) - \log(\int_{y^{'}} \exp ( \eta(\theta).T(x,y^{'}))dy^{'}) ) = \exp ( \eta(\theta).T(x,y) - A(\theta|x) )
$$ | Conditional distribution for Exponential family
I have answered my own question. It turned out to be a rather obvious application of Bayes Rule only after making a somewhat arbitrary assumption. My question was not very clear, mostly due to my own |
36,344 | Explanation that the prior predictive (marginal) distribution follows from prior and sampling distributions | The equation follows from the definition of marginal distribution:
$$
p(y) = \int_\theta{p(y, \theta)}
$$
And, from factoring the joint probability of data and parameters into conditional probabilities, like so: $$p(y, \theta) = p(y|\theta)p(\theta)$$
(If this is confusing, divide both sides by $p(\theta)$ to get the familiar definition of conditional probability.)
More plainly, and as referenced in comments, the prior predictive distribution is the Bayesian term defined as the marginal distribution of the data over the prior: It denotes an interpretation of a particular marginal distribution. | Explanation that the prior predictive (marginal) distribution follows from prior and sampling distri | The equation follows from the definition of marginal distribution:
$$
p(y) = \int_\theta{p(y, \theta)}
$$
And, from factoring the joint probability of data and parameters into conditional probabilitie | Explanation that the prior predictive (marginal) distribution follows from prior and sampling distributions
The equation follows from the definition of marginal distribution:
$$
p(y) = \int_\theta{p(y, \theta)}
$$
And, from factoring the joint probability of data and parameters into conditional probabilities, like so: $$p(y, \theta) = p(y|\theta)p(\theta)$$
(If this is confusing, divide both sides by $p(\theta)$ to get the familiar definition of conditional probability.)
More plainly, and as referenced in comments, the prior predictive distribution is the Bayesian term defined as the marginal distribution of the data over the prior: It denotes an interpretation of a particular marginal distribution. | Explanation that the prior predictive (marginal) distribution follows from prior and sampling distri
The equation follows from the definition of marginal distribution:
$$
p(y) = \int_\theta{p(y, \theta)}
$$
And, from factoring the joint probability of data and parameters into conditional probabilitie |
36,345 | Explanation that the prior predictive (marginal) distribution follows from prior and sampling distributions | Yes it removes the conditionality. Prior Predictive is for predictive a new value BEFORE the sample has been gathered. The only information we have at this stage is our belief about the Prior, $p(\theta$) and sampling distribution i.e. $p(y_{new}|\theta)$.
After the sample has been gathered, we have new information i.e. the likelihood. Hence, now we can predict based on Posterior Predictive Distribution $p(y_{new}|y_{data})$. | Explanation that the prior predictive (marginal) distribution follows from prior and sampling distri | Yes it removes the conditionality. Prior Predictive is for predictive a new value BEFORE the sample has been gathered. The only information we have at this stage is our belief about the Prior, $p(\the | Explanation that the prior predictive (marginal) distribution follows from prior and sampling distributions
Yes it removes the conditionality. Prior Predictive is for predictive a new value BEFORE the sample has been gathered. The only information we have at this stage is our belief about the Prior, $p(\theta$) and sampling distribution i.e. $p(y_{new}|\theta)$.
After the sample has been gathered, we have new information i.e. the likelihood. Hence, now we can predict based on Posterior Predictive Distribution $p(y_{new}|y_{data})$. | Explanation that the prior predictive (marginal) distribution follows from prior and sampling distri
Yes it removes the conditionality. Prior Predictive is for predictive a new value BEFORE the sample has been gathered. The only information we have at this stage is our belief about the Prior, $p(\the |
36,346 | Dealing with Postcode in Regression? | There are a couple approaches you can take here, from least to most laborious:
If there are few enough post codes in your study, it's probably fine to leave it as is. A general rule of thumb is that there should be ten events per variable (where each postal code is a different variable, plus all the other variables you're considering). If each postal code has more than 10 residents and you don't have too many other features, this is probably fine, though you should of course test for overfitting.
If you don't have enough events to make all postcodes into dummy variables, you could also dummify only the most-often-sampled post codes (for instance, every post code with more than 50 residents).
You could take the solution that you mentioned and cluster postcodes in some way. Of course there are multiple ways to cluster them--geographically is the most obvious, but income, demographics, or population density might be more informative.
If you have ideas about what attributes of the postal code might mediate the relationship between it and your dependent variable, you could use a multilevel model. This requires the most additional effort since it requires you to fit a more complex model and acquire post-code data, but it is potentially the most rewarding since it allows you to understand the postcode relationship better.
Finally, this is probably obvious, but make sure the postcode is encoded as a categorical rather than numerical variable--this one's bitten me too many times! | Dealing with Postcode in Regression? | There are a couple approaches you can take here, from least to most laborious:
If there are few enough post codes in your study, it's probably fine to leave it as is. A general rule of thumb is that | Dealing with Postcode in Regression?
There are a couple approaches you can take here, from least to most laborious:
If there are few enough post codes in your study, it's probably fine to leave it as is. A general rule of thumb is that there should be ten events per variable (where each postal code is a different variable, plus all the other variables you're considering). If each postal code has more than 10 residents and you don't have too many other features, this is probably fine, though you should of course test for overfitting.
If you don't have enough events to make all postcodes into dummy variables, you could also dummify only the most-often-sampled post codes (for instance, every post code with more than 50 residents).
You could take the solution that you mentioned and cluster postcodes in some way. Of course there are multiple ways to cluster them--geographically is the most obvious, but income, demographics, or population density might be more informative.
If you have ideas about what attributes of the postal code might mediate the relationship between it and your dependent variable, you could use a multilevel model. This requires the most additional effort since it requires you to fit a more complex model and acquire post-code data, but it is potentially the most rewarding since it allows you to understand the postcode relationship better.
Finally, this is probably obvious, but make sure the postcode is encoded as a categorical rather than numerical variable--this one's bitten me too many times! | Dealing with Postcode in Regression?
There are a couple approaches you can take here, from least to most laborious:
If there are few enough post codes in your study, it's probably fine to leave it as is. A general rule of thumb is that |
36,347 | cost function in logistic regression vs optimization algorithms | If I understand what you have done, you have done things out of order. Maximum likelihood or penalized maximum likelihood estimation is the gold standard method for estimating parameters in a regression model. The cost function does not apply to how one estimates risk. The cost function is applied to individual risk estimates to provide an optimum decision for that one observation. | cost function in logistic regression vs optimization algorithms | If I understand what you have done, you have done things out of order. Maximum likelihood or penalized maximum likelihood estimation is the gold standard method for estimating parameters in a regress | cost function in logistic regression vs optimization algorithms
If I understand what you have done, you have done things out of order. Maximum likelihood or penalized maximum likelihood estimation is the gold standard method for estimating parameters in a regression model. The cost function does not apply to how one estimates risk. The cost function is applied to individual risk estimates to provide an optimum decision for that one observation. | cost function in logistic regression vs optimization algorithms
If I understand what you have done, you have done things out of order. Maximum likelihood or penalized maximum likelihood estimation is the gold standard method for estimating parameters in a regress |
36,348 | GLMM overfitting solutions | Computing the standard deviation (or variance of the coefficients) essentially means getting the fixed-effect estimates for each level (analogous to the BLUPs/conditional modes in a mixed model) and computing their variance. You can do this by appropriately setting contrasts to contr.sum (sum-to-zero contrasts) (in this case you'll still have to reconstruct the value of one level, since the model will only fit n-1 coefficients in a model with an intercept), and/or appropriate use of -1 or +0 in the model to fit a no-intercept model where the coefficients are computed for every level. Or, as shown below, you can just use brute force via predict (or e.g. via the lsmeans package) to compute values for each level ...
Make up data with only two levels of the RE grouping variable:
dd <- expand.grid(f1=factor(1:3),f2=factor(1:2),rep=1:10)
library(lme4)
simList <-
suppressMessages(simulate(~f1+(1|f2),
newdata=dd,
family="gaussian",
newparams=list(theta=1,beta=c(0,1,2),sigma=1),
seed=101,n=500))
Fit f2 as a random effect and retrieve estimated variance:
sumfun1 <- function(y0) {
m <- lmer(y~f1+(1|f2),data=transform(dd,y=y0))
unlist(VarCorr(m))
}
library(plyr)
r1 <- laply(simList,sumfun1,.progress="text")
This actually works surprisingly well given the small number of levels:
mean(r1) ## 0.98
confint(lm(r1~1))
## 2.5 % 97.5 %
## (Intercept) 0.9248779 1.189029
But we often get zero estimates of the variance:
sum(r1==0) ## 60
(and a handful of very small values)
sum(log10(r1)<(-6)) ## 69
Now try it via fixed effects:
sumfun2 <- function(y0) {
lm1 <- lm(y~f1+f2,data=transform(dd,y=y0))
pframe <- data.frame(f1="1",f2=levels(dd$f2))
var(predict(lm1,newdata=pframe))
}
r2 <- laply(simList,sumfun2,.progress="text")
mean(r2) ## 1.01294
confint(lm(r2~1))
## 2.5 % 97.5 %
## (Intercept) 0.89081 1.135071
r1[log10(r1)< (-6)] <- 1e-6
p0 <- rbind(data.frame(m="f1=random",r=r1),
data.frame(m="f1=fixed",r=r2))
library(ggplot2); theme_set(theme_bw())
ggplot(p0,aes(x=log10(r),fill=m))+
geom_histogram(alpha=0.5,position="identity")+
geom_vline(xintercept=0,lty=2)
The fixed-effect approach actually works better than I expected ... | GLMM overfitting solutions | Computing the standard deviation (or variance of the coefficients) essentially means getting the fixed-effect estimates for each level (analogous to the BLUPs/conditional modes in a mixed model) and c | GLMM overfitting solutions
Computing the standard deviation (or variance of the coefficients) essentially means getting the fixed-effect estimates for each level (analogous to the BLUPs/conditional modes in a mixed model) and computing their variance. You can do this by appropriately setting contrasts to contr.sum (sum-to-zero contrasts) (in this case you'll still have to reconstruct the value of one level, since the model will only fit n-1 coefficients in a model with an intercept), and/or appropriate use of -1 or +0 in the model to fit a no-intercept model where the coefficients are computed for every level. Or, as shown below, you can just use brute force via predict (or e.g. via the lsmeans package) to compute values for each level ...
Make up data with only two levels of the RE grouping variable:
dd <- expand.grid(f1=factor(1:3),f2=factor(1:2),rep=1:10)
library(lme4)
simList <-
suppressMessages(simulate(~f1+(1|f2),
newdata=dd,
family="gaussian",
newparams=list(theta=1,beta=c(0,1,2),sigma=1),
seed=101,n=500))
Fit f2 as a random effect and retrieve estimated variance:
sumfun1 <- function(y0) {
m <- lmer(y~f1+(1|f2),data=transform(dd,y=y0))
unlist(VarCorr(m))
}
library(plyr)
r1 <- laply(simList,sumfun1,.progress="text")
This actually works surprisingly well given the small number of levels:
mean(r1) ## 0.98
confint(lm(r1~1))
## 2.5 % 97.5 %
## (Intercept) 0.9248779 1.189029
But we often get zero estimates of the variance:
sum(r1==0) ## 60
(and a handful of very small values)
sum(log10(r1)<(-6)) ## 69
Now try it via fixed effects:
sumfun2 <- function(y0) {
lm1 <- lm(y~f1+f2,data=transform(dd,y=y0))
pframe <- data.frame(f1="1",f2=levels(dd$f2))
var(predict(lm1,newdata=pframe))
}
r2 <- laply(simList,sumfun2,.progress="text")
mean(r2) ## 1.01294
confint(lm(r2~1))
## 2.5 % 97.5 %
## (Intercept) 0.89081 1.135071
r1[log10(r1)< (-6)] <- 1e-6
p0 <- rbind(data.frame(m="f1=random",r=r1),
data.frame(m="f1=fixed",r=r2))
library(ggplot2); theme_set(theme_bw())
ggplot(p0,aes(x=log10(r),fill=m))+
geom_histogram(alpha=0.5,position="identity")+
geom_vline(xintercept=0,lty=2)
The fixed-effect approach actually works better than I expected ... | GLMM overfitting solutions
Computing the standard deviation (or variance of the coefficients) essentially means getting the fixed-effect estimates for each level (analogous to the BLUPs/conditional modes in a mixed model) and c |
36,349 | Why $Y$ should be transformed before the predictors? | Transforming X doesn't impact the shape of the conditional distribution, nor heteroskedasticity, so transforming X really only serves to deal with nonlinear relationships. (If you're fitting additive models it might serve to help with eliminating interaction, but even that's often best left to transforming Y)
An example where transforming only X makes sense:
If that's - lack of fit in conditional mean - is your main issue, then transforming X may make sense, but if you're transforming because of the shape of the conditional Y or because of heteroskedasticity, if you're solving that by transformation (not necessarily the best choice, but we're taking transformation as a given for this question), then you must transform Y in some way to change it.
Consider, for example, a model where conditional variance is proportional to mean:
An example where transforming only X can't solve the problems:
Moving values on the x-axis won't change the fact that the spread is greater for values on the right than values on the left. If you want to fix this changing variance by transformation, you have to squish down high Y-values and stretch out low Y-values.
Now, if you're considering transforming Y, that will change the shape of the relationship between response and predictors ... so you'll often expect to transform X as well if you want a linear model (if it was linear before transforming, it won't be afterward). Sometimes (as in the second plot above), a Y=transformation will make the relationship more linear at the same time - but it's not always the case.
If you're transforming both X and Y, you want to do Y first, because of that change in the shape of the relationship between Y and X - usually you need to see what relationships are like after you transform. Subsequent transformation of X will then aim to obtain linearity of relationship.
So in general, if you're transforming at all, you often need to transform Y, and if you're doing that, you nearly always want to do it first. | Why $Y$ should be transformed before the predictors? | Transforming X doesn't impact the shape of the conditional distribution, nor heteroskedasticity, so transforming X really only serves to deal with nonlinear relationships. (If you're fitting additive | Why $Y$ should be transformed before the predictors?
Transforming X doesn't impact the shape of the conditional distribution, nor heteroskedasticity, so transforming X really only serves to deal with nonlinear relationships. (If you're fitting additive models it might serve to help with eliminating interaction, but even that's often best left to transforming Y)
An example where transforming only X makes sense:
If that's - lack of fit in conditional mean - is your main issue, then transforming X may make sense, but if you're transforming because of the shape of the conditional Y or because of heteroskedasticity, if you're solving that by transformation (not necessarily the best choice, but we're taking transformation as a given for this question), then you must transform Y in some way to change it.
Consider, for example, a model where conditional variance is proportional to mean:
An example where transforming only X can't solve the problems:
Moving values on the x-axis won't change the fact that the spread is greater for values on the right than values on the left. If you want to fix this changing variance by transformation, you have to squish down high Y-values and stretch out low Y-values.
Now, if you're considering transforming Y, that will change the shape of the relationship between response and predictors ... so you'll often expect to transform X as well if you want a linear model (if it was linear before transforming, it won't be afterward). Sometimes (as in the second plot above), a Y=transformation will make the relationship more linear at the same time - but it's not always the case.
If you're transforming both X and Y, you want to do Y first, because of that change in the shape of the relationship between Y and X - usually you need to see what relationships are like after you transform. Subsequent transformation of X will then aim to obtain linearity of relationship.
So in general, if you're transforming at all, you often need to transform Y, and if you're doing that, you nearly always want to do it first. | Why $Y$ should be transformed before the predictors?
Transforming X doesn't impact the shape of the conditional distribution, nor heteroskedasticity, so transforming X really only serves to deal with nonlinear relationships. (If you're fitting additive |
36,350 | Why $Y$ should be transformed before the predictors? | Transforming Y initially is an anachronistic approach to data analysis. Our great-great-great grandfathers did that so why shouldn't we? Lots of reasons and your post reflecting that Gaussian assumptions are solely based on the errors from a model NOT the Y series is dead-on. | Why $Y$ should be transformed before the predictors? | Transforming Y initially is an anachronistic approach to data analysis. Our great-great-great grandfathers did that so why shouldn't we? Lots of reasons and your post reflecting that Gaussian assumpti | Why $Y$ should be transformed before the predictors?
Transforming Y initially is an anachronistic approach to data analysis. Our great-great-great grandfathers did that so why shouldn't we? Lots of reasons and your post reflecting that Gaussian assumptions are solely based on the errors from a model NOT the Y series is dead-on. | Why $Y$ should be transformed before the predictors?
Transforming Y initially is an anachronistic approach to data analysis. Our great-great-great grandfathers did that so why shouldn't we? Lots of reasons and your post reflecting that Gaussian assumpti |
36,351 | Interpretation of $\theta$ in negative binomial regression | $\theta$ is known as a dispersion parameter in GLM. But what does that really mean? Let me use an example to explain what the $\theta$ parameter is. Say you went to a party of mixed faculty members. You, as a statistician, looked for another statistician. Let $p$ be the probability of you succeeding in finding a statistician, and $X$ be the number of people you "randomly" approach and talk to, until you find the first statistician. $X$ follows a geometric distribution with the probability mass function:
$f(x) = P(X=x) = (1-p)^{x-1}p$
Now consider another example. You are interested in talking to 3 different statisticians. Then let us denote X as the number of people you "randomly" select until you find $r=3$ statisticians. $X$ now follows a negative binomial distribution with the probability mass function
$
f(x) = P(X=x) =
\left(
\begin{matrix}
x-1\\
r-1
\end{matrix}
\right)
(1-p)^{x-r}p^r
$
So the $\theta$ parameter, the $r$ in this probability mass function, represents the number of successful trials. When it is 1, $X$ follows a geometric distribution; otherwise, X follows a negative-binomial distribution.
So how does changing $\theta$ affects the shape of a distribution? With a give $p$, greater $\theta$'s result in greater spreads of $X$, hence the dispersion parameter. If you use R, you may want to get a feel by plugging in different values using dnbinom or rnbinom. | Interpretation of $\theta$ in negative binomial regression | $\theta$ is known as a dispersion parameter in GLM. But what does that really mean? Let me use an example to explain what the $\theta$ parameter is. Say you went to a party of mixed faculty members. Y | Interpretation of $\theta$ in negative binomial regression
$\theta$ is known as a dispersion parameter in GLM. But what does that really mean? Let me use an example to explain what the $\theta$ parameter is. Say you went to a party of mixed faculty members. You, as a statistician, looked for another statistician. Let $p$ be the probability of you succeeding in finding a statistician, and $X$ be the number of people you "randomly" approach and talk to, until you find the first statistician. $X$ follows a geometric distribution with the probability mass function:
$f(x) = P(X=x) = (1-p)^{x-1}p$
Now consider another example. You are interested in talking to 3 different statisticians. Then let us denote X as the number of people you "randomly" select until you find $r=3$ statisticians. $X$ now follows a negative binomial distribution with the probability mass function
$
f(x) = P(X=x) =
\left(
\begin{matrix}
x-1\\
r-1
\end{matrix}
\right)
(1-p)^{x-r}p^r
$
So the $\theta$ parameter, the $r$ in this probability mass function, represents the number of successful trials. When it is 1, $X$ follows a geometric distribution; otherwise, X follows a negative-binomial distribution.
So how does changing $\theta$ affects the shape of a distribution? With a give $p$, greater $\theta$'s result in greater spreads of $X$, hence the dispersion parameter. If you use R, you may want to get a feel by plugging in different values using dnbinom or rnbinom. | Interpretation of $\theta$ in negative binomial regression
$\theta$ is known as a dispersion parameter in GLM. But what does that really mean? Let me use an example to explain what the $\theta$ parameter is. Say you went to a party of mixed faculty members. Y |
36,352 | Understanding scipy Kolmogorov-Smirnov test [duplicate] | For the KS test the p-value is itself distributed uniformly in [0,1] if the H0 is true (which it is if you test whether it your sample is from $U(0,1)$ and the random number generation works okay). It therefore must "vary wildly" between 0 and 1, in fact its standard deviation is $1/\sqrt{12}$ which is roughly 0.3.
You can check this by looking whether the percentages of p values smaller or equal to some $p_0$ over your independent consecutive runs is close to said $p_0$.
See also Why are p-values uniformly distributed under the null hypothesis? | Understanding scipy Kolmogorov-Smirnov test [duplicate] | For the KS test the p-value is itself distributed uniformly in [0,1] if the H0 is true (which it is if you test whether it your sample is from $U(0,1)$ and the random number generation works okay). It | Understanding scipy Kolmogorov-Smirnov test [duplicate]
For the KS test the p-value is itself distributed uniformly in [0,1] if the H0 is true (which it is if you test whether it your sample is from $U(0,1)$ and the random number generation works okay). It therefore must "vary wildly" between 0 and 1, in fact its standard deviation is $1/\sqrt{12}$ which is roughly 0.3.
You can check this by looking whether the percentages of p values smaller or equal to some $p_0$ over your independent consecutive runs is close to said $p_0$.
See also Why are p-values uniformly distributed under the null hypothesis? | Understanding scipy Kolmogorov-Smirnov test [duplicate]
For the KS test the p-value is itself distributed uniformly in [0,1] if the H0 is true (which it is if you test whether it your sample is from $U(0,1)$ and the random number generation works okay). It |
36,353 | finding global minima of a random forest estimator | It's easy with scipy.optimize.fmin, evaluating your model on sampled points or rolling your own optimization routine. This is the bread and butter of how many models work, so it's worth learning about in great detail. See for instance, these lecture notes.
This probably isn't what you want though. The $r^2$ you cross-validated is for the distribution of the input space. The $\operatorname*{arg\,max}_x f(x)$ that the random forest will evaluate to will probably be in a low confidence neighborhood, away from the support of the training data.
You want a model that generates confidence intervals. In Scikit-Learn, GaussianProcess and GradientBoostingRegressor both do this. Gaussian Processes are excellent for this problem if you don't have more than a thousand training observations.
If you can collect more data after consulting with your model, then you evaluate your black box at the $\arg\max$ of the upper confidence bound, add the result as a new data-point and repeat until there is no change.
This problem is known as the Contextual Bandit. The choice of confidence bound is dependent on the exploration until convergence/exploitation of the intermittent values that you want. Since you don't care about how poorly the model performs while training, you'd pick a large upper confidence bound so the model will converge faster.
There are several related toolkits for this sort of problem. Spearmint, Hyperopt, and MOE.
If you cannot collect more data then you should take the $\arg\max$ of the lower confidence bound of the model. This penalizes predictions that the model is uncertain of. | finding global minima of a random forest estimator | It's easy with scipy.optimize.fmin, evaluating your model on sampled points or rolling your own optimization routine. This is the bread and butter of how many models work, so it's worth learning about | finding global minima of a random forest estimator
It's easy with scipy.optimize.fmin, evaluating your model on sampled points or rolling your own optimization routine. This is the bread and butter of how many models work, so it's worth learning about in great detail. See for instance, these lecture notes.
This probably isn't what you want though. The $r^2$ you cross-validated is for the distribution of the input space. The $\operatorname*{arg\,max}_x f(x)$ that the random forest will evaluate to will probably be in a low confidence neighborhood, away from the support of the training data.
You want a model that generates confidence intervals. In Scikit-Learn, GaussianProcess and GradientBoostingRegressor both do this. Gaussian Processes are excellent for this problem if you don't have more than a thousand training observations.
If you can collect more data after consulting with your model, then you evaluate your black box at the $\arg\max$ of the upper confidence bound, add the result as a new data-point and repeat until there is no change.
This problem is known as the Contextual Bandit. The choice of confidence bound is dependent on the exploration until convergence/exploitation of the intermittent values that you want. Since you don't care about how poorly the model performs while training, you'd pick a large upper confidence bound so the model will converge faster.
There are several related toolkits for this sort of problem. Spearmint, Hyperopt, and MOE.
If you cannot collect more data then you should take the $\arg\max$ of the lower confidence bound of the model. This penalizes predictions that the model is uncertain of. | finding global minima of a random forest estimator
It's easy with scipy.optimize.fmin, evaluating your model on sampled points or rolling your own optimization routine. This is the bread and butter of how many models work, so it's worth learning about |
36,354 | why is adaboost predicting probabilities with so little standard deviation? | When using AdaBoost (and most other machine learning algorithms, such as Support Vector Machines), it is important to calibrate prediction scores. One popular method is Isotonic Regression, which I recommend for most machine learning tasks. If you pass the prediction scores from your AdaBoost model through an Isotonic Regression you'll find that it provides calibrated probabilities that range from near zero to near one. In fact, you should do this with all of the models you have mentioned before combining them in an ensemble model.
Sci-kit learn provides an Isotonic Regression function, as well as a new CalibratedClassifierCV function which will allow you to calibrate your prediction scores using cross-validation rather than holding out a separate calibration set from your training sample.
To learn more, check out these papers;
http://www.cs.cornell.edu/~caruana/niculescu.scldbst.crc.rev4.pdf
http://ijcai.org/papers13/Papers/IJCAI13-286.pdf | why is adaboost predicting probabilities with so little standard deviation? | When using AdaBoost (and most other machine learning algorithms, such as Support Vector Machines), it is important to calibrate prediction scores. One popular method is Isotonic Regression, which I re | why is adaboost predicting probabilities with so little standard deviation?
When using AdaBoost (and most other machine learning algorithms, such as Support Vector Machines), it is important to calibrate prediction scores. One popular method is Isotonic Regression, which I recommend for most machine learning tasks. If you pass the prediction scores from your AdaBoost model through an Isotonic Regression you'll find that it provides calibrated probabilities that range from near zero to near one. In fact, you should do this with all of the models you have mentioned before combining them in an ensemble model.
Sci-kit learn provides an Isotonic Regression function, as well as a new CalibratedClassifierCV function which will allow you to calibrate your prediction scores using cross-validation rather than holding out a separate calibration set from your training sample.
To learn more, check out these papers;
http://www.cs.cornell.edu/~caruana/niculescu.scldbst.crc.rev4.pdf
http://ijcai.org/papers13/Papers/IJCAI13-286.pdf | why is adaboost predicting probabilities with so little standard deviation?
When using AdaBoost (and most other machine learning algorithms, such as Support Vector Machines), it is important to calibrate prediction scores. One popular method is Isotonic Regression, which I re |
36,355 | What exactly does a Type III test do? | It may help you to read my answer here: How to interpret type I (sequential) ANOVA and MANOVA to get a fuller sense of the types of sums of squares.
The distinction between the different types of SS only matters if you have more than one variable. It isn't clear that you do from your description, but imagine that you have two independent / predictor variables, $X_1$ and $X_2$. In that case the type III test of $X_1$ tests whether the coefficient for $X_1$ is equal to $0$, after having accounted for the influence of $X_2$ on $Y$. The type III test for $X_2$ is the same.
Type III SS tests are equivalent to the Wald tests that come with standard output in the sense that the $p$-values will always be the same. However, type III SS tests are $F$-tests (i.e., the test statistic is distributed as $F$); they are not Wald tests. A Wald test is a statistical test where the test statistic is calculated by subtracting the null value of the parameter from the estimated parameter and dividing that difference by the standard error of the parameter estimate. Importantly, the distribution of this test statistic must be asymptotically normal (e.g., not $F$). This is, frankly, very technical, and may well be legitimately more detail that you need to be concerned with. | What exactly does a Type III test do? | It may help you to read my answer here: How to interpret type I (sequential) ANOVA and MANOVA to get a fuller sense of the types of sums of squares.
The distinction between the different types of SS | What exactly does a Type III test do?
It may help you to read my answer here: How to interpret type I (sequential) ANOVA and MANOVA to get a fuller sense of the types of sums of squares.
The distinction between the different types of SS only matters if you have more than one variable. It isn't clear that you do from your description, but imagine that you have two independent / predictor variables, $X_1$ and $X_2$. In that case the type III test of $X_1$ tests whether the coefficient for $X_1$ is equal to $0$, after having accounted for the influence of $X_2$ on $Y$. The type III test for $X_2$ is the same.
Type III SS tests are equivalent to the Wald tests that come with standard output in the sense that the $p$-values will always be the same. However, type III SS tests are $F$-tests (i.e., the test statistic is distributed as $F$); they are not Wald tests. A Wald test is a statistical test where the test statistic is calculated by subtracting the null value of the parameter from the estimated parameter and dividing that difference by the standard error of the parameter estimate. Importantly, the distribution of this test statistic must be asymptotically normal (e.g., not $F$). This is, frankly, very technical, and may well be legitimately more detail that you need to be concerned with. | What exactly does a Type III test do?
It may help you to read my answer here: How to interpret type I (sequential) ANOVA and MANOVA to get a fuller sense of the types of sums of squares.
The distinction between the different types of SS |
36,356 | How do I investigate how long it takes one variable to affect another in a time series | Try looking at cross-correlations between the two series:
correlate series 1 with series 2;
correlate series 1 with series 2 lagged by 1 period;
correlate series 1 with series 2 lagged by 2 periods;
etc.
Explore as many lags as can reasonably be expected to be plausible in the context you are in. Also, depending on the context of the application, you may need to look at lagged series 1 against (non-lagged) series 2.
Note which lag gives the highest absolute correlation - this will be a rough estimate of the "true" lag.
It is comfortable to inspect the cross-correlations visually. In R, you may use function ccf(.) to obtain and plot the correlogram. | How do I investigate how long it takes one variable to affect another in a time series | Try looking at cross-correlations between the two series:
correlate series 1 with series 2;
correlate series 1 with series 2 lagged by 1 period;
correlate series 1 with series 2 lagged by 2 periods; | How do I investigate how long it takes one variable to affect another in a time series
Try looking at cross-correlations between the two series:
correlate series 1 with series 2;
correlate series 1 with series 2 lagged by 1 period;
correlate series 1 with series 2 lagged by 2 periods;
etc.
Explore as many lags as can reasonably be expected to be plausible in the context you are in. Also, depending on the context of the application, you may need to look at lagged series 1 against (non-lagged) series 2.
Note which lag gives the highest absolute correlation - this will be a rough estimate of the "true" lag.
It is comfortable to inspect the cross-correlations visually. In R, you may use function ccf(.) to obtain and plot the correlogram. | How do I investigate how long it takes one variable to affect another in a time series
Try looking at cross-correlations between the two series:
correlate series 1 with series 2;
correlate series 1 with series 2 lagged by 1 period;
correlate series 1 with series 2 lagged by 2 periods; |
36,357 | How do I investigate how long it takes one variable to affect another in a time series | As often in regression, there are several ways to proceed, but the most straightforward one is probably given by the moving-average approach. That is, you assume a linear (linear-in-the-parameters) relationship between your target $y_t$ (change_in_rank) and your regressand $x_t$ (change_in_goodness) given by
$$
y_t = \sum_{i=1}^p \beta_{t-k} \, x_{t-k}
$$
Here, the input-parameter $p$ determines the maximum lag-time. Next, you fit your model using some seleted data of the form $(x_{j-1}, \ldots, x_{j-p}; y_j)$ where $j\in \{1,\ldots, N_\text{data}\}$, e.g. by using standard least-squares regression.
Finally, you can use the result either to forecast (in this case more flexible models like neural networks might be doing better), or to interprete the result using the fitted parameters $\boldsymbol \beta$ (--in interpretability, almost nothing beats linear models).
If that model is not flexible enough, you can extend it to higher dimensions and more general functions $f(x_{t-1}, \ldots, f_{t-p})$, and also to autoregressive-moving-average models where you further include some previous regression results $y_j$ for $j<t$. | How do I investigate how long it takes one variable to affect another in a time series | As often in regression, there are several ways to proceed, but the most straightforward one is probably given by the moving-average approach. That is, you assume a linear (linear-in-the-parameters) re | How do I investigate how long it takes one variable to affect another in a time series
As often in regression, there are several ways to proceed, but the most straightforward one is probably given by the moving-average approach. That is, you assume a linear (linear-in-the-parameters) relationship between your target $y_t$ (change_in_rank) and your regressand $x_t$ (change_in_goodness) given by
$$
y_t = \sum_{i=1}^p \beta_{t-k} \, x_{t-k}
$$
Here, the input-parameter $p$ determines the maximum lag-time. Next, you fit your model using some seleted data of the form $(x_{j-1}, \ldots, x_{j-p}; y_j)$ where $j\in \{1,\ldots, N_\text{data}\}$, e.g. by using standard least-squares regression.
Finally, you can use the result either to forecast (in this case more flexible models like neural networks might be doing better), or to interprete the result using the fitted parameters $\boldsymbol \beta$ (--in interpretability, almost nothing beats linear models).
If that model is not flexible enough, you can extend it to higher dimensions and more general functions $f(x_{t-1}, \ldots, f_{t-p})$, and also to autoregressive-moving-average models where you further include some previous regression results $y_j$ for $j<t$. | How do I investigate how long it takes one variable to affect another in a time series
As often in regression, there are several ways to proceed, but the most straightforward one is probably given by the moving-average approach. That is, you assume a linear (linear-in-the-parameters) re |
36,358 | Notation: Deterministic Variable, Random Variable, Realization of Random Variable, Function | I think people usually use late-in-alphabet letters like $X, Y, Z$ for random variables -- and $x, y, z$ for realizations thereof. Then you have early-in-alphabet letters like $a, b, c$ that can be used for deterministic values, and later letters like $f, g, h$ for names of functions (also capitals like $F, G, H$ for cumulative distributions). Am I understanding the question correctly?
But always explain your notations carefully, because there are always reasonable exceptions. For example, if you're writing about children's ages, it might well be appropriate to model the distribution of $A$, the age of a randomly selected child, with observed values of $a_1, a_2, \ldots$. | Notation: Deterministic Variable, Random Variable, Realization of Random Variable, Function | I think people usually use late-in-alphabet letters like $X, Y, Z$ for random variables -- and $x, y, z$ for realizations thereof. Then you have early-in-alphabet letters like $a, b, c$ that can be us | Notation: Deterministic Variable, Random Variable, Realization of Random Variable, Function
I think people usually use late-in-alphabet letters like $X, Y, Z$ for random variables -- and $x, y, z$ for realizations thereof. Then you have early-in-alphabet letters like $a, b, c$ that can be used for deterministic values, and later letters like $f, g, h$ for names of functions (also capitals like $F, G, H$ for cumulative distributions). Am I understanding the question correctly?
But always explain your notations carefully, because there are always reasonable exceptions. For example, if you're writing about children's ages, it might well be appropriate to model the distribution of $A$, the age of a randomly selected child, with observed values of $a_1, a_2, \ldots$. | Notation: Deterministic Variable, Random Variable, Realization of Random Variable, Function
I think people usually use late-in-alphabet letters like $X, Y, Z$ for random variables -- and $x, y, z$ for realizations thereof. Then you have early-in-alphabet letters like $a, b, c$ that can be us |
36,359 | Number of distinct bootstrap samples | Let's ask the computer to generate some small examples. (The language is R.)
Take $n=5$. Begin by placing $n-1$ bars (represented as ones) randomly within $n + n-1 = 2n-1$ places; that is, by selecting an $n-1$ element subset of $\{1,2,\ldots,2n-1\}$:
n <- 5
set.seed(17)
y <- rep(0, 2*n-1)
y[sample.int(2*n-1, n-1, replace=FALSE)] <- 1
names(y) <- c("_","|")[y+1]
print(y)
The output is
_ | _ | | _ _ | _
0 1 0 1 1 0 0 1 0
The $n-1=4$ selected elements are shown with bars. Between them appear five boxes of sizes 1, 1, 0, 2, and 1, respectively. These counts can be easily computed:
x <- tabulate(cumsum(c(1,y)))-1
names(x) <- 1:n
print(x)
The output is
1 2 3 4 5
1 1 0 2 1
This tabulation means that 1 "1" was selected, 1 "2", no "3"s, 2 "4"s, and 1 "5". (To appreciate what happened, inspect the intermediate result:
cumsum(c(1,y))
_ | _ | | _ _ | _
1 1 2 2 3 4 4 4 5 5
Beginning with a 1 (which corresponds to none of the boxes or bars), the cumulative sum incremented the value every time a bar was crossed. Because there are $n-1=4$ bars, the final value is $1+(n-1)=n=5$. Thus every possible outcome in $\{1,2,\ldots,n\}$ is named at least once. The code counted the number of times each outcome was mentioned and decremented that count by one.)
We could equally well write the same information as an array of the sample values by replicating each value (in the first row) the number of times indicated (in the second row):
print(z <- unlist(mapply(rep, 1:n, x)))
The output is
[1] 1 2 4 4 5
These are the sample values, sorted for your convenience. Finally, they can be converted back to boxes and bars:
unlist(sapply(tabulate(z), function(i) c(1,rep(0, i))))[-1]
This command creates one box for each sample element and sticks a bar in front of the first box for each new element processed. After removing the initial bar, the output is what we started with (y).
Because this code goes full circle from one of the three different representations of a given sample back to itself, it shows that any one of the representations can be converted uniquely to any of the other two forms. Therefore all configurations of each of the three forms of representation are in one-to-one correspondence. In particular, the number of possible arrays z that name the sample members explicitly is the same as the number of ways of creating y, which (by definition) is $\binom{2n-1}{n-1}$. | Number of distinct bootstrap samples | Let's ask the computer to generate some small examples. (The language is R.)
Take $n=5$. Begin by placing $n-1$ bars (represented as ones) randomly within $n + n-1 = 2n-1$ places; that is, by select | Number of distinct bootstrap samples
Let's ask the computer to generate some small examples. (The language is R.)
Take $n=5$. Begin by placing $n-1$ bars (represented as ones) randomly within $n + n-1 = 2n-1$ places; that is, by selecting an $n-1$ element subset of $\{1,2,\ldots,2n-1\}$:
n <- 5
set.seed(17)
y <- rep(0, 2*n-1)
y[sample.int(2*n-1, n-1, replace=FALSE)] <- 1
names(y) <- c("_","|")[y+1]
print(y)
The output is
_ | _ | | _ _ | _
0 1 0 1 1 0 0 1 0
The $n-1=4$ selected elements are shown with bars. Between them appear five boxes of sizes 1, 1, 0, 2, and 1, respectively. These counts can be easily computed:
x <- tabulate(cumsum(c(1,y)))-1
names(x) <- 1:n
print(x)
The output is
1 2 3 4 5
1 1 0 2 1
This tabulation means that 1 "1" was selected, 1 "2", no "3"s, 2 "4"s, and 1 "5". (To appreciate what happened, inspect the intermediate result:
cumsum(c(1,y))
_ | _ | | _ _ | _
1 1 2 2 3 4 4 4 5 5
Beginning with a 1 (which corresponds to none of the boxes or bars), the cumulative sum incremented the value every time a bar was crossed. Because there are $n-1=4$ bars, the final value is $1+(n-1)=n=5$. Thus every possible outcome in $\{1,2,\ldots,n\}$ is named at least once. The code counted the number of times each outcome was mentioned and decremented that count by one.)
We could equally well write the same information as an array of the sample values by replicating each value (in the first row) the number of times indicated (in the second row):
print(z <- unlist(mapply(rep, 1:n, x)))
The output is
[1] 1 2 4 4 5
These are the sample values, sorted for your convenience. Finally, they can be converted back to boxes and bars:
unlist(sapply(tabulate(z), function(i) c(1,rep(0, i))))[-1]
This command creates one box for each sample element and sticks a bar in front of the first box for each new element processed. After removing the initial bar, the output is what we started with (y).
Because this code goes full circle from one of the three different representations of a given sample back to itself, it shows that any one of the representations can be converted uniquely to any of the other two forms. Therefore all configurations of each of the three forms of representation are in one-to-one correspondence. In particular, the number of possible arrays z that name the sample members explicitly is the same as the number of ways of creating y, which (by definition) is $\binom{2n-1}{n-1}$. | Number of distinct bootstrap samples
Let's ask the computer to generate some small examples. (The language is R.)
Take $n=5$. Begin by placing $n-1$ bars (represented as ones) randomly within $n + n-1 = 2n-1$ places; that is, by select |
36,360 | Number of distinct bootstrap samples | Notice that we want to take $n$ elements from the original set ($n$ distinct elements sample set) with replicates allowed.
Then suppose if I denote $x_1$: number of replicates of the first element, $x_2$: number of replicates of second element,...., $x_n$: number of replicates of $n$th element.
While we must take elements $n$ times, that is, we can convert this question to number of different solutions of the equation: $x_1+...+x_n = n$.
Now suppose we have $n$ indistinguishable balls and $n$ distinguishable cells, and we want to put $n$ balls into cells.
The key is how many balls that each cell contains? Since there are $n$ cells thus $n - 1$ bars to separate them, the point to make each assignment of balls distinct is: how many different ways can we assign the locations of $n - 1$ bars to make each assignment different?
We have $n$ balls and $n - 1$ cells thus $2n - 1$ objects and $\binom{2n-1}{n - 1}$ ways to place the bars. Thus we get the answer. | Number of distinct bootstrap samples | Notice that we want to take $n$ elements from the original set ($n$ distinct elements sample set) with replicates allowed.
Then suppose if I denote $x_1$: number of replicates of the first element, $x | Number of distinct bootstrap samples
Notice that we want to take $n$ elements from the original set ($n$ distinct elements sample set) with replicates allowed.
Then suppose if I denote $x_1$: number of replicates of the first element, $x_2$: number of replicates of second element,...., $x_n$: number of replicates of $n$th element.
While we must take elements $n$ times, that is, we can convert this question to number of different solutions of the equation: $x_1+...+x_n = n$.
Now suppose we have $n$ indistinguishable balls and $n$ distinguishable cells, and we want to put $n$ balls into cells.
The key is how many balls that each cell contains? Since there are $n$ cells thus $n - 1$ bars to separate them, the point to make each assignment of balls distinct is: how many different ways can we assign the locations of $n - 1$ bars to make each assignment different?
We have $n$ balls and $n - 1$ cells thus $2n - 1$ objects and $\binom{2n-1}{n - 1}$ ways to place the bars. Thus we get the answer. | Number of distinct bootstrap samples
Notice that we want to take $n$ elements from the original set ($n$ distinct elements sample set) with replicates allowed.
Then suppose if I denote $x_1$: number of replicates of the first element, $x |
36,361 | Advantage of multiple simulations in old-fashioned Monte Carlo? | As long as problems regarding pseudo-random number generation are avoided (see note at the end), the two approaches ($k$ simulations with $n$ draws vs. single simulation with sufficiently large $n$) are equivalent with respect to estimating the mean. Regarding memory, observe that, in the $k$ simulations case, you need to store the sample means $\hat{\mu}_{n,1}, \dots, \hat{\mu}_{n,k}$ before performing the final mean, while this does not happen in the single simulation scenario. With modern computers, performing a single simulation with sufficiently large $n$ should not be harder than what previously described and, in fact, should save time.
The mathematical reason beyond the equivalence is linearity. To be more precise, in the $k$ simulations scenario, you calculate the "final" sample mean $\hat{\mu}$ as follows
$$
\hat{\mu} = \frac{1}{k} \sum_{h=1}^k \hat{\mu}_{n,h} = \frac{1}{k} \sum_{h=1}^k \frac{1}{n} \sum_{i=1}^n X^{(h)}_i = \frac{1}{nk} \sum_{h=1}^k \sum_{i=1}^n X^{(h)}_i
$$
where $X_i^{(h)}$ denotes the draw numbered $i$ at simulation $h$. This ordening is arbitrary if nothing strange happens, thus you can re-label each $X_i^{(h)}$ with a new index, say $m=1,\dots,nk$, obtaining
$$
\hat{\mu} = \frac{1}{nk} \sum_{m=1}^{nk} X_m
$$
But this is equivalent to performing a single simulation with $nk$ draws (obviously, the draws must be i.i.d., as already remarked).
Note: Potential problems with PRNGs are described in the Wikipedia page. | Advantage of multiple simulations in old-fashioned Monte Carlo? | As long as problems regarding pseudo-random number generation are avoided (see note at the end), the two approaches ($k$ simulations with $n$ draws vs. single simulation with sufficiently large $n$) a | Advantage of multiple simulations in old-fashioned Monte Carlo?
As long as problems regarding pseudo-random number generation are avoided (see note at the end), the two approaches ($k$ simulations with $n$ draws vs. single simulation with sufficiently large $n$) are equivalent with respect to estimating the mean. Regarding memory, observe that, in the $k$ simulations case, you need to store the sample means $\hat{\mu}_{n,1}, \dots, \hat{\mu}_{n,k}$ before performing the final mean, while this does not happen in the single simulation scenario. With modern computers, performing a single simulation with sufficiently large $n$ should not be harder than what previously described and, in fact, should save time.
The mathematical reason beyond the equivalence is linearity. To be more precise, in the $k$ simulations scenario, you calculate the "final" sample mean $\hat{\mu}$ as follows
$$
\hat{\mu} = \frac{1}{k} \sum_{h=1}^k \hat{\mu}_{n,h} = \frac{1}{k} \sum_{h=1}^k \frac{1}{n} \sum_{i=1}^n X^{(h)}_i = \frac{1}{nk} \sum_{h=1}^k \sum_{i=1}^n X^{(h)}_i
$$
where $X_i^{(h)}$ denotes the draw numbered $i$ at simulation $h$. This ordening is arbitrary if nothing strange happens, thus you can re-label each $X_i^{(h)}$ with a new index, say $m=1,\dots,nk$, obtaining
$$
\hat{\mu} = \frac{1}{nk} \sum_{m=1}^{nk} X_m
$$
But this is equivalent to performing a single simulation with $nk$ draws (obviously, the draws must be i.i.d., as already remarked).
Note: Potential problems with PRNGs are described in the Wikipedia page. | Advantage of multiple simulations in old-fashioned Monte Carlo?
As long as problems regarding pseudo-random number generation are avoided (see note at the end), the two approaches ($k$ simulations with $n$ draws vs. single simulation with sufficiently large $n$) a |
36,362 | Issues with fitting distribution to heavy-tailed data | I applied Tukey-Lambda PPCC to your data to get the following plot:
You see the local max at $\lambda=-0.47$, which implies heavier tails than normal distribution. For normal it's 0.14 and for Cauchy it's -1. So, if you go with this view, then your data's tail is not as "fat" as Cauchy's, but much fatter than normal.
However the global max is at $\lambda=33.17$
I drew the Tukey lambda for the above two maxima here:
So, you have two very different views of the distribution. One is fat tailed, the other one's very convex.
I think that the convex distribution is the better fit. Cauchy and other fat tailed ones are not a good fit here, go for these weird distributions like in my last plot.
Here's how Tukey Lambda distribution looks like for some $\lambda$.
I use this tool to gauge the shape of my data. | Issues with fitting distribution to heavy-tailed data | I applied Tukey-Lambda PPCC to your data to get the following plot:
You see the local max at $\lambda=-0.47$, which implies heavier tails than normal distribution. For normal it's 0.14 and for Cauchy | Issues with fitting distribution to heavy-tailed data
I applied Tukey-Lambda PPCC to your data to get the following plot:
You see the local max at $\lambda=-0.47$, which implies heavier tails than normal distribution. For normal it's 0.14 and for Cauchy it's -1. So, if you go with this view, then your data's tail is not as "fat" as Cauchy's, but much fatter than normal.
However the global max is at $\lambda=33.17$
I drew the Tukey lambda for the above two maxima here:
So, you have two very different views of the distribution. One is fat tailed, the other one's very convex.
I think that the convex distribution is the better fit. Cauchy and other fat tailed ones are not a good fit here, go for these weird distributions like in my last plot.
Here's how Tukey Lambda distribution looks like for some $\lambda$.
I use this tool to gauge the shape of my data. | Issues with fitting distribution to heavy-tailed data
I applied Tukey-Lambda PPCC to your data to get the following plot:
You see the local max at $\lambda=-0.47$, which implies heavier tails than normal distribution. For normal it's 0.14 and for Cauchy |
36,363 | Issues with fitting distribution to heavy-tailed data | your data set is really very long-tailed. Consider making 1st some tests on less extreme data (to check this look e.g. to sampling kurtosis). L-moments are not suited for very-very-long tail data, e.g. for Cauchy distribution not all L-moments exist.
Bye Stephan | Issues with fitting distribution to heavy-tailed data | your data set is really very long-tailed. Consider making 1st some tests on less extreme data (to check this look e.g. to sampling kurtosis). L-moments are not suited for very-very-long tail data, e.g | Issues with fitting distribution to heavy-tailed data
your data set is really very long-tailed. Consider making 1st some tests on less extreme data (to check this look e.g. to sampling kurtosis). L-moments are not suited for very-very-long tail data, e.g. for Cauchy distribution not all L-moments exist.
Bye Stephan | Issues with fitting distribution to heavy-tailed data
your data set is really very long-tailed. Consider making 1st some tests on less extreme data (to check this look e.g. to sampling kurtosis). L-moments are not suited for very-very-long tail data, e.g |
36,364 | Issues with fitting distribution to heavy-tailed data | One way to do this is to construct an L-moment diagram with your data. There in an R package (with full manual) at http://cran.r-project.org/web/packages/lmom/index.html.
The L-moment diagram will plot the L-skewness and L-kurtosis of your data on a chart and show how different distribution-types would appear on that same chart so you can try to select a known distribution. | Issues with fitting distribution to heavy-tailed data | One way to do this is to construct an L-moment diagram with your data. There in an R package (with full manual) at http://cran.r-project.org/web/packages/lmom/index.html.
The L-moment diagram will pl | Issues with fitting distribution to heavy-tailed data
One way to do this is to construct an L-moment diagram with your data. There in an R package (with full manual) at http://cran.r-project.org/web/packages/lmom/index.html.
The L-moment diagram will plot the L-skewness and L-kurtosis of your data on a chart and show how different distribution-types would appear on that same chart so you can try to select a known distribution. | Issues with fitting distribution to heavy-tailed data
One way to do this is to construct an L-moment diagram with your data. There in an R package (with full manual) at http://cran.r-project.org/web/packages/lmom/index.html.
The L-moment diagram will pl |
36,365 | Issues with fitting distribution to heavy-tailed data | experimented a bit with a mixture of distributions but am still far from a satisfying result..
Data-set is the same as above (v1).
The maximum-likelihood function for the pareto is given by:
pareto.MLE <- function(X)
{
n <- length(X)
m <- min(X)
a <- n/sum(log(X)-log(m))
return( c(m,a) )
}
Now, I fit the upper tail of the data-set separately:
pquant <- .95
idx <- which(v1>quantile(v1,pquant))
v1a <- v1[idx]
vpars1 <- pareto.MLE(v1a)
qqplot(v1a, rpareto(1e4, vpars1[1],vpars1[2]),ylim=c(0,1e4))
abline(0,1)
v1b <- v1[-idx]
vpars2 <- pareto.MLE(v1b)
qqplot(v1b, rpareto(1e4, vpars2[1],vpars2[2]))
abline(0,1)
v3 <- c(rpareto(1e5*.95, vpars2[1],vpars2[2]),rpareto(1e5*.05,vpars1[1],vpars1[2]))
qqplot(v1,v3,ylim=c(0,1e4))
abline(0,1)
The qq-plots look very poor. Furthermore, whenever fitting the upper tail, I get ridicously high values with a too high probability..
The remaining part of the distributions is not fitted well, too.. I would welcome any further suggestions in that regard!
Another question: What kind of "tail-measures" for evaluating the goodness of the fit for the tail are sensible? RMSE does not seem to be the right choice here? I still ony judge qualitatively by insepcting qq-plots.
Best | Issues with fitting distribution to heavy-tailed data | experimented a bit with a mixture of distributions but am still far from a satisfying result..
Data-set is the same as above (v1).
The maximum-likelihood function for the pareto is given by:
pareto.M | Issues with fitting distribution to heavy-tailed data
experimented a bit with a mixture of distributions but am still far from a satisfying result..
Data-set is the same as above (v1).
The maximum-likelihood function for the pareto is given by:
pareto.MLE <- function(X)
{
n <- length(X)
m <- min(X)
a <- n/sum(log(X)-log(m))
return( c(m,a) )
}
Now, I fit the upper tail of the data-set separately:
pquant <- .95
idx <- which(v1>quantile(v1,pquant))
v1a <- v1[idx]
vpars1 <- pareto.MLE(v1a)
qqplot(v1a, rpareto(1e4, vpars1[1],vpars1[2]),ylim=c(0,1e4))
abline(0,1)
v1b <- v1[-idx]
vpars2 <- pareto.MLE(v1b)
qqplot(v1b, rpareto(1e4, vpars2[1],vpars2[2]))
abline(0,1)
v3 <- c(rpareto(1e5*.95, vpars2[1],vpars2[2]),rpareto(1e5*.05,vpars1[1],vpars1[2]))
qqplot(v1,v3,ylim=c(0,1e4))
abline(0,1)
The qq-plots look very poor. Furthermore, whenever fitting the upper tail, I get ridicously high values with a too high probability..
The remaining part of the distributions is not fitted well, too.. I would welcome any further suggestions in that regard!
Another question: What kind of "tail-measures" for evaluating the goodness of the fit for the tail are sensible? RMSE does not seem to be the right choice here? I still ony judge qualitatively by insepcting qq-plots.
Best | Issues with fitting distribution to heavy-tailed data
experimented a bit with a mixture of distributions but am still far from a satisfying result..
Data-set is the same as above (v1).
The maximum-likelihood function for the pareto is given by:
pareto.M |
36,366 | Difference between rel error and xerror in rpart regression trees | The "rel error" is $1 - R^2$ Root mean squared error, similar to linear regression. This is the error on the observations used to estimate the model.
The "xerror" is related to the PRESS statistic. This is the error on the observations from cross validation data. | Difference between rel error and xerror in rpart regression trees | The "rel error" is $1 - R^2$ Root mean squared error, similar to linear regression. This is the error on the observations used to estimate the model.
The "xerror" is related to the PRESS statistic. Th | Difference between rel error and xerror in rpart regression trees
The "rel error" is $1 - R^2$ Root mean squared error, similar to linear regression. This is the error on the observations used to estimate the model.
The "xerror" is related to the PRESS statistic. This is the error on the observations from cross validation data. | Difference between rel error and xerror in rpart regression trees
The "rel error" is $1 - R^2$ Root mean squared error, similar to linear regression. This is the error on the observations used to estimate the model.
The "xerror" is related to the PRESS statistic. Th |
36,367 | Difference between rel error and xerror in rpart regression trees | Can not comment but 1-r^2 is not called Root mean squared error, Root mean squared error is RMSE, The square root of MSE
r^2 is called coefficient of determination, which is SSR/SSTO
SSR = total error sum of (predicted value - mean value)^2
SSTO = total error sum of (real value - mean value)^2
can also be calculated by 1 - SSE/SSTO
SSE = total error sum of (real value - predicted value)^2
But I am not one hundred percent sure rel error is 1-r^2, since in rpart, there are two cases: regression and category, I think the definition should be different for this two cases | Difference between rel error and xerror in rpart regression trees | Can not comment but 1-r^2 is not called Root mean squared error, Root mean squared error is RMSE, The square root of MSE
r^2 is called coefficient of determination, which is SSR/SSTO
SSR = total error | Difference between rel error and xerror in rpart regression trees
Can not comment but 1-r^2 is not called Root mean squared error, Root mean squared error is RMSE, The square root of MSE
r^2 is called coefficient of determination, which is SSR/SSTO
SSR = total error sum of (predicted value - mean value)^2
SSTO = total error sum of (real value - mean value)^2
can also be calculated by 1 - SSE/SSTO
SSE = total error sum of (real value - predicted value)^2
But I am not one hundred percent sure rel error is 1-r^2, since in rpart, there are two cases: regression and category, I think the definition should be different for this two cases | Difference between rel error and xerror in rpart regression trees
Can not comment but 1-r^2 is not called Root mean squared error, Root mean squared error is RMSE, The square root of MSE
r^2 is called coefficient of determination, which is SSR/SSTO
SSR = total error |
36,368 | Generating a correlated data matrix where both observations and variables are correlated | You can do the same thing that you did to the columns of the matrix to make them correlated, just do it to the rows instead. This will adjust the correlation on the observations within a column without affecting the correlations between the columns much:
L = chol(OCRMt)# Cholesky decomposition
p = dim(L)[1]
M2 <- t(L) %*% M1
hist( cor(M2)[ lower.tri(cor(M2), diag=FALSE)])
hist( cor(t(M2))[ lower.tri(cor(t(M2)), diag=FALSE)])
You can also create one observation from a distribution with n times p columns, then wrap that into your matrix. The correlation matrix is the Kronecker product of your other correlation matrices. My computer ran out of memory for your example, but works for a smaller matrix:
library(MASS)
vcmat <- matrix( 0.5, 10,10 )
diag(vcmat) <- 1
ocmat <- matrix( 0.3, 20,20 )
diag(ocmat) <- 1
cmat <- kronecker( ocmat, vcmat )
obs <- matrix( mvrnorm(1, mu=rep(0,10*20), Sigma=cmat), 20, 10 )
hist(cor(obs))
hist(cor(t(obs))) | Generating a correlated data matrix where both observations and variables are correlated | You can do the same thing that you did to the columns of the matrix to make them correlated, just do it to the rows instead. This will adjust the correlation on the observations within a column witho | Generating a correlated data matrix where both observations and variables are correlated
You can do the same thing that you did to the columns of the matrix to make them correlated, just do it to the rows instead. This will adjust the correlation on the observations within a column without affecting the correlations between the columns much:
L = chol(OCRMt)# Cholesky decomposition
p = dim(L)[1]
M2 <- t(L) %*% M1
hist( cor(M2)[ lower.tri(cor(M2), diag=FALSE)])
hist( cor(t(M2))[ lower.tri(cor(t(M2)), diag=FALSE)])
You can also create one observation from a distribution with n times p columns, then wrap that into your matrix. The correlation matrix is the Kronecker product of your other correlation matrices. My computer ran out of memory for your example, but works for a smaller matrix:
library(MASS)
vcmat <- matrix( 0.5, 10,10 )
diag(vcmat) <- 1
ocmat <- matrix( 0.3, 20,20 )
diag(ocmat) <- 1
cmat <- kronecker( ocmat, vcmat )
obs <- matrix( mvrnorm(1, mu=rep(0,10*20), Sigma=cmat), 20, 10 )
hist(cor(obs))
hist(cor(t(obs))) | Generating a correlated data matrix where both observations and variables are correlated
You can do the same thing that you did to the columns of the matrix to make them correlated, just do it to the rows instead. This will adjust the correlation on the observations within a column witho |
36,369 | Creating and interpreting Bland-Altman plot | Have you looked at the Wikipedia entry I linked in your question?
You don't plot "the mean of the data", but for each data point measured in two ways, you plot the difference in the two measurements ($y$) against the average of the two measurements ($x$). Using R and some toy data:
> set.seed(1)
> measurements <- matrix(rnorm(20), ncol=2)
> measurements
[,1] [,2]
[1,] -0.6264538 1.51178117
[2,] 0.1836433 0.38984324
[3,] -0.8356286 -0.62124058
[4,] 1.5952808 -2.21469989
[5,] 0.3295078 1.12493092
[6,] -0.8204684 -0.04493361
[7,] 0.4874291 -0.01619026
[8,] 0.7383247 0.94383621
[9,] 0.5757814 0.82122120
[10,] -0.3053884 0.59390132
> xx <- rowMeans(measurements) # x coordinate: row-wise average
> yy <- apply(measurements, 1, diff) # y coordinate: row-wise difference
> xx
[1] 0.4426637 0.2867433 -0.7284346 -0.3097095 0.7272193 -0.4327010 0.2356194
0.8410805 0.6985013 0.1442565
> yy
[1] 2.1382350 0.2061999 0.2143880 -3.8099807 0.7954231 0.7755348 -0.5036193
0.2055115 0.2454398 0.8992897
> plot(xx, yy, pch=19, xlab="Average", ylab="Difference")
To get the limits of agreement (see under "Application" in the Wikipedia page), you calculate the mean and the standard deviation of the differences, i.e., the $y$ values, and plot horizontal lines at the mean $\pm 1.96$ standard deviations.
> upper <- mean(yy) + 1.96*sd(yy)
> lower <- mean(yy) - 1.96*sd(yy)
> upper
[1] 3.141753
> lower
[1] -2.908468
> abline(h=c(upper,lower), lty=2)
(You can't see the upper limit of agreement because the plot only goes up to $y\approx 2.1$.)
As to the interpretation of the plot and the limits of agreement, again look to Wikipedia:
If the differences within mean ± 1.96 SD are not clinically important, the two methods may be used interchangeably. | Creating and interpreting Bland-Altman plot | Have you looked at the Wikipedia entry I linked in your question?
You don't plot "the mean of the data", but for each data point measured in two ways, you plot the difference in the two measurements ( | Creating and interpreting Bland-Altman plot
Have you looked at the Wikipedia entry I linked in your question?
You don't plot "the mean of the data", but for each data point measured in two ways, you plot the difference in the two measurements ($y$) against the average of the two measurements ($x$). Using R and some toy data:
> set.seed(1)
> measurements <- matrix(rnorm(20), ncol=2)
> measurements
[,1] [,2]
[1,] -0.6264538 1.51178117
[2,] 0.1836433 0.38984324
[3,] -0.8356286 -0.62124058
[4,] 1.5952808 -2.21469989
[5,] 0.3295078 1.12493092
[6,] -0.8204684 -0.04493361
[7,] 0.4874291 -0.01619026
[8,] 0.7383247 0.94383621
[9,] 0.5757814 0.82122120
[10,] -0.3053884 0.59390132
> xx <- rowMeans(measurements) # x coordinate: row-wise average
> yy <- apply(measurements, 1, diff) # y coordinate: row-wise difference
> xx
[1] 0.4426637 0.2867433 -0.7284346 -0.3097095 0.7272193 -0.4327010 0.2356194
0.8410805 0.6985013 0.1442565
> yy
[1] 2.1382350 0.2061999 0.2143880 -3.8099807 0.7954231 0.7755348 -0.5036193
0.2055115 0.2454398 0.8992897
> plot(xx, yy, pch=19, xlab="Average", ylab="Difference")
To get the limits of agreement (see under "Application" in the Wikipedia page), you calculate the mean and the standard deviation of the differences, i.e., the $y$ values, and plot horizontal lines at the mean $\pm 1.96$ standard deviations.
> upper <- mean(yy) + 1.96*sd(yy)
> lower <- mean(yy) - 1.96*sd(yy)
> upper
[1] 3.141753
> lower
[1] -2.908468
> abline(h=c(upper,lower), lty=2)
(You can't see the upper limit of agreement because the plot only goes up to $y\approx 2.1$.)
As to the interpretation of the plot and the limits of agreement, again look to Wikipedia:
If the differences within mean ± 1.96 SD are not clinically important, the two methods may be used interchangeably. | Creating and interpreting Bland-Altman plot
Have you looked at the Wikipedia entry I linked in your question?
You don't plot "the mean of the data", but for each data point measured in two ways, you plot the difference in the two measurements ( |
36,370 | Creating and interpreting Bland-Altman plot | If you would like to do this in Python you can use this code
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import random
%matplotlib inline
plt.style.use('ggplot')
I just added the last line because I like the ggplot style.
def plotblandaltman(x,y,title,sd_limit):
plt.figure(figsize=(20,8))
plt.suptitle(title, fontsize="20")
if len(x) != len(y):
raise ValueError('x does not have the same length as y')
else:
for i in range(len(x)):
a = np.asarray(x)
b = np.asarray(x)+np.asarray(y)
mean_diff = np.mean(b)
std_diff = np.std(b, axis=0)
limit_of_agreement = sd_limit * std_diff
lower = mean_diff - limit_of_agreement
upper = mean_diff + limit_of_agreement
difference = upper - lower
lowerplot = lower - (difference * 0.5)
upperplot = upper + (difference * 0.5)
plt.axhline(y=mean_diff, linestyle = "--", color = "red", label="mean diff")
plt.axhline(y=lower, linestyle = "--", color = "grey", label="-1.96 SD")
plt.axhline(y=upper, linestyle = "--", color = "grey", label="1.96 SD")
plt.text(a.max()*0.85, upper * 1.1, " 1.96 SD", color = "grey", fontsize = "14")
plt.text(a.max()*0.85, lower * 0.9, "-1.96 SD", color = "grey", fontsize = "14")
plt.text(a.max()*0.85, mean_diff * 0.85, "Mean", color = "red", fontsize = "14")
plt.ylim(lowerplot, upperplot)
plt.scatter(x=a,y=b)
And finaly I just make some random values and compare them in this function
x = np.random.rand(100)
y = np.random.rand(100)
plotblandaltman(x,y,"Bland-altman plot",1.96)
With some minor modification, you can easily add a for-loop and make several plots | Creating and interpreting Bland-Altman plot | If you would like to do this in Python you can use this code
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import random
%matplotlib inline
plt.style.use('ggplot')
I just added | Creating and interpreting Bland-Altman plot
If you would like to do this in Python you can use this code
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import random
%matplotlib inline
plt.style.use('ggplot')
I just added the last line because I like the ggplot style.
def plotblandaltman(x,y,title,sd_limit):
plt.figure(figsize=(20,8))
plt.suptitle(title, fontsize="20")
if len(x) != len(y):
raise ValueError('x does not have the same length as y')
else:
for i in range(len(x)):
a = np.asarray(x)
b = np.asarray(x)+np.asarray(y)
mean_diff = np.mean(b)
std_diff = np.std(b, axis=0)
limit_of_agreement = sd_limit * std_diff
lower = mean_diff - limit_of_agreement
upper = mean_diff + limit_of_agreement
difference = upper - lower
lowerplot = lower - (difference * 0.5)
upperplot = upper + (difference * 0.5)
plt.axhline(y=mean_diff, linestyle = "--", color = "red", label="mean diff")
plt.axhline(y=lower, linestyle = "--", color = "grey", label="-1.96 SD")
plt.axhline(y=upper, linestyle = "--", color = "grey", label="1.96 SD")
plt.text(a.max()*0.85, upper * 1.1, " 1.96 SD", color = "grey", fontsize = "14")
plt.text(a.max()*0.85, lower * 0.9, "-1.96 SD", color = "grey", fontsize = "14")
plt.text(a.max()*0.85, mean_diff * 0.85, "Mean", color = "red", fontsize = "14")
plt.ylim(lowerplot, upperplot)
plt.scatter(x=a,y=b)
And finaly I just make some random values and compare them in this function
x = np.random.rand(100)
y = np.random.rand(100)
plotblandaltman(x,y,"Bland-altman plot",1.96)
With some minor modification, you can easily add a for-loop and make several plots | Creating and interpreting Bland-Altman plot
If you would like to do this in Python you can use this code
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import random
%matplotlib inline
plt.style.use('ggplot')
I just added |
36,371 | Total expectation theorem for Poisson processes | heropup is right. The problem is that once you know that $X=A$, $X$ is not merely drawn from the exponential with rate $\lambda_A$ since you also know that the sampled value had to be small enough to win the comparison with the hypothetical sampled value from $B$.
So, the density given that $X=A$ is the renormalized pointwise product of the density of an exponential with rate $\lambda_A$ and the right cdf of an exponential with rate $\lambda_B$. This gives an exponential density with rate $\lambda_A + \lambda_B$. So:
\begin{align}
\mathbb{E}(T_{A+B}) &= \mathbb{E}( T_{A+B} \mid X =A )\mathbb{P}[X = A] + \mathbb{E}( T_{A+B}\mid X =B)\mathbb{P}[X = B]\\
&= \frac 1{\lambda_A+\lambda_B} \frac {\lambda_A}{\lambda_A+\lambda_B} + \frac 1{\lambda_A+\lambda_B}\frac {\lambda_B}{\lambda_A+\lambda_B} \\
&= \frac {1}{\lambda_A+\lambda_B}
\end{align}
as desired. | Total expectation theorem for Poisson processes | heropup is right. The problem is that once you know that $X=A$, $X$ is not merely drawn from the exponential with rate $\lambda_A$ since you also know that the sampled value had to be small enough to | Total expectation theorem for Poisson processes
heropup is right. The problem is that once you know that $X=A$, $X$ is not merely drawn from the exponential with rate $\lambda_A$ since you also know that the sampled value had to be small enough to win the comparison with the hypothetical sampled value from $B$.
So, the density given that $X=A$ is the renormalized pointwise product of the density of an exponential with rate $\lambda_A$ and the right cdf of an exponential with rate $\lambda_B$. This gives an exponential density with rate $\lambda_A + \lambda_B$. So:
\begin{align}
\mathbb{E}(T_{A+B}) &= \mathbb{E}( T_{A+B} \mid X =A )\mathbb{P}[X = A] + \mathbb{E}( T_{A+B}\mid X =B)\mathbb{P}[X = B]\\
&= \frac 1{\lambda_A+\lambda_B} \frac {\lambda_A}{\lambda_A+\lambda_B} + \frac 1{\lambda_A+\lambda_B}\frac {\lambda_B}{\lambda_A+\lambda_B} \\
&= \frac {1}{\lambda_A+\lambda_B}
\end{align}
as desired. | Total expectation theorem for Poisson processes
heropup is right. The problem is that once you know that $X=A$, $X$ is not merely drawn from the exponential with rate $\lambda_A$ since you also know that the sampled value had to be small enough to |
36,372 | Total expectation theorem for Poisson processes | \begin{align}
& \Pr( T_{A+B} > t \mid X=A) \\[10pt]
= {} & \frac{\Pr(T_{A+B} > t\ \&\ X=A)}{\Pr(X=A)} \\[10pt]
= {} & \frac{\Pr(t < T_A < T_B)}{\Pr(X=A)}, \tag 1
\end{align}
${}$
\begin{align}
\text{and } & \Pr(t < T_A < T_B) \\[10pt]
= {} & \int_t^\infty \left( \int_u^\infty
e^{-\lambda_A u} e^{-\lambda_B v} (\lambda_B\, dv) \right) (\lambda_A \, du) \\[10pt]
= {} & \int_t^\infty e^{-\lambda_A u} e^{-\lambda_B u} (\lambda_A\,du) = e^{-(\lambda_A+\lambda_B)t} \cdot \frac{\lambda_A}{\lambda_A + \lambda_B}.
\end{align}
Therefore the expression on line $(1)$ is equal to $e^{-(\lambda_A + \lambda_B)t},$ which is the same as $\Pr(T_{A+B} > t).$
Thus the events $[T_{A+B} >t]$ and $[X=A]$ are actually independent. | Total expectation theorem for Poisson processes | \begin{align}
& \Pr( T_{A+B} > t \mid X=A) \\[10pt]
= {} & \frac{\Pr(T_{A+B} > t\ \&\ X=A)}{\Pr(X=A)} \\[10pt]
= {} & \frac{\Pr(t < T_A < T_B)}{\Pr(X=A)}, \tag 1
\end{align}
${}$
\begin{align}
\text{ | Total expectation theorem for Poisson processes
\begin{align}
& \Pr( T_{A+B} > t \mid X=A) \\[10pt]
= {} & \frac{\Pr(T_{A+B} > t\ \&\ X=A)}{\Pr(X=A)} \\[10pt]
= {} & \frac{\Pr(t < T_A < T_B)}{\Pr(X=A)}, \tag 1
\end{align}
${}$
\begin{align}
\text{and } & \Pr(t < T_A < T_B) \\[10pt]
= {} & \int_t^\infty \left( \int_u^\infty
e^{-\lambda_A u} e^{-\lambda_B v} (\lambda_B\, dv) \right) (\lambda_A \, du) \\[10pt]
= {} & \int_t^\infty e^{-\lambda_A u} e^{-\lambda_B u} (\lambda_A\,du) = e^{-(\lambda_A+\lambda_B)t} \cdot \frac{\lambda_A}{\lambda_A + \lambda_B}.
\end{align}
Therefore the expression on line $(1)$ is equal to $e^{-(\lambda_A + \lambda_B)t},$ which is the same as $\Pr(T_{A+B} > t).$
Thus the events $[T_{A+B} >t]$ and $[X=A]$ are actually independent. | Total expectation theorem for Poisson processes
\begin{align}
& \Pr( T_{A+B} > t \mid X=A) \\[10pt]
= {} & \frac{\Pr(T_{A+B} > t\ \&\ X=A)}{\Pr(X=A)} \\[10pt]
= {} & \frac{\Pr(t < T_A < T_B)}{\Pr(X=A)}, \tag 1
\end{align}
${}$
\begin{align}
\text{ |
36,373 | Relation of Mahalanobis Distance to Log Likelihood | For completeness, I'll answer myself.
I eventually found the equation here, and as @whuber writes in his comment:
Define:
$k$: the multivariate dimension
$\mu$: the multivariate mean (a $k$-dimensional vector);
$\Sigma$: the $k\times k$ covariance matrix;
Then:
The squared Mahalanobis Distance is: $D^2=(x-\mu)^T\Sigma^{-1}(x-\mu)$
The log-likelihood is: $ln(L)=-\frac12ln(|\Sigma|)-\frac12(x-\mu)^T\Sigma^{-1}(x-\mu)-\frac k2 ln(2\pi)$
or: $ln(L)=-\frac12ln(|\Sigma|)-\frac12D^2-\frac k2 ln(2\pi)$
Thus, define $c\equiv\frac12(ln(|\Sigma|) + k\cdot ln(2\pi))$ then:
$ln(L)=-\frac12D^2-c$ and;
$D=\sqrt{-2(ln(L)+c)} $ | Relation of Mahalanobis Distance to Log Likelihood | For completeness, I'll answer myself.
I eventually found the equation here, and as @whuber writes in his comment:
Define:
$k$: the multivariate dimension
$\mu$: the multivariate mean (a $k$-dimens | Relation of Mahalanobis Distance to Log Likelihood
For completeness, I'll answer myself.
I eventually found the equation here, and as @whuber writes in his comment:
Define:
$k$: the multivariate dimension
$\mu$: the multivariate mean (a $k$-dimensional vector);
$\Sigma$: the $k\times k$ covariance matrix;
Then:
The squared Mahalanobis Distance is: $D^2=(x-\mu)^T\Sigma^{-1}(x-\mu)$
The log-likelihood is: $ln(L)=-\frac12ln(|\Sigma|)-\frac12(x-\mu)^T\Sigma^{-1}(x-\mu)-\frac k2 ln(2\pi)$
or: $ln(L)=-\frac12ln(|\Sigma|)-\frac12D^2-\frac k2 ln(2\pi)$
Thus, define $c\equiv\frac12(ln(|\Sigma|) + k\cdot ln(2\pi))$ then:
$ln(L)=-\frac12D^2-c$ and;
$D=\sqrt{-2(ln(L)+c)} $ | Relation of Mahalanobis Distance to Log Likelihood
For completeness, I'll answer myself.
I eventually found the equation here, and as @whuber writes in his comment:
Define:
$k$: the multivariate dimension
$\mu$: the multivariate mean (a $k$-dimens |
36,374 | Is it valid to use Hartigans' dip test to reject uni-modal null hypothesis with large N? | It isn't so much that a hypothesis test has "too much power" with large n, it's that hypothesis tests don't seem to answer the question you're interested in.
Given the large sample size, the second plot looks to me like there is some suggestion of at least 2 modes.
"Qualitatively different" is basically "is this different enough to matter?" which is more a question of effect size than significance (hypothesis tests will identify even trivial differences, so they're simply not answering a question like "how different are they?"). In fact, it's often the case that we already know the null to be false, so we certainly shouldn't be using one in that case. Some diagnostic measure of whatever you regard as important in terms of difference in distribution might be useful.
I think there are indeed two questions - 1) Am I seeing an effect (multi-mode output resulting from unimodal input) and 2) how big is that effect (and, related, is it big enough to matter?)
The first question might be cast as a hypothesis testing question (though it's not the only way to take it). On the second question, the paper by Hartigan&Hartigan says
"The dip test measures multimodality in a sample by the maximum difference, over all sample points, between the empirical distribution function, and the unimodal distribution function that minimizes that maximum difference."
-- that statistic appears to be a perfectly reasonable measure of the extent of deviation from unimodality. As for whether the size of difference matters, that's harder to say without knowing the application - you might be better placed to judge it (or to identify some other measure that you can say whether it matters with).
What I want to know is whether my simulation fed with the same input distribution but with one parameter changed (what I've plotted) leads to qualitatively different output distributions, particularly if the system has a different number of modes of operation.
Since you're interested in a two-sample comparison of number of modes, it might even be possible to modify a statistic for the one-sample case to be used for the two-sample case.
One way to approach that occurs to me, which is a form of resampling.
Compute the difference in dip-test statistics for the two samples. That's your measure of the effect.
You could do bootstrapping, for example, to estimate the standard error or to build a confidence interval for the difference in dip statistics. Given the difference in location, you might try resampling within-samples. A test might be based off whether the confidence interval covers 0. You might want to do some simulation to see whether the coverage of such an interval is reasonable, and whether techniques for esitmating/reducing bias might help.
Another alternative way to bootstrap might be to have some estimates of location and scale and resample standardized residuals, if you regard the shapes as being the same under the null.
Yet another alternative might be to consider a model that might be suitable for the distributional shape if it were unimodal, and then treat the two samples as finite mixtures of such distributions (location or scale mixtures, if either are indicated by your knowledge of the problem); then you'd have some difference in estimated number of components as a measure.
That's a little less specific than I'd like to be, but it's at least a starting point. | Is it valid to use Hartigans' dip test to reject uni-modal null hypothesis with large N? | It isn't so much that a hypothesis test has "too much power" with large n, it's that hypothesis tests don't seem to answer the question you're interested in.
Given the large sample size, the second p | Is it valid to use Hartigans' dip test to reject uni-modal null hypothesis with large N?
It isn't so much that a hypothesis test has "too much power" with large n, it's that hypothesis tests don't seem to answer the question you're interested in.
Given the large sample size, the second plot looks to me like there is some suggestion of at least 2 modes.
"Qualitatively different" is basically "is this different enough to matter?" which is more a question of effect size than significance (hypothesis tests will identify even trivial differences, so they're simply not answering a question like "how different are they?"). In fact, it's often the case that we already know the null to be false, so we certainly shouldn't be using one in that case. Some diagnostic measure of whatever you regard as important in terms of difference in distribution might be useful.
I think there are indeed two questions - 1) Am I seeing an effect (multi-mode output resulting from unimodal input) and 2) how big is that effect (and, related, is it big enough to matter?)
The first question might be cast as a hypothesis testing question (though it's not the only way to take it). On the second question, the paper by Hartigan&Hartigan says
"The dip test measures multimodality in a sample by the maximum difference, over all sample points, between the empirical distribution function, and the unimodal distribution function that minimizes that maximum difference."
-- that statistic appears to be a perfectly reasonable measure of the extent of deviation from unimodality. As for whether the size of difference matters, that's harder to say without knowing the application - you might be better placed to judge it (or to identify some other measure that you can say whether it matters with).
What I want to know is whether my simulation fed with the same input distribution but with one parameter changed (what I've plotted) leads to qualitatively different output distributions, particularly if the system has a different number of modes of operation.
Since you're interested in a two-sample comparison of number of modes, it might even be possible to modify a statistic for the one-sample case to be used for the two-sample case.
One way to approach that occurs to me, which is a form of resampling.
Compute the difference in dip-test statistics for the two samples. That's your measure of the effect.
You could do bootstrapping, for example, to estimate the standard error or to build a confidence interval for the difference in dip statistics. Given the difference in location, you might try resampling within-samples. A test might be based off whether the confidence interval covers 0. You might want to do some simulation to see whether the coverage of such an interval is reasonable, and whether techniques for esitmating/reducing bias might help.
Another alternative way to bootstrap might be to have some estimates of location and scale and resample standardized residuals, if you regard the shapes as being the same under the null.
Yet another alternative might be to consider a model that might be suitable for the distributional shape if it were unimodal, and then treat the two samples as finite mixtures of such distributions (location or scale mixtures, if either are indicated by your knowledge of the problem); then you'd have some difference in estimated number of components as a measure.
That's a little less specific than I'd like to be, but it's at least a starting point. | Is it valid to use Hartigans' dip test to reject uni-modal null hypothesis with large N?
It isn't so much that a hypothesis test has "too much power" with large n, it's that hypothesis tests don't seem to answer the question you're interested in.
Given the large sample size, the second p |
36,375 | Chi-square test: difference between goodness-of-fit test and test of independence | 1) A goodness of fit test is for testing whether a set of multinomial counts is distributed according to a prespecified (i.e. before you see the data!) set of population proportions.
2) A test of homogeneity tests whether two (or more) sets of multinomial counts come from different sets of population proportions.
3) A test of independence tests is for a bivariate** multinomial, of whether $p_{ij}$ is different from $p_{i}\,p_{j}$.
**(usually)
Sometimes people make the mistake of treating the second case as if it were the first. This underestimates the variability between the proportions. (If one sample is very large the error in treating it as population proportions will be relatively small.) | Chi-square test: difference between goodness-of-fit test and test of independence | 1) A goodness of fit test is for testing whether a set of multinomial counts is distributed according to a prespecified (i.e. before you see the data!) set of population proportions.
2) A test of hom | Chi-square test: difference between goodness-of-fit test and test of independence
1) A goodness of fit test is for testing whether a set of multinomial counts is distributed according to a prespecified (i.e. before you see the data!) set of population proportions.
2) A test of homogeneity tests whether two (or more) sets of multinomial counts come from different sets of population proportions.
3) A test of independence tests is for a bivariate** multinomial, of whether $p_{ij}$ is different from $p_{i}\,p_{j}$.
**(usually)
Sometimes people make the mistake of treating the second case as if it were the first. This underestimates the variability between the proportions. (If one sample is very large the error in treating it as population proportions will be relatively small.) | Chi-square test: difference between goodness-of-fit test and test of independence
1) A goodness of fit test is for testing whether a set of multinomial counts is distributed according to a prespecified (i.e. before you see the data!) set of population proportions.
2) A test of hom |
36,376 | Chi-square test: difference between goodness-of-fit test and test of independence | There are 2 primary differences between a Pearson goodness of fit test and a Pearson test of independence:
The test of independence presumes that you have 2 random variables and you want to test their independence given the sample at hand. The goodness of fit test, on the other hand, works on 1 random variable at a time. You can test whether the Pearson d statistic is large enough to reject the null hypothesis that your sample came from the hypothesized distribution. You can do so a) if all parameters are known or b) if parameters are unknown and need to be estimated (using MLE for example). In the latter case, the number of degrees of freedom of the Pearson d statistic is reduced by the number of estimated parameters.
But the key difference, in my mind, between the goodness of fit test and the test of independence is the assumption under which the expected counts are calculated. In the case of goodness of fit, the expected counts are calculated under the assumption that the sample came from the hypothesized distribution. In the case of the test of independence, the expected counts are calculated under the assumption that the 2 random variables are independent, as follows. Suppose you have random variables A and B, each partitioned as depicted in the table of observed counts below.
To calculate the expected counts for the first cell: | Chi-square test: difference between goodness-of-fit test and test of independence | There are 2 primary differences between a Pearson goodness of fit test and a Pearson test of independence:
The test of independence presumes that you have 2 random variables and you want to test thei | Chi-square test: difference between goodness-of-fit test and test of independence
There are 2 primary differences between a Pearson goodness of fit test and a Pearson test of independence:
The test of independence presumes that you have 2 random variables and you want to test their independence given the sample at hand. The goodness of fit test, on the other hand, works on 1 random variable at a time. You can test whether the Pearson d statistic is large enough to reject the null hypothesis that your sample came from the hypothesized distribution. You can do so a) if all parameters are known or b) if parameters are unknown and need to be estimated (using MLE for example). In the latter case, the number of degrees of freedom of the Pearson d statistic is reduced by the number of estimated parameters.
But the key difference, in my mind, between the goodness of fit test and the test of independence is the assumption under which the expected counts are calculated. In the case of goodness of fit, the expected counts are calculated under the assumption that the sample came from the hypothesized distribution. In the case of the test of independence, the expected counts are calculated under the assumption that the 2 random variables are independent, as follows. Suppose you have random variables A and B, each partitioned as depicted in the table of observed counts below.
To calculate the expected counts for the first cell: | Chi-square test: difference between goodness-of-fit test and test of independence
There are 2 primary differences between a Pearson goodness of fit test and a Pearson test of independence:
The test of independence presumes that you have 2 random variables and you want to test thei |
36,377 | Chi-square test: difference between goodness-of-fit test and test of independence | You may want to calculate the independence between two variables, A and B (test of independence) or if the distribution of A given B=B1 (first column) fits the distribution of A given B=B2 (second column). That is if P(A|B=B1)=P(A|B=B2). I'm taking as example the data table posted by @ColorStatistics in her answer.
The two calculations are slightly different, the test of independence takes into account the differences of both distributions with the expected counts, so you have more terms but smaller (the expected counts are "in between" the observed values), the goodness of fit test takes into account the differences of the first distribution from the other (the expected counts are the values of the second distribution), so you have less terms but bigger.
The two methods tend to be same if one subtotal of B is much greater than the other and accounts for most of the elements, that is the B2 elements are very slightly influenced by the exctraction of the B1 elements (c2>>c1 and c2~N). In this case the expected counts for the B2 column are almost equal to their values. So computing the difference with the expected counts (test of independence) is almost the same as computing the difference with the B2 column (goodness of fit test). | Chi-square test: difference between goodness-of-fit test and test of independence | You may want to calculate the independence between two variables, A and B (test of independence) or if the distribution of A given B=B1 (first column) fits the distribution of A given B=B2 (second col | Chi-square test: difference between goodness-of-fit test and test of independence
You may want to calculate the independence between two variables, A and B (test of independence) or if the distribution of A given B=B1 (first column) fits the distribution of A given B=B2 (second column). That is if P(A|B=B1)=P(A|B=B2). I'm taking as example the data table posted by @ColorStatistics in her answer.
The two calculations are slightly different, the test of independence takes into account the differences of both distributions with the expected counts, so you have more terms but smaller (the expected counts are "in between" the observed values), the goodness of fit test takes into account the differences of the first distribution from the other (the expected counts are the values of the second distribution), so you have less terms but bigger.
The two methods tend to be same if one subtotal of B is much greater than the other and accounts for most of the elements, that is the B2 elements are very slightly influenced by the exctraction of the B1 elements (c2>>c1 and c2~N). In this case the expected counts for the B2 column are almost equal to their values. So computing the difference with the expected counts (test of independence) is almost the same as computing the difference with the B2 column (goodness of fit test). | Chi-square test: difference between goodness-of-fit test and test of independence
You may want to calculate the independence between two variables, A and B (test of independence) or if the distribution of A given B=B1 (first column) fits the distribution of A given B=B2 (second col |
36,378 | Machine learning techniques for spam detection, and in general for text classification | One basic technique is Naive Bayes, which is often used for spam filtering. Essentially, you look at the frequencies of words appearing in sentences that you have already judged to be spam, and also at the frequencies of those words appearing in sentences you have already judged to be not spam, and then use those frequencies to make a judgement about new sentences.
You first estimate the conditional probabilities:
feature on(1) or off(0) given spam, $\newcommand{\bm}[1]{\mathbf{#1}}P(\bm{f}_i=1|S), P(\bm{f}_i=0|S)$ for all features $\bm{f}_i$, and
feature on or off given not spam, $P(\bm{f}_i=1|\neg S), P(\bm{f}_i=0|\neg S)$.
These can be estimated from the training set by summing columns for spam training examples and dividing by the number of spam examples and likewise for non-spam examples. You also need to estimate the incidence of spam: the prior probabilities for spam $P(S)$ and not spam $P(\neg S)$.
Given a new example with a feature vector $\bm{f}$, you can use Bayes rule and the naive assumption of independence of feature probabilities to write
$$P(S|\bm{f})=\frac{P(\bm{f}|S)P(S)}{P(\bm{f})} = \frac{P(\bm{f}_1|S)P(\bm{f}_2|S)\ldots P(\bm{f}_n|S)\;P(S)}{P(\bm{f})}=\frac{\left(\prod P(\bm{f}_i|S)\right)\;P(S)}{P(\bm{f})}$$
Similarly $P(\neg S|\bm{f}) = (\prod P(\bm{f}_i|\neg S))P(\neg S)\;/P(\bm{f})$. So you can get the probabilities $P(S|\bm{f})$ and $P(\neg S|\bm{f})$ based on the probabilities estimated earlier. You decide whether the new example is spam or not spam based on which probability is higher, which means that you can drop the denominator $P(\bm{f})$.
This is easy to implement in rapidminer, from the looks of a quick web search. It's generally very easy to implement from scratch: you're talking low 10s of lines of code in a language like R or Matlab. If you do so, it's worth noting that when the estimated conditional probabilities are zero, you need to pick some small non-zero value instead to avoid the products of conditional probabilities being zero. (Also, it's worth considering doing multiplications by adding logs.)
Naive Bayes is a very simple technique, but it has some drawbacks. One is how to deal with conditional probabilities that are zero, as discussed above. Perhaps more seriously, Naive Bayes as described here pays no attention to ordering or context (words occurring together can have quite different meanings from occurring singly). A good way to find information on more sophisticated techniques would be to research sentiment analysis. | Machine learning techniques for spam detection, and in general for text classification | One basic technique is Naive Bayes, which is often used for spam filtering. Essentially, you look at the frequencies of words appearing in sentences that you have already judged to be spam, and also a | Machine learning techniques for spam detection, and in general for text classification
One basic technique is Naive Bayes, which is often used for spam filtering. Essentially, you look at the frequencies of words appearing in sentences that you have already judged to be spam, and also at the frequencies of those words appearing in sentences you have already judged to be not spam, and then use those frequencies to make a judgement about new sentences.
You first estimate the conditional probabilities:
feature on(1) or off(0) given spam, $\newcommand{\bm}[1]{\mathbf{#1}}P(\bm{f}_i=1|S), P(\bm{f}_i=0|S)$ for all features $\bm{f}_i$, and
feature on or off given not spam, $P(\bm{f}_i=1|\neg S), P(\bm{f}_i=0|\neg S)$.
These can be estimated from the training set by summing columns for spam training examples and dividing by the number of spam examples and likewise for non-spam examples. You also need to estimate the incidence of spam: the prior probabilities for spam $P(S)$ and not spam $P(\neg S)$.
Given a new example with a feature vector $\bm{f}$, you can use Bayes rule and the naive assumption of independence of feature probabilities to write
$$P(S|\bm{f})=\frac{P(\bm{f}|S)P(S)}{P(\bm{f})} = \frac{P(\bm{f}_1|S)P(\bm{f}_2|S)\ldots P(\bm{f}_n|S)\;P(S)}{P(\bm{f})}=\frac{\left(\prod P(\bm{f}_i|S)\right)\;P(S)}{P(\bm{f})}$$
Similarly $P(\neg S|\bm{f}) = (\prod P(\bm{f}_i|\neg S))P(\neg S)\;/P(\bm{f})$. So you can get the probabilities $P(S|\bm{f})$ and $P(\neg S|\bm{f})$ based on the probabilities estimated earlier. You decide whether the new example is spam or not spam based on which probability is higher, which means that you can drop the denominator $P(\bm{f})$.
This is easy to implement in rapidminer, from the looks of a quick web search. It's generally very easy to implement from scratch: you're talking low 10s of lines of code in a language like R or Matlab. If you do so, it's worth noting that when the estimated conditional probabilities are zero, you need to pick some small non-zero value instead to avoid the products of conditional probabilities being zero. (Also, it's worth considering doing multiplications by adding logs.)
Naive Bayes is a very simple technique, but it has some drawbacks. One is how to deal with conditional probabilities that are zero, as discussed above. Perhaps more seriously, Naive Bayes as described here pays no attention to ordering or context (words occurring together can have quite different meanings from occurring singly). A good way to find information on more sophisticated techniques would be to research sentiment analysis. | Machine learning techniques for spam detection, and in general for text classification
One basic technique is Naive Bayes, which is often used for spam filtering. Essentially, you look at the frequencies of words appearing in sentences that you have already judged to be spam, and also a |
36,379 | Is it ever okay to ignore heteroskedastic residuals and continue with analysis? | The spread of those residuals look okay to me. With that arrangement of x's what did you expect the spread should look like? (I'd worry more about transformations making your mean function nonlinear in x.)
Specifically, if I generate random data with a similar pattern of x's for which the y's have constant variance, the residual plots do often look like that. Note that your impression of spread is heavily influenced by the range of residuals at each x, which does shrink on average as the x-density gets thinner, even when the sd is constant.
Here's four example residual plots, for which the data was randomly generated -- where the population spread at each x is constant (I know because I generated the data that way). As you see, the plots have a broadly similar appearance to yours, tending to look like vaguely elliptical point clouds (somewhat reminiscent of the shape of Stewie Griffin's head).
When the x's are vaguely normal, that's how residual plots should look. So if that's your objection, it's not only not a problem, its what you should hope to see.
Now let's imagine we had instead clear evidence of actual heteroskedasticity. Can we ignore that?
Well, that depends. Your estimates of standard deviations (e.g. of regression coefficients) will be biased. Your p-values in tests will be wrong. Confidence intervals will be biased and prediction intervals too narrow in some places and too wide in other places.
If you're not doing any of those things, it may not matter so much; some inefficiency in estimation of the coefficients may be about the worst of it. | Is it ever okay to ignore heteroskedastic residuals and continue with analysis? | The spread of those residuals look okay to me. With that arrangement of x's what did you expect the spread should look like? (I'd worry more about transformations making your mean function nonlinear i | Is it ever okay to ignore heteroskedastic residuals and continue with analysis?
The spread of those residuals look okay to me. With that arrangement of x's what did you expect the spread should look like? (I'd worry more about transformations making your mean function nonlinear in x.)
Specifically, if I generate random data with a similar pattern of x's for which the y's have constant variance, the residual plots do often look like that. Note that your impression of spread is heavily influenced by the range of residuals at each x, which does shrink on average as the x-density gets thinner, even when the sd is constant.
Here's four example residual plots, for which the data was randomly generated -- where the population spread at each x is constant (I know because I generated the data that way). As you see, the plots have a broadly similar appearance to yours, tending to look like vaguely elliptical point clouds (somewhat reminiscent of the shape of Stewie Griffin's head).
When the x's are vaguely normal, that's how residual plots should look. So if that's your objection, it's not only not a problem, its what you should hope to see.
Now let's imagine we had instead clear evidence of actual heteroskedasticity. Can we ignore that?
Well, that depends. Your estimates of standard deviations (e.g. of regression coefficients) will be biased. Your p-values in tests will be wrong. Confidence intervals will be biased and prediction intervals too narrow in some places and too wide in other places.
If you're not doing any of those things, it may not matter so much; some inefficiency in estimation of the coefficients may be about the worst of it. | Is it ever okay to ignore heteroskedastic residuals and continue with analysis?
The spread of those residuals look okay to me. With that arrangement of x's what did you expect the spread should look like? (I'd worry more about transformations making your mean function nonlinear i |
36,380 | Permutation test for factor analysis | Several authors have explored rerandomization-based criteria for component retention. For example, Peres-Neto et al., (2009) implemented a rerandomization-based version of parallel analysis and of Monte Carlo parallel analysis (which uses a high centile of eigenvalues of random data, rather than the mean). Dray developed a rerandomization-based component retention method using the RV-coefficient.
Aside: I use the term rerandomization-based to indicate the process by which uncorrelated comparator data sets, such as those used in parallel analysis, are generated. One can preserve the exact univariate distribution of each variable in observed data $\mathbf{X}$, while reducing correlation with each other variable in $\mathbf{X}$ to chance by independently rerandomizing (i.e. shuffling, or sampling without replacement all observations) each variable .
However, Dinno (2009) found that parallel analysis was insensitive to the distributional form of the data. This is because the (usual) object of analysis in principal component analysis is the correlation matrix, $\mathbf{R}$, and with any decent sample size, linear correlations become accurate regardless of the distribution of the data.
References
Dinno, A. (2009). Exploring the Sensitivity of Horn’s Parallel Analysis to the Distributional Form of Simulated Data. Multivariate Behavioral Research, 44(3):362–388.
Dray, S. (2008). On the number of principal components: A test of dimensionality based on measurements of similarity between matrices. Computational Statistics & Data Analysis, 52(4):2228–2237.
Peres-Neto, P., Jackson, D., and Somers, K. (2005). How many principal components? stopping rules for determining the number of non-trivial axes revisited. Computational Statistics & Data Analysis, 49(4):974–997. | Permutation test for factor analysis | Several authors have explored rerandomization-based criteria for component retention. For example, Peres-Neto et al., (2009) implemented a rerandomization-based version of parallel analysis and of Mon | Permutation test for factor analysis
Several authors have explored rerandomization-based criteria for component retention. For example, Peres-Neto et al., (2009) implemented a rerandomization-based version of parallel analysis and of Monte Carlo parallel analysis (which uses a high centile of eigenvalues of random data, rather than the mean). Dray developed a rerandomization-based component retention method using the RV-coefficient.
Aside: I use the term rerandomization-based to indicate the process by which uncorrelated comparator data sets, such as those used in parallel analysis, are generated. One can preserve the exact univariate distribution of each variable in observed data $\mathbf{X}$, while reducing correlation with each other variable in $\mathbf{X}$ to chance by independently rerandomizing (i.e. shuffling, or sampling without replacement all observations) each variable .
However, Dinno (2009) found that parallel analysis was insensitive to the distributional form of the data. This is because the (usual) object of analysis in principal component analysis is the correlation matrix, $\mathbf{R}$, and with any decent sample size, linear correlations become accurate regardless of the distribution of the data.
References
Dinno, A. (2009). Exploring the Sensitivity of Horn’s Parallel Analysis to the Distributional Form of Simulated Data. Multivariate Behavioral Research, 44(3):362–388.
Dray, S. (2008). On the number of principal components: A test of dimensionality based on measurements of similarity between matrices. Computational Statistics & Data Analysis, 52(4):2228–2237.
Peres-Neto, P., Jackson, D., and Somers, K. (2005). How many principal components? stopping rules for determining the number of non-trivial axes revisited. Computational Statistics & Data Analysis, 49(4):974–997. | Permutation test for factor analysis
Several authors have explored rerandomization-based criteria for component retention. For example, Peres-Neto et al., (2009) implemented a rerandomization-based version of parallel analysis and of Mon |
36,381 | How to split nodes in regression trees | You can compute variance with the same cost as the averages. Simply put you have to use an on-line version of algorithm for computing variance. It is crystal clear explained on an article of John D. Cook.
I used myself this online computing for a regression tree - split numeric method where I use an online computation of variance. I used to compute 2 running statistics, one starting from left and another one starting from right. It is possible to do that in a single step, I considered however that multiplication by a constant, gives also linear time and that does not bother me.
For more information you can take a look on Wikipedia also. | How to split nodes in regression trees | You can compute variance with the same cost as the averages. Simply put you have to use an on-line version of algorithm for computing variance. It is crystal clear explained on an article of John D. C | How to split nodes in regression trees
You can compute variance with the same cost as the averages. Simply put you have to use an on-line version of algorithm for computing variance. It is crystal clear explained on an article of John D. Cook.
I used myself this online computing for a regression tree - split numeric method where I use an online computation of variance. I used to compute 2 running statistics, one starting from left and another one starting from right. It is possible to do that in a single step, I considered however that multiplication by a constant, gives also linear time and that does not bother me.
For more information you can take a look on Wikipedia also. | How to split nodes in regression trees
You can compute variance with the same cost as the averages. Simply put you have to use an on-line version of algorithm for computing variance. It is crystal clear explained on an article of John D. C |
36,382 | Comparing dependent regression coefficients from models with different dependent variables | The tool you want is called seemingly unrelated regression (SUR). SUR is a way of estimating more than one regression equation on the same data at the same time. Obviously, one thing you can do is just run the two regressions separately. What would be wrong with that? Let's write your model as:
\begin{align}
DV_{1i} &= \beta_1 + \beta_2 A_i + \beta_3 B_i + \beta_4 C_i + \beta_5 D_i + \epsilon_i \\~\\
DV_{2i} &=\alpha_1 +\alpha_2 A_i +\alpha_3 B_i +\alpha_4 C_i +\alpha_5 D_i + \delta_i \\
\end{align}
It sounds like you are interested in testing hypotheses like $H_0:\beta_2=\alpha_2$. A typical way to test a hypothesis like this by looking to see if a t-statistic is greater than 2 in absolute value:
\begin{align}
t-stat &= \frac{\hat{\beta}_2-\hat{\alpha}_2}{\sqrt{V(\hat{\beta}_2-\hat{\alpha}_2)}}\\
\strut\\
V(\hat{\beta}_2-\hat{\alpha}_2) &= V(\hat{\beta}_2)+V(\hat{\alpha}_2)-2Cov(\hat{\beta}_2,\hat{\alpha}_2)
\end{align}
When you run the two models separately, you can read off estimates of $\sqrt{V(\hat{\beta}_2)}$ and $\sqrt{V(\hat{\alpha}_2)}$ from the regression output---the standard errors of the coefficient estimates. But what do you do to get the covariance? Sometimes it may be reasonable to assume that this covariance is zero, but not often. SUR will calculate this covariance for you, making the calculation of the t-statistic possible.
In R, I think you want systemfit, and in Stata you definitely want sureg. | Comparing dependent regression coefficients from models with different dependent variables | The tool you want is called seemingly unrelated regression (SUR). SUR is a way of estimating more than one regression equation on the same data at the same time. Obviously, one thing you can do is j | Comparing dependent regression coefficients from models with different dependent variables
The tool you want is called seemingly unrelated regression (SUR). SUR is a way of estimating more than one regression equation on the same data at the same time. Obviously, one thing you can do is just run the two regressions separately. What would be wrong with that? Let's write your model as:
\begin{align}
DV_{1i} &= \beta_1 + \beta_2 A_i + \beta_3 B_i + \beta_4 C_i + \beta_5 D_i + \epsilon_i \\~\\
DV_{2i} &=\alpha_1 +\alpha_2 A_i +\alpha_3 B_i +\alpha_4 C_i +\alpha_5 D_i + \delta_i \\
\end{align}
It sounds like you are interested in testing hypotheses like $H_0:\beta_2=\alpha_2$. A typical way to test a hypothesis like this by looking to see if a t-statistic is greater than 2 in absolute value:
\begin{align}
t-stat &= \frac{\hat{\beta}_2-\hat{\alpha}_2}{\sqrt{V(\hat{\beta}_2-\hat{\alpha}_2)}}\\
\strut\\
V(\hat{\beta}_2-\hat{\alpha}_2) &= V(\hat{\beta}_2)+V(\hat{\alpha}_2)-2Cov(\hat{\beta}_2,\hat{\alpha}_2)
\end{align}
When you run the two models separately, you can read off estimates of $\sqrt{V(\hat{\beta}_2)}$ and $\sqrt{V(\hat{\alpha}_2)}$ from the regression output---the standard errors of the coefficient estimates. But what do you do to get the covariance? Sometimes it may be reasonable to assume that this covariance is zero, but not often. SUR will calculate this covariance for you, making the calculation of the t-statistic possible.
In R, I think you want systemfit, and in Stata you definitely want sureg. | Comparing dependent regression coefficients from models with different dependent variables
The tool you want is called seemingly unrelated regression (SUR). SUR is a way of estimating more than one regression equation on the same data at the same time. Obviously, one thing you can do is j |
36,383 | Difference between Random Forest and MART | First question
When you consider the prediction error through bias-variance decomposition you face the well-know compromise between how well you fit on average (bias) and how stable is you prediction model (variance).
One can improve the error by decreasing the variance or by increasing the bias. Either way you choose, you might loose at the other hand. However, one can hope that overall you improve your prediction error.
Random Forests use trees which usually overfit. The trees used in RF are fully-grown (no pruning). The bias is small since they capture locally the whole details. However fully-grown trees have few prediction power, due to high variance. Variance is high because the trees depends too much on any piece of data. One observation added/removed can give a totally different tree.
Bagging (many averaged trees on bootstrap samples) have the nice result that it creates smoother surfaces (the RF is still a piece-wise model, but the regions produced by averaging are much smaller). The surfaces resulted from averaging are smoother, more stable and thus have less variance. One can link this averaging with Central Limit Theorem where one can note how variance decrease.
A final note on RF is that the averaging works well when the trees resulted are independent. And Breiman et all. realized that by choosing randomly some of the input features will increase the independence between the trees, and have the nice effect that the variance decrease more.
Boosting works the other way, regarding bias-variance decomposition. Boosting starts with a weak-model which have low variance and high bias. The same trees used in boosting are not grown to many nodes, only to a small limit. Sometimes works fine even with decision stumps, which are the simplest form of a tree.
So, boosting starts with a low-variance tree with high bias (learners are weak because they do not capture well the structure of the data) and works gradually to improve bias. MART (I usually prefer the modern name of Gradient Boosting Trees) improve bias by "walking" on the error surface in the direction given by gradients. They usually loose in variance, on this way, but, again, one can hope that the loose in variance is well-compensated by gain in bias term.
As a conclusion these two families (bagging and boosting) are not at all the same. They start their search for the best compromise from opposite ends and works in opposite directions.
Second question
Random Forests uses CART trees, if you want to do it by the book. However were reported very small differences if one uses different trees (like C4.5) with various splitting criteria. As a matter of fact the Weka's implementation of RF uses C4.5 (the name is J4.8 in Weka library). The reason is probably the computation time, caused by smaller trees produced. | Difference between Random Forest and MART | First question
When you consider the prediction error through bias-variance decomposition you face the well-know compromise between how well you fit on average (bias) and how stable is you prediction | Difference between Random Forest and MART
First question
When you consider the prediction error through bias-variance decomposition you face the well-know compromise between how well you fit on average (bias) and how stable is you prediction model (variance).
One can improve the error by decreasing the variance or by increasing the bias. Either way you choose, you might loose at the other hand. However, one can hope that overall you improve your prediction error.
Random Forests use trees which usually overfit. The trees used in RF are fully-grown (no pruning). The bias is small since they capture locally the whole details. However fully-grown trees have few prediction power, due to high variance. Variance is high because the trees depends too much on any piece of data. One observation added/removed can give a totally different tree.
Bagging (many averaged trees on bootstrap samples) have the nice result that it creates smoother surfaces (the RF is still a piece-wise model, but the regions produced by averaging are much smaller). The surfaces resulted from averaging are smoother, more stable and thus have less variance. One can link this averaging with Central Limit Theorem where one can note how variance decrease.
A final note on RF is that the averaging works well when the trees resulted are independent. And Breiman et all. realized that by choosing randomly some of the input features will increase the independence between the trees, and have the nice effect that the variance decrease more.
Boosting works the other way, regarding bias-variance decomposition. Boosting starts with a weak-model which have low variance and high bias. The same trees used in boosting are not grown to many nodes, only to a small limit. Sometimes works fine even with decision stumps, which are the simplest form of a tree.
So, boosting starts with a low-variance tree with high bias (learners are weak because they do not capture well the structure of the data) and works gradually to improve bias. MART (I usually prefer the modern name of Gradient Boosting Trees) improve bias by "walking" on the error surface in the direction given by gradients. They usually loose in variance, on this way, but, again, one can hope that the loose in variance is well-compensated by gain in bias term.
As a conclusion these two families (bagging and boosting) are not at all the same. They start their search for the best compromise from opposite ends and works in opposite directions.
Second question
Random Forests uses CART trees, if you want to do it by the book. However were reported very small differences if one uses different trees (like C4.5) with various splitting criteria. As a matter of fact the Weka's implementation of RF uses C4.5 (the name is J4.8 in Weka library). The reason is probably the computation time, caused by smaller trees produced. | Difference between Random Forest and MART
First question
When you consider the prediction error through bias-variance decomposition you face the well-know compromise between how well you fit on average (bias) and how stable is you prediction |
36,384 | Difference between Random Forest and MART | We can understand them from the training data.
Random forest is to learn different trees based on partial training data, where the training data sets are drawn from the raw data set and the attribute at each split is on random. It encourages the diversity of samples.
The MART or generally boosting usually train a single tree over the entire training set while with different adaptive loss functions.
The loss function matters. | Difference between Random Forest and MART | We can understand them from the training data.
Random forest is to learn different trees based on partial training data, where the training data sets are drawn from the raw data set and the attribute | Difference between Random Forest and MART
We can understand them from the training data.
Random forest is to learn different trees based on partial training data, where the training data sets are drawn from the raw data set and the attribute at each split is on random. It encourages the diversity of samples.
The MART or generally boosting usually train a single tree over the entire training set while with different adaptive loss functions.
The loss function matters. | Difference between Random Forest and MART
We can understand them from the training data.
Random forest is to learn different trees based on partial training data, where the training data sets are drawn from the raw data set and the attribute |
36,385 | Deviate vs. Variable | My understanding is that a deviate/variate a particular outcome of random variable. If I generate a 100 draws from standard normal (a random variable) using my favorite PRNG, I get 100 standard normal deviates. | Deviate vs. Variable | My understanding is that a deviate/variate a particular outcome of random variable. If I generate a 100 draws from standard normal (a random variable) using my favorite PRNG, I get 100 standard normal | Deviate vs. Variable
My understanding is that a deviate/variate a particular outcome of random variable. If I generate a 100 draws from standard normal (a random variable) using my favorite PRNG, I get 100 standard normal deviates. | Deviate vs. Variable
My understanding is that a deviate/variate a particular outcome of random variable. If I generate a 100 draws from standard normal (a random variable) using my favorite PRNG, I get 100 standard normal |
36,386 | Deviate vs. Variable | The terms "variate" and "deviate" appear to be interchangeable:
a random variable is a measurable function from a probability space to a measurable space of values that the variable can take on. In that context, and in statistics, those values are known as a random variates, or occasionally random deviates[1]
[1] https://en.wikipedia.org/wiki/Random_variate (3/8/2018) | Deviate vs. Variable | The terms "variate" and "deviate" appear to be interchangeable:
a random variable is a measurable function from a probability space to a measurable space of values that the variable can take on. In t | Deviate vs. Variable
The terms "variate" and "deviate" appear to be interchangeable:
a random variable is a measurable function from a probability space to a measurable space of values that the variable can take on. In that context, and in statistics, those values are known as a random variates, or occasionally random deviates[1]
[1] https://en.wikipedia.org/wiki/Random_variate (3/8/2018) | Deviate vs. Variable
The terms "variate" and "deviate" appear to be interchangeable:
a random variable is a measurable function from a probability space to a measurable space of values that the variable can take on. In t |
36,387 | If the dependent variable is standardized by age and sex, does it still make sense to include these as controls in a multivariate regression? | This is permissible. If the standardization has been done on a sample similar to the one you are using, then you would expect that the parameter estimates for age and gender would be small, but I see no reason that cannot be included (except that it may make the model more complex than it needs to be).
The problem you may have is interpretation of the scores. What you will have is not really the effect of age and gender on test score, it is the difference in those effects between your sample and the standardization sample.
Usually, with such scores, the standardization formula is available somewhere; it certainly ought to be available. You say it is not. Then how did you get your raw scores transformed? Or was this all done by computer? | If the dependent variable is standardized by age and sex, does it still make sense to include these | This is permissible. If the standardization has been done on a sample similar to the one you are using, then you would expect that the parameter estimates for age and gender would be small, but I see | If the dependent variable is standardized by age and sex, does it still make sense to include these as controls in a multivariate regression?
This is permissible. If the standardization has been done on a sample similar to the one you are using, then you would expect that the parameter estimates for age and gender would be small, but I see no reason that cannot be included (except that it may make the model more complex than it needs to be).
The problem you may have is interpretation of the scores. What you will have is not really the effect of age and gender on test score, it is the difference in those effects between your sample and the standardization sample.
Usually, with such scores, the standardization formula is available somewhere; it certainly ought to be available. You say it is not. Then how did you get your raw scores transformed? Or was this all done by computer? | If the dependent variable is standardized by age and sex, does it still make sense to include these
This is permissible. If the standardization has been done on a sample similar to the one you are using, then you would expect that the parameter estimates for age and gender would be small, but I see |
36,388 | If the dependent variable is standardized by age and sex, does it still make sense to include these as controls in a multivariate regression? | There are potential problems with this approach, besides the obvious question of why not just condition on age and sex in your model.
The standardization may have been done on a group of subjects that differ from your target group in a meaningful way, tilting its assessment of the age and sex effects
The standardization may have falsely assumed linearity in age and additivity for age and sex
The standardization may have been done using an improperly transformed $Y$
You are not taken into account the uncertainties associated with the standardization
As you can tell from the above, there are many advantages of avoiding "standardization" and instead doing full conditioning in your analysis. | If the dependent variable is standardized by age and sex, does it still make sense to include these | There are potential problems with this approach, besides the obvious question of why not just condition on age and sex in your model.
The standardization may have been done on a group of subjects tha | If the dependent variable is standardized by age and sex, does it still make sense to include these as controls in a multivariate regression?
There are potential problems with this approach, besides the obvious question of why not just condition on age and sex in your model.
The standardization may have been done on a group of subjects that differ from your target group in a meaningful way, tilting its assessment of the age and sex effects
The standardization may have falsely assumed linearity in age and additivity for age and sex
The standardization may have been done using an improperly transformed $Y$
You are not taken into account the uncertainties associated with the standardization
As you can tell from the above, there are many advantages of avoiding "standardization" and instead doing full conditioning in your analysis. | If the dependent variable is standardized by age and sex, does it still make sense to include these
There are potential problems with this approach, besides the obvious question of why not just condition on age and sex in your model.
The standardization may have been done on a group of subjects tha |
36,389 | If the dependent variable is standardized by age and sex, does it still make sense to include these as controls in a multivariate regression? | If $\alpha_1$ and $\alpha_2$ are applied consistently to the entire sample, then you are correct in your thinking that it will bias the OLS estimates of age and gender but not of the adoption estimate, as it is just a linear transformation of scores based on Age and Gender. To boot if you know the value of the $\alpha$'s then you can back transform to get the estimates you are interested in, and if you know that they are correlated with being adopted they should definitely still be included in the model.
Consider that we aren't interested in the effects on the adjusted score, but on the original score;
$score_i = \beta_{01} + \beta_{11} Age + \beta_{21} Gender + \beta_{31} Adopted$
But we only observe $score^*_{i} = score_i - \alpha_1 Age - \alpha_2 Gender$. So we can only estimate the equation;
$score^*_{i} = \beta_{02} + \beta_{12} Age + \beta_{22} Gender + \beta_{32} Adopted$
We can now replace $score^*_{i}$ on the left hand side with the original score in which we are interested in, and then rearrange the equation so the age and gender are only on the right hand side.
$score_i - \alpha_1 Age - \alpha_2 Gender = \beta_{02} + \beta_{12} Age + \beta_{22} Gender + \beta_{32} Adopted$
$score_i = \beta_{02} + (\beta_{12} + \alpha_1) Age + (\beta_{22} + \alpha_2) Gender + \beta_{32} Adopted$
So if we actually know the values of $\alpha_1$ and $\alpha_2$ we can backtransform the estimates of $\beta_{12}$ and $\beta_{22}$ to the original estimates we are interested in. This actually shows that by standardizing the score age and gender should be included in the equation, as it can introduce dependencies that weren't originally there. E.g. $\beta_{11} Age$ and $\beta_{21} Gender$ could originally be zero in the unobserved equation, but are non-zero in the transformed equation (e.g. you would have to have the fortuitous luck that $\alpha_1 = -1 \cdot \beta_{11}$ for the effect of age to be zero in the transformed equation).
Unfortunately my experience with vendors who adjust scores like this is that they don't release the $\alpha$'s and the $\alpha$'s aren't applied uniformily to the entire sample (e.g. girls aged 10 would have different $\alpha$'s than boys aged 12). I don't believe this logic applies in those circumstances. | If the dependent variable is standardized by age and sex, does it still make sense to include these | If $\alpha_1$ and $\alpha_2$ are applied consistently to the entire sample, then you are correct in your thinking that it will bias the OLS estimates of age and gender but not of the adoption estimate | If the dependent variable is standardized by age and sex, does it still make sense to include these as controls in a multivariate regression?
If $\alpha_1$ and $\alpha_2$ are applied consistently to the entire sample, then you are correct in your thinking that it will bias the OLS estimates of age and gender but not of the adoption estimate, as it is just a linear transformation of scores based on Age and Gender. To boot if you know the value of the $\alpha$'s then you can back transform to get the estimates you are interested in, and if you know that they are correlated with being adopted they should definitely still be included in the model.
Consider that we aren't interested in the effects on the adjusted score, but on the original score;
$score_i = \beta_{01} + \beta_{11} Age + \beta_{21} Gender + \beta_{31} Adopted$
But we only observe $score^*_{i} = score_i - \alpha_1 Age - \alpha_2 Gender$. So we can only estimate the equation;
$score^*_{i} = \beta_{02} + \beta_{12} Age + \beta_{22} Gender + \beta_{32} Adopted$
We can now replace $score^*_{i}$ on the left hand side with the original score in which we are interested in, and then rearrange the equation so the age and gender are only on the right hand side.
$score_i - \alpha_1 Age - \alpha_2 Gender = \beta_{02} + \beta_{12} Age + \beta_{22} Gender + \beta_{32} Adopted$
$score_i = \beta_{02} + (\beta_{12} + \alpha_1) Age + (\beta_{22} + \alpha_2) Gender + \beta_{32} Adopted$
So if we actually know the values of $\alpha_1$ and $\alpha_2$ we can backtransform the estimates of $\beta_{12}$ and $\beta_{22}$ to the original estimates we are interested in. This actually shows that by standardizing the score age and gender should be included in the equation, as it can introduce dependencies that weren't originally there. E.g. $\beta_{11} Age$ and $\beta_{21} Gender$ could originally be zero in the unobserved equation, but are non-zero in the transformed equation (e.g. you would have to have the fortuitous luck that $\alpha_1 = -1 \cdot \beta_{11}$ for the effect of age to be zero in the transformed equation).
Unfortunately my experience with vendors who adjust scores like this is that they don't release the $\alpha$'s and the $\alpha$'s aren't applied uniformily to the entire sample (e.g. girls aged 10 would have different $\alpha$'s than boys aged 12). I don't believe this logic applies in those circumstances. | If the dependent variable is standardized by age and sex, does it still make sense to include these
If $\alpha_1$ and $\alpha_2$ are applied consistently to the entire sample, then you are correct in your thinking that it will bias the OLS estimates of age and gender but not of the adoption estimate |
36,390 | Does party package in R provide out-of-bag estimates of error for Random Forest models? | The caret package has a method for getting that. You can use train as the interface. For example:
> mod1 <- train(Species ~ .,
+ data = iris,
+ method = "cforest",
+ tuneGrid = data.frame(.mtry = 2),
+ trControl = trainControl(method = "oob"))
> mod1
150 samples
4 predictors
3 classes: 'setosa', 'versicolor', 'virginica'
No pre-processing
Resampling:
Summary of sample sizes:
Resampling results
Accuracy Kappa
0.967 0.95
Tuning parameter 'mtry' was held constant at a value of 2
Alternatively, there is an internal function that can be used if you want to go straight to cforest but you have to call it using the namespace operator:
> mod2 <- cforest(Species ~ ., data = iris,
+ controls = cforest_unbiased(mtry = 2))
> caret:::cforestStats(mod2)
Accuracy Kappa
0.9666667 0.9500000
HTH,
Max | Does party package in R provide out-of-bag estimates of error for Random Forest models? | The caret package has a method for getting that. You can use train as the interface. For example:
> mod1 <- train(Species ~ .,
+ data = iris,
+ method = "cforest",
+ | Does party package in R provide out-of-bag estimates of error for Random Forest models?
The caret package has a method for getting that. You can use train as the interface. For example:
> mod1 <- train(Species ~ .,
+ data = iris,
+ method = "cforest",
+ tuneGrid = data.frame(.mtry = 2),
+ trControl = trainControl(method = "oob"))
> mod1
150 samples
4 predictors
3 classes: 'setosa', 'versicolor', 'virginica'
No pre-processing
Resampling:
Summary of sample sizes:
Resampling results
Accuracy Kappa
0.967 0.95
Tuning parameter 'mtry' was held constant at a value of 2
Alternatively, there is an internal function that can be used if you want to go straight to cforest but you have to call it using the namespace operator:
> mod2 <- cforest(Species ~ ., data = iris,
+ controls = cforest_unbiased(mtry = 2))
> caret:::cforestStats(mod2)
Accuracy Kappa
0.9666667 0.9500000
HTH,
Max | Does party package in R provide out-of-bag estimates of error for Random Forest models?
The caret package has a method for getting that. You can use train as the interface. For example:
> mod1 <- train(Species ~ .,
+ data = iris,
+ method = "cforest",
+ |
36,391 | Does party package in R provide out-of-bag estimates of error for Random Forest models? | Perhaps to expand a bit on Momo's answer, party doesn't provide an OOB estimate by default, but the computation of it is not too difficult, according to the manual. In the predict function you can use the parameter OOB=T, and leave the parameter newdata with its default of NULL (i.e., using the training data).
Something like this should work (slighlty adapted from party manual):
### honest (i.e., out-of-bag) cross-classification of
### true vs. predicted classes
set.seed(290875)
data("mammoexp", package = "TH.data")
forestmodel=cforest(ME ~ ., data = mammoexp)
oobPredicted=predict(forestmodel,OOB=T)
table(mammoexp$ME,oobPredicted) | Does party package in R provide out-of-bag estimates of error for Random Forest models? | Perhaps to expand a bit on Momo's answer, party doesn't provide an OOB estimate by default, but the computation of it is not too difficult, according to the manual. In the predict function you can use | Does party package in R provide out-of-bag estimates of error for Random Forest models?
Perhaps to expand a bit on Momo's answer, party doesn't provide an OOB estimate by default, but the computation of it is not too difficult, according to the manual. In the predict function you can use the parameter OOB=T, and leave the parameter newdata with its default of NULL (i.e., using the training data).
Something like this should work (slighlty adapted from party manual):
### honest (i.e., out-of-bag) cross-classification of
### true vs. predicted classes
set.seed(290875)
data("mammoexp", package = "TH.data")
forestmodel=cforest(ME ~ ., data = mammoexp)
oobPredicted=predict(forestmodel,OOB=T)
table(mammoexp$ME,oobPredicted) | Does party package in R provide out-of-bag estimates of error for Random Forest models?
Perhaps to expand a bit on Momo's answer, party doesn't provide an OOB estimate by default, but the computation of it is not too difficult, according to the manual. In the predict function you can use |
36,392 | Bivariate Normal distribution and correlation | Yes.
By definition, the value of the CDF (call it $F_\rho$) at $(s,t)$ is the chance that the first component is less than or equal to $s$ and the second is less than or equal to $t$:
$$F_\rho(s,t) = \frac{1}{2 \pi \sqrt{1-\rho ^2}}\int_{-\infty}^t \int_{-\infty}^s e^{-\frac{\frac{x^2}{2}-\rho x y+\frac{y^2}{2}}{1-\rho ^2}} dx dy.$$
Performing the $x$ integration and then differentiating with respect to $\rho$ under the integral sign yields
$$\frac{-1}{2 \pi \left(1-\rho ^2\right)^{3/2}} \int_{-\infty}^t e^{\frac{s^2-2 \rho s y+y^2}{2 \left(\rho ^2-1\right)}} (y-\rho s) dy.$$
This can be integrated directly to produce the PDF
$$f_\rho(s,t) = \frac{1}{2 \pi \sqrt{1-\rho ^2}}e^{-\frac{\frac{s^2}{2}-\rho s t+\frac{t^2}{2}}{1-\rho ^2}}.$$
Because the integrands are so well-behaved, we may reverse the order of integration and differentiation, concluding that for all $(s,t)$,
$$\frac{\partial}{\partial \rho} F_\rho(s,t) = f_\rho(s,t).$$
Because $f_\rho(s,t)\gt 0$ everywhere, $F_\rho$ is strictly monotone in $\rho$ everywhere, QED. | Bivariate Normal distribution and correlation | Yes.
By definition, the value of the CDF (call it $F_\rho$) at $(s,t)$ is the chance that the first component is less than or equal to $s$ and the second is less than or equal to $t$:
$$F_\rho(s,t) = | Bivariate Normal distribution and correlation
Yes.
By definition, the value of the CDF (call it $F_\rho$) at $(s,t)$ is the chance that the first component is less than or equal to $s$ and the second is less than or equal to $t$:
$$F_\rho(s,t) = \frac{1}{2 \pi \sqrt{1-\rho ^2}}\int_{-\infty}^t \int_{-\infty}^s e^{-\frac{\frac{x^2}{2}-\rho x y+\frac{y^2}{2}}{1-\rho ^2}} dx dy.$$
Performing the $x$ integration and then differentiating with respect to $\rho$ under the integral sign yields
$$\frac{-1}{2 \pi \left(1-\rho ^2\right)^{3/2}} \int_{-\infty}^t e^{\frac{s^2-2 \rho s y+y^2}{2 \left(\rho ^2-1\right)}} (y-\rho s) dy.$$
This can be integrated directly to produce the PDF
$$f_\rho(s,t) = \frac{1}{2 \pi \sqrt{1-\rho ^2}}e^{-\frac{\frac{s^2}{2}-\rho s t+\frac{t^2}{2}}{1-\rho ^2}}.$$
Because the integrands are so well-behaved, we may reverse the order of integration and differentiation, concluding that for all $(s,t)$,
$$\frac{\partial}{\partial \rho} F_\rho(s,t) = f_\rho(s,t).$$
Because $f_\rho(s,t)\gt 0$ everywhere, $F_\rho$ is strictly monotone in $\rho$ everywhere, QED. | Bivariate Normal distribution and correlation
Yes.
By definition, the value of the CDF (call it $F_\rho$) at $(s,t)$ is the chance that the first component is less than or equal to $s$ and the second is less than or equal to $t$:
$$F_\rho(s,t) = |
36,393 | Bivariate Normal distribution and correlation | The answer would appear to be YES. I am not sure how this is usually proven (since the bivariate Normal cdf does not have a convenient closed form) ... but as a quick thought, I would appeal perhaps to graphical ideas. In particular, consider the contours of the zero mean bivariate Normal as $\rho$ increases, as per:
(source: tri.org.au)
Choose any $(x,y)$ point ... The cdf at $(x,y)$ is the joint integral of the pdf up to $(x,y)$. When $\rho = -1$, the contours of the pdf lie maximally out of alignment with the rectangular area defined by the integral. When $\rho = 1$, the opposite extreme is attained. | Bivariate Normal distribution and correlation | The answer would appear to be YES. I am not sure how this is usually proven (since the bivariate Normal cdf does not have a convenient closed form) ... but as a quick thought, I would appeal perhaps t | Bivariate Normal distribution and correlation
The answer would appear to be YES. I am not sure how this is usually proven (since the bivariate Normal cdf does not have a convenient closed form) ... but as a quick thought, I would appeal perhaps to graphical ideas. In particular, consider the contours of the zero mean bivariate Normal as $\rho$ increases, as per:
(source: tri.org.au)
Choose any $(x,y)$ point ... The cdf at $(x,y)$ is the joint integral of the pdf up to $(x,y)$. When $\rho = -1$, the contours of the pdf lie maximally out of alignment with the rectangular area defined by the integral. When $\rho = 1$, the opposite extreme is attained. | Bivariate Normal distribution and correlation
The answer would appear to be YES. I am not sure how this is usually proven (since the bivariate Normal cdf does not have a convenient closed form) ... but as a quick thought, I would appeal perhaps t |
36,394 | Good internal factor structure but poor Cronbach's $\alpha$? | You can calculate the reliability of your items from the CFA.
From your standardized solution, calculate:
(L1+...Lk)*2/[(L1+...Lk)*2+(Var(E1)+...+Var(Ek))]
This will give the composite reliability, which should be close to alpha.
It's harder to have good fit if you have high alpha, and it's harder to have high alpha if you have good fit. The extreme example of this is if all of the items are uncorrelated - chi-square will be zero, and RMSEA will be zero, indicating great fit. But alpha will also be zero, indicating appalling reliability. The usual flag for this is low CFI (because the null model chi-square is so low), but you don't have that. I wrote about that in this paper: http://www.sciencedirect.com/science/article/pii/S0191886906003874 (which I think is not behind a paywall).
You mention your loadings in a comment (are these standardized?). Loadings of 0.45 lead to implied correlations of 0.23, so if your loadings are that high, I don't see how your correlations can be that low, and the model still fit. (What's your sample size?)
What estimator are you using? | Good internal factor structure but poor Cronbach's $\alpha$? | You can calculate the reliability of your items from the CFA.
From your standardized solution, calculate:
(L1+...Lk)*2/[(L1+...Lk)*2+(Var(E1)+...+Var(Ek))]
This will give the composite reliability, w | Good internal factor structure but poor Cronbach's $\alpha$?
You can calculate the reliability of your items from the CFA.
From your standardized solution, calculate:
(L1+...Lk)*2/[(L1+...Lk)*2+(Var(E1)+...+Var(Ek))]
This will give the composite reliability, which should be close to alpha.
It's harder to have good fit if you have high alpha, and it's harder to have high alpha if you have good fit. The extreme example of this is if all of the items are uncorrelated - chi-square will be zero, and RMSEA will be zero, indicating great fit. But alpha will also be zero, indicating appalling reliability. The usual flag for this is low CFI (because the null model chi-square is so low), but you don't have that. I wrote about that in this paper: http://www.sciencedirect.com/science/article/pii/S0191886906003874 (which I think is not behind a paywall).
You mention your loadings in a comment (are these standardized?). Loadings of 0.45 lead to implied correlations of 0.23, so if your loadings are that high, I don't see how your correlations can be that low, and the model still fit. (What's your sample size?)
What estimator are you using? | Good internal factor structure but poor Cronbach's $\alpha$?
You can calculate the reliability of your items from the CFA.
From your standardized solution, calculate:
(L1+...Lk)*2/[(L1+...Lk)*2+(Var(E1)+...+Var(Ek))]
This will give the composite reliability, w |
36,395 | Good internal factor structure but poor Cronbach's $\alpha$? | If your instrument is evaluating two or more constructs, it is possible that your alpha could be low. I advise you to estimate one alpha for each sub-scale. | Good internal factor structure but poor Cronbach's $\alpha$? | If your instrument is evaluating two or more constructs, it is possible that your alpha could be low. I advise you to estimate one alpha for each sub-scale. | Good internal factor structure but poor Cronbach's $\alpha$?
If your instrument is evaluating two or more constructs, it is possible that your alpha could be low. I advise you to estimate one alpha for each sub-scale. | Good internal factor structure but poor Cronbach's $\alpha$?
If your instrument is evaluating two or more constructs, it is possible that your alpha could be low. I advise you to estimate one alpha for each sub-scale. |
36,396 | What is the intuition behind (M)ANCOVA and when/why should one use it? | To complete your scheme:
ANCOVA: ANOVA conducted to compare multiple (possibly only two) conditions on at least one independent variable while controlling for a set of continuous nuisance variables (possibly only one).
MANCOVA: MANOVA conducted to compare multiple (possibly only two) conditions on at least one independent variable while controlling for a set of continuous nuisance variables (possibly only one). | What is the intuition behind (M)ANCOVA and when/why should one use it? | To complete your scheme:
ANCOVA: ANOVA conducted to compare multiple (possibly only two) conditions on at least one independent variable while controlling for a set of continuous nuisance variables | What is the intuition behind (M)ANCOVA and when/why should one use it?
To complete your scheme:
ANCOVA: ANOVA conducted to compare multiple (possibly only two) conditions on at least one independent variable while controlling for a set of continuous nuisance variables (possibly only one).
MANCOVA: MANOVA conducted to compare multiple (possibly only two) conditions on at least one independent variable while controlling for a set of continuous nuisance variables (possibly only one). | What is the intuition behind (M)ANCOVA and when/why should one use it?
To complete your scheme:
ANCOVA: ANOVA conducted to compare multiple (possibly only two) conditions on at least one independent variable while controlling for a set of continuous nuisance variables |
36,397 | Approximating the relative quantities of coins in Canada | I would have to say that it would be extremely difficult for you to estimate the relative quantities of coins in circulation through any but an exhaustive (collecting a large portion of those coins simultaneously) survey.
The reason is because most businesses (I believe) hold a reasonably large portion of coins in stock and will only distribute the coins which most efficiently lead to correct change. Thus even if you go into the same store 100 times and collect change each time unless you have exhausted the stock of available coins, the coins that you receive in exchange for your sampling will only be those which correspond only with the least change required to fulfill your needs.
Assuming you draw change requirements uniformly between 1 cent and 499 cents this ratio is:
200 100 25 10 5 1
0.13559322 0.06779661 0.25423729 0.13559322 0.06779661 0.33898305
If the store has no shortage of coins then your sampling procedure will automatically return the above ratios which have no correlation between the specific samples and the greater population of coins in circulation. To see how I came up with these numbers see my blog post on the topic.
But this does not account for the oddities of prices which tend to cluster ending in .09 as in .99, .49, or .39 (in the US at least) which will definitely contribute to higher ratio of pennies required for many purchases than in the uniform draw of change. Purchase requirements would need be specified so as to not cause further contamination of the data. Overall, I think it is clear that this is a pretty problematic study design.
If you were forced to do something like this then you might be alt to 1. record change totals for each purchase, 2. calculating efficient coinage selection via the method I propose on my blog for each purchase, 3. record coins actually returned, 4. estimate the different between the optimal returned coin quantities and that actually returned to estimate to what degree coin stocks might be diverging from the optimal quantities. From there I am not sure what to do with it in order to estimate total coins available in the currency.
Good luck and thanks for the interesting question! | Approximating the relative quantities of coins in Canada | I would have to say that it would be extremely difficult for you to estimate the relative quantities of coins in circulation through any but an exhaustive (collecting a large portion of those coins si | Approximating the relative quantities of coins in Canada
I would have to say that it would be extremely difficult for you to estimate the relative quantities of coins in circulation through any but an exhaustive (collecting a large portion of those coins simultaneously) survey.
The reason is because most businesses (I believe) hold a reasonably large portion of coins in stock and will only distribute the coins which most efficiently lead to correct change. Thus even if you go into the same store 100 times and collect change each time unless you have exhausted the stock of available coins, the coins that you receive in exchange for your sampling will only be those which correspond only with the least change required to fulfill your needs.
Assuming you draw change requirements uniformly between 1 cent and 499 cents this ratio is:
200 100 25 10 5 1
0.13559322 0.06779661 0.25423729 0.13559322 0.06779661 0.33898305
If the store has no shortage of coins then your sampling procedure will automatically return the above ratios which have no correlation between the specific samples and the greater population of coins in circulation. To see how I came up with these numbers see my blog post on the topic.
But this does not account for the oddities of prices which tend to cluster ending in .09 as in .99, .49, or .39 (in the US at least) which will definitely contribute to higher ratio of pennies required for many purchases than in the uniform draw of change. Purchase requirements would need be specified so as to not cause further contamination of the data. Overall, I think it is clear that this is a pretty problematic study design.
If you were forced to do something like this then you might be alt to 1. record change totals for each purchase, 2. calculating efficient coinage selection via the method I propose on my blog for each purchase, 3. record coins actually returned, 4. estimate the different between the optimal returned coin quantities and that actually returned to estimate to what degree coin stocks might be diverging from the optimal quantities. From there I am not sure what to do with it in order to estimate total coins available in the currency.
Good luck and thanks for the interesting question! | Approximating the relative quantities of coins in Canada
I would have to say that it would be extremely difficult for you to estimate the relative quantities of coins in circulation through any but an exhaustive (collecting a large portion of those coins si |
36,398 | Approximating the relative quantities of coins in Canada | The bigger problem is going to be part 1, not part 2.
It will be relatively easy to get a big sample of coins. But how do you know those coins are a random sample? Maybe people where you live use more of a particular coin than people in other parts of Canada. You certainly use money in a way that is not the same as everyone else.
For example, some people will pay for nearly everything with credit or debit cards; some will make even large purchases with cash. If you only buy cheap stuff with cash, you are going to get smaller coins. If you tend to have a lot of small bills and coins in your wallet, you will get smaller coins.
Probably not possible to get a truly random sample, but I'd try to get samples from different people in different parts of the country (rural/urban; west, center, Atlantic, etc.) and different ages, incomes etc. | Approximating the relative quantities of coins in Canada | The bigger problem is going to be part 1, not part 2.
It will be relatively easy to get a big sample of coins. But how do you know those coins are a random sample? Maybe people where you live use more | Approximating the relative quantities of coins in Canada
The bigger problem is going to be part 1, not part 2.
It will be relatively easy to get a big sample of coins. But how do you know those coins are a random sample? Maybe people where you live use more of a particular coin than people in other parts of Canada. You certainly use money in a way that is not the same as everyone else.
For example, some people will pay for nearly everything with credit or debit cards; some will make even large purchases with cash. If you only buy cheap stuff with cash, you are going to get smaller coins. If you tend to have a lot of small bills and coins in your wallet, you will get smaller coins.
Probably not possible to get a truly random sample, but I'd try to get samples from different people in different parts of the country (rural/urban; west, center, Atlantic, etc.) and different ages, incomes etc. | Approximating the relative quantities of coins in Canada
The bigger problem is going to be part 1, not part 2.
It will be relatively easy to get a big sample of coins. But how do you know those coins are a random sample? Maybe people where you live use more |
36,399 | Regression with rank order as dependent variable | Ordinal regression is ideal for this problem in my opinion. There is no problem other than computational burden caused by having as many unique $Y$ as there are observations. The R rms package's orm function solves the computational burden problem using a special sparse matrix representation. For an example see Which model should I use to fit my data ? ordinal and non-ordinal, not normal and not homoscedastic | Regression with rank order as dependent variable | Ordinal regression is ideal for this problem in my opinion. There is no problem other than computational burden caused by having as many unique $Y$ as there are observations. The R rms package's orm | Regression with rank order as dependent variable
Ordinal regression is ideal for this problem in my opinion. There is no problem other than computational burden caused by having as many unique $Y$ as there are observations. The R rms package's orm function solves the computational burden problem using a special sparse matrix representation. For an example see Which model should I use to fit my data ? ordinal and non-ordinal, not normal and not homoscedastic | Regression with rank order as dependent variable
Ordinal regression is ideal for this problem in my opinion. There is no problem other than computational burden caused by having as many unique $Y$ as there are observations. The R rms package's orm |
36,400 | Regression with rank order as dependent variable | In principle, you are right to worry that the response is bounded. In practice, with this kind of data, you are unlikely to get predictions beyond the observed range of the data. This won't be your fault, but just the effect of the high degree of unpredictability with firm-level data.
Put it this way: The worst you can get is that no predictors really help, in which case the model will predict the average rank for every firm, at least to a good first approximation. In practice, you hope you can do better, but there is little reason to expect that predictions will be outside the observed range. (Or is there?)
But why predict rank at all? Why not try to predict some performance measure, and then rank the predictions, and then compare with the expert's ranks? That sounds much less problematic. | Regression with rank order as dependent variable | In principle, you are right to worry that the response is bounded. In practice, with this kind of data, you are unlikely to get predictions beyond the observed range of the data. This won't be your fa | Regression with rank order as dependent variable
In principle, you are right to worry that the response is bounded. In practice, with this kind of data, you are unlikely to get predictions beyond the observed range of the data. This won't be your fault, but just the effect of the high degree of unpredictability with firm-level data.
Put it this way: The worst you can get is that no predictors really help, in which case the model will predict the average rank for every firm, at least to a good first approximation. In practice, you hope you can do better, but there is little reason to expect that predictions will be outside the observed range. (Or is there?)
But why predict rank at all? Why not try to predict some performance measure, and then rank the predictions, and then compare with the expert's ranks? That sounds much less problematic. | Regression with rank order as dependent variable
In principle, you are right to worry that the response is bounded. In practice, with this kind of data, you are unlikely to get predictions beyond the observed range of the data. This won't be your fa |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.